Search code examples
pythontelegram-bot

A telegram bot should send a "quiz" how to do it?


@bot.callback_query_handler(func=lambda call: True)
def callback_handler(call):
    if call.data == 'start':
        question = "Which city is the capital of France?"
        options = ["Paris", "Berlin", "Madrid", "London"]
        bot.send_poll(call.message.chat.id, question, options)

So far, there is such a code. But right now, any answer is the right one. How do I make sure that there is only one correct answer?

It should be borne in mind that I need a "quiz". That is, InlineButtons should not be used.


Solution

  • To create a poll where only one option is correct, you can use the send_poll method with the is_anonymous=False and type='quiz' parameters, along with the correct_option_id parameter to specify which option is correct. Since "Paris" is the correct answer and the first option in your options list (with an index of 0), you would set correct_option_id=0. This ensures that your poll is recognized as a quiz, and only the option you designate as correct will be treated as such.

    Here is how you can modify your code to include these changes:

    @bot.callback_query_handler(func=lambda call: True)
    def callback_handler(call):
        if call.data == 'start':
            question = "Which city is the capital of France?"
            options = ["Paris", "Berlin", "Madrid", "London"]
            # Setting correct_option_id to 0 since "Paris" is the first option and the correct answer.
            # Note: The is_anonymous parameter is optional for quizzes, as quizzes are not anonymous by default.
            bot.send_poll(
                chat_id=call.message.chat.id,
                question=question,
                options=options,
                is_anonymous=False,
                type='quiz',
                correct_option_id=0
            )
    

    In this modified code snippet:

    • is_anonymous=False ensures that the poll is not anonymous. This is optional for quizzes since quiz polls are not anonymous by default.
    • type='quiz' specifies that the poll is a quiz type, which allows for specifying correct answers and automatically calculates scores for each participant.
    • correct_option_id=0 indicates that the first option ("Paris") is the correct one. The correct_option_id is based on the index of the correct answer in the options list, starting from 0. By making these adjustments, you'll ensure that your poll behaves as a quiz, with only "Paris" recognized as the correct answer to the question about the capital of France.