Skip to content

Commit dc2dfa2

Browse files
committed
Adding .sublime
2 parents ce58f45 + 7059930 commit dc2dfa2

4 files changed

Lines changed: 91 additions & 28 deletions

File tree

examples/command_handler_example.py

Lines changed: 13 additions & 15 deletions
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

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,10 +45,12 @@
4545
from .message import Message
4646
from .update import Update
4747
from .bot import Bot
48+
from .command_handler import *
4849

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

telegram/command_handler.py

Lines changed: 69 additions & 12 deletions
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/message.py

Lines changed: 6 additions & 0 deletions
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:

0 commit comments

Comments
 (0)