Skip to content

Commit 38637ec

Browse files
Simon Schürrletsnoam
authored andcommitted
Update examples with consistent string formatting (python-telegram-bot#870)
* Use the modern string.format(). * Wherever logging is involved, let logging take care of the expansion.
1 parent bb5357a commit 38637ec

File tree

9 files changed

+118
-89
lines changed

9 files changed

+118
-89
lines changed

AUTHORS.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ The following wonderful people contributed directly or indirectly to this projec
5555
- `Rahiel Kasim <https://github.com/rahiel>`_
5656
- `Sascha <https://github.com/saschalalala>`_
5757
- `Shelomentsev D <https://github.com/shelomentsevd>`_
58+
- `Simon Schürrle <https://github.com/SitiSchu>`_
5859
- `sooyhwang <https://github.com/sooyhwang>`_
5960
- `thodnev <https://github.com/thodnev>`_
6061
- `Valentijn <https://github.com/Faalentijn>`_

examples/conversationbot.py

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ def start(bot, update):
4646

4747
def gender(bot, update):
4848
user = update.message.from_user
49-
logger.info("Gender of %s: %s" % (user.first_name, update.message.text))
49+
logger.info("Gender of %s: %s", user.first_name, update.message.text)
5050
update.message.reply_text('I see! Please send me a photo of yourself, '
5151
'so I know what you look like, or send /skip if you don\'t want to.',
5252
reply_markup=ReplyKeyboardRemove())
@@ -58,7 +58,7 @@ def photo(bot, update):
5858
user = update.message.from_user
5959
photo_file = bot.get_file(update.message.photo[-1].file_id)
6060
photo_file.download('user_photo.jpg')
61-
logger.info("Photo of %s: %s" % (user.first_name, 'user_photo.jpg'))
61+
logger.info("Photo of %s: %s", user.first_name, 'user_photo.jpg')
6262
update.message.reply_text('Gorgeous! Now, send me your location please, '
6363
'or send /skip if you don\'t want to.')
6464

@@ -67,7 +67,7 @@ def photo(bot, update):
6767

6868
def skip_photo(bot, update):
6969
user = update.message.from_user
70-
logger.info("User %s did not send a photo." % user.first_name)
70+
logger.info("User %s did not send a photo.", user.first_name)
7171
update.message.reply_text('I bet you look great! Now, send me your location please, '
7272
'or send /skip.')
7373

@@ -77,8 +77,8 @@ def skip_photo(bot, update):
7777
def location(bot, update):
7878
user = update.message.from_user
7979
user_location = update.message.location
80-
logger.info("Location of %s: %f / %f"
81-
% (user.first_name, user_location.latitude, user_location.longitude))
80+
logger.info("Location of %s: %f / %f", user.first_name, user_location.latitude,
81+
user_location.longitude)
8282
update.message.reply_text('Maybe I can visit you sometime! '
8383
'At last, tell me something about yourself.')
8484

@@ -87,7 +87,7 @@ def location(bot, update):
8787

8888
def skip_location(bot, update):
8989
user = update.message.from_user
90-
logger.info("User %s did not send a location." % user.first_name)
90+
logger.info("User %s did not send a location.", user.first_name)
9191
update.message.reply_text('You seem a bit paranoid! '
9292
'At last, tell me something about yourself.')
9393

@@ -96,23 +96,24 @@ def skip_location(bot, update):
9696

9797
def bio(bot, update):
9898
user = update.message.from_user
99-
logger.info("Bio of %s: %s" % (user.first_name, update.message.text))
99+
logger.info("Bio of %s: %s", user.first_name, update.message.text)
100100
update.message.reply_text('Thank you! I hope we can talk again some day.')
101101

102102
return ConversationHandler.END
103103

104104

105105
def cancel(bot, update):
106106
user = update.message.from_user
107-
logger.info("User %s canceled the conversation." % user.first_name)
107+
logger.info("User %s canceled the conversation.", user.first_name)
108108
update.message.reply_text('Bye! I hope we can talk again some day.',
109109
reply_markup=ReplyKeyboardRemove())
110110

111111
return ConversationHandler.END
112112

113113

114114
def error(bot, update, error):
115-
logger.warn('Update "%s" caused error "%s"' % (update, error))
115+
"""Log Errors caused by Updates."""
116+
logger.warning('Update "%s" caused error "%s"', update, error)
116117

117118

118119
def main():

examples/conversationbot2.py

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ def facts_to_str(user_data):
4141
facts = list()
4242

4343
for key, value in user_data.items():
44-
facts.append('%s - %s' % (key, value))
44+
facts.append('{} - {}'.format(key, value))
4545

4646
return "\n".join(facts).join(['\n', '\n'])
4747

@@ -58,7 +58,8 @@ def start(bot, update):
5858
def regular_choice(bot, update, user_data):
5959
text = update.message.text
6060
user_data['choice'] = text
61-
update.message.reply_text('Your %s? Yes, I would love to hear about that!' % text.lower())
61+
update.message.reply_text(
62+
'Your {}? Yes, I would love to hear about that!'.format(text.lower()))
6263

6364
return TYPING_REPLY
6465

@@ -77,10 +78,9 @@ def received_information(bot, update, user_data):
7778
del user_data['choice']
7879

7980
update.message.reply_text("Neat! Just so you know, this is what you already told me:"
80-
"%s"
81-
"You can tell me more, or change your opinion on something."
82-
% facts_to_str(user_data),
83-
reply_markup=markup)
81+
"{}"
82+
"You can tell me more, or change your opinion on something.".format(
83+
facts_to_str(user_data)), reply_markup=markup)
8484

