|
| 1 | +#!/usr/bin/env python |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | +# |
| 4 | +# Simple Bot to reply to Telegram messages |
| 5 | +# This program is dedicated to the public domain under the CC0 license. |
| 6 | +""" |
| 7 | +This Bot uses the Updater class to handle the bot. |
| 8 | +
|
| 9 | +First, a few callback functions are defined. Then, those functions are passed to |
| 10 | +the Dispatcher and registered at their respective places. |
| 11 | +Then, the bot is started and runs until we press Ctrl-C on the command line. |
| 12 | +
|
| 13 | +Usage: |
| 14 | +Example of a bot-user conversation using ConversationHandler. |
| 15 | +Send /start to initiate the conversation. |
| 16 | +Press Ctrl-C on the command line or send a signal to the process to stop the |
| 17 | +bot. |
| 18 | +""" |
| 19 | + |
| 20 | +from telegram import ReplyKeyboardMarkup |
| 21 | +from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters, RegexHandler, |
| 22 | + ConversationHandler, PicklePersistence) |
| 23 | + |
| 24 | +import logging |
| 25 | + |
| 26 | +# Enable logging |
| 27 | +logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', |
| 28 | + level=logging.INFO) |
| 29 | + |
| 30 | +logger = logging.getLogger(__name__) |
| 31 | + |
| 32 | +CHOOSING, TYPING_REPLY, TYPING_CHOICE = range(3) |
| 33 | + |
| 34 | +reply_keyboard = [['Age', 'Favourite colour'], |
| 35 | + ['Number of siblings', 'Something else...'], |
| 36 | + ['Done']] |
| 37 | +markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True) |
| 38 | + |
| 39 | + |
| 40 | +def facts_to_str(user_data): |
| 41 | + facts = list() |
| 42 | + |
| 43 | + for key, value in user_data.items(): |
| 44 | + facts.append('{} - {}'.format(key, value)) |
| 45 | + |
| 46 | + return "\n".join(facts).join(['\n', '\n']) |
| 47 | + |
| 48 | + |
| 49 | +def start(bot, update, user_data): |
| 50 | + reply_text = "Hi! My name is Doctor Botter." |
| 51 | + if user_data: |
| 52 | + reply_text += " You already told me your {}. Why don't you tell me something more " \ |
| 53 | + "about yourself? Or change enything I " \ |
| 54 | + "already know.".format(", ".join(user_data.keys())) |
| 55 | + else: |
| 56 | + reply_text += " I will hold a more complex conversation with you. Why don't you tell me " \ |
| 57 | + "something about yourself?" |
| 58 | + update.message.reply_text(reply_text, reply_markup=markup) |
| 59 | + |
| 60 | + return CHOOSING |
| 61 | + |
| 62 | + |
| 63 | +def regular_choice(bot, update, user_data): |
| 64 | + text = update.message.text |
| 65 | + user_data['choice'] = text |
| 66 | + if user_data.get(text): |
| 67 | + reply_text = 'Your {}, I already know the following ' \ |
| 68 | + 'about that: {}'.format(text.lower(), user_data[text.lower()]) |
| 69 | + else: |
| 70 | + reply_text = 'Your {}? Yes, I would love to hear about that!'.format(text.lower()) |
| 71 | + update.message.reply_text(reply_text) |
| 72 | + |
| 73 | + return TYPING_REPLY |
| 74 | + |
| 75 | + |
| 76 | +def custom_choice(bot, update): |
| 77 | + update.message.reply_text('Alright, please send me the category first, ' |
| 78 | + 'for example "Most impressive skill"') |
| 79 | + |
| 80 | + return TYPING_CHOICE |
| 81 | + |
| 82 | + |
| 83 | +def received_information(bot, update, user_data): |
| 84 | + text = update.message.text |
| 85 | + category = user_data['choice'] |
| 86 | + user_data[category] = text.lower() |
| 87 | + del user_data['choice'] |
| 88 | + |
| 89 | + update.message.reply_text("Neat! Just so you know, this is what you already told me:" |
| 90 | + "{}" |
| 91 | + "You can tell me more, or change your opinion on " |
| 92 | + "something.".format(facts_to_str(user_data)), reply_markup=markup) |
| 93 | + |
| 94 | + return CHOOSING |
| 95 | + |
| 96 | + |
| 97 | +def show_data(bot, update, user_data): |
| 98 | + update.message.reply_text("This is what you already told me:" |
| 99 | + "{}".format(facts_to_str(user_data))) |
| 100 | + |
| 101 | + |
| 102 | +def done(bot, update, user_data): |
| 103 | + if 'choice' in user_data: |
| 104 | + del user_data['choice'] |
| 105 | + |
| 106 | + update.message.reply_text("I learned these facts about you:" |
| 107 | + "{}" |
| 108 | + "Until next time!".format(facts_to_str(user_data))) |
| 109 | + return ConversationHandler.END |
| 110 | + |
| 111 | + |
| 112 | +def error(bot, update, error): |
| 113 | + """Log Errors caused by Updates.""" |
| 114 | + logger.warning('Update "%s" caused error "%s"', update, error) |
| 115 | + |
| 116 | + |
| 117 | +def main(): |
| 118 | + # Create the Updater and pass it your bot's token. |
| 119 | + pp = PicklePersistence(filename='conversationbot') |
| 120 | + updater = Updater("TOKEN", persistence=pp) |
| 121 | + |
| 122 | + # Get the dispatcher to register handlers |
| 123 | + dp = updater.dispatcher |
| 124 | + |
| 125 | + # Add conversation handler with the states CHOOSING, TYPING_CHOICE and TYPING_REPLY |
| 126 | + conv_handler = ConversationHandler( |
| 127 | + entry_points=[CommandHandler('start', start, pass_user_data=True)], |
| 128 | + |
| 129 | + states={ |
| 130 | + CHOOSING: [RegexHandler('^(Age|Favourite colour|Number of siblings)$', |
| 131 | + regular_choice, |
| 132 | + pass_user_data=True), |
| 133 | + RegexHandler('^Something else...$', |
| 134 | + custom_choice), |
| 135 | + ], |
| 136 | + |
| 137 | + TYPING_CHOICE: [MessageHandler(Filters.text, |
| 138 | + regular_choice, |
| 139 | + pass_user_data=True), |
| 140 | + ], |
| 141 | + |
| 142 | + TYPING_REPLY: [MessageHandler(Filters.text, |
| 143 | + received_information, |
| 144 | + pass_user_data=True), |
| 145 | + ], |
| 146 | + }, |
| 147 | + |
| 148 | + fallbacks=[RegexHandler('^Done$', done, pass_user_data=True)], |
| 149 | + name="my_conversation", |
| 150 | + persistent=True |
| 151 | + ) |
| 152 | + |
| 153 | + dp.add_handler(conv_handler) |
| 154 | + |
| 155 | + show_data_handler = CommandHandler('show_data', show_data, pass_user_data=True) |
| 156 | + dp.add_handler(show_data_handler) |
| 157 | + # log all errors |
| 158 | + dp.add_error_handler(error) |
| 159 | + |
| 160 | + # Start the Bot |
| 161 | + updater.start_polling() |
| 162 | + |
| 163 | + # Run the bot until you press Ctrl-C or the process receives SIGINT, |
| 164 | + # SIGTERM or SIGABRT. This should be used most of the time, since |
| 165 | + # start_polling() is non-blocking and will stop the bot gracefully. |
| 166 | + updater.idle() |
| 167 | + |
| 168 | + |
| 169 | +if __name__ == '__main__': |
| 170 | + main() |
0 commit comments