如何为新客户端重新启动Python中的电报机器人(具有初始变量状态)?

时间:2016-03-24 12:05:29

标签: python python-2.7 google-app-engine telegram-bot python-telegram-bot

这是我的第一个问题。我尝试用Python重写电报机器人。我无法解决一个问题。当我自己测试我的机器人一切都很好,但如果另一个用户连接我的机器人脚本并没有为他启动变量的初始状态。例如,在此代码脚本中,当用户发送“1”时递增x变量。但对于新用户x已经不是null。请帮我修理一下。

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)

1 个答案:

答案 0 :(得分:0)

而不是变量x,你可能想要像这样使用python字典 -

x = {}

然后像这样使用它 -

key = str(chat_id)
if key in x:
  x[key] += 1
else:
  x[key] = 1