8585
return CHOOSING
8686

@@ -90,15 +90,16 @@ def done(bot, update, user_data):
9090
del user_data['choice']
9191

9292
update.message.reply_text("I learned these facts about you:"
93-
"%s"
94-
"Until next time!" % facts_to_str(user_data))
93+
"{}"
94+
"Until next time!".format(facts_to_str(user_data)))
9595

9696
user_data.clear()
9797
return ConversationHandler.END
9898

9999

100100
def error(bot, update, error):
101-
logger.warn('Update "%s" caused error "%s"' % (update, error))
101+
"""Log Errors caused by Updates."""
102+
logger.warning('Update "%s" caused error "%s"', update, error)
102103

103104

104105
def main():

examples/echobot.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
#!/usr/bin/env python
22
# -*- coding: utf-8 -*-
3-
#
4-
# Simple Bot to reply to Telegram messages. This is built on the API wrapper, see
5-
# echobot2.py to see the same example built on the telegram.ext bot framework.
6-
# This program is dedicated to the public domain under the CC0 license.
3+
"""Simple Bot to reply to Telegram messages.
4+
5+
This is built on the API wrapper, see echobot2.py to see the same example built
6+
on the telegram.ext bot framework.
7+
This program is dedicated to the public domain under the CC0 license.
8+
"""
79
import logging
810
import telegram
911
from telegram.error import NetworkError, Unauthorized
@@ -12,7 +14,9 @@
1214

1315
update_id = None
1416

17+
1518
def main():
19+
"""Run the bot."""
1620
global update_id
1721
# Telegram Bot Authorization Token
1822
bot = telegram.Bot('TOKEN')
@@ -37,6 +41,7 @@ def main():
3741

3842

3943
def echo(bot):
44+
"""Echo the message the user sent."""
4045
global update_id
4146
# Request updates after the last update_id
4247
for update in bot.get_updates(offset=update_id, timeout=10):

examples/echobot2.py

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
#!/usr/bin/env python
22
# -*- 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-
"""
3+
4+
"""Simple Bot to reply to Telegram messages.
5+
6+
This program is dedicated to the public domain under the CC0 license.
7+
78
This Bot uses the Updater class to handle the bot.
89
910
First, a few handler functions are defined. Then, those functions are passed to
@@ -29,22 +30,27 @@
2930
# Define a few command handlers. These usually take the two arguments bot and
3031
# update. Error handlers also receive the raised TelegramError object in error.
3132
def start(bot, update):
33+
"""Send a message when the command /start is issued."""
3234
update.message.reply_text('Hi!')
3335

3436

3537
def help(bot, update):
38+
"""Send a message when the command /help is issued."""
3639
update.message.reply_text('Help!')
3740

3841

3942
def echo(bot, update):
43+
"""Echo the user message."""
4044
update.message.reply_text(update.message.text)
4145

4246

4347
def error(bot, update, error):
44-
logger.warn('Update "%s" caused error "%s"' % (update, error))
48+
"""Log Errors caused by Updates."""
49+
logger.warning('Update "%s" caused error "%s"', update, error)
4550

4651

4752
def main():
53+
"""Start the bot."""
4854
# Create the EventHandler and pass it your bot's token.
4955
updater = Updater("TOKEN")
5056

examples/inlinebot.py

Lines changed: 30 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
#!/usr/bin/env python
22
# -*- 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-
"""
3+
4+
"""Simple Bot to reply to Telegram messages.
5+
6+
This program is dedicated to the public domain under the CC0 license.
7+
78
This Bot uses the Updater class to handle the bot.
89
910
First, a few handler functions are defined. Then, those functions are passed to
@@ -19,6 +20,8 @@
1920

2021
import re
2122

23+
from telegram.utils.helpers import escape_markdown
24+
2225
from telegram import InlineQueryResultArticle, ParseMode, \
2326
InputTextMessageContent
2427
from telegram.ext import Updater, InlineQueryHandler, CommandHandler
@@ -34,45 +37,43 @@
3437
# Define a few command handlers. These usually take the two arguments bot and
3538
# update. Error handlers also receive the raised TelegramError object in error.
3639
def start(bot, update):
40+
"""Send a message when the command /start is issued."""
3741
update.message.reply_text('Hi!')
3842

