mirror of
https://github.com/python-telegram-bot/python-telegram-bot.git
synced 2025-03-23 23:39:42 +01:00
Merge pull request #55 from njittam/testing
add a father command. and hide commands in help.
This commit is contained in:
commit
7059930b5d
5 changed files with 94 additions and 28 deletions
3
.gitignore
vendored
3
.gitignore
vendored
|
@ -58,3 +58,6 @@ docs/_build/
|
||||||
# PyBuilder
|
# PyBuilder
|
||||||
target/
|
target/
|
||||||
.idea/
|
.idea/
|
||||||
|
|
||||||
|
# token
|
||||||
|
mytoken.py
|
||||||
|
|
|
@ -1,11 +1,5 @@
|
||||||
# There could be some unused imports
|
from telegram import CommandHandlerWithHelpAndFather, CommandHandler
|
||||||
from inspect import getmembers, ismethod
|
class ExampleCommandHandler(CommandHandlerWithHelpAndFather):
|
||||||
import threading
|
|
||||||
import logging
|
|
||||||
import telegram
|
|
||||||
import time
|
|
||||||
from telegram import CommandHandlerWithHelp, CommandHandler
|
|
||||||
class ExampleCommandHandler(CommandHandlerWithHelp):
|
|
||||||
"""This is an example how to use a CommandHandlerWithHelp or just a CommandHandler.
|
"""This is an example how to use a CommandHandlerWithHelp or just a CommandHandler.
|
||||||
|
|
||||||
If You want to use a CommandHandler it is very easy.
|
If You want to use a CommandHandler it is very easy.
|
||||||
|
@ -31,7 +25,7 @@ class ExampleCommandHandler(CommandHandlerWithHelp):
|
||||||
chat_id = update.message.chat.id
|
chat_id = update.message.chat.id
|
||||||
reply_to = update.message.message_id
|
reply_to = update.message.message_id
|
||||||
message = "Sorry, I don't know how to do {command}.".format(command=update.message.text.split(' ')[0])
|
message = "Sorry, I don't know how to do {command}.".format(command=update.message.text.split(' ')[0])
|
||||||
self.bot.sendMessage(chat_id, message, reply_to_message_id=reply_to)
|
self.bot.sendMessage(chat_id=chat_id, text=message, reply_to_message_id=reply_to)
|
||||||
|
|
||||||
# creates /test command. This code gets called when a telegram user enters /test
|
# creates /test command. This code gets called when a telegram user enters /test
|
||||||
def command_test(self, update):
|
def command_test(self, update):
|
||||||
|
@ -39,7 +33,7 @@ class ExampleCommandHandler(CommandHandlerWithHelp):
|
||||||
chat_id = update.message.chat.id
|
chat_id = update.message.chat.id
|
||||||
reply_to = update.message.message_id
|
reply_to = update.message.message_id
|
||||||
message = 'Yeah, the server is online!'
|
message = 'Yeah, the server is online!'
|
||||||
self.bot.sendMessage(chat_id, message, reply_to_message_id=reply_to)
|
self.bot.sendMessage(chat_id=chat_id, text=message, reply_to_message_id=reply_to)
|
||||||
|
|
||||||
# creates /parrot command
|
# creates /parrot command
|
||||||
def command_parrot(self, update):
|
def command_parrot(self, update):
|
||||||
|
@ -50,7 +44,7 @@ class ExampleCommandHandler(CommandHandlerWithHelp):
|
||||||
message = update.message.text[len(send[0]):]
|
message = update.message.text[len(send[0]):]
|
||||||
if len(send) == 1:
|
if len(send) == 1:
|
||||||
message = '...'
|
message = '...'
|
||||||
self.bot.sendMessage(chat_id, message, reply_to_message_id=reply_to)
|
self.bot.sendMessage(chat_id=chat_id, text=message, reply_to_message_id=reply_to)
|
||||||
|
|
||||||
# creates /p command
|
# creates /p command
|
||||||
def command_p(self, update):
|
def command_p(self, update):
|
||||||
|
@ -67,7 +61,7 @@ class ExampleCommandHandler(CommandHandlerWithHelp):
|
||||||
chat_id = update.message.chat.id
|
chat_id = update.message.chat.id
|
||||||
reply_to = update.message.message_id
|
reply_to = update.message.message_id
|
||||||
message = 'Yeah, this is another test'
|
message = 'Yeah, this is another test'
|
||||||
self.bot.sendMessage(chat_id, message, reply_to_message_id=reply_to)
|
self.bot.sendMessage(chat_id=chat_id, text=message, reply_to_message_id=reply_to)
|
||||||
|
|
||||||
|
|
||||||
class Exampe2CommandHandler(CommandHandler):
|
class Exampe2CommandHandler(CommandHandler):
|
||||||
|
@ -79,11 +73,15 @@ class Exampe2CommandHandler(CommandHandler):
|
||||||
chat_id = update.message.chat.id
|
chat_id = update.message.chat.id
|
||||||
reply_to = update.message.message_id
|
reply_to = update.message.message_id
|
||||||
message = 'Yeah, the server is online!'
|
message = 'Yeah, the server is online!'
|
||||||
self.bot.sendMessage(chat_id, message, reply_to_message_id=reply_to)
|
self.bot.sendMessage(chat_id=chat_id, text=message, reply_to_message_id=reply_to)
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
import telegram
|
import telegram as telegram
|
||||||
token = '' # use your own token here
|
try:
|
||||||
|
from mytoken import token
|
||||||
|
except:
|
||||||
|
token = '' # use your own token here
|
||||||
|
print ('token = ', token)
|
||||||
Bot = telegram.Bot(token=token)
|
Bot = telegram.Bot(token=token)
|
||||||
test_command_handler = ExampleCommandHandler(Bot)
|
test_command_handler = ExampleCommandHandler(Bot)
|
||||||
test_command_handler.run()
|
test_command_handler.run()
|
||||||
|
|
|
@ -45,10 +45,12 @@ from .emoji import Emoji
|
||||||
from .message import Message
|
from .message import Message
|
||||||
from .update import Update
|
from .update import Update
|
||||||
from .bot import Bot
|
from .bot import Bot
|
||||||
|
from .command_handler import *
|
||||||
|
|
||||||
__all__ = ['Bot', 'Emoji', 'TelegramError', 'InputFile', 'ReplyMarkup',
|
__all__ = ['Bot', 'Emoji', 'TelegramError', 'InputFile', 'ReplyMarkup',
|
||||||
'ForceReply', 'ReplyKeyboardHide', 'ReplyKeyboardMarkup',
|
'ForceReply', 'ReplyKeyboardHide', 'ReplyKeyboardMarkup',
|
||||||
'UserProfilePhotos', 'ChatAction', 'Location', 'Contact',
|
'UserProfilePhotos', 'ChatAction', 'Location', 'Contact',
|
||||||
'Video', 'Sticker', 'Document', 'Audio', 'PhotoSize', 'GroupChat',
|
'Video', 'Sticker', 'Document', 'Audio', 'PhotoSize', 'GroupChat',
|
||||||
'Update', 'Message', 'User', 'TelegramObject', 'NullHandler',
|
'Update', 'Message', 'User', 'TelegramObject', 'NullHandler',
|
||||||
'Voice']
|
'Voice','CommandHandler', 'CommandHandlerWithHelp',
|
||||||
|
'CommandHandlerWithFatherCommand', 'CommandHandlerWithHelpAndFather']
|
||||||
|
|
|
@ -4,7 +4,10 @@ import logging
|
||||||
import telegram
|
import telegram
|
||||||
import time
|
import time
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
__all__ = ['CommandHandler', 'CommandHandlerWithHelp']
|
__all__ = ['CommandHandler', 'CommandHandlerWithHelp', 'CommandHandlerWithFatherCommand',
|
||||||
|
'CommandHandlerWithHelpAndFather']
|
||||||
|
|
||||||
|
|
||||||
class CommandHandler(object):
|
class CommandHandler(object):
|
||||||
""" This handles incomming commands and gives an easy way to create commands.
|
""" This handles incomming commands and gives an easy way to create commands.
|
||||||
|
|
||||||
|
@ -15,7 +18,8 @@ class CommandHandler(object):
|
||||||
"""
|
"""
|
||||||
def __init__(self, bot):
|
def __init__(self, bot):
|
||||||
self.bot = bot # a telegram bot
|
self.bot = bot # a telegram bot
|
||||||
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.
|
self.isValidCommand = None # a function that returns a boolean and takes one agrument an update.
|
||||||
|
# If False is returned the the command is not executed.
|
||||||
|
|
||||||
def _get_command_func(self, command):
|
def _get_command_func(self, command):
|
||||||
if command[0] == '/':
|
if command[0] == '/':
|
||||||
|
@ -38,6 +42,7 @@ class CommandHandler(object):
|
||||||
The timeout on a thread. If a thread is alive after this period then try to join the thread in
|
The timeout on a thread. If a thread is alive after this period then try to join the thread in
|
||||||
the next loop.
|
the next loop.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
old_threads = []
|
old_threads = []
|
||||||
while True:
|
while True:
|
||||||
time.sleep(sleep)
|
time.sleep(sleep)
|
||||||
|
@ -82,7 +87,7 @@ class CommandHandler(object):
|
||||||
if username == bot_name:
|
if username == bot_name:
|
||||||
command_func = self._get_command_func(command)
|
command_func = self._get_command_func(command)
|
||||||
if command_func is not None:
|
if command_func is not None:
|
||||||
self.bot.sendChatAction(update.message.chat.id,telegram.ChatAction.TYPING)
|
self.bot.sendChatAction(chat_id=update.message.chat.id, action=telegram.ChatAction.TYPING)
|
||||||
if self.isValidCommand is None or self.isValidCommand(update):
|
if self.isValidCommand is None or self.isValidCommand(update):
|
||||||
if make_thread:
|
if make_thread:
|
||||||
t = threading.Thread(target=command_func, args=(update,))
|
t = threading.Thread(target=command_func, args=(update,))
|
||||||
|
@ -107,8 +112,9 @@ class CommandHandler(object):
|
||||||
"""
|
"""
|
||||||
chat_id = update.message.chat.id
|
chat_id = update.message.chat.id
|
||||||
reply_to = update.message.message_id
|
reply_to = update.message.message_id
|
||||||
message = "Sorry, the command was not authorised or valid: {command}.".format(command=update.message.text.split(' ')[0])
|
message = "Sorry, the command was not authorised or valid: {command}.".format(
|
||||||
self.bot.sendMessage(chat_id, message, reply_to_message_id=reply_to)
|
command=update.message.text.split(' ')[0])
|
||||||
|
self.bot.sendMessage(chat_id=chat_id, text=message, reply_to_message_id=reply_to)
|
||||||
|
|
||||||
def _command_not_found(self, update):
|
def _command_not_found(self, update):
|
||||||
"""Inform the telegram user that the command was not found.
|
"""Inform the telegram user that the command was not found.
|
||||||
|
@ -119,7 +125,7 @@ class CommandHandler(object):
|
||||||
chat_id = update.message.chat.id
|
chat_id = update.message.chat.id
|
||||||
reply_to = update.message.message_id
|
reply_to = update.message.message_id
|
||||||
message = "Sorry, I didn't understand the command: {command}.".format(command=update.message.text.split(' ')[0])
|
message = "Sorry, I didn't understand the command: {command}.".format(command=update.message.text.split(' ')[0])
|
||||||
self.bot.sendMessage(chat_id, message, reply_to_message_id=reply_to)
|
self.bot.sendMessage(chat_id=chat_id, text=message, reply_to_message_id=reply_to)
|
||||||
|
|
||||||
|
|
||||||
class CommandHandlerWithHelp(CommandHandler):
|
class CommandHandlerWithHelp(CommandHandler):
|
||||||
|
@ -130,8 +136,23 @@ class CommandHandlerWithHelp(CommandHandler):
|
||||||
self._help_before_list = '' # text with information about the bot
|
self._help_before_list = '' # text with information about the bot
|
||||||
self._help_after_list = '' # a footer
|
self._help_after_list = '' # a footer
|
||||||
self._help_list_title = 'These are the commands:' # the title of the list
|
self._help_list_title = 'These are the commands:' # the title of the list
|
||||||
|
self._help_extra_message = 'These commands are only usefull to the developer.'
|
||||||
self.is_reply = True
|
self.is_reply = True
|
||||||
self.command_start = self.command_help
|
self.command_start = self.command_help
|
||||||
|
self.skip_in_help = []
|
||||||
|
|
||||||
|
def command_helpextra(self,update):
|
||||||
|
""" The commands in here are only usefull to the developer of the bot"""
|
||||||
|
command_functions = [attr[1] for attr in getmembers(self, predicate=ismethod) if attr[0][:8] == 'command_' and
|
||||||
|
attr[0] in self.skip_in_help]
|
||||||
|
chat_id = update.message.chat.id
|
||||||
|
help_message = self._help_extra_message + '\n'
|
||||||
|
for command_function in command_functions:
|
||||||
|
if command_function.__doc__ is not None:
|
||||||
|
help_message += ' /' + command_function.__name__[8:] + ' - ' + command_function.__doc__ + '\n'
|
||||||
|
else:
|
||||||
|
help_message += ' /' + command_function.__name__[8:] + ' - ' + '\n'
|
||||||
|
self.bot.sendMessage(chat_id=chat_id, text=help_message)
|
||||||
|
|
||||||
def _generate_help(self):
|
def _generate_help(self):
|
||||||
""" Generate a string which can be send as a help file.
|
""" Generate a string which can be send as a help file.
|
||||||
|
@ -141,17 +162,23 @@ class CommandHandlerWithHelp(CommandHandler):
|
||||||
command to the telegram user.
|
command to the telegram user.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
command_functions = [attr[1] for attr in getmembers(self, predicate=ismethod) if attr[0][:8] == 'command_']
|
|
||||||
help_message = self._help_title + '\n\n'
|
help_message = self._help_title + '\n\n'
|
||||||
help_message += self._help_before_list + '\n\n'
|
help_message += self._help_before_list + '\n\n'
|
||||||
help_message += self._help_list_title + '\n'
|
help_message += self._help_list_title + '\n'
|
||||||
|
help_message += self._generate_help_list()
|
||||||
|
help_message += '\n'
|
||||||
|
help_message += self._help_after_list
|
||||||
|
return help_message
|
||||||
|
|
||||||
|
def _generate_help_list(self):
|
||||||
|
command_functions = [attr[1] for attr in getmembers(self, predicate=ismethod) if attr[0][:8] == 'command_' and
|
||||||
|
attr[0] not in self.skip_in_help]
|
||||||
|
help_message = ''
|
||||||
for command_function in command_functions:
|
for command_function in command_functions:
|
||||||
if command_function.__doc__ is not None:
|
if command_function.__doc__ is not None:
|
||||||
help_message += ' /' + command_function.__name__[8:] + ' - ' + command_function.__doc__ + '\n'
|
help_message += ' /' + command_function.__name__[8:] + ' - ' + command_function.__doc__ + '\n'
|
||||||
else:
|
else:
|
||||||
help_message += ' /' + command_function.__name__[8:] + ' - ' + '\n'
|
help_message += ' /' + command_function.__name__[8:] + ' - ' + '\n'
|
||||||
help_message += '\n'
|
|
||||||
help_message += self._help_after_list
|
|
||||||
return help_message
|
return help_message
|
||||||
|
|
||||||
def _command_not_found(self, update):
|
def _command_not_found(self, update):
|
||||||
|
@ -160,15 +187,45 @@ class CommandHandlerWithHelp(CommandHandler):
|
||||||
reply_to = update.message.message_id
|
reply_to = update.message.message_id
|
||||||
message = 'Sorry, I did not understand the command: {command}. Please see /help for all available commands'
|
message = 'Sorry, I did not understand the command: {command}. Please see /help for all available commands'
|
||||||
if self.is_reply:
|
if self.is_reply:
|
||||||
self.bot.sendMessage(chat_id, message.format(command=update.message.text.split(' ')[0]),
|
self.bot.sendMessage(chat_id=chat_id, text=message.format(command=update.message.text.split(' ')[0]),
|
||||||
reply_to_message_id=reply_to)
|
reply_to_message_id=reply_to)
|
||||||
else:
|
else:
|
||||||
self.bot.sendMessage(chat_id, message.format(command=update.message.text.split(' ')[0]))
|
self.bot.sendMessage(chat_id=chat_id, text=message.format(command=update.message.text.split(' ')[0]))
|
||||||
|
|
||||||
def command_help(self, update):
|
def command_help(self, update):
|
||||||
""" The help file. """
|
""" The help file. """
|
||||||
chat_id = update.message.chat.id
|
chat_id = update.message.chat.id
|
||||||
reply_to = update.message.message_id
|
reply_to = update.message.message_id
|
||||||
message = self._generate_help()
|
message = self._generate_help()
|
||||||
self.bot.sendMessage(chat_id, message, reply_to_message_id=reply_to)
|
self.bot.sendMessage(chat_id=chat_id, text=message, reply_to_message_id=reply_to)
|
||||||
|
|
||||||
|
|
||||||
|
class CommandHandlerWithFatherCommand(CommandHandler):
|
||||||
|
""" A class that creates some commands that are usefull when setting up the bot
|
||||||
|
"""
|
||||||
|
def __init__(self, bot):
|
||||||
|
super(CommandHandlerWithFatherCommand, self).__init__(bot)
|
||||||
|
self.skip_in_help = ['command_father']
|
||||||
|
|
||||||
|
def command_father(self, update):
|
||||||
|
"""Gives you the commands you need to setup this bot. in telegram.me/BotFather"""
|
||||||
|
chat_id = update.message.chat.id
|
||||||
|
self.bot.sendMessage(chat_id=chat_id, text='Send the following messages to telegram.me/BotFather')
|
||||||
|
self.bot.sendMessage(chat_id=chat_id, text='/setcommands')
|
||||||
|
self.bot.sendMessage(chat_id=chat_id, text='@' + self.bot.getMe()['username'])
|
||||||
|
commands = ''
|
||||||
|
command_functions = [attr[1] for attr in getmembers(self, predicate=ismethod) if attr[0][:8] == 'command_' and
|
||||||
|
attr[0] not in self.skip_in_help]
|
||||||
|
|
||||||
|
for command_function in command_functions:
|
||||||
|
if command_function.__doc__ is not None:
|
||||||
|
commands += command_function.__name__[8:] + ' - ' + command_function.__doc__ + '\n'
|
||||||
|
else:
|
||||||
|
commands += command_function.__name__[8:] + ' - ' + '\n'
|
||||||
|
self.bot.sendMessage(chat_id=chat_id, text=commands)
|
||||||
|
|
||||||
|
|
||||||
|
class CommandHandlerWithHelpAndFather(CommandHandlerWithFatherCommand, CommandHandlerWithHelp):
|
||||||
|
"""A class that combines CommandHandlerWithHelp and CommandHandlerWithFatherCommand.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
|
@ -171,6 +171,12 @@ class Message(TelegramObject):
|
||||||
|
|
||||||
return Message(**data)
|
return Message(**data)
|
||||||
|
|
||||||
|
def __getitem__(self, item):
|
||||||
|
if item in self.__dict__.keys():
|
||||||
|
return self.__dict__[item]
|
||||||
|
elif item == 'chat_id':
|
||||||
|
return self.chat.id
|
||||||
|
|
||||||
def to_dict(self):
|
def to_dict(self):
|
||||||
"""
|
"""
|
||||||
Returns:
|
Returns:
|
||||||
|
|
Loading…
Add table
Reference in a new issue