From ed9c6b948dcafb068e2d0c0440e4d720841cc27a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20Sch=C3=BCrrle?= Date: Fri, 13 Oct 2017 23:47:48 +0200 Subject: [PATCH 01/12] Update Examples with the str.format() syntax. conversationbot.py: Use `str.format()` conversationbot2.py: Use `str.format()` make the states dict flake8 compatible. echobot.py: Change Docstring to a Docstring using triple quotes. Add Docstrings to `main()` and `echo()` echobot2.py: Add File Description to Docstring Add License notice to Docstring Add Docstrings to `start()`, `help()`, `echo()` and `main()` inlinebot.py: Use `str.format()` Add File Description to Docstring Add License notice to Docstring Add Docstring to `start()`, `help()`, `inlinequery()`, `error()` Create the list "results" with the Inline Results instead of appending them. inlinekeyboard.py: Use `str.format()` Put the Update in a `main()` function. paymentbot.py: Use `str.format()` Shorten comment on how to get a provider token to avoid the comment being longer than 99 characters timerbot.py: Use `str.format()` Add Docstrings to `alarm()`, `set_timer()`, `unset()` Rename `set()` to `set_timer()` to avoud shadowing the built-in `set()` --- AUTHORS.rst | 1 + examples/conversationbot.py | 18 +++++----- examples/conversationbot2.py | 66 ++++++++++++++++++------------------ examples/echobot.py | 12 ++++--- examples/echobot2.py | 15 +++++--- examples/inlinebot.py | 47 ++++++++++++------------- examples/inlinekeyboard.py | 31 ++++++++++------- examples/paymentbot.py | 9 ++--- examples/timerbot.py | 14 ++++---- 9 files changed, 116 insertions(+), 97 deletions(-) diff --git a/AUTHORS.rst b/AUTHORS.rst index 56a701896c0..9f0f86d667b 100644 --- a/AUTHORS.rst +++ b/AUTHORS.rst @@ -55,6 +55,7 @@ The following wonderful people contributed directly or indirectly to this projec - `Rahiel Kasim `_ - `Sascha `_ - `Shelomentsev D `_ +- `Simon Schürrle `_ - `sooyhwang `_ - `thodnev `_ - `Valentijn `_ diff --git a/examples/conversationbot.py b/examples/conversationbot.py index 6dcff8643dc..4f8615f14a5 100644 --- a/examples/conversationbot.py +++ b/examples/conversationbot.py @@ -46,7 +46,7 @@ def start(bot, update): def gender(bot, update): user = update.message.from_user - logger.info("Gender of %s: %s" % (user.first_name, update.message.text)) + logger.info("Gender of {}: {}".format(user.first_name, update.message.text)) update.message.reply_text('I see! Please send me a photo of yourself, ' 'so I know what you look like, or send /skip if you don\'t want to.', reply_markup=ReplyKeyboardRemove()) @@ -58,7 +58,7 @@ def photo(bot, update): user = update.message.from_user photo_file = bot.get_file(update.message.photo[-1].file_id) photo_file.download('user_photo.jpg') - logger.info("Photo of %s: %s" % (user.first_name, 'user_photo.jpg')) + logger.info("Photo of {}: {}".format(user.first_name, 'user_photo.jpg')) update.message.reply_text('Gorgeous! Now, send me your location please, ' 'or send /skip if you don\'t want to.') @@ -67,7 +67,7 @@ def photo(bot, update): def skip_photo(bot, update): user = update.message.from_user - logger.info("User %s did not send a photo." % user.first_name) + logger.info("User {} did not send a photo.".format(user.first_name)) update.message.reply_text('I bet you look great! Now, send me your location please, ' 'or send /skip.') @@ -77,8 +77,8 @@ def skip_photo(bot, update): def location(bot, update): user = update.message.from_user user_location = update.message.location - logger.info("Location of %s: %f / %f" - % (user.first_name, user_location.latitude, user_location.longitude)) + logger.info("Location of {}: {} / {}".format( + user.first_name, user_location.latitude, user_location.longitude)) update.message.reply_text('Maybe I can visit you sometime! ' 'At last, tell me something about yourself.') @@ -87,7 +87,7 @@ def location(bot, update): def skip_location(bot, update): user = update.message.from_user - logger.info("User %s did not send a location." % user.first_name) + logger.info("User {} did not send a location.".format(user.first_name)) update.message.reply_text('You seem a bit paranoid! ' 'At last, tell me something about yourself.') @@ -96,7 +96,7 @@ def skip_location(bot, update): def bio(bot, update): user = update.message.from_user - logger.info("Bio of %s: %s" % (user.first_name, update.message.text)) + logger.info("Bio of {}: {}".format(user.first_name, update.message.text)) update.message.reply_text('Thank you! I hope we can talk again some day.') return ConversationHandler.END @@ -104,7 +104,7 @@ def bio(bot, update): def cancel(bot, update): user = update.message.from_user - logger.info("User %s canceled the conversation." % user.first_name) + logger.info("User {} canceled the conversation.".format(user.first_name)) update.message.reply_text('Bye! I hope we can talk again some day.', reply_markup=ReplyKeyboardRemove()) @@ -112,7 +112,7 @@ def cancel(bot, update): def error(bot, update, error): - logger.warn('Update "%s" caused error "%s"' % (update, error)) + logger.warn('Update "{}" caused error "{}"',format(update, error)) def main(): diff --git a/examples/conversationbot2.py b/examples/conversationbot2.py index 452f50fbe90..0c1efae50d6 100644 --- a/examples/conversationbot2.py +++ b/examples/conversationbot2.py @@ -41,16 +41,16 @@ def facts_to_str(user_data): facts = list() for key, value in user_data.items(): - facts.append('%s - %s' % (key, value)) + facts.append('{} - {}'.format(key, value)) return "\n".join(facts).join(['\n', '\n']) def start(bot, update): update.message.reply_text( - "Hi! My name is Doctor Botter. I will hold a more complex conversation with you. " - "Why don't you tell me something about yourself?", - reply_markup=markup) + "Hi! My name is Doctor Botter. I will hold a more complex conversation with you. " + "Why don't you tell me something about yourself?", + reply_markup=markup) return CHOOSING @@ -58,7 +58,8 @@ def start(bot, update): def regular_choice(bot, update, user_data): text = update.message.text user_data['choice'] = text - update.message.reply_text('Your %s? Yes, I would love to hear about that!' % text.lower()) + update.message.reply_text( + 'Your {}? Yes, I would love to hear about that!'.format(text.lower())) return TYPING_REPLY @@ -77,10 +78,9 @@ def received_information(bot, update, user_data): del user_data['choice'] update.message.reply_text("Neat! Just so you know, this is what you already told me:" - "%s" - "You can tell me more, or change your opinion on something." - % facts_to_str(user_data), - reply_markup=markup) + "{}" + "You can tell me more, or change your opinion on something.".format( + facts_to_str(user_data)), reply_markup=markup) return CHOOSING @@ -90,15 +90,15 @@ def done(bot, update, user_data): del user_data['choice'] update.message.reply_text("I learned these facts about you:" - "%s" - "Until next time!" % facts_to_str(user_data)) + "{}" + "Until next time!".format(facts_to_str(user_data))) user_data.clear() return ConversationHandler.END def error(bot, update, error): - logger.warn('Update "%s" caused error "%s"' % (update, error)) + logger.warn('Update "{}" caused error "{}"'.format(update, error)) def main(): @@ -110,29 +110,29 @@ def main(): # Add conversation handler with the states GENDER, PHOTO, LOCATION and BIO conv_handler = ConversationHandler( - entry_points=[CommandHandler('start', start)], - - states={ - CHOOSING: [RegexHandler('^(Age|Favourite colour|Number of siblings)$', - regular_choice, - pass_user_data=True), - RegexHandler('^Something else...$', - custom_choice), - ], - - TYPING_CHOICE: [MessageHandler(Filters.text, - regular_choice, - pass_user_data=True), - ], - - TYPING_REPLY: [MessageHandler(Filters.text, - received_information, - pass_user_data=True), + entry_points=[CommandHandler('start', start)], + + states={ + CHOOSING: [RegexHandler('^(Age|Favourite colour|Number of siblings)$', + regular_choice, + pass_user_data=True), + RegexHandler('^Something else...$', + custom_choice), ], - }, - fallbacks=[RegexHandler('^Done$', done, pass_user_data=True)] - ) + TYPING_CHOICE: [MessageHandler(Filters.text, + regular_choice, + pass_user_data=True), + ], + + TYPING_REPLY: [MessageHandler(Filters.text, + received_information, + pass_user_data=True), + ], + }, + + fallbacks=[RegexHandler('^Done$', done, pass_user_data=True)] + ) dp.add_handler(conv_handler) diff --git a/examples/echobot.py b/examples/echobot.py index b7e6e0a4afd..84d7182a5bb 100644 --- a/examples/echobot.py +++ b/examples/echobot.py @@ -1,9 +1,10 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -# -# Simple Bot to reply to Telegram messages. This is built on the API wrapper, see -# echobot2.py to see the same example built on the telegram.ext bot framework. -# This program is dedicated to the public domain under the CC0 license. +"""Simple Bot to reply to Telegram messages. +This is built on the API wrapper, see echobot2.py to see the same example built +on the telegram.ext bot framework. +This program is dedicated to the public domain under the CC0 license. +""" import logging import telegram from telegram.error import NetworkError, Unauthorized @@ -12,7 +13,9 @@ update_id = None + def main(): + """Run the bot.""" global update_id # Telegram Bot Authorization Token bot = telegram.Bot('TOKEN') @@ -37,6 +40,7 @@ def main(): def echo(bot): + """Echo the message the user sent.""" global update_id # Request updates after the last update_id for update in bot.get_updates(offset=update_id, timeout=10): diff --git a/examples/echobot2.py b/examples/echobot2.py index 4a8652cf491..f9eb5d54f22 100644 --- a/examples/echobot2.py +++ b/examples/echobot2.py @@ -1,9 +1,9 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -# -# Simple Bot to reply to Telegram messages -# This program is dedicated to the public domain under the CC0 license. -""" + +"""Simple Bot to reply to Telegram messages. +This program is dedicated to the public domain under the CC0 license. + This Bot uses the Updater class to handle the bot. First, a few handler functions are defined. Then, those functions are passed to @@ -29,22 +29,27 @@ # Define a few command handlers. These usually take the two arguments bot and # update. Error handlers also receive the raised TelegramError object in error. def start(bot, update): + """Send a message when the command /start is issued.""" update.message.reply_text('Hi!') def help(bot, update): + """Send a message when the command /help is issued.""" update.message.reply_text('Help!') def echo(bot, update): + """Echo the user message.""" update.message.reply_text(update.message.text) def error(bot, update, error): - logger.warn('Update "%s" caused error "%s"' % (update, error)) + """Log any Errors.""" + logger.warn('Update "{}" caused error "{}"'.format(update, error)) def main(): + """Start the bot.""" # Create the EventHandler and pass it your bot's token. updater = Updater("TOKEN") diff --git a/examples/inlinebot.py b/examples/inlinebot.py index 457ef5bc1ac..9dbffacb7cf 100644 --- a/examples/inlinebot.py +++ b/examples/inlinebot.py @@ -1,9 +1,9 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -# -# Simple Bot to reply to Telegram messages -# This program is dedicated to the public domain under the CC0 license. -""" + +"""Simple Bot to reply to Telegram messages. +This program is dedicated to the public domain under the CC0 license. + This Bot uses the Updater class to handle the bot. First, a few handler functions are defined. Then, those functions are passed to @@ -34,10 +34,12 @@ # Define a few command handlers. These usually take the two arguments bot and # update. Error handlers also receive the raised TelegramError object in error. def start(bot, update): + """Send a message when the command /start is issued.""" update.message.reply_text('Hi!') def help(bot, update): + """Send a message when the command /help is issued.""" update.message.reply_text('Help!') @@ -48,31 +50,30 @@ def escape_markdown(text): def inlinequery(bot, update): + """Handle the inline query.""" query = update.inline_query.query - results = list() - - results.append(InlineQueryResultArticle(id=uuid4(), - title="Caps", - input_message_content=InputTextMessageContent( - query.upper()))) - - results.append(InlineQueryResultArticle(id=uuid4(), - title="Bold", - input_message_content=InputTextMessageContent( - "*%s*" % escape_markdown(query), - parse_mode=ParseMode.MARKDOWN))) - - results.append(InlineQueryResultArticle(id=uuid4(), - title="Italic", - input_message_content=InputTextMessageContent( - "_%s_" % escape_markdown(query), - parse_mode=ParseMode.MARKDOWN))) + results = [ + InlineQueryResultArticle(id=uuid4(), + title="Caps", + input_message_content=InputTextMessageContent( + query.upper())), + InlineQueryResultArticle(id=uuid4(), + title="Bold", + input_message_content=InputTextMessageContent( + "*{}*".format(escape_markdown(query)), + parse_mode=ParseMode.MARKDOWN)), + InlineQueryResultArticle(id=uuid4(), + title="Italic", + input_message_content=InputTextMessageContent( + "_{}_".format(escape_markdown(query)), + parse_mode=ParseMode.MARKDOWN))] update.inline_query.answer(results) def error(bot, update, error): - logger.warning('Update "%s" caused error "%s"' % (update, error)) + """Log any Errors.""" + logger.warning('Update "{}" caused error "{}"'.format(update, error)) def main(): diff --git a/examples/inlinekeyboard.py b/examples/inlinekeyboard.py index 4966702b0cc..c484943c1a8 100644 --- a/examples/inlinekeyboard.py +++ b/examples/inlinekeyboard.py @@ -26,7 +26,7 @@ def start(bot, update): def button(bot, update): query = update.callback_query - bot.edit_message_text(text="Selected option: %s" % query.data, + bot.edit_message_text(text="Selected option: {}".format(query.data), chat_id=query.message.chat_id, message_id=query.message.message_id) @@ -36,20 +36,25 @@ def help(bot, update): def error(bot, update, error): - logging.warning('Update "%s" caused error "%s"' % (update, error)) + logging.warning('Update "{}" caused error "{}"'.format(update, error)) -# Create the Updater and pass it your bot's token. -updater = Updater("TOKEN") +def main(): + # Create the Updater and pass it your bot's token. + updater = Updater("TOKEN") -updater.dispatcher.add_handler(CommandHandler('start', start)) -updater.dispatcher.add_handler(CallbackQueryHandler(button)) -updater.dispatcher.add_handler(CommandHandler('help', help)) -updater.dispatcher.add_error_handler(error) + updater.dispatcher.add_handler(CommandHandler('start', start)) + updater.dispatcher.add_handler(CallbackQueryHandler(button)) + updater.dispatcher.add_handler(CommandHandler('help', help)) + updater.dispatcher.add_error_handler(error) -# Start the Bot -updater.start_polling() + # Start the Bot + updater.start_polling() -# Run the bot until the user presses Ctrl-C or the process receives SIGINT, -# SIGTERM or SIGABRT -updater.idle() + # Run the bot until the user presses Ctrl-C or the process receives SIGINT, + # SIGTERM or SIGABRT + updater.idle() + + +if __name__ == '__main__': + main() diff --git a/examples/paymentbot.py b/examples/paymentbot.py index 7a0e1341972..720b44430f1 100644 --- a/examples/paymentbot.py +++ b/examples/paymentbot.py @@ -10,13 +10,14 @@ import logging # Enable logging -logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) +logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + level=logging.INFO) logger = logging.getLogger(__name__) def error(bot, update, error): - logger.warn('Update "%s" caused error "%s"' % (update, error)) + logger.warn('Update "{}" caused error "{}"'.format(update, error)) def start_callback(bot, update): @@ -31,7 +32,7 @@ def start_with_shipping_callback(bot, update): description = "Payment Example using python-telegram-bot" # select a payload just for you to recognize its the donation from your bot payload = "Custom-Payload" - # get your provider_token at @botfather, see https://core.telegram.org/bots/payments#getting-a-token + # to get your provider_token see https://core.telegram.org/bots/payments#getting-a-token provider_token = "PROVIDER_TOKEN" start_parameter = "test-payment" currency = "USD" @@ -55,7 +56,7 @@ def start_without_shipping_callback(bot, update): description = "Payment Example using python-telegram-bot" # select a payload just for you to recognize its the donation from your bot payload = "Custom-Payload" - # get your provider_token at @botfather, see https://core.telegram.org/bots/payments#getting-a-token + # check https://core.telegram.org/bots/payments#supported-currencies for more details provider_token = "PROVIDER_TOKEN" start_parameter = "test-payment" currency = "USD" diff --git a/examples/timerbot.py b/examples/timerbot.py index 2a7d7cbe250..16cdb231eb2 100644 --- a/examples/timerbot.py +++ b/examples/timerbot.py @@ -34,12 +34,12 @@ def start(bot, update): def alarm(bot, job): - """Function to send the alarm message""" + """Send the alarm message.""" bot.send_message(job.context, text='Beep!') -def set(bot, update, args, job_queue, chat_data): - """Adds a job to the queue""" +def set_timer(bot, update, args, job_queue, chat_data): + """Add a job to the queue.""" chat_id = update.message.chat_id try: # args[0] should contain the time for the timer in seconds @@ -59,7 +59,7 @@ def set(bot, update, args, job_queue, chat_data): def unset(bot, update, chat_data): - """Removes the job if the user changed their mind""" + """Remove the job if the user changed their mind.""" if 'job' not in chat_data: update.message.reply_text('You have no active timer') @@ -73,10 +73,12 @@ def unset(bot, update, chat_data): def error(bot, update, error): - logger.warning('Update "%s" caused error "%s"' % (update, error)) + """Log errors.""" + logger.warning('Update "{}" caused error "{}"'.format(update, error)) def main(): + """Run bot.""" updater = Updater("TOKEN") # Get the dispatcher to register handlers @@ -85,7 +87,7 @@ def main(): # on different commands - answer in Telegram dp.add_handler(CommandHandler("start", start)) dp.add_handler(CommandHandler("help", start)) - dp.add_handler(CommandHandler("set", set, + dp.add_handler(CommandHandler("set", set_timer, pass_args=True, pass_job_queue=True, pass_chat_data=True)) From a261943d936cc2e38bbe3664dd10915f26f8516d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20Sch=C3=BCrrle?= Date: Sat, 14 Oct 2017 03:13:28 +0200 Subject: [PATCH 02/12] Use the "proper" way to format logging strings. Thanks to @KamranMackey for making me aware of the fact that Log messages shouldnt use str.format() according to this article: http://reinout.vanrees.org/weblog/2015/06/05/logging-formatting.html --- examples/conversationbot.py | 3 ++- examples/conversationbot2.py | 3 ++- examples/echobot2.py | 4 ++-- examples/inlinebot.py | 3 +-- examples/inlinekeyboard.py | 3 ++- examples/paymentbot.py | 3 ++- examples/timerbot.py | 3 +-- 7 files changed, 12 insertions(+), 10 deletions(-) diff --git a/examples/conversationbot.py b/examples/conversationbot.py index 4f8615f14a5..a1558530773 100644 --- a/examples/conversationbot.py +++ b/examples/conversationbot.py @@ -112,7 +112,8 @@ def cancel(bot, update): def error(bot, update, error): - logger.warn('Update "{}" caused error "{}"',format(update, error)) + logger.warn('Update "%s" caused error "%s"', update, error) + def main(): diff --git a/examples/conversationbot2.py b/examples/conversationbot2.py index 0c1efae50d6..89c561a8bb8 100644 --- a/examples/conversationbot2.py +++ b/examples/conversationbot2.py @@ -98,7 +98,8 @@ def done(bot, update, user_data): def error(bot, update, error): - logger.warn('Update "{}" caused error "{}"'.format(update, error)) + logger.warn('Update "%s" caused error "%s"', update, error) + def main(): diff --git a/examples/echobot2.py b/examples/echobot2.py index f9eb5d54f22..53d9a461def 100644 --- a/examples/echobot2.py +++ b/examples/echobot2.py @@ -44,8 +44,8 @@ def echo(bot, update): def error(bot, update, error): - """Log any Errors.""" - logger.warn('Update "{}" caused error "{}"'.format(update, error)) + logger.warn('Update "%s" caused error "%s"', update, error) + def main(): diff --git a/examples/inlinebot.py b/examples/inlinebot.py index 9dbffacb7cf..922fd5600ba 100644 --- a/examples/inlinebot.py +++ b/examples/inlinebot.py @@ -72,8 +72,7 @@ def inlinequery(bot, update): def error(bot, update, error): - """Log any Errors.""" - logger.warning('Update "{}" caused error "{}"'.format(update, error)) + logger.warn('Update "%s" caused error "%s"', update, error) def main(): diff --git a/examples/inlinekeyboard.py b/examples/inlinekeyboard.py index c484943c1a8..c3ca2660366 100644 --- a/examples/inlinekeyboard.py +++ b/examples/inlinekeyboard.py @@ -36,7 +36,8 @@ def help(bot, update): def error(bot, update, error): - logging.warning('Update "{}" caused error "{}"'.format(update, error)) + logger.warn('Update "%s" caused error "%s"', update, error) + def main(): diff --git a/examples/paymentbot.py b/examples/paymentbot.py index 720b44430f1..fd44484b2b4 100644 --- a/examples/paymentbot.py +++ b/examples/paymentbot.py @@ -17,7 +17,8 @@ def error(bot, update, error): - logger.warn('Update "{}" caused error "{}"'.format(update, error)) + logger.warn('Update "%s" caused error "%s"', update, error) + def start_callback(bot, update): diff --git a/examples/timerbot.py b/examples/timerbot.py index 16cdb231eb2..848cad45866 100644 --- a/examples/timerbot.py +++ b/examples/timerbot.py @@ -73,8 +73,7 @@ def unset(bot, update, chat_data): def error(bot, update, error): - """Log errors.""" - logger.warning('Update "{}" caused error "{}"'.format(update, error)) + logger.warn('Update "%s" caused error "%s"', update, error) def main(): From 25bf8e3c126b255324dc8793a5b7ff76a65af24a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20Sch=C3=BCrrle?= Date: Sun, 15 Oct 2017 01:00:38 +0200 Subject: [PATCH 03/12] Update paymentbot.py with requested changes. --- examples/paymentbot.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/examples/paymentbot.py b/examples/paymentbot.py index fd44484b2b4..7f09500b4f5 100644 --- a/examples/paymentbot.py +++ b/examples/paymentbot.py @@ -20,7 +20,6 @@ def error(bot, update, error): logger.warn('Update "%s" caused error "%s"', update, error) - def start_callback(bot, update): msg = "Use /shipping to get an invoice for shipping-payment, " msg += "or /noshipping for an invoice without shipping." @@ -33,7 +32,8 @@ def start_with_shipping_callback(bot, update): description = "Payment Example using python-telegram-bot" # select a payload just for you to recognize its the donation from your bot payload = "Custom-Payload" - # to get your provider_token see https://core.telegram.org/bots/payments#getting-a-token + # In order to get a provider_token to get your provider_token see + # https://core.telegram.org/bots/payments#getting-a-token provider_token = "PROVIDER_TOKEN" start_parameter = "test-payment" currency = "USD" @@ -57,7 +57,8 @@ def start_without_shipping_callback(bot, update): description = "Payment Example using python-telegram-bot" # select a payload just for you to recognize its the donation from your bot payload = "Custom-Payload" - # check https://core.telegram.org/bots/payments#supported-currencies for more details + # In order to get a provider_token to get your provider_token see + # https://core.telegram.org/bots/payments#getting-a-token provider_token = "PROVIDER_TOKEN" start_parameter = "test-payment" currency = "USD" From 5745997aa039cbcddc2cb3695ddcf774468c3591 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20Sch=C3=BCrrle?= Date: Sun, 15 Oct 2017 01:01:37 +0200 Subject: [PATCH 04/12] Revert Indentation in conversationbot2.py Removed the Extra Indent in the start() function. --- examples/conversationbot2.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/conversationbot2.py b/examples/conversationbot2.py index 89c561a8bb8..faf2f12a295 100644 --- a/examples/conversationbot2.py +++ b/examples/conversationbot2.py @@ -48,9 +48,9 @@ def facts_to_str(user_data): def start(bot, update): update.message.reply_text( - "Hi! My name is Doctor Botter. I will hold a more complex conversation with you. " - "Why don't you tell me something about yourself?", - reply_markup=markup) + "Hi! My name is Doctor Botter. I will hold a more complex conversation with you. " + "Why don't you tell me something about yourself?", + reply_markup=markup) return CHOOSING From 1d48a8375f372d2803f37f21b49a7d81aee8e6a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20Sch=C3=BCrrle?= Date: Sun, 15 Oct 2017 01:08:02 +0200 Subject: [PATCH 05/12] Use the proper way to format loggin strings in conversationbot.py --- examples/conversationbot.py | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/examples/conversationbot.py b/examples/conversationbot.py index a1558530773..df2a1232028 100644 --- a/examples/conversationbot.py +++ b/examples/conversationbot.py @@ -46,7 +46,7 @@ def start(bot, update): def gender(bot, update): user = update.message.from_user - logger.info("Gender of {}: {}".format(user.first_name, update.message.text)) + logger.info("Gender of %s: %s", user.first_name, update.message.text) update.message.reply_text('I see! Please send me a photo of yourself, ' 'so I know what you look like, or send /skip if you don\'t want to.', reply_markup=ReplyKeyboardRemove()) @@ -58,7 +58,7 @@ def photo(bot, update): user = update.message.from_user photo_file = bot.get_file(update.message.photo[-1].file_id) photo_file.download('user_photo.jpg') - logger.info("Photo of {}: {}".format(user.first_name, 'user_photo.jpg')) + logger.info("Photo of %s: %s", user.first_name, 'user_photo.jpg') update.message.reply_text('Gorgeous! Now, send me your location please, ' 'or send /skip if you don\'t want to.') @@ -67,7 +67,7 @@ def photo(bot, update): def skip_photo(bot, update): user = update.message.from_user - logger.info("User {} did not send a photo.".format(user.first_name)) + logger.info("User %s did not send a photo.", user.first_name) update.message.reply_text('I bet you look great! Now, send me your location please, ' 'or send /skip.') @@ -77,8 +77,8 @@ def skip_photo(bot, update): def location(bot, update): user = update.message.from_user user_location = update.message.location - logger.info("Location of {}: {} / {}".format( - user.first_name, user_location.latitude, user_location.longitude)) + logger.info("Location of %s: %f / %f", user.first_name, user_location.latitude, + user_location.longitude) update.message.reply_text('Maybe I can visit you sometime! ' 'At last, tell me something about yourself.') @@ -87,7 +87,7 @@ def location(bot, update): def skip_location(bot, update): user = update.message.from_user - logger.info("User {} did not send a location.".format(user.first_name)) + logger.info("User %s did not send a location.", user.first_name) update.message.reply_text('You seem a bit paranoid! ' 'At last, tell me something about yourself.') @@ -96,7 +96,7 @@ def skip_location(bot, update): def bio(bot, update): user = update.message.from_user - logger.info("Bio of {}: {}".format(user.first_name, update.message.text)) + logger.info("Bio of %s: %s", user.first_name, update.message.text) update.message.reply_text('Thank you! I hope we can talk again some day.') return ConversationHandler.END @@ -104,7 +104,7 @@ def bio(bot, update): def cancel(bot, update): user = update.message.from_user - logger.info("User {} canceled the conversation.".format(user.first_name)) + logger.info("User %s canceled the conversation.", user.first_name) update.message.reply_text('Bye! I hope we can talk again some day.', reply_markup=ReplyKeyboardRemove()) @@ -115,7 +115,6 @@ def error(bot, update, error): logger.warn('Update "%s" caused error "%s"', update, error) - def main(): # Create the EventHandler and pass it your bot's token. updater = Updater("TOKEN") From a3c4059c0564213456c1e2e2a1eb78cdd410696a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20Sch=C3=BCrrle?= Date: Sun, 15 Oct 2017 03:08:56 +0200 Subject: [PATCH 06/12] Revert Indentation in conversationbot2.py --- examples/conversationbot2.py | 42 ++++++++++++++++++------------------ 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/examples/conversationbot2.py b/examples/conversationbot2.py index faf2f12a295..58f7ef71821 100644 --- a/examples/conversationbot2.py +++ b/examples/conversationbot2.py @@ -111,29 +111,29 @@ def main(): # Add conversation handler with the states GENDER, PHOTO, LOCATION and BIO conv_handler = ConversationHandler( - entry_points=[CommandHandler('start', start)], - - states={ - CHOOSING: [RegexHandler('^(Age|Favourite colour|Number of siblings)$', - regular_choice, - pass_user_data=True), - RegexHandler('^Something else...$', - custom_choice), + entry_points=[CommandHandler('start', start)], + + states={ + CHOOSING: [RegexHandler('^(Age|Favourite colour|Number of siblings)$', + regular_choice, + pass_user_data=True), + RegexHandler('^Something else...$', + custom_choice), + ], + + TYPING_CHOICE: [MessageHandler(Filters.text, + regular_choice, + pass_user_data=True), + ], + + TYPING_REPLY: [MessageHandler(Filters.text, + received_information, + pass_user_data=True), ], + }, - TYPING_CHOICE: [MessageHandler(Filters.text, - regular_choice, - pass_user_data=True), - ], - - TYPING_REPLY: [MessageHandler(Filters.text, - received_information, - pass_user_data=True), - ], - }, - - fallbacks=[RegexHandler('^Done$', done, pass_user_data=True)] - ) + fallbacks=[RegexHandler('^Done$', done, pass_user_data=True)] + ) dp.add_handler(conv_handler) From 49096edf90b5597e2c8a326c1e9a0e0d8fb9a00d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20Sch=C3=BCrrle?= Date: Sun, 15 Oct 2017 03:10:58 +0200 Subject: [PATCH 07/12] Change Indentation in inlinebot.py --- examples/inlinebot.py | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/examples/inlinebot.py b/examples/inlinebot.py index 922fd5600ba..f9fec138707 100644 --- a/examples/inlinebot.py +++ b/examples/inlinebot.py @@ -53,20 +53,20 @@ def inlinequery(bot, update): """Handle the inline query.""" query = update.inline_query.query results = [ - InlineQueryResultArticle(id=uuid4(), - title="Caps", - input_message_content=InputTextMessageContent( - query.upper())), - InlineQueryResultArticle(id=uuid4(), - title="Bold", - input_message_content=InputTextMessageContent( - "*{}*".format(escape_markdown(query)), - parse_mode=ParseMode.MARKDOWN)), - InlineQueryResultArticle(id=uuid4(), - title="Italic", - input_message_content=InputTextMessageContent( - "_{}_".format(escape_markdown(query)), - parse_mode=ParseMode.MARKDOWN))] + InlineQueryResultArticle(id=uuid4(), + title="Caps", + input_message_content=InputTextMessageContent( + query.upper())), + InlineQueryResultArticle(id=uuid4(), + title="Bold", + input_message_content=InputTextMessageContent( + "*{}*".format(escape_markdown(query)), + parse_mode=ParseMode.MARKDOWN)), + InlineQueryResultArticle(id=uuid4(), + title="Italic", + input_message_content=InputTextMessageContent( + "_{}_".format(escape_markdown(query)), + parse_mode=ParseMode.MARKDOWN))] update.inline_query.answer(results) From adff0257567a7aa109cdb0494054656c69de99d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20Sch=C3=BCrrle?= Date: Sun, 15 Oct 2017 22:54:46 +0200 Subject: [PATCH 08/12] autopep8 convobot2, fix payment bot derp Use autopep8 on the conversationbot2.py Fix the provide token comment (duplicated some words) --- examples/conversationbot2.py | 10 +++++----- examples/paymentbot.py | 3 +-- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/examples/conversationbot2.py b/examples/conversationbot2.py index 58f7ef71821..1597d23e389 100644 --- a/examples/conversationbot2.py +++ b/examples/conversationbot2.py @@ -59,7 +59,7 @@ def regular_choice(bot, update, user_data): text = update.message.text user_data['choice'] = text update.message.reply_text( - 'Your {}? Yes, I would love to hear about that!'.format(text.lower())) + 'Your {}? Yes, I would love to hear about that!'.format(text.lower())) return TYPING_REPLY @@ -80,7 +80,7 @@ def received_information(bot, update, user_data): update.message.reply_text("Neat! Just so you know, this is what you already told me:" "{}" "You can tell me more, or change your opinion on something.".format( - facts_to_str(user_data)), reply_markup=markup) + facts_to_str(user_data)), reply_markup=markup) return CHOOSING @@ -101,7 +101,6 @@ def error(bot, update, error): logger.warn('Update "%s" caused error "%s"', update, error) - def main(): # Create the Updater and pass it your bot's token. updater = Updater("TOKEN") @@ -130,10 +129,10 @@ def main(): received_information, pass_user_data=True), ], - }, + }, fallbacks=[RegexHandler('^Done$', done, pass_user_data=True)] - ) + ) dp.add_handler(conv_handler) @@ -151,3 +150,4 @@ def main(): if __name__ == '__main__': main() + diff --git a/examples/paymentbot.py b/examples/paymentbot.py index 7f09500b4f5..4ca84d4e15e 100644 --- a/examples/paymentbot.py +++ b/examples/paymentbot.py @@ -57,8 +57,7 @@ def start_without_shipping_callback(bot, update): description = "Payment Example using python-telegram-bot" # select a payload just for you to recognize its the donation from your bot payload = "Custom-Payload" - # In order to get a provider_token to get your provider_token see - # https://core.telegram.org/bots/payments#getting-a-token + # In order to get a provider_token see https://core.telegram.org/bots/payments#getting-a-token provider_token = "PROVIDER_TOKEN" start_parameter = "test-payment" currency = "USD" From 3efc6b96a64f97d177600dd5099e81dc2b25d7d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20Sch=C3=BCrrle?= Date: Sun, 15 Oct 2017 22:55:42 +0200 Subject: [PATCH 09/12] Fix both provider_token comments --- examples/paymentbot.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/examples/paymentbot.py b/examples/paymentbot.py index 4ca84d4e15e..14be76d20aa 100644 --- a/examples/paymentbot.py +++ b/examples/paymentbot.py @@ -32,8 +32,7 @@ def start_with_shipping_callback(bot, update): description = "Payment Example using python-telegram-bot" # select a payload just for you to recognize its the donation from your bot payload = "Custom-Payload" - # In order to get a provider_token to get your provider_token see - # https://core.telegram.org/bots/payments#getting-a-token + # In order to get a provider_token see https://core.telegram.org/bots/payments#getting-a-token provider_token = "PROVIDER_TOKEN" start_parameter = "test-payment" currency = "USD" From 9b6d857da79ce12f829888d1d357cf50b1d044c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20Sch=C3=BCrrle?= Date: Mon, 16 Oct 2017 08:05:00 +0200 Subject: [PATCH 10/12] Used Jannes(jh0ker) suggestion for the inlinequery.py --- examples/inlinebot.py | 31 +++++++++++++++++-------------- 1 file changed, 17 insertions(+), 14 deletions(-) diff --git a/examples/inlinebot.py b/examples/inlinebot.py index f9fec138707..d5687c09960 100644 --- a/examples/inlinebot.py +++ b/examples/inlinebot.py @@ -53,20 +53,23 @@ def inlinequery(bot, update): """Handle the inline query.""" query = update.inline_query.query results = [ - InlineQueryResultArticle(id=uuid4(), - title="Caps", - input_message_content=InputTextMessageContent( - query.upper())), - InlineQueryResultArticle(id=uuid4(), - title="Bold", - input_message_content=InputTextMessageContent( - "*{}*".format(escape_markdown(query)), - parse_mode=ParseMode.MARKDOWN)), - InlineQueryResultArticle(id=uuid4(), - title="Italic", - input_message_content=InputTextMessageContent( - "_{}_".format(escape_markdown(query)), - parse_mode=ParseMode.MARKDOWN))] + InlineQueryResultArticle( + id=uuid4(), + title="Caps", + input_message_content=InputTextMessageContent( + query.upper())), + InlineQueryResultArticle( + id=uuid4(), + title="Bold", + input_message_content=InputTextMessageContent( + "*{}*".format(escape_markdown(query)), + parse_mode=ParseMode.MARKDOWN)), + InlineQueryResultArticle( + id=uuid4(), + title="Italic", + input_message_content=InputTextMessageContent( + "_{}_".format(escape_markdown(query)), + parse_mode=ParseMode.MARKDOWN))] update.inline_query.answer(results) From c6d41336951acf8a5ed272b947051dc2bd96a6d2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20Sch=C3=BCrrle?= Date: Mon, 16 Oct 2017 13:48:34 +0200 Subject: [PATCH 11/12] Change logger.warn to logger.warning, Fix flake8 errors(except D103) --- examples/conversationbot.py | 3 ++- examples/conversationbot2.py | 4 ++-- examples/echobot.py | 1 + examples/echobot2.py | 5 +++-- examples/inlinebot.py | 6 ++++-- examples/inlinekeyboard.py | 11 ++++++----- examples/paymentbot.py | 9 ++++++--- examples/timerbot.py | 14 ++++++++------ 8 files changed, 32 insertions(+), 21 deletions(-) diff --git a/examples/conversationbot.py b/examples/conversationbot.py index df2a1232028..06412ca354f 100644 --- a/examples/conversationbot.py +++ b/examples/conversationbot.py @@ -112,7 +112,8 @@ def cancel(bot, update): def error(bot, update, error): - logger.warn('Update "%s" caused error "%s"', update, error) + """Log Errors caused by Updates.""" + logger.warning('Update "%s" caused error "%s"', update, error) def main(): diff --git a/examples/conversationbot2.py b/examples/conversationbot2.py index 1597d23e389..34002792a07 100644 --- a/examples/conversationbot2.py +++ b/examples/conversationbot2.py @@ -98,7 +98,8 @@ def done(bot, update, user_data): def error(bot, update, error): - logger.warn('Update "%s" caused error "%s"', update, error) + """Log Errors caused by Updates.""" + logger.warning('Update "%s" caused error "%s"', update, error) def main(): @@ -150,4 +151,3 @@ def main(): if __name__ == '__main__': main() - diff --git a/examples/echobot.py b/examples/echobot.py index 84d7182a5bb..9b72310beac 100644 --- a/examples/echobot.py +++ b/examples/echobot.py @@ -1,6 +1,7 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- """Simple Bot to reply to Telegram messages. + This is built on the API wrapper, see echobot2.py to see the same example built on the telegram.ext bot framework. This program is dedicated to the public domain under the CC0 license. diff --git a/examples/echobot2.py b/examples/echobot2.py index 53d9a461def..d6b102bcdfb 100644 --- a/examples/echobot2.py +++ b/examples/echobot2.py @@ -2,6 +2,7 @@ # -*- coding: utf-8 -*- """Simple Bot to reply to Telegram messages. + This program is dedicated to the public domain under the CC0 license. This Bot uses the Updater class to handle the bot. @@ -44,8 +45,8 @@ def echo(bot, update): def error(bot, update, error): - logger.warn('Update "%s" caused error "%s"', update, error) - + """Log Errors caused by Updates.""" + logger.warning('Update "%s" caused error "%s"', update, error) def main(): diff --git a/examples/inlinebot.py b/examples/inlinebot.py index d5687c09960..3a6735d8e01 100644 --- a/examples/inlinebot.py +++ b/examples/inlinebot.py @@ -2,6 +2,7 @@ # -*- coding: utf-8 -*- """Simple Bot to reply to Telegram messages. + This program is dedicated to the public domain under the CC0 license. This Bot uses the Updater class to handle the bot. @@ -44,7 +45,7 @@ def help(bot, update): def escape_markdown(text): - """Helper function to escape telegram markup symbols""" + """Escape telegram markup symbols.""" escape_chars = '\*_`\[' return re.sub(r'([%s])' % escape_chars, r'\\\1', text) @@ -75,7 +76,8 @@ def inlinequery(bot, update): def error(bot, update, error): - logger.warn('Update "%s" caused error "%s"', update, error) + """Log Errors caused by Updates.""" + logger.warning('Update "%s" caused error "%s"', update, error) def main(): diff --git a/examples/inlinekeyboard.py b/examples/inlinekeyboard.py index c3ca2660366..84c0966adc0 100644 --- a/examples/inlinekeyboard.py +++ b/examples/inlinekeyboard.py @@ -1,15 +1,16 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -# -# Basic example for a bot that uses inline keyboards. -# This program is dedicated to the public domain under the CC0 license. +"""Basic example for a bot that uses inline keyboards. +# This program is dedicated to the public domain under the CC0 license. +""" import logging from telegram import InlineKeyboardButton, InlineKeyboardMarkup from telegram.ext import Updater, CommandHandler, CallbackQueryHandler logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) +logger = logging.getLogger(__name__) def start(bot, update): @@ -36,8 +37,8 @@ def help(bot, update): def error(bot, update, error): - logger.warn('Update "%s" caused error "%s"', update, error) - + """Log Errors caused by Updates.""" + logger.warning('Update "%s" caused error "%s"', update, error) def main(): diff --git a/examples/paymentbot.py b/examples/paymentbot.py index 14be76d20aa..a419034de94 100644 --- a/examples/paymentbot.py +++ b/examples/paymentbot.py @@ -1,8 +1,10 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- # -# Basic example for a bot that can receive payment from user. -# This program is dedicated to the public domain under the CC0 license. +"""Basic example for a bot that can receive payment from user. + +This program is dedicated to the public domain under the CC0 license. +""" from telegram import (LabeledPrice, ShippingOption) from telegram.ext import (Updater, CommandHandler, MessageHandler, @@ -17,7 +19,8 @@ def error(bot, update, error): - logger.warn('Update "%s" caused error "%s"', update, error) + """Log Errors caused by Updates.""" + logger.warning('Update "%s" caused error "%s"', update, error) def start_callback(bot, update): diff --git a/examples/timerbot.py b/examples/timerbot.py index 848cad45866..1a1c7ff9447 100644 --- a/examples/timerbot.py +++ b/examples/timerbot.py @@ -1,9 +1,11 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -# -# Simple Bot to send timed Telegram messages + + +"""Simple Bot to send timed Telegram messages. + # This program is dedicated to the public domain under the CC0 license. -""" + This Bot uses the Updater class to handle the bot and the JobQueue to send timed messages. @@ -17,7 +19,7 @@ bot. """ -from telegram.ext import Updater, CommandHandler, Job +from telegram.ext import Updater, CommandHandler import logging # Enable logging @@ -60,7 +62,6 @@ def set_timer(bot, update, args, job_queue, chat_data): def unset(bot, update, chat_data): """Remove the job if the user changed their mind.""" - if 'job' not in chat_data: update.message.reply_text('You have no active timer') return @@ -73,7 +74,8 @@ def unset(bot, update, chat_data): def error(bot, update, error): - logger.warn('Update "%s" caused error "%s"', update, error) + """Log Errors caused by Updates.""" + logger.warning('Update "%s" caused error "%s"', update, error) def main(): From 7df6c0895fc62e836f3cfd5ab75a68801316eabe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20Sch=C3=BCrrle?= Date: Mon, 16 Oct 2017 16:33:30 +0200 Subject: [PATCH 12/12] replace custom escape_markdown function in inlinebot.py with the builtin --- examples/inlinebot.py | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/examples/inlinebot.py b/examples/inlinebot.py index 3a6735d8e01..4784cba7475 100644 --- a/examples/inlinebot.py +++ b/examples/inlinebot.py @@ -20,6 +20,8 @@ import re +from telegram.utils.helpers import escape_markdown + from telegram import InlineQueryResultArticle, ParseMode, \ InputTextMessageContent from telegram.ext import Updater, InlineQueryHandler, CommandHandler @@ -44,12 +46,6 @@ def help(bot, update): update.message.reply_text('Help!') -def escape_markdown(text): - """Escape telegram markup symbols.""" - escape_chars = '\*_`\[' - return re.sub(r'([%s])' % escape_chars, r'\\\1', text) - - def inlinequery(bot, update): """Handle the inline query.""" query = update.inline_query.query pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy