X Tutup
Skip to content

Commit 7c84516

Browse files
committed
Merge branch 'master' of github.com:python-telegram-bot/python-telegram-bot
2 parents af89cbe + 53a91be commit 7c84516

17 files changed

+122
-102
lines changed

.pre-commit-config.yaml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
- repo: git://github.com/pre-commit/mirrors-yapf
2-
sha: d79d3113a991229b8f9d329e8e97b615abad91ba
2+
sha: 316b795b2f32cbe80047aff7e842b72368d5a2c1
33
hooks:
44
- id: yapf
5-
files: ^(telegram|tests)/.*\.py$
5+
files: ^(examples|telegram|tests)/.*\.py$
66
- repo: git://github.com/pre-commit/pre-commit-hooks
77
sha: adbb569fe9a64ad9bce3b53a77f1bc39ef31f682
88
hooks:

CONTRIBUTING.rst

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,52 @@ Here's how to make a one-off code change.
131131

132132
7. **Celebrate.** Congratulations, you have contributed to ``python-telegram-bot``!
133133

134+
Style commandments
135+
==================
136+
137+
Specific commandments
138+
---------------------
139+
140+
- Avoid using "double quotes" where you can reasonably use 'single quotes'.
141+
142+
AssertEqual argument order
143+
--------------------------
144+
145+
assertEqual method's arguments should be in ('actual', 'expected') order.
146+
147+
Properly calling callables
148+
--------------------------
149+
150+
Methods, functions and classes can specify optional parameters (with default
151+
values) using Python's keyword arg syntax. When providing a value to such a
152+
callable we prefer that the call also uses keyword arg syntax. For example::
153+
154+
# GOOD
155+
f(0, optional=True)
156+
157+
# BAD
158+
f(0, True)
159+
160+
This gives us the flexibility to re-order arguments and more importantly
161+
to add new required arguments. It's also more explicit and easier to read.
162+
163+
Properly defining optional arguments
164+
------------------------------------
165+
166+
It's always good to not initialize optional arguments at class creation,
167+
instead use ``**kwargs`` to get them. It's well known Telegram API can
168+
change without notice, in that case if a new argument is added it won't
169+
break the API classes. For example::
170+
171+
# GOOD
172+
def __init__(self, id, name, **kwargs):
173+
self.last_name = kwargs.get('last_name', '')
174+
175+
# BAD
176+
def __init__(self, id, name, last_name=''):
177+
self.last_name = last_name
178+
179+
134180
.. _`Code of Conduct`: https://www.python.org/psf/codeofconduct/
135181
.. _`issue tracker`: https://github.com/python-telegram-bot/python-telegram-bot/issues
136182
.. _`developers' mailing list`: mailto:devs@python-telegram-bot.org

examples/clibot.py

Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
#
44
# Example Bot to show some of the functionality of the library
55
# This program is dedicated to the public domain under the CC0 license.
6-
76
"""
87
This Bot uses the Updater class to handle the bot.
98
@@ -27,9 +26,8 @@
2726
from future.builtins import input
2827

2928
# Enable Logging
30-
logging.basicConfig(
31-
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
32-
level=logging.INFO)
29+
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
30+
level=logging.INFO)
3331

3432
logger = logging.getLogger(__name__)
3533

@@ -58,9 +56,7 @@ def any_message(bot, update):
5856
last_chat_id = update.message.chat_id
5957

6058
logger.info("New message\nFrom: %s\nchat_id: %d\nText: %s" %
61-
(update.message.from_user,
62-
update.message.chat_id,
63-
update.message.text))
59+
(update.message.from_user, update.message.chat_id, update.message.text))
6460

6561

6662
@run_async
@@ -72,8 +68,7 @@ def message(bot, update):
7268
"""
7369

7470
sleep(2) # IO-heavy operation here
75-
bot.sendMessage(update.message.chat_id, text='Echo: %s' %
76-
update.message.text)
71+
bot.sendMessage(update.message.chat_id, text='Echo: %s' % update.message.text)
7772

7873

7974
# These handlers are for updates of type str. We use them to react to inputs
@@ -126,16 +121,14 @@ def main():
126121
# String handlers work pretty much the same. Note that we have to tell
127122
# the handler to pass the args or update_queue parameter
128123
dp.add_handler(StringCommandHandler('reply', cli_reply, pass_args=True))
129-
dp.add_handler(StringRegexHandler('[^/].*', cli_noncommand,
130-
pass_update_queue=True))
124+
dp.add_handler(StringRegexHandler('[^/].*', cli_noncommand, pass_update_queue=True))
131125

132126
# All TelegramErrors are caught for you and delivered to the error
133127
# handler(s). Other types of Errors are not caught.
134128
dp.add_error_handler(error)
135129

