From 43f5aeaff359f0a6041ccb4164033bf0ba379810 Mon Sep 17 00:00:00 2001 From: Harshil <37377066+harshil21@users.noreply.github.com> Date: Sun, 28 Mar 2021 20:53:44 +0400 Subject: [PATCH] Improve Examples (#2441) * close issue, typo fixes, remove unnecessary condition, etc * use ForceReply in example * remove extra whitespace * address review, handle empty inline queries. * Cosmetics Co-authored-by: Hinrich Mahler --- examples/conversationbot2.py | 5 +- examples/deeplinking.py | 6 +- examples/echobot.py | 12 ++- examples/inlinebot.py | 6 +- examples/inlinekeyboard2.py | 5 +- examples/nestedconversationbot.py | 27 +++--- examples/passportbot.py | 133 +++++++++++++------------- examples/paymentbot.py | 7 +- examples/persistentconversationbot.py | 11 ++- examples/pollbot.py | 2 +- 10 files changed, 113 insertions(+), 101 deletions(-) diff --git a/examples/conversationbot2.py b/examples/conversationbot2.py index 0397b6499..98d45aef8 100644 --- a/examples/conversationbot2.py +++ b/examples/conversationbot2.py @@ -17,7 +17,7 @@ bot. import logging from typing import Dict -from telegram import ReplyKeyboardMarkup, Update +from telegram import ReplyKeyboardMarkup, Update, ReplyKeyboardRemove from telegram.ext import ( Updater, CommandHandler, @@ -102,7 +102,8 @@ def done(update: Update, context: CallbackContext) -> int: del user_data['choice'] update.message.reply_text( - f"I learned these facts about you: {facts_to_str(user_data)} Until next time!" + f"I learned these facts about you: {facts_to_str(user_data)}Until next time!", + reply_markup=ReplyKeyboardRemove(), ) user_data.clear() diff --git a/examples/deeplinking.py b/examples/deeplinking.py index 340b05122..7df2864b3 100644 --- a/examples/deeplinking.py +++ b/examples/deeplinking.py @@ -44,7 +44,7 @@ USING_ENTITIES = "using-entities-here" USING_KEYBOARD = "using-keyboard-here" SO_COOL = "so-cool" -# Callback data to pass in 3rd level deeplinking +# Callback data to pass in 3rd level deep-linking KEYBOARD_CALLBACKDATA = "keyboard-callback-data" @@ -62,7 +62,7 @@ def deep_linked_level_1(update: Update, context: CallbackContext) -> None: url = helpers.create_deep_linked_url(bot.username, SO_COOL) text = ( "Awesome, you just accessed hidden functionality! " - " Now let's get back to the private chat." + "Now let's get back to the private chat." ) keyboard = InlineKeyboardMarkup.from_button( InlineKeyboardButton(text="Continue here!", url=url) @@ -127,7 +127,7 @@ def main() -> None: CommandHandler("start", deep_linked_level_3, Filters.regex(USING_ENTITIES), pass_args=True) ) - # Possible with inline keyboard buttons aswell + # Possible with inline keyboard buttons as well dispatcher.add_handler( CommandHandler("start", deep_linked_level_4, Filters.regex(USING_KEYBOARD)) ) diff --git a/examples/echobot.py b/examples/echobot.py index ec4e7914a..d5a058ae4 100644 --- a/examples/echobot.py +++ b/examples/echobot.py @@ -17,7 +17,7 @@ bot. import logging -from telegram import Update +from telegram import Update, ForceReply from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext # Enable logging @@ -29,10 +29,14 @@ logger = logging.getLogger(__name__) # Define a few command handlers. These usually take the two arguments update and -# context. Error handlers also receive the raised TelegramError object in error. +# context. def start(update: Update, _: CallbackContext) -> None: """Send a message when the command /start is issued.""" - update.message.reply_text('Hi!') + user = update.effective_user + update.message.reply_markdown_v2( + f'Hi {user.mention_markdown_v2()}!', + reply_markup=ForceReply(selective=True), + ) def help_command(update: Update, _: CallbackContext) -> None: @@ -57,7 +61,7 @@ def main() -> None: dispatcher.add_handler(CommandHandler("start", start)) dispatcher.add_handler(CommandHandler("help", help_command)) - # on noncommand i.e message - echo the message on Telegram + # on non command i.e message - echo the message on Telegram dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, echo)) # Start the Bot diff --git a/examples/inlinebot.py b/examples/inlinebot.py index 9971eedd3..62e04f12e 100644 --- a/examples/inlinebot.py +++ b/examples/inlinebot.py @@ -42,6 +42,10 @@ def help_command(update: Update, _: CallbackContext) -> None: def inlinequery(update: Update, _: CallbackContext) -> None: """Handle the inline query.""" query = update.inline_query.query + + if query == "": + return + results = [ InlineQueryResultArticle( id=str(uuid4()), @@ -78,7 +82,7 @@ def main() -> None: dispatcher.add_handler(CommandHandler("start", start)) dispatcher.add_handler(CommandHandler("help", help_command)) - # on noncommand i.e message - echo the message on Telegram + # on non command i.e message - echo the message on Telegram dispatcher.add_handler(InlineQueryHandler(inlinequery)) # Start the Bot diff --git a/examples/inlinekeyboard2.py b/examples/inlinekeyboard2.py index 800f04c61..fa16c4073 100644 --- a/examples/inlinekeyboard2.py +++ b/examples/inlinekeyboard2.py @@ -139,7 +139,7 @@ def four(update: Update, _: CallbackContext) -> int: keyboard = [ [ InlineKeyboardButton("2", callback_data=str(TWO)), - InlineKeyboardButton("4", callback_data=str(FOUR)), + InlineKeyboardButton("3", callback_data=str(THREE)), ] ] reply_markup = InlineKeyboardMarkup(keyboard) @@ -188,8 +188,7 @@ def main() -> None: fallbacks=[CommandHandler('start', start)], ) - # Add ConversationHandler to dispatcher that will be used for handling - # updates + # Add ConversationHandler to dispatcher that will be used for handling updates dispatcher.add_handler(conv_handler) # Start the Bot diff --git a/examples/nestedconversationbot.py b/examples/nestedconversationbot.py index 6c7b88074..0ce9eee01 100644 --- a/examples/nestedconversationbot.py +++ b/examples/nestedconversationbot.py @@ -74,9 +74,10 @@ def _name_switcher(level: str) -> Tuple[str, str]: def start(update: Update, context: CallbackContext) -> str: """Select an action: Adding parent/child or show data.""" text = ( - 'You may add a familiy member, yourself show the gathered data or end the ' - 'conversation. To abort, simply type /stop.' + "You may choose to add a family member, yourself, show the gathered data, or end the " + "conversation. To abort, simply type /stop." ) + buttons = [ [ InlineKeyboardButton(text='Add family member', callback_data=str(ADDING_MEMBER)), @@ -89,13 +90,13 @@ def start(update: Update, context: CallbackContext) -> str: ] keyboard = InlineKeyboardMarkup(buttons) - # If we're starting over we don't need do send a new message + # If we're starting over we don't need to send a new message if context.user_data.get(START_OVER): update.callback_query.answer() update.callback_query.edit_message_text(text=text, reply_markup=keyboard) else: update.message.reply_text( - 'Hi, I\'m FamiliyBot and here to help you gather information' 'about your family.' + "Hi, I'm Family Bot and I'm here to help you gather information about your family." ) update.message.reply_text(text=text, reply_markup=keyboard) @@ -104,7 +105,7 @@ def start(update: Update, context: CallbackContext) -> str: def adding_self(update: Update, context: CallbackContext) -> str: - """Add information about youself.""" + """Add information about yourself.""" context.user_data[CURRENT_LEVEL] = SELF text = 'Okay, please tell me about yourself.' button = InlineKeyboardButton(text='Add info', callback_data=str(MALE)) @@ -137,9 +138,9 @@ def show_data(update: Update, context: CallbackContext) -> str: return text user_data = context.user_data - text = 'Yourself:' + prettyprint(user_data, SELF) - text += '\n\nParents:' + prettyprint(user_data, PARENTS) - text += '\n\nChildren:' + prettyprint(user_data, CHILDREN) + text = f"Yourself:{prettyprint(user_data, SELF)}" + text += f"\n\nParents:{prettyprint(user_data, PARENTS)}" + text += f"\n\nChildren:{prettyprint(user_data, CHILDREN)}" buttons = [[InlineKeyboardButton(text='Back', callback_data=str(END))]] keyboard = InlineKeyboardMarkup(buttons) @@ -201,8 +202,8 @@ def select_gender(update: Update, context: CallbackContext) -> str: buttons = [ [ - InlineKeyboardButton(text='Add ' + male, callback_data=str(MALE)), - InlineKeyboardButton(text='Add ' + female, callback_data=str(FEMALE)), + InlineKeyboardButton(text=f'Add {male}', callback_data=str(MALE)), + InlineKeyboardButton(text=f'Add {female}', callback_data=str(FEMALE)), ], [ InlineKeyboardButton(text='Show data', callback_data=str(SHOWING)), @@ -326,7 +327,7 @@ def main() -> None: map_to_parent={ # Return to second level menu END: SELECTING_LEVEL, - # End conversation alltogether + # End conversation altogether STOPPING: STOPPING, }, ) @@ -350,13 +351,13 @@ def main() -> None: SHOWING: SHOWING, # Return to top level menu END: SELECTING_ACTION, - # End conversation alltogether + # End conversation altogether STOPPING: END, }, ) # Set up top level ConversationHandler (selecting action) - # Because the states of the third level conversation map to the ones of the econd level + # Because the states of the third level conversation map to the ones of the second level # conversation, we need to make sure the top level conversation can also handle them selection_handlers = [ add_member_conv, diff --git a/examples/passportbot.py b/examples/passportbot.py index 195e1cdc4..4c57170a3 100644 --- a/examples/passportbot.py +++ b/examples/passportbot.py @@ -24,75 +24,74 @@ logger = logging.getLogger(__name__) def msg(update: Update, _: CallbackContext) -> None: - # If we received any passport data + # Retrieve passport data passport_data = update.message.passport_data - if passport_data: - # If our nonce doesn't match what we think, this Update did not originate from us - # Ideally you would randomize the nonce on the server - if passport_data.decrypted_credentials.nonce != 'thisisatest': - return + # If our nonce doesn't match what we think, this Update did not originate from us + # Ideally you would randomize the nonce on the server + if passport_data.decrypted_credentials.nonce != 'thisisatest': + return - # Print the decrypted credential data - # For all elements - # Print their decrypted data - # Files will be downloaded to current directory - for data in passport_data.decrypted_data: # This is where the data gets decrypted - if data.type == 'phone_number': - print('Phone: ', data.phone_number) - elif data.type == 'email': - print('Email: ', data.email) - if data.type in ( - 'personal_details', - 'passport', - 'driver_license', - 'identity_card', - 'internal_passport', - 'address', - ): - print(data.type, data.data) - if data.type in ( - 'utility_bill', - 'bank_statement', - 'rental_agreement', - 'passport_registration', - 'temporary_registration', - ): - print(data.type, len(data.files), 'files') - for file in data.files: - actual_file = file.get_file() - print(actual_file) - actual_file.download() - if data.type in ('passport', 'driver_license', 'identity_card', 'internal_passport'): - if data.front_side: - front_file = data.front_side.get_file() - print(data.type, front_file) - front_file.download() - if data.type in ('driver_license' and 'identity_card'): - if data.reverse_side: - reverse_file = data.reverse_side.get_file() - print(data.type, reverse_file) - reverse_file.download() - if data.type in ('passport', 'driver_license', 'identity_card', 'internal_passport'): - if data.selfie: - selfie_file = data.selfie.get_file() - print(data.type, selfie_file) - selfie_file.download() - if data.type in ( - 'passport', - 'driver_license', - 'identity_card', - 'internal_passport', - 'utility_bill', - 'bank_statement', - 'rental_agreement', - 'passport_registration', - 'temporary_registration', - ): - print(data.type, len(data.translation), 'translation') - for file in data.translation: - actual_file = file.get_file() - print(actual_file) - actual_file.download() + # Print the decrypted credential data + # For all elements + # Print their decrypted data + # Files will be downloaded to current directory + for data in passport_data.decrypted_data: # This is where the data gets decrypted + if data.type == 'phone_number': + print('Phone: ', data.phone_number) + elif data.type == 'email': + print('Email: ', data.email) + if data.type in ( + 'personal_details', + 'passport', + 'driver_license', + 'identity_card', + 'internal_passport', + 'address', + ): + print(data.type, data.data) + if data.type in ( + 'utility_bill', + 'bank_statement', + 'rental_agreement', + 'passport_registration', + 'temporary_registration', + ): + print(data.type, len(data.files), 'files') + for file in data.files: + actual_file = file.get_file() + print(actual_file) + actual_file.download() + if data.type in ('passport', 'driver_license', 'identity_card', 'internal_passport'): + if data.front_side: + front_file = data.front_side.get_file() + print(data.type, front_file) + front_file.download() + if data.type in ('driver_license' and 'identity_card'): + if data.reverse_side: + reverse_file = data.reverse_side.get_file() + print(data.type, reverse_file) + reverse_file.download() + if data.type in ('passport', 'driver_license', 'identity_card', 'internal_passport'): + if data.selfie: + selfie_file = data.selfie.get_file() + print(data.type, selfie_file) + selfie_file.download() + if data.type in ( + 'passport', + 'driver_license', + 'identity_card', + 'internal_passport', + 'utility_bill', + 'bank_statement', + 'rental_agreement', + 'passport_registration', + 'temporary_registration', + ): + print(data.type, len(data.translation), 'translation') + for file in data.translation: + actual_file = file.get_file() + print(actual_file) + actual_file.download() def main() -> None: diff --git a/examples/paymentbot.py b/examples/paymentbot.py index 34f93df93..6b38f2cfd 100644 --- a/examples/paymentbot.py +++ b/examples/paymentbot.py @@ -28,8 +28,11 @@ logger = logging.getLogger(__name__) def start_callback(update: Update, _: CallbackContext) -> None: - msg = "Use /shipping to get an invoice for shipping-payment, " - msg += "or /noshipping for an invoice without shipping." + msg = ( + "Use /shipping to get an invoice for shipping-payment, or /noshipping for an " + "invoice without shipping." + ) + update.message.reply_text(msg) diff --git a/examples/persistentconversationbot.py b/examples/persistentconversationbot.py index 686f737f0..3022a449f 100644 --- a/examples/persistentconversationbot.py +++ b/examples/persistentconversationbot.py @@ -17,7 +17,7 @@ bot. import logging from typing import Dict -from telegram import ReplyKeyboardMarkup, Update +from telegram import ReplyKeyboardMarkup, Update, ReplyKeyboardRemove from telegram.ext import ( Updater, CommandHandler, @@ -47,7 +47,7 @@ markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True) def facts_to_str(user_data: Dict[str, str]) -> str: - facts = list() + facts = [] for key, value in user_data.items(): facts.append(f'{key} - {value}') @@ -77,7 +77,7 @@ def regular_choice(update: Update, context: CallbackContext) -> int: context.user_data['choice'] = text if context.user_data.get(text): reply_text = ( - f'Your {text}, I already know the following about that: {context.user_data[text]}' + f'Your {text}? I already know the following about that: {context.user_data[text]}' ) else: reply_text = f'Your {text}? Yes, I would love to hear about that!' @@ -88,7 +88,7 @@ def regular_choice(update: Update, context: CallbackContext) -> int: def custom_choice(update: Update, _: CallbackContext) -> int: update.message.reply_text( - 'Alright, please send me the category first, ' 'for example "Most impressive skill"' + 'Alright, please send me the category first, for example "Most impressive skill"' ) return TYPING_CHOICE @@ -122,7 +122,8 @@ def done(update: Update, context: CallbackContext) -> int: del context.user_data['choice'] update.message.reply_text( - "I learned these facts about you:" f"{facts_to_str(context.user_data)} Until next time!" + "I learned these facts about you:" f"{facts_to_str(context.user_data)}Until next time!", + reply_markup=ReplyKeyboardRemove(), ) return ConversationHandler.END diff --git a/examples/pollbot.py b/examples/pollbot.py index 8e4a6d13d..e2ea0f112 100644 --- a/examples/pollbot.py +++ b/examples/pollbot.py @@ -4,7 +4,7 @@ """ Basic example for a bot that works with polls. Only 3 people are allowed to interact with each -poll/quiz the bot generates. The preview command generates a closed poll/quiz, excatly like the +poll/quiz the bot generates. The preview command generates a closed poll/quiz, exactly like the one the user sends the bot """ import logging