|
| 1 | +#!/usr/bin/env python |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | +# This program is dedicated to the public domain under the CC0 license. |
| 4 | + |
| 5 | +""" |
| 6 | +Basic example for a bot that works with polls. Only 3 people are allowed to interact with each |
| 7 | +poll/quiz the bot generates. The preview command generates a closed poll/quiz, excatly like the |
| 8 | +one the user sends the bot |
| 9 | +""" |
| 10 | +import logging |
| 11 | + |
| 12 | +from telegram import (Poll, ParseMode, KeyboardButton, KeyboardButtonPollType, |
| 13 | + ReplyKeyboardMarkup, ReplyKeyboardRemove) |
| 14 | +from telegram.ext import (Updater, CommandHandler, PollAnswerHandler, PollHandler, MessageHandler, |
| 15 | + Filters) |
| 16 | +from telegram.utils.helpers import mention_html |
| 17 | + |
| 18 | +logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', |
| 19 | + level=logging.INFO) |
| 20 | +logger = logging.getLogger(__name__) |
| 21 | + |
| 22 | + |
| 23 | +def start(update, context): |
| 24 | + """Inform user about what this bot can do""" |
| 25 | + update.message.reply_text('Please select /poll to get a Poll, /quiz to get a Quiz or /preview' |
| 26 | + ' to generate a preview for your poll') |
| 27 | + |
| 28 | + |
| 29 | +def poll(update, context): |
| 30 | + """Sends a predefined poll""" |
| 31 | + questions = ["Good", "Really good", "Fantastic", "Great"] |
| 32 | + message = context.bot.send_poll(update.effective_user.id, "How are you?", questions, |
| 33 | + is_anonymous=False, allows_multiple_answers=True) |
| 34 | + # Save some info about the poll the bot_data for later use in receive_poll_answer |
| 35 | + payload = {message.poll.id: {"questions": questions, "message_id": message.message_id, |
| 36 | + "chat_id": update.effective_chat.id, "answers": 0}} |
| 37 | + context.bot_data.update(payload) |
| 38 | + |
| 39 | + |
| 40 | +def receive_poll_answer(update, context): |
| 41 | + """Summarize a users poll vote""" |
| 42 | + answer = update.poll_answer |
| 43 | + poll_id = answer.poll_id |
| 44 | + try: |
| 45 | + questions = context.bot_data[poll_id]["questions"] |
| 46 | + # this means this poll answer update is from an old poll, we can't do our answering then |
| 47 | + except KeyError: |
| 48 | + return |
| 49 | + selected_options = answer.option_ids |
| 50 | + answer_string = "" |
| 51 | + for question_id in selected_options: |
| 52 | + if question_id != selected_options[-1]: |
| 53 | + answer_string += questions[question_id] + " and " |
| 54 | + else: |
| 55 | + answer_string += questions[question_id] |
| 56 | + user_mention = mention_html(update.effective_user.id, update.effective_user.full_name) |
| 57 | + context.bot.send_message(context.bot_data[poll_id]["chat_id"], |
| 58 | + "{} feels {}!".format(user_mention, answer_string), |
| 59 | + parse_mode=ParseMode.HTML) |
| 60 | + context.bot_data[poll_id]["answers"] += 1 |
| 61 | + # Close poll after three participants voted |
| 62 | + if context.bot_data[poll_id]["answers"] == 3: |
| 63 | + context.bot.stop_poll(context.bot_data[poll_id]["chat_id"], |
| 64 | + context.bot_data[poll_id]["message_id"]) |
| 65 | + |
| 66 | + |
| 67 | +def quiz(update, context): |
| 68 | + """Send a predefined poll""" |
| 69 | + questions = ["1", "2", "4", "20"] |
| 70 | + message = update.effective_message.reply_poll("How many eggs do you need for a cake?", |
| 71 | + questions, type=Poll.QUIZ, correct_option_id=2) |
| 72 | + # Save some info about the poll the bot_data for later use in receive_quiz_answer |
| 73 | + payload = {message.poll.id: {"chat_id": update.effective_chat.id, |
| 74 | + "message_id": message.message_id}} |
| 75 | + context.bot_data.update(payload) |
| 76 | + |
| 77 | + |
| 78 | +def receive_quiz_answer(update, context): |
| 79 | + """Close quiz after three participants took it""" |
| 80 | + # the bot can receive closed poll updates we don't care about |
| 81 | + if update.poll.is_closed: |
| 82 | + return |
| 83 | + if update.poll.total_voter_count == 3: |
| 84 | + try: |
| 85 | + quiz_data = context.bot_data[update.poll.id] |
| 86 | + # this means this poll answer update is from an old poll, we can't stop it then |
| 87 | + except KeyError: |
| 88 | + return |
| 89 | + context.bot.stop_poll(quiz_data["chat_id"], quiz_data["message_id"]) |
| 90 | + |
| 91 | + |
| 92 | +def preview(update, context): |
| 93 | + """Ask user to create a poll and display a preview of it""" |
| 94 | + # using this without a type lets the user chooses what he wants (quiz or poll) |
| 95 | + button = [[KeyboardButton("Press me!", request_poll=KeyboardButtonPollType())]] |
| 96 | + message = "Press the button to let the bot generate a preview for your poll" |
| 97 | + # using one_time_keyboard to hide the keyboard |
| 98 | + update.effective_message.reply_text(message, |
| 99 | + reply_markup=ReplyKeyboardMarkup(button, |
| 100 | + one_time_keyboard=True)) |
| 101 | + |
| 102 | + |
| 103 | +def receive_poll(update, context): |
| 104 | + """On receiving polls, reply to it by a closed poll copying the received poll""" |
| 105 | + actual_poll = update.effective_message.poll |
| 106 | + # Only need to set the question and options, since all other parameters don't matter for |
| 107 | + # a closed poll |
| 108 | + update.effective_message.reply_poll( |
| 109 | + question=actual_poll.question, |
| 110 | + options=[o.text for o in actual_poll.options], |
| 111 | + # with is_closed true, the poll/quiz is immediately closed |
| 112 | + is_closed=True, |
| 113 | + reply_markup=ReplyKeyboardRemove() |
| 114 | + ) |
| 115 | + |
| 116 | + |
| 117 | +def help_handler(update, context): |
| 118 | + """Display a help message""" |
| 119 | + update.message.reply_text("Use /quiz, /poll or /preview to test this " |
| 120 | + "bot.") |
| 121 | + |
| 122 | + |
| 123 | +def main(): |
| 124 | + # Create the Updater and pass it your bot's token. |
| 125 | + # Make sure to set use_context=True to use the new context based callbacks |
| 126 | + # Post version 12 this will no longer be necessary |
| 127 | + updater = Updater("TOKEN", use_context=True) |
| 128 | + dp = updater.dispatcher |
| 129 | + dp.add_handler(CommandHandler('start', start)) |
| 130 | + dp.add_handler(CommandHandler('poll', poll)) |
| 131 | + dp.add_handler(PollAnswerHandler(receive_poll_answer)) |
| 132 | + dp.add_handler(CommandHandler('quiz', quiz)) |
| 133 | + dp.add_handler(PollHandler(receive_quiz_answer)) |
| 134 | + dp.add_handler(CommandHandler('preview', preview)) |
| 135 | + dp.add_handler(MessageHandler(Filters.poll, receive_poll)) |
| 136 | + dp.add_handler(CommandHandler('help', help_handler)) |
| 137 | + |
| 138 | + # Start the Bot |
| 139 | + updater.start_polling() |
| 140 | + |
| 141 | + # Run the bot until the user presses Ctrl-C or the process receives SIGINT, |
| 142 | + # SIGTERM or SIGABRT |
| 143 | + updater.idle() |
| 144 | + |
| 145 | + |
| 146 | +if __name__ == '__main__': |
| 147 | + main() |
0 commit comments