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
51async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
52 """Inform user about what this bot can do"""
53 await update.message.reply_text(
54 "Please select /poll to get a Poll, /quiz to get a Quiz or /preview"
55 " to generate a preview for your poll"
56 )
57
58
59async def poll(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
60 """Sends a predefined poll"""
61 questions = ["Good", "Really good", "Fantastic", "Great"]
62 message = await context.bot.send_poll(
63 update.effective_chat.id,
64 "How are you?",
65 questions,
66 is_anonymous=False,
67 allows_multiple_answers=True,
68 )
69 # Save some info about the poll the bot_data for later use in receive_poll_answer
70 payload = {
71 message.poll.id: {
72 "questions": questions,
73 "message_id": message.message_id,
74 "chat_id": update.effective_chat.id,
75 "answers": 0,
76 }
77 }
78 context.bot_data.update(payload)
79
80
81async def receive_poll_answer(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
82 """Summarize a users poll vote"""
83 answer = update.poll_answer
84 answered_poll = context.bot_data[answer.poll_id]
85 try:
86 questions = answered_poll["questions"]
87 # this means this poll answer update is from an old poll, we can't do our answering then
88 except KeyError:
89 return
90 selected_options = answer.option_ids
91 answer_string = ""
92 for question_id in selected_options:
93 if question_id != selected_options[-1]:
94 answer_string += questions[question_id] + " and "
95 else:
96 answer_string += questions[question_id]
97 await context.bot.send_message(
98 answered_poll["chat_id"],
99 f"{update.effective_user.mention_html()} feels {answer_string}!",
100 parse_mode=ParseMode.HTML,
101 )
102 answered_poll["answers"] += 1
103 # Close poll after three participants voted
104 if answered_poll["answers"] == 3:
105 await context.bot.stop_poll(answered_poll["chat_id"], answered_poll["message_id"])
106
107
108async def quiz(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
109 """Send a predefined poll"""
110 questions = ["1", "2", "4", "20"]
111 message = await update.effective_message.reply_poll(
112 "How many eggs do you need for a cake?", questions, type=Poll.QUIZ, correct_option_id=2
113 )
114 # Save some info about the poll the bot_data for later use in receive_quiz_answer
115 payload = {
116 message.poll.id: {"chat_id": update.effective_chat.id, "message_id": message.message_id}
117 }
118 context.bot_data.update(payload)
119
120
121async def receive_quiz_answer(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
122 """Close quiz after three participants took it"""
123 # the bot can receive closed poll updates we don't care about
124 if update.poll.is_closed:
125 return
126 if update.poll.total_voter_count == 3:
127 try:
128 quiz_data = context.bot_data[update.poll.id]
129 # this means this poll answer update is from an old poll, we can't stop it then
130 except KeyError:
131 return
132 await context.bot.stop_poll(quiz_data["chat_id"], quiz_data["message_id"])
133
134
135async def preview(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
136 """Ask user to create a poll and display a preview of it"""
137 # using this without a type lets the user chooses what he wants (quiz or poll)
138 button = [[KeyboardButton("Press me!", request_poll=KeyboardButtonPollType())]]
139 message = "Press the button to let the bot generate a preview for your poll"
140 # using one_time_keyboard to hide the keyboard
141 await update.effective_message.reply_text(
142 message, reply_markup=ReplyKeyboardMarkup(button, one_time_keyboard=True)
143 )
144
145
146async def receive_poll(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
147 """On receiving polls, reply to it by a closed poll copying the received poll"""
148 actual_poll = update.effective_message.poll
149 # Only need to set the question and options, since all other parameters don't matter for
150 # a closed poll
151 await update.effective_message.reply_poll(
152 question=actual_poll.question,
153 options=[o.text for o in actual_poll.options],
154 # with is_closed true, the poll/quiz is immediately closed
155 is_closed=True,
156 reply_markup=ReplyKeyboardRemove(),
157 )
158
159
160async def help_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
161 """Display a help message"""
162 await update.message.reply_text("Use /quiz, /poll or /preview to test this bot.")
163
164
165def main() -> None:
166 """Run bot."""
167 # Create the Application and pass it your bot's token.
168 application = Application.builder().token("TOKEN").build()
169 application.add_handler(CommandHandler("start", start))
170 application.add_handler(CommandHandler("poll", poll))
171 application.add_handler(CommandHandler("quiz", quiz))
172 application.add_handler(CommandHandler("preview", preview))
173 application.add_handler(CommandHandler("help", help_handler))
174 application.add_handler(MessageHandler(filters.POLL, receive_poll))
175 application.add_handler(PollAnswerHandler(receive_poll_answer))
176 application.add_handler(PollHandler(receive_quiz_answer))
177
178 # Run the bot until the user presses Ctrl-C
179 application.run_polling()
180
181
182if __name__ == "__main__":
183 main()