Search code examples
pythonbotstelegram-botpython-telegram-bot

Deleting a poll python-telegram-bot


I'm working on a telegram bot using python-telegram-bot library in python I want my bot to send a quiz to the user Here is the code:

 question = dict_api.get_question()
    word = question['word']
    answer = question['answer']
    options = question['options']
    q = f"What is the translation of the word '{word}'"
    context.bot.send_poll(chat_id=person_id, question=q, options=options, type=Poll.QUIZ, correct_option_id=answer)

and i have PollHandler to take care of the response, when the user had responded i want the bot to delete the quiz for the user, how can i do that?

i've tried to delete it by

context.bot.delete_message(message_id=update.poll.id, chat_id=chat_id)

as someone would delete a message, but it didn't work and i assume because polls are treated differently by telegram. Thanks in advance


Solution

  • The message_id parameter of bot.delete_message needs the message id, not the poll id. Note that poll updates don't contain a message_id, because polls can e.g. be forwarded, so they can have multiple message_ids even in chats where your bot isn't even a member.

    However if you only want to delete the original message, you can e.g. store a mapping poll id -> (chat_id, message_id) in e.g. context.bot_data and then use chat_id, message_id = context.bot_data[update.poll.id] to get the stored values back to delete the message. Note that context.user/chat_data can't work for this here, because poll updates are not associated with a specific user/chat and hence context.user/chat_data will be None in PollHandler callbacks.

    Instead of storing (chat_id, message_id), you could also just store the Message object that bot.send_poll returns - then you only have to call context.bot_data[update.poll.id].delete().

    Referencos:


    Disclaimer: I'm currently the maintainer of python-telegram-bot.