Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to restart this bot for a new user? #44

Open
DenisNepomnyashchikh opened this issue Mar 24, 2016 · 3 comments
Open

How to restart this bot for a new user? #44

DenisNepomnyashchikh opened this issue Mar 24, 2016 · 3 comments

Comments

@DenisNepomnyashchikh
Copy link

Thanks a lot for your bot! I cant solve one problem. When I test my bot by myself everything fine, but if another user connect with my bot script doesnt start for him with initial state of variables. For example, in this code script increment x variable when user send "1". But for new user x already not null. Please help me to fix it. Every user who connect to bot have to start work with script like no other users, and the script is the first time for him with initial state e.g. x=0.

import StringIO
import json
import logging
import random
import urllib
import urllib2

# for sending images
from PIL import Image
import multipart

# standard app engine imports
from google.appengine.api import urlfetch
from google.appengine.ext import ndb
import webapp2

TOKEN = 'TOKEN HERE'

BASE_URL = 'https://api.telegram.org/bot' + TOKEN + '/'

x = 0

# ================================

class EnableStatus(ndb.Model):
# key name: str(chat_id)
enabled = ndb.BooleanProperty(indexed=False, default=False)


# ================================

def setEnabled(chat_id, yes):
es = EnableStatus.get_or_insert(str(chat_id))
es.enabled = yes
es.put()

def getEnabled(chat_id):
es = EnableStatus.get_by_id(str(chat_id))
if es:
    return es.enabled
return False


# ================================

class MeHandler(webapp2.RequestHandler):
def get(self):
    urlfetch.set_default_fetch_deadline(60)
    self.response.write(json.dumps(json.load(urllib2.urlopen(BASE_URL + 'getMe'))))


class GetUpdatesHandler(webapp2.RequestHandler):
def get(self):
    urlfetch.set_default_fetch_deadline(60)
    self.response.write(json.dumps(json.load(urllib2.urlopen(BASE_URL + 'getUpdates'))))


class SetWebhookHandler(webapp2.RequestHandler):
def get(self):
    urlfetch.set_default_fetch_deadline(60)
    url = self.request.get('url')
    if url:
        self.response.write(json.dumps(json.load(urllib2.urlopen(BASE_URL + 'setWebhook', urllib.urlencode({'url': url})))))


class WebhookHandler(webapp2.RequestHandler):
def post(self):
    urlfetch.set_default_fetch_deadline(60)
    body = json.loads(self.request.body)
    logging.info('request body:')
    logging.info(body)
    self.response.write(json.dumps(body))

    update_id = body['update_id']
    message = body['message']
    message_id = message.get('message_id')
    date = message.get('date')
    text = message.get('text')
    fr = message.get('from')
    chat = message['chat']
    chat_id = chat['id']

    if not text:
        logging.info('no text')
        return
    def reply(msg=None, img=None):
        if msg:
            resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({
                'chat_id': str(chat_id),
                'text': msg.encode('utf-8'),
                'disable_web_page_preview': 'true',
                #'reply_to_message_id': str(message_id),
            })).read()
        elif img:
            resp = multipart.post_multipart(BASE_URL + 'sendPhoto', [
                ('chat_id', str(chat_id)),
                #('reply_to_message_id', str(message_id)),
            ], [
                ('photo', 'image.jpg', img),
            ])
        else:
            logging.error('no msg or img specified')
            resp = None

        logging.info('send response:')
        logging.info(resp)

    if text.startswith('/'):
        if text == '/start':
            reply('Bot start')
            setEnabled(chat_id, True)
        elif text == '/stop':
            reply('Bot disabled')
            setEnabled(chat_id, False)
        else:
            reply('What command?')

    elif '1' in text:
        global x
        x = x + 1
        reply(str(x))
    else:
        if getEnabled(chat_id):
            reply('?')
        else:
            logging.info('not enabled for chat_id {}'.format(chat_id))


app = webapp2.WSGIApplication([
('/me', MeHandler),
('/updates', GetUpdatesHandler),
('/set_webhook', SetWebhookHandler),
('/webhook', WebhookHandler),
], debug=True)`
@Walkman100
Copy link

What does your global x do? I'd think that it'd work fine without that

@Walkman100
Copy link

Re-reading your question, I think you want to permanently store variable x? for that, you should look into the NDB storage, look at the getEnabled(chat_id) and setEnabled(chat_id, True/False) methods.

@stolyarovden
Copy link

I have exactly the same problem. @DenisNepomnyashchikh, did you solve it somehow? Please, advise.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants