Handle multiple questions for Telegram bot in python

六月ゝ 毕业季﹏ 提交于 2019-12-05 08:44:11

There is not a most pythonic way of doing this. It is a problem you have to program to solve.

Basically, you have to maintain some state variables concerning each user. When a new message arrives, the bot checks what state that user is in, and responds accordingly.

Suppose you have a function, handle(msg), that gets called for each arriving message:

user_states = {}

def handle(msg):
    chat_id = msg['chat']['id']

    if chat_id not in user_states:
        user_states[chat_id] = some initial state ...

    state = user_states[chat_id]

    # respond according to `state`

This will do for a simple program.

For more complicated situations, I recommend using telepot, a Python framework I have created for Telegram Bot API. It has features that specifically solve this kind of problems.

For example, below is a bot that counts how many messages have been sent by an individual user. If no message is received after 10 seconds, it starts over (timeout). The counting is done per chat - that's the important point.

import sys
import telepot
from telepot.delegate import per_chat_id, create_open

class MessageCounter(telepot.helper.ChatHandler):
    def __init__(self, seed_tuple, timeout):
        super(MessageCounter, self).__init__(seed_tuple, timeout)
        self._count = 0

    def on_message(self, msg):
        self._count += 1
        self.sender.sendMessage(self._count)

TOKEN = sys.argv[1]  # get token from command-line

bot = telepot.DelegatorBot(TOKEN, [
    (per_chat_id(), create_open(MessageCounter, timeout=10)),
])
bot.notifyOnMessage(run_forever=True)

Run the program by:

python messagecounter.py <token>

Go to the project page to learn more if you are interested. There are a lot of documentations and non-trivial examples.

In my bots I use webhooking. If you can to use web hooks - do it, it's more comfortable way to interactive with telegram bots.

If you can't webhooking (ssl problems, for example), there is workaround for you. Use ForceReply in order to get previous bot answer and write logic based on user replies.

Check if update contains reply (reply_to_message key), then make bot answer based on this reply. These actions must be asynchronous in order to get high bot performance.

If you are python programmer, I recommend Tornado for these purposes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!