Python Telegram Bot 如何等待用户回答问题并返回

Esp*_*azi 5 python telegram python-telegram-bot telegram-bot

语境:

我正在使用PyTelegramBotAPiPython Telegram Bot

当用户开始对话时,我正在运行一个代码。

当用户开始对话时,我需要向他发送第一张图片和一个问题他是否看到图片中的东西,该函数需要等待用户输入并返回他是否看到它。

之后,我将需要继续循环发送图片并等待答案并对其运行二分算法。

到目前为止我尝试过的:

我尝试使用等待响应的回复标记或带有处理程序的内联键盘,但我被卡住了,因为我的代码正在运行而没有等待用户输入。

编码:

@bot.message_handler(func=lambda msg: msg in ['Yes', 'No'])
@bot.message_handler(commands=['start', 'help'])
def main(message):
    """
    This is my main function
    """
    chat_id = message.chat.id
    try:
        reply_answer = message.reply_to_message.text
    except AttributeError:
        reply_answer = '0'
    # TODO : should wait for the answer asynchnonossly
    def tester(n, reply_answer):
        """
        Displays the current candidate to the user and asks them to
        check if they see wildfire damages.
        """
        print('call......')
        bisector.index = n
        bot.send_photo(
            chat_id=chat_id,
            photo=bisector.image.save_image(),
            caption=f"Did you see it Yes or No {bisector.date}",
            reply_markup=types.ForceReply(selective=True))
        # I SHOUL WAIT FOR THE INPUT HERE AND RETURN THE USER INPUT
        return eval(reply_answer)
    culprit = bisect(bisector.count, lambda x: x, partial(tester, reply_answer=reply_answer) )
    bisector.index = culprit
    bot.send_message(chat_id, f"Found! First apparition = {bisector.date}")


bot.polling(none_stop=True)
Run Code Online (Sandbox Code Playgroud)

我在用户输入上运行的算法是这样的:

def bisect(n, mapper, tester):
    """
    Runs a bisection.

    - `n` is the number of elements to be bisected
    - `mapper` is a callable that will transform an integer from "0" to "n"
      into a value that can be tested
    - `tester` returns true if the value is within the "right" range
    """

    if n < 1:
        raise ValueError('Cannot bissect an empty array')

    left = 0
    right = n - 1

    while left + 1 < right:
        mid = int((left + right) / 2)

        val = mapper(mid)
        tester_values = tester(val) # Here is where I am using the ouput from Telegram bot
        if tester_values:
            right = mid
        else:
            left = mid

    return mapper(right)
Run Code Online (Sandbox Code Playgroud)

我希望我清楚地解释了这个问题,请随时提出任何澄清。如果您知道可以为我指明正确方向以解决此问题的内容,请告诉我。

我试过一个类似的问题,但我没有得到答案。

Ali*_*ida 9

您应该将用户信息保存在数据库中。基本字段是:

(id, first_name, last_name, username, menu)

什么是菜单?

菜单保持用户的当前状态。当用户向您的机器人发送消息时,您会检查数据库以了解用户的当前状态。

因此,如果用户不存在,您可以使用menuset to MainMenuor WelcomeMenuor 在您的情况下将它们添加到您的 users 表中PictureMenu

现在你将有一个更新函数的监听器,让我们假设每一个都是一个菜单。

@bot.message_handler(commands=['start', 'help'])

因此,当用户发送时,start您将检查函数内的用户菜单字段。

@bot.message_handler(commands=['start', 'help'])
def main(message):
    user = fetch_user_from_db(chat_id)
    if user.menu == "PictureMenu":
        if message.photo is Not None:
            photo = message.photo[0].file_id
            photo_file = download_photo_from_telegram(photo)
            do_other_things()
            user.menu = "Picture2Menu";
            user.save();
        else:
            send_message("Please send a photo")
    if user.menu == "Picture2Menu":
        if message.photo is Not None:
            photo = message.photo[0].file_id
            photo_file = download_photo_from_telegram(photo)
            do_other_things()
            user.menu = "Picture3Menu";
            user.save();
        else:
            send_message("Please send a photo")   
    ...
Run Code Online (Sandbox Code Playgroud)

我希望你明白了。