3943

4044
def help(bot, update):
45+
"""Send a message when the command /help is issued."""
4146
update.message.reply_text('Help!')
4247

4348

44-
def escape_markdown(text):
45-
"""Helper function to escape telegram markup symbols"""
46-
escape_chars = '\*_`\['
47-
return re.sub(r'([%s])' % escape_chars, r'\\\1', text)
48-
49-
5049
def inlinequery(bot, update):
50+
"""Handle the inline query."""
5151
query = update.inline_query.query
52-
results = list()
53-
54-
results.append(InlineQueryResultArticle(id=uuid4(),
55-
title="Caps",
56-
input_message_content=InputTextMessageContent(
57-
query.upper())))
58-
59-
results.append(InlineQueryResultArticle(id=uuid4(),
60-
title="Bold",
61-
input_message_content=InputTextMessageContent(
62-
"*%s*" % escape_markdown(query),
63-
parse_mode=ParseMode.MARKDOWN)))
64-
65-
results.append(InlineQueryResultArticle(id=uuid4(),
66-
title="Italic",
67-
input_message_content=InputTextMessageContent(
68-
"_%s_" % escape_markdown(query),
69-
parse_mode=ParseMode.MARKDOWN)))
52+
results = [
53+
InlineQueryResultArticle(
54+
id=uuid4(),
55+
title="Caps",
56+
input_message_content=InputTextMessageContent(
57+
query.upper())),
58+
InlineQueryResultArticle(
59+
id=uuid4(),
60+
title="Bold",
61+
input_message_content=InputTextMessageContent(
62+
"*{}*".format(escape_markdown(query)),
63+
parse_mode=ParseMode.MARKDOWN)),
64+
InlineQueryResultArticle(
65+
id=uuid4(),
66+
title="Italic",
67+
input_message_content=InputTextMessageContent(
68+
"_{}_".format(escape_markdown(query)),
69+
parse_mode=ParseMode.MARKDOWN))]
7070

7171
update.inline_query.answer(results)
7272

7373

7474
def error(bot, update, error):
75-
logger.warning('Update "%s" caused error "%s"' % (update, error))
75+
"""Log Errors caused by Updates."""
76+
logger.warning('Update "%s" caused error "%s"', update, error)
7677

7778

7879
def main():

examples/inlinekeyboard.py

Lines changed: 23 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,16 @@
11
#!/usr/bin/env python
22
# -*- coding: utf-8 -*-
3-
#
4-
# Basic example for a bot that uses inline keyboards.
5-
# This program is dedicated to the public domain under the CC0 license.
3+
"""Basic example for a bot that uses inline keyboards.
64
5+
# This program is dedicated to the public domain under the CC0 license.
6+
"""
77
import logging
88
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
99
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler
1010

1111
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
1212
level=logging.INFO)
13+
logger = logging.getLogger(__name__)
1314

1415

1516
def start(bot, update):
@@ -26,7 +27,7 @@ def start(bot, update):
2627
def button(bot, update):
2728
query = update.callback_query
2829

29-
bot.edit_message_text(text="Selected option: %s" % query.data,
30+
bot.edit_message_text(text="Selected option: {}".format(query.data),
3031
chat_id=query.message.chat_id,
3132
message_id=query.message.message_id)
3233

@@ -36,20 +37,26 @@ def help(bot, update):
3637

3738

3839
def error(bot, update, error):
39-
logging.warning('Update "%s" caused error "%s"' % (update, error))
40+
"""Log Errors caused by Updates."""
41+
logger.warning('Update "%s" caused error "%s"', update, error)
42+
43+
44+
def main():
45+
# Create the Updater and pass it your bot's token.
46+
updater = Updater("TOKEN")
4047

48+
updater.dispatcher.add_handler(CommandHandler('start', start))
49+
updater.dispatcher.add_handler(CallbackQueryHandler(button))
50+
updater.dispatcher.add_handler(CommandHandler('help', help))
51+
updater.dispatcher.add_error_handler(error)
4152

42-
# Create the Updater and pass it your bot's token.
43-
updater = Updater("TOKEN")
53+
# Start the Bot
54+
updater.start_polling()
4455

45-
updater.dispatcher.add_handler(CommandHandler('start', start))
46-
updater.dispatcher.add_handler(CallbackQueryHandler(button))
47-
updater.dispatcher.add_handler(CommandHandler('help', help))
48-
updater.dispatcher.add_error_handler(error)
56+
# Run the bot until the user presses Ctrl-C or the process receives SIGINT,
57+
# SIGTERM or SIGABRT
58+
updater.idle()
4959

50-
# Start the Bot
51-
updater.start_polling()
5260

53-
# Run the bot until the user presses Ctrl-C or the process receives SIGINT,
54-
# SIGTERM or SIGABRT
55-
updater.idle()
61+
if __name__ == '__main__':
62+
main()

0 commit comments

Comments
 (0)