pollbot.pyΒΆ

  1#!/usr/bin/env python
  2# pylint: disable=unused-argument, wrong-import-position
  3# This program is dedicated to the public domain under the CC0 license.
  4
  5"""
  6Basic example for a bot that works with polls. Only 3 people are allowed to interact with each
  7poll/quiz the bot generates. The preview command generates a closed poll/quiz, exactly like the
  8one the user sends the bot
  9"""
 10import logging
 11
 12from telegram import __version__ as TG_VER
 13
 14try:
 15    from telegram import __version_info__
 16except ImportError:
 17    __version_info__ = (0, 0, 0, 0, 0)  # type: ignore[assignment]
 18
 19if __version_info__ < (20, 0, 0, "alpha", 1):
 20    raise RuntimeError(
 21        f"This example is not compatible with your current PTB version {TG_VER}. To view the "
 22        f"{TG_VER} version of this example, "
 23        f"visit https://docs.python-telegram-bot.org/en/v{TG_VER}/examples.html"
 24    )
 25from telegram import (
 26    KeyboardButton,
 27    KeyboardButtonPollType,
 28    Poll,
 29    ReplyKeyboardMarkup,
 30    ReplyKeyboardRemove,
 31    Update,
 32)
 33from telegram.constants import ParseMode
 34from telegram.ext import (
 35    Application,
 36    CommandHandler,
 37    ContextTypes,
 38    MessageHandler,
 39    PollAnswerHandler,
 40    PollHandler,
 41    filters,
 42)
 43
 44# Enable logging
 45logging.basicConfig(
 46    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
 47)
 48logger = logging.getLogger(__name__)
 49
 50
 51TOTAL_VOTER_COUNT = 3
 52
 53
 54async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
 55    """Inform user about what this bot can do"""
 56    await update.message.reply_text(
 57        "Please select /poll to get a Poll, /quiz to get a Quiz or /preview"
 58        " to generate a preview for your poll"
 59    )
 60
 61
 62async def poll(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
 63    """Sends a predefined poll"""
 64    questions = ["Good", "Really good", "Fantastic", "Great"]
 65    message = await context.bot.send_poll(
 66        update.effective_chat.id,
 67        "How are you?",
 68        questions,
 69        is_anonymous=False,
 70        allows_multiple_answers=True,
 71    )
 72    # Save some info about the poll the bot_data for later use in receive_poll_answer
 73    payload = {
 74        message.poll.id: {
 75            "questions": questions,
 76            "message_id": message.message_id,
 77            "chat_id": update.effective_chat.id,
 78            "answers": 0,
 79        }
 80    }
 81    context.bot_data.update(payload)
 82
 83
 84async def receive_poll_answer(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
 85    """Summarize a users poll vote"""
 86    answer = update.poll_answer
 87    answered_poll = context.bot_data[answer.poll_id]
 88    try:
 89        questions = answered_poll["questions"]
 90    # this means this poll answer update is from an old poll, we can't do our answering then
 91    except KeyError:
 92        return
 93    selected_options = answer.option_ids
 94    answer_string = ""
 95    for question_id in selected_options:
 96        if question_id != selected_options[-1]:
 97            answer_string += questions[question_id] + " and "
 98        else:
 99            answer_string += questions[question_id]
100    await context.bot.send_message(
101        answered_poll["chat_id"],
102        f"{update.effective_user.mention_html()} feels {answer_string}!",
103        parse_mode=ParseMode.HTML,
104    )
105    answered_poll["answers"] += 1
106    # Close poll after three participants voted
107    if answered_poll["answers"] == TOTAL_VOTER_COUNT:
108        await context.bot.stop_poll(answered_poll["chat_id"], answered_poll["message_id"])
109
110
111async def quiz(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
112    """Send a predefined poll"""
113    questions = ["1", "2", "4", "20"]
114    message = await update.effective_message.reply_poll(
115        "How many eggs do you need for a cake?", questions, type=Poll.QUIZ, correct_option_id=2
116    )
117    # Save some info about the poll the bot_data for later use in receive_quiz_answer
118    payload = {
119        message.poll.id: {"chat_id": update.effective_chat.id, "message_id": message.message_id}
120    }
121    context.bot_data.update(payload)
122
123
124async def receive_quiz_answer(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
125    """Close quiz after three participants took it"""
126    # the bot can receive closed poll updates we don't care about
127    if update.poll.is_closed:
128        return
129    if update.poll.total_voter_count == TOTAL_VOTER_COUNT:
130        try:
131            quiz_data = context.bot_data[update.poll.id]
132        # this means this poll answer update is from an old poll, we can't stop it then
133        except KeyError:
134            return
135        await context.bot.stop_poll(quiz_data["chat_id"], quiz_data["message_id"])
136
137
138async def preview(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
139    """Ask user to create a poll and display a preview of it"""
140    # using this without a type lets the user chooses what he wants (quiz or poll)
141    button = [[KeyboardButton("Press me!", request_poll=KeyboardButtonPollType())]]
142    message = "Press the button to let the bot generate a preview for your poll"
143    # using one_time_keyboard to hide the keyboard
144    await update.effective_message.reply_text(
145        message, reply_markup=ReplyKeyboardMarkup(button, one_time_keyboard=True)
146    )
147
148
149async def receive_poll(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
150    """On receiving polls, reply to it by a closed poll copying the received poll"""
151    actual_poll = update.effective_message.poll
152    # Only need to set the question and options, since all other parameters don't matter for
153    # a closed poll
154    await update.effective_message.reply_poll(
155        question=actual_poll.question,
156        options=[o.text for o in actual_poll.options],
157        # with is_closed true, the poll/quiz is immediately closed
158        is_closed=True,
159        reply_markup=ReplyKeyboardRemove(),
160    )
161
162
163async def help_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
164    """Display a help message"""
165    await update.message.reply_text("Use /quiz, /poll or /preview to test this bot.")
166
167
168def main() -> None:
169    """Run bot."""
170    # Create the Application and pass it your bot's token.
171    application = Application.builder().token("TOKEN").build()
172    application.add_handler(CommandHandler("start", start))
173    application.add_handler(CommandHandler("poll", poll))
174    application.add_handler(CommandHandler("quiz", quiz))
175    application.add_handler(CommandHandler("preview", preview))
176    application.add_handler(CommandHandler("help", help_handler))
177    application.add_handler(MessageHandler(filters.POLL, receive_poll))
178    application.add_handler(PollAnswerHandler(receive_poll_answer))
179    application.add_handler(PollHandler(receive_quiz_answer))
180
181    # Run the bot until the user presses Ctrl-C
182    application.run_polling()
183
184
185if __name__ == "__main__":
186    main()