コード例 #1
0
ファイル: main.py プロジェクト: Rimminen/telegram-bots
    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),
                ])
            elif not msg:
                resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({
                    'chat_id': str(chat_id),
                    'text': "error".encode('utf-8'),
                    'disable_web_page_preview': 'true',
                    'reply_to_message_id': str(message_id),
                })).read()
                logging.info("Empty message warning")
            else:
                logging.error('no msg or img specified')
                resp = None

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

        conclusion = formResponse(text)

        # return values: 0 requires posting a message, 1 posting one as a reply, -1 to do nothing
        if conclusion[0] == 0:
            reply(conclusion[1])
        elif conclusion[0] == 1:
            reply(conclusion[1])
        else:
            # no response needed
            pass
コード例 #2
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from handleresponse import formResponse

while True:
    msg = raw_input("\n>>>")
    resp = formResponse(msg)
    if resp[0] == -1:
        print "no response"
    else:
        print resp[1]