136130
# Start the Bot and store the update Queue, so we can insert updates
137131
update_queue = updater.start_polling(timeout=10)
138-
139132
'''
140133
# Alternatively, run with webhook:
141134
@@ -166,5 +159,6 @@ def main():
166159
elif len(text) > 0:
167160
update_queue.put(text)
168161

162+
169163
if __name__ == '__main__':
170164
main()

examples/echobot2.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
#
44
# Simple Bot to reply to Telegram messages
55
# This program is dedicated to the public domain under the CC0 license.
6-
76
"""
87
This Bot uses the Updater class to handle the bot.
98
@@ -21,9 +20,8 @@
2120
import logging
2221

2322
# Enable logging
24-
logging.basicConfig(
25-
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
26-
level=logging.INFO)
23+
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
24+
level=logging.INFO)
2725

2826
logger = logging.getLogger(__name__)
2927

@@ -71,5 +69,6 @@ def main():
7169
# start_polling() is non-blocking and will stop the bot gracefully.
7270
updater.idle()
7371

72+
7473
if __name__ == '__main__':
7574
main()

examples/inlinebot.py

Lines changed: 19 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
#
44
# Simple Bot to reply to Telegram messages
55
# This program is dedicated to the public domain under the CC0 license.
6-
76
"""
87
This Bot uses the Updater class to handle the bot.
98
@@ -26,9 +25,8 @@
2625
import logging
2726

2827
# Enable logging
29-
logging.basicConfig(
30-
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
31-
level=logging.INFO)
28+
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
29+
level=logging.INFO)
3230

3331
logger = logging.getLogger(__name__)
3432

@@ -53,24 +51,22 @@ def inlinequery(bot, update):
5351
query = update.inline_query.query
5452
results = list()
5553

56-
results.append(InlineQueryResultArticle(
57-
id=uuid4(),
58-
title="Caps",
59-
input_message_content=InputTextMessageContent(query.upper())))
60-
61-
results.append(InlineQueryResultArticle(
62-
id=uuid4(),
63-
title="Bold",
64-
input_message_content=InputTextMessageContent(
65-
"*%s*" % escape_markdown(query),
66-
parse_mode=ParseMode.MARKDOWN)))
67-
68-
results.append(InlineQueryResultArticle(
69-
id=uuid4(),
70-
title="Italic",
71-
input_message_content=InputTextMessageContent(
72-
"_%s_" % escape_markdown(query),
73-
parse_mode=ParseMode.MARKDOWN)))
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)))
7470

7571
bot.answerInlineQuery(update.inline_query.id, results=results)
7672

@@ -104,5 +100,6 @@ def main():
104100
# start_polling() is non-blocking and will stop the bot gracefully.
105101
updater.idle()
106102

103+
107104
if __name__ == '__main__':
108105
main()

examples/inlinekeyboard_example.py

Lines changed: 9 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -11,17 +11,15 @@
1111
from telegram.ext import Updater, CommandHandler, MessageHandler, \
1212
CallbackQueryHandler, Filters
1313

14-
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - '
15-
'%(message)s',
14+
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
1615
level=logging.DEBUG)
1716

1817
# Define the different states a chat can be in
1918
MENU, AWAIT_CONFIRMATION, AWAIT_INPUT = range(3)
2019

2120
# Python 2 and 3 unicode differences
2221
try:
23-
YES, NO = (Emoji.THUMBS_UP_SIGN.decode('utf-8'),
24-
Emoji.THUMBS_DOWN_SIGN.decode('utf-8'))
22+
YES, NO = (Emoji.THUMBS_UP_SIGN.decode('utf-8'), Emoji.THUMBS_DOWN_SIGN.decode('utf-8'))
2523
except AttributeError:
2624
YES, NO = (Emoji.THUMBS_UP_SIGN, Emoji.THUMBS_DOWN_SIGN)
2725

@@ -58,11 +56,9 @@ def entered_value(bot, update):
5856

5957
# Save the user id and the answer to context
6058
context[user_id] = update.message.text
61-
reply_markup = InlineKeyboardMarkup(
62-
[[InlineKeyboardButton(YES, callback_data=YES),
63-
InlineKeyboardButton(NO, callback_data=NO)]])
64-
bot.sendMessage(chat_id, text="Are you sure?",
65-
reply_markup=reply_markup)
59+
reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton(YES, callback_data=YES),
60+
InlineKeyboardButton(NO, callback_data=NO)]])
61+
bot.sendMessage(chat_id, text="Are you sure?", reply_markup=reply_markup)
6662

6763

6864
def confirm_value(bot, update):
@@ -82,14 +78,12 @@ def confirm_value(bot, update):
8278
values[user_id] = user_context
8379
bot.editMessageText(text="Changed value to %s." % values[user_id],
8480
chat_id=chat_id,
85-
message_id=
86-
query.message.message_id)
81+
message_id=query.message.message_id)
8782
else:
88-
bot.editMessageText(text="Alright, value is still %s."
89-
% values.get(user_id, 'not set'),
83+
bot.editMessageText(text="Alright, value is still %s." %
84+
values.get(user_id, 'not set'),
9085
chat_id=chat_id,
91-
message_id=
92-
query.message.message_id)
86+
message_id=query.message.message_id)
9387

9488

9589
def help(bot, update):

examples/legacy/echobot.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,7 @@ def main():
2121
except IndexError:
2222
update_id = None
2323

24-
logging.basicConfig(
25-
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
24+
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
2625

2726
while True:
2827
try:
@@ -45,8 +44,7 @@ def echo(bot, update_id):
4544

4645
if message:
4746
# Reply to the message
48-
bot.sendMessage(chat_id=chat_id,
49-
text=message)
47+
bot.sendMessage(chat_id=chat_id, text=message)
5048

5149
return update_id
5250

examples/legacy/roboed.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,7 @@
1010

1111

1212
def main():
13-
logging.basicConfig(
14-
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
13+
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
1514
bot = telegram.Bot('TOKEN') # Telegram Bot Authorization Token
1615

1716
LAST_UPDATE_ID = bot.getUpdates()[-1].update_id # Get lastest update
@@ -34,5 +33,6 @@ def ed(text):
3433

3534
return data.strip()
3635

36+
3737
if __name__ == '__main__':
3838
main()

examples/state_machine_bot.py

Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -8,17 +8,15 @@
88
from telegram import Emoji, ForceReply, ReplyKeyboardMarkup, KeyboardButton
99
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
1010

11-
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - '
12-
'%(message)s',
11+
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
1312
level=logging.INFO)
1413

1514
# Define the different states a chat can be in
1615
MENU, AWAIT_CONFIRMATION, AWAIT_INPUT = range(3)
1716

1817
# Python 2 and 3 unicode differences
1918
try:
20-
YES, NO = (Emoji.THUMBS_UP_SIGN.decode('utf-8'),
21-
Emoji.THUMBS_DOWN_SIGN.decode('utf-8'))
19+
YES, NO = (Emoji.THUMBS_UP_SIGN.decode('utf-8'), Emoji.THUMBS_DOWN_SIGN.decode('utf-8'))
2220
except AttributeError:
2321
YES, NO = (Emoji.THUMBS_UP_SIGN, Emoji.THUMBS_DOWN_SIGN)
2422

@@ -46,7 +44,7 @@ def set_value(bot, update):
4644
context[chat_id] = user_id # save the user id to context
4745
bot.sendMessage(chat_id,
4846
text="Please enter your settings value or send "
49-
"/cancel to abort",
47+
"/cancel to abort",
5048
reply_markup=ForceReply())
5149

5250
# If we are waiting for input and the right user answered
@@ -58,21 +56,18 @@ def set_value(bot, update):
5856
reply_markup = ReplyKeyboardMarkup(
5957
[[KeyboardButton(YES), KeyboardButton(NO)]],
6058
one_time_keyboard=True)
61-
bot.sendMessage(chat_id, text="Are you sure?",
62-
reply_markup=reply_markup)
59+
bot.sendMessage(chat_id, text="Are you sure?", reply_markup=reply_markup)
6360

6461
# If we are waiting for confirmation and the right user answered
6562
elif chat_state == AWAIT_CONFIRMATION and chat_context[0] == user_id:
6663
del state[chat_id]
6764
del context[chat_id]
6865
if text == YES:
6966
values[chat_id] = chat_context[1]
70-
bot.sendMessage(chat_id,
71-
text="Changed value to %s." % values[chat_id])
67+
bot.sendMessage(chat_id, text="Changed value to %s." % values[chat_id])
7268
else:
7369
bot.sendMessage(chat_id,
74-
text="Value not changed: %s."
75-
% values.get(chat_id, '<not set>'))
70+
text="Value not changed: %s." % values.get(chat_id, '<not set>'))
7671

7772

7873
# Handler for the /cancel command.
@@ -86,7 +81,6 @@ def cancel(bot, update):
8681
def help(bot, update):
8782
bot.sendMessage(update.message.chat_id, text="Use /set to test this bot.")
8883

89-
9084
# Create the Updater and pass it your bot's token.
9185
updater = Updater("TOKEN")
9286

0 commit comments

Comments
 (0)
X Tutup