Created
August 28, 2016 09:53
-
-
Save liiight/e38c019bfedb97d4463603fda46175e0 to your computer and use it in GitHub Desktop.
Argparse Telegram bot
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import argparse | |
from telegram.ext import Updater | |
from telegram.ext.commandhandler import CommandHandler | |
import logging | |
# Enable logging | |
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', | |
level=logging.INFO) | |
logger = logging.getLogger(__name__) | |
class ArgumentParser(argparse.ArgumentParser): | |
""" | |
The default (and only) argparse behavior is to throw error to sys.stderr via the error method. | |
""" | |
def error(self, message): | |
raise ParserError(message) | |
class ParserError(Exception): pass | |
# Example of standard usage | |
command_1_parser = ArgumentParser(description='Command 1 Parser') | |
command_1_parser.add_argument('-f', '--foo') | |
command_1_parser.add_argument('-b', '--bar', required=True) | |
# Using subparsers, as in postional arguments, provides a more natural way to use this via a chat | |
command_2_parser = ArgumentParser(description='Command 2 Parser') | |
subparsers = command_2_parser.add_subparsers() | |
foo_parser = subparsers.add_parser('foo') | |
foo_parser.add_argument('-b') | |
def command_1(bot, update, args): | |
try: | |
options = command_1_parser.parse_args(args) | |
message = repr(options) | |
except ParserError as e: | |
message = 'ERROR!: %s' % str(e) | |
bot.sendMessage(update.message.chat_id, text=message) | |
def command_2(bot, update, args): | |
try: | |
options = command_2_parser.parse_args(args) | |
message = repr(options) | |
except ParserError as e: | |
message = 'ERROR!: %s' % str(e) | |
bot.sendMessage(update.message.chat_id, text=message) | |
def error(bot, update, error): | |
logger.warn('Update "%s" caused error "%s"' % (update, error)) | |
def main(): | |
# Create the EventHandler and pass it your bot's token. | |
updater = Updater("TOKEN") | |
# Get the dispatcher to register handlers | |
dp = updater.dispatcher | |
dp.add_handler(CommandHandler('command1', command_1, pass_args=True)) | |
dp.add_handler(CommandHandler('command2', command_2, pass_args=True)) | |
dp.add_error_handler(error) | |
# Start the Bot | |
updater.start_polling() | |
# Run the bot until the you presses Ctrl-C or the process receives SIGINT, | |
# SIGTERM or SIGABRT. This should be used most of the time, since | |
# start_polling() is non-blocking and will stop the bot gracefully. | |
updater.idle() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment