Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit c8a14bf

Browse files
committed
Merge branch 'testing' of https://github.com/leandrotoledo/python-telegram-bot into ISSUE-58
Conflicts: telegram/__init__.py
2 parents 53c44f1 + e75deea commit c8a14bf

14 files changed

+192
-70
lines changed

.gitignore

+3
Original file line numberDiff line numberDiff line change
@@ -58,3 +58,6 @@ docs/_build/
5858
# PyBuilder
5959
target/
6060
.idea/
61+
62+
# Sublime Text 2
63+
*.sublime*

.travis.yml

+1-1
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,6 @@ python:
99
install:
1010
- pip install coveralls
1111
script:
12-
coverage run tests/run.py
12+
nosetests --with-coverage --cover-package telegram/
1313
after_success:
1414
coveralls

Makefile

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
.PHONY: clean pep8 lint test coverage
1+
.PHONY: clean pep8 lint test
22

33
clean:
44
rm -fr build
@@ -14,7 +14,7 @@ lint:
1414
pylint -E telegram
1515

1616
test:
17-
python tests/run.py
17+
nosetests
1818

1919
help:
2020
@echo "Available targets:"

examples/command_handler_example.py

+13-15
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,5 @@
1-
# There could be some unused imports
2-
from inspect import getmembers, ismethod
3-
import threading
4-
import logging
5-
import telegram
6-
import time
7-
from telegram import CommandHandlerWithHelp, CommandHandler
8-
class ExampleCommandHandler(CommandHandlerWithHelp):
1+
from telegram import CommandHandlerWithHelpAndFather, CommandHandler
2+
class ExampleCommandHandler(CommandHandlerWithHelpAndFather):
93
"""This is an example how to use a CommandHandlerWithHelp or just a CommandHandler.
104
115
If You want to use a CommandHandler it is very easy.
@@ -31,15 +25,15 @@ def _command_not_found(self, update):
3125
chat_id = update.message.chat.id
3226
reply_to = update.message.message_id
3327
message = "Sorry, I don't know how to do {command}.".format(command=update.message.text.split(' ')[0])
34-
self.bot.sendMessage(chat_id, message, reply_to_message_id=reply_to)
28+
self.bot.sendMessage(chat_id=chat_id, text=message, reply_to_message_id=reply_to)
3529

3630
# creates /test command. This code gets called when a telegram user enters /test
3731
def command_test(self, update):
3832
""" Test if the server is online. """
3933
chat_id = update.message.chat.id
4034
reply_to = update.message.message_id
4135
message = 'Yeah, the server is online!'
42-
self.bot.sendMessage(chat_id, message, reply_to_message_id=reply_to)
36+
self.bot.sendMessage(chat_id=chat_id, text=message, reply_to_message_id=reply_to)
4337

4438
# creates /parrot command
4539
def command_parrot(self, update):
@@ -50,7 +44,7 @@ def command_parrot(self, update):
5044
message = update.message.text[len(send[0]):]
5145
if len(send) == 1:
5246
message = '...'
53-
self.bot.sendMessage(chat_id, message, reply_to_message_id=reply_to)
47+
self.bot.sendMessage(chat_id=chat_id, text=message, reply_to_message_id=reply_to)
5448

5549
# creates /p command
5650
def command_p(self, update):
@@ -67,7 +61,7 @@ def another_test(self, update):
6761
chat_id = update.message.chat.id
6862
reply_to = update.message.message_id
6963
message = 'Yeah, this is another test'
70-
self.bot.sendMessage(chat_id, message, reply_to_message_id=reply_to)
64+
self.bot.sendMessage(chat_id=chat_id, text=message, reply_to_message_id=reply_to)
7165

7266

7367
class Exampe2CommandHandler(CommandHandler):
@@ -79,11 +73,15 @@ def command_test(self, update):
7973
chat_id = update.message.chat.id
8074
reply_to = update.message.message_id
8175
message = 'Yeah, the server is online!'
82-
self.bot.sendMessage(chat_id, message, reply_to_message_id=reply_to)
76+
self.bot.sendMessage(chat_id=chat_id, text=message, reply_to_message_id=reply_to)
8377

8478
if __name__ == '__main__':
85-
import telegram
86-
token = '' # use your own token here
79+
import telegram as telegram
80+
try:
81+
from mytoken import token
82+
except:
83+
token = '' # use your own token here
84+
print ('token = ', token)
8785
Bot = telegram.Bot(token=token)
8886
test_command_handler = ExampleCommandHandler(Bot)
8987
test_command_handler.run()

telegram/__init__.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -46,10 +46,12 @@
4646
from .message import Message
4747
from .update import Update
4848
from .bot import Bot
49+
from .command_handler import *
4950

5051
__all__ = ['Bot', 'Emoji', 'TelegramError', 'InputFile', 'ReplyMarkup',
5152
'ForceReply', 'ReplyKeyboardHide', 'ReplyKeyboardMarkup',
5253
'UserProfilePhotos', 'ChatAction', 'Location', 'Contact',
5354
'Video', 'Sticker', 'Document', 'Audio', 'PhotoSize', 'GroupChat',
5455
'Update', 'ParseMode', 'Message', 'User', 'TelegramObject', 'NullHandler',
55-
'Voice']
56+
'Voice', 'CommandHandler', 'CommandHandlerWithHelp',
57+
'CommandHandlerWithFatherCommand', 'CommandHandlerWithHelpAndFather']

telegram/command_handler.py

+69-12
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,10 @@
44
import telegram
55
import time
66
logger = logging.getLogger(__name__)
7-
__all__ = ['CommandHandler', 'CommandHandlerWithHelp']
7+
__all__ = ['CommandHandler', 'CommandHandlerWithHelp', 'CommandHandlerWithFatherCommand',
8+
'CommandHandlerWithHelpAndFather']
9+
10+
811
class CommandHandler(object):
912
""" This handles incomming commands and gives an easy way to create commands.
1013
@@ -15,7 +18,8 @@ class CommandHandler(object):
1518
"""
1619
def __init__(self, bot):
1720
self.bot = bot # a telegram bot
18-
self.isValidCommand = None # a function that returns a boolean and takes one agrument an update. if False is returned the the comaand is not executed.
21+
self.isValidCommand = None # a function that returns a boolean and takes one agrument an update.
22+
# If False is returned the the command is not executed.
1923

2024
def _get_command_func(self, command):
2125
if command[0] == '/':
@@ -38,6 +42,7 @@ def run(self, make_thread=True, last_update_id=None, thread_timeout=2, sleep=0.2
3842
The timeout on a thread. If a thread is alive after this period then try to join the thread in
3943
the next loop.
4044
"""
45+
4146
old_threads = []
4247
while True:
4348
time.sleep(sleep)
@@ -82,7 +87,7 @@ def run_once(self, make_thread=True, last_update_id=None):
8287
if username == bot_name:
8388
command_func = self._get_command_func(command)
8489
if command_func is not None:
85-
self.bot.sendChatAction(update.message.chat.id,telegram.ChatAction.TYPING)
90+
self.bot.sendChatAction(chat_id=update.message.chat.id, action=telegram.ChatAction.TYPING)
8691
if self.isValidCommand is None or self.isValidCommand(update):
8792
if make_thread:
8893
t = threading.Thread(target=command_func, args=(update,))
@@ -107,8 +112,9 @@ def _command_not_valid(self, update):
107112
"""
108113
chat_id = update.message.chat.id
109114
reply_to = update.message.message_id
110-
message = "Sorry, the command was not authorised or valid: {command}.".format(command=update.message.text.split(' ')[0])
111-
self.bot.sendMessage(chat_id, message, reply_to_message_id=reply_to)
115+
message = "Sorry, the command was not authorised or valid: {command}.".format(
116+
command=update.message.text.split(' ')[0])
117+
self.bot.sendMessage(chat_id=chat_id, text=message, reply_to_message_id=reply_to)
112118

113119
def _command_not_found(self, update):
114120
"""Inform the telegram user that the command was not found.
@@ -119,7 +125,7 @@ def _command_not_found(self, update):
119125
chat_id = update.message.chat.id
120126
reply_to = update.message.message_id
121127
message = "Sorry, I didn't understand the command: {command}.".format(command=update.message.text.split(' ')[0])
122-
self.bot.sendMessage(chat_id, message, reply_to_message_id=reply_to)
128+
self.bot.sendMessage(chat_id=chat_id, text=message, reply_to_message_id=reply_to)
123129

124130

125131
class CommandHandlerWithHelp(CommandHandler):
@@ -130,8 +136,23 @@ def __init__(self, bot):
130136
self._help_before_list = '' # text with information about the bot
131137
self._help_after_list = '' # a footer
132138
self._help_list_title = 'These are the commands:' # the title of the list
139+
self._help_extra_message = 'These commands are only usefull to the developer.'
133140
self.is_reply = True
134141
self.command_start = self.command_help
142+
self.skip_in_help = []
143+
144+
def command_helpextra(self,update):
145+
""" The commands in here are only usefull to the developer of the bot"""
146+
command_functions = [attr[1] for attr in getmembers(self, predicate=ismethod) if attr[0][:8] == 'command_' and
147+
attr[0] in self.skip_in_help]
148+
chat_id = update.message.chat.id
149+
help_message = self._help_extra_message + '\n'
150+
for command_function in command_functions:
151+
if command_function.__doc__ is not None:
152+
help_message += ' /' + command_function.__name__[8:] + ' - ' + command_function.__doc__ + '\n'
153+
else:
154+
help_message += ' /' + command_function.__name__[8:] + ' - ' + '\n'
155+
self.bot.sendMessage(chat_id=chat_id, text=help_message)
135156

136157
def _generate_help(self):
137158
""" Generate a string which can be send as a help file.
@@ -141,17 +162,23 @@ def _generate_help(self):
141162
command to the telegram user.
142163
"""
143164

144-
command_functions = [attr[1] for attr in getmembers(self, predicate=ismethod) if attr[0][:8] == 'command_']
145165
help_message = self._help_title + '\n\n'
146166
help_message += self._help_before_list + '\n\n'
147167
help_message += self._help_list_title + '\n'
168+
help_message += self._generate_help_list()
169+
help_message += '\n'
170+
help_message += self._help_after_list
171+
return help_message
172+
173+
def _generate_help_list(self):
174+
command_functions = [attr[1] for attr in getmembers(self, predicate=ismethod) if attr[0][:8] == 'command_' and
175+
attr[0] not in self.skip_in_help]
176+
help_message = ''
148177
for command_function in command_functions:
149178
if command_function.__doc__ is not None:
150179
help_message += ' /' + command_function.__name__[8:] + ' - ' + command_function.__doc__ + '\n'
151180
else:
152181
help_message += ' /' + command_function.__name__[8:] + ' - ' + '\n'
153-
help_message += '\n'
154-
help_message += self._help_after_list
155182
return help_message
156183

157184
def _command_not_found(self, update):
@@ -160,15 +187,45 @@ def _command_not_found(self, update):
160187
reply_to = update.message.message_id
161188
message = 'Sorry, I did not understand the command: {command}. Please see /help for all available commands'
162189
if self.is_reply:
163-
self.bot.sendMessage(chat_id, message.format(command=update.message.text.split(' ')[0]),
190+
self.bot.sendMessage(chat_id=chat_id, text=message.format(command=update.message.text.split(' ')[0]),
164191
reply_to_message_id=reply_to)
165192
else:
166-
self.bot.sendMessage(chat_id, message.format(command=update.message.text.split(' ')[0]))
193+
self.bot.sendMessage(chat_id=chat_id, text=message.format(command=update.message.text.split(' ')[0]))
167194

168195
def command_help(self, update):
169196
""" The help file. """
170197
chat_id = update.message.chat.id
171198
reply_to = update.message.message_id
172199
message = self._generate_help()
173-
self.bot.sendMessage(chat_id, message, reply_to_message_id=reply_to)
200+
self.bot.sendMessage(chat_id=chat_id, text=message, reply_to_message_id=reply_to)
201+
202+
203+
class CommandHandlerWithFatherCommand(CommandHandler):
204+
""" A class that creates some commands that are usefull when setting up the bot
205+
"""
206+
def __init__(self, bot):
207+
super(CommandHandlerWithFatherCommand, self).__init__(bot)
208+
self.skip_in_help = ['command_father']
209+
210+
def command_father(self, update):
211+
"""Gives you the commands you need to setup this bot. in telegram.me/BotFather"""
212+
chat_id = update.message.chat.id
213+
self.bot.sendMessage(chat_id=chat_id, text='Send the following messages to telegram.me/BotFather')
214+
self.bot.sendMessage(chat_id=chat_id, text='/setcommands')
215+
self.bot.sendMessage(chat_id=chat_id, text='@' + self.bot.getMe()['username'])
216+
commands = ''
217+
command_functions = [attr[1] for attr in getmembers(self, predicate=ismethod) if attr[0][:8] == 'command_' and
218+
attr[0] not in self.skip_in_help]
219+
220+
for command_function in command_functions:
221+
if command_function.__doc__ is not None:
222+
commands += command_function.__name__[8:] + ' - ' + command_function.__doc__ + '\n'
223+
else:
224+
commands += command_function.__name__[8:] + ' - ' + '\n'
225+
self.bot.sendMessage(chat_id=chat_id, text=commands)
226+
174227

228+
class CommandHandlerWithHelpAndFather(CommandHandlerWithFatherCommand, CommandHandlerWithHelp):
229+
"""A class that combines CommandHandlerWithHelp and CommandHandlerWithFatherCommand.
230+
"""
231+
pass

telegram/inputfile.py

+6-3
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,9 @@ def __init__(self,
5555
if 'photo' in data:
5656
self.input_name = 'photo'
5757
self.input_file = data.pop('photo')
58+
if 'sticker' in data:
59+
self.input_name = 'sticker'
60+
self.input_file = data.pop('sticker')
5861
if 'video' in data:
5962
self.input_name = 'video'
6063
self.input_file = data.pop('video')
@@ -67,7 +70,7 @@ def __init__(self,
6770

6871
if isinstance(self.input_file, file):
6972
self.input_file_content = self.input_file.read()
70-
if 'filename' in self.data:
73+
if 'filename' in data:
7174
self.filename = self.data.pop('filename')
7275
else:
7376
self.filename = os.path.basename(self.input_file.name)
@@ -174,8 +177,8 @@ def is_inputfile(data):
174177
bool
175178
"""
176179
if data:
177-
file_types = ['audio', 'document', 'photo', 'video', 'voice',
178-
'certificate']
180+
file_types = ['audio', 'document', 'photo', 'sticker', 'video',
181+
'voice', 'certificate']
179182
file_type = [i for i in list(data.keys()) if i in file_types]
180183

181184
if file_type:

telegram/message.py

+6
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,12 @@ def de_json(data):
171171

172172
return Message(**data)
173173

174+
def __getitem__(self, item):
175+
if item in self.__dict__.keys():
176+
return self.__dict__[item]
177+
elif item == 'chat_id':
178+
return self.chat.id
179+
174180
def to_dict(self):
175181
"""
176182
Returns:

telegram/utils/request.py

+7-4
Original file line numberDiff line numberDiff line change
@@ -84,11 +84,14 @@ def post(url,
8484
try:
8585
if InputFile.is_inputfile(data):
8686
data = InputFile(data)
87-
request = Request(url, data=data.to_form(), headers=data.headers)
88-
89-
result = urlopen(request).read()
87+
request = Request(url, data=data.to_form(),
88+
headers=data.headers)
9089
else:
91-
result = urlopen(url, urlencode(data).encode()).read()
90+
data = json.dumps(data)
91+
request = Request(url, data=data.encode(),
92+
headers={'Content-Type': 'application/json'})
93+
94+
result = urlopen(request).read()
9295
except HTTPError as error:
9396
message = _parse(error.read())
9497
raise TelegramError(message)

tests/run.py

-28
This file was deleted.

0 commit comments

Comments
 (0)