首页 > 解决方案 > 如何使用 python-telegram-bot 库从测验中识别用户答案

问题描述

我正在尝试编写 Python 代码,以便可以远程向物理学生应用问卷。他们将通过 Telegram 机器人接收和回复测验。我正在使用 python-telegram-bot 模块。我已经可以确定哪些用户回复了,但我还不能得到他们的答案。

我从这里的示例代码 pollbot.py 开始:https ://raw.githubusercontent.com/python-telegram-bot/python-telegram-bot/master/examples/pollbot.py

具体方法如下:

def quiz(update: Update, context: CallbackContext) -> None:
    """Send a predefined poll"""
    questions = ["1", "2", "4", "20"]
    message = update.effective_message.reply_poll(
        "How many eggs do you need for a cake?", questions, type=Poll.QUIZ, correct_option_id=2
    )
    # Save some info about the poll the bot_data for later use in receive_quiz_answer
    payload = {
        message.poll.id: {"chat_id": update.effective_chat.id, "message_id": message.message_id}
    }
    context.bot_data.update(payload)

def receive_quiz_answer(update: Update, context: CallbackContext) -> None:
    """Close quiz after three participants took it"""
    # the bot can receive closed poll updates we don't care about
    if update.poll.is_closed:
        return
    if update.poll.total_voter_count == 3:
        try:
            quiz_data = context.bot_data[update.poll.id]
        # this means this poll answer update is from an old poll, we can't stop it then
        except KeyError:
            return
        context.bot.stop_poll(quiz_data["chat_id"], quiz_data["message_id"])

电报应用程序会向用户显示他/她是否正确回答。我已经知道哪个用户回答了测验。我想以编程方式知道用户回答了哪些可能的测验选项。

我确实在测验方法中打印了消息,我发现了这个:

{'message_id': 93, 'date': 1614250320, 'chat': {'id': xxxxxxxx, 'type': 'private', 'first_name': 'user', 'last_name': 'name'}, '实体':[],'caption_entities':[],'照片':[],'new_chat_members':[],'new_chat_photo':[],'delete_chat_photo':假,'group_chat_created':假,'supergroup_chat_created': False, 'channel_chat_created': False, 'poll': {'id': '5024004102909067266', 'question': '一个蛋糕需要多少个鸡蛋?', 'options': [{'text': '1 ', 'voter_count': 0}, {'text': '2', 'voter_count': 0}, {'text': '4', 'voter_count': 0}, {'text': '20','voter_count': 0}], 'total_voter_count': 0, 'is_closed': False, 'is_anonymous': True, 'type': 'quiz', 'allows_multiple_answers': False, 'correct_option_id': 2, 'explanation_entities': [], 'close_date': 无}, 'from': {'id': 144******6, 'first_name': ' my_own','is_bot':真,'用户名':'_my_own_Bot'}}

似乎用户答案的​​信息在这里不存在。voter_count 也没有改变,无论我在聊天组点击多少答案,它都保持为零。我在方法 receive_quiz_answer 中添加了这些行:

 quiz_data = context.bot_data[update.poll.id]
 print(quiz_data)

我只得到了这个信息:

{'chat_id':15******53,'message_id':87}

这与我想要的无关。我相信答案应该在 telegram.PollAnswer 中,上面的代码中没有列出。

我添加了以下几行:

answer = update.poll_answer
print("answer is {}". format(answer))

在 receive_quiz_answer 方法中,但我得到了答复:

答案是无

任何帮助表示赞赏。非常感谢。

标签: telegrampython-telegram-bot

解决方案


推荐阅读