python-telegram-bot/examples/eventhandler_bot.py

155 lines
4.4 KiB
Python
Raw Normal View History

2015-11-05 13:52:57 +01:00
#!/usr/bin/env python
"""
This Bot uses the BotEventHandler class to handle the bot.
First, a few handler functions are defined. Then, those functions are passed to
2015-11-22 14:47:38 +01:00
the Dispatcher and registered at their respective places.
2015-11-05 13:52:57 +01:00
Then, the bot is started and the CLI-Loop is entered, where all text inputs are
inserted into the update queue for the bot to handle.
2015-11-15 20:13:03 +01:00
Usage:
Basic Echobot example, repeats messages. Reply to last chat from the command
line by typing "/reply <text>"
Type 'stop' on the command line to stop the bot.
2015-11-05 13:52:57 +01:00
"""
2015-11-22 19:15:37 +01:00
from telegram import Updater
from telegram.dispatcher import run_async
2015-11-05 16:01:25 +01:00
from time import sleep
2015-11-15 19:21:35 +01:00
import logging
import sys
root = logging.getLogger()
root.setLevel(logging.INFO)
ch = logging.StreamHandler(sys.stdout)
2015-11-22 19:15:37 +01:00
ch.setLevel(logging.INFO)
formatter = \
logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
2015-11-15 19:21:35 +01:00
ch.setFormatter(formatter)
root.addHandler(ch)
2015-11-05 13:52:57 +01:00
last_chat_id = 0
2015-11-22 19:15:37 +01:00
logger = logging.getLogger(__name__)
2015-11-11 13:32:11 +01:00
# Command Handlers
2015-11-22 19:15:37 +01:00
def start(bot, update):
""" Answer in Telegram """
2015-11-05 13:52:57 +01:00
bot.sendMessage(update.message.chat_id, text='Hi!')
2015-11-11 13:32:11 +01:00
2015-11-22 19:15:37 +01:00
def help(bot, update):
""" Answer in Telegram """
2015-11-05 13:52:57 +01:00
bot.sendMessage(update.message.chat_id, text='Help!')
2015-11-11 13:32:11 +01:00
2015-11-22 19:15:37 +01:00
def any_message(bot, update):
""" Print to console """
# Save last chat_id to use in reply handler
global last_chat_id
last_chat_id = update.message.chat_id
logger.info("New message\nFrom: %s\nchat_id: %d\nText: %s" %
(update.message.from_user,
update.message.chat_id,
update.message.text))
2015-11-05 13:52:57 +01:00
2015-11-11 13:32:11 +01:00
2015-11-22 19:15:37 +01:00
def unknown_command(bot, update):
""" Answer in Telegram """
2015-11-05 13:52:57 +01:00
bot.sendMessage(update.message.chat_id, text='Command not recognized!')
2015-11-06 00:24:01 +01:00
2015-11-05 16:01:25 +01:00
@run_async
2015-11-22 19:15:37 +01:00
def message(bot, update):
2015-11-05 16:01:25 +01:00
"""
Example for an asynchronous handler. It's not guaranteed that replies will
2015-11-15 17:37:01 +01:00
be in order when using @run_async.
2015-11-05 16:01:25 +01:00
"""
2015-11-22 19:15:37 +01:00
2015-11-05 16:01:25 +01:00
sleep(2) # IO-heavy operation here
2015-11-22 19:15:37 +01:00
bot.sendMessage(update.message.chat_id, text='Echo: %s' %
update.message.text)
2015-11-05 13:52:57 +01:00
2015-11-11 13:32:11 +01:00
2015-11-22 19:15:37 +01:00
def error(bot, update, error):
""" Print error to console """
logger.warn('Update %s caused error %s' % (update, error))
2015-11-05 13:52:57 +01:00
2015-11-11 13:32:11 +01:00
2015-11-22 19:15:37 +01:00
def cli_reply(bot, update, args):
2015-11-22 13:58:40 +01:00
"""
For any update of type telegram.Update or str, you can get the argument
list by appending args to the function parameters.
2015-11-22 19:15:37 +01:00
Here, we reply to the last active chat with the text after the command.
2015-11-22 13:58:40 +01:00
"""
2015-11-05 13:52:57 +01:00
if last_chat_id is not 0:
2015-11-22 13:58:40 +01:00
bot.sendMessage(chat_id=last_chat_id, text=' '.join(args))
2015-11-05 13:52:57 +01:00
2015-11-11 13:32:11 +01:00
2015-11-22 19:15:37 +01:00
def cli_noncommand(bot, update, update_queue):
2015-11-15 17:37:01 +01:00
"""
2015-11-22 13:58:40 +01:00
You can also get the update queue as an argument in any handler by
appending it to the argument list. Be careful with this though.
2015-11-22 19:15:37 +01:00
Here, we put the input string back into the queue, but as a command.
2015-11-15 17:37:01 +01:00
"""
update_queue.put('/%s' % update)
2015-11-22 19:15:37 +01:00
def unknown_cli_command(bot, update):
logger.warn("Command not found: %s" % update)
2015-11-05 13:52:57 +01:00
2015-11-11 13:32:11 +01:00
2015-11-05 13:52:57 +01:00
def main():
2015-11-15 17:37:01 +01:00
# Create the EventHandler and pass it your bot's token.
2015-11-22 19:15:37 +01:00
updater = Updater("TOKEN", workers=2)
2015-11-05 13:52:57 +01:00
2015-11-22 14:47:38 +01:00
# Get the dispatcher to register handlers
2015-11-22 19:15:37 +01:00
dp = updater.dispatcher
2015-11-05 13:52:57 +01:00
2015-11-22 19:15:37 +01:00
dp.addTelegramCommandHandler("start", start)
dp.addTelegramCommandHandler("help", help)
dp.addUnknownTelegramCommandHandler(unknown_command)
dp.addTelegramMessageHandler(message)
dp.addTelegramRegexHandler('.*', any_message)
2015-11-15 17:37:01 +01:00
2015-11-22 19:15:37 +01:00
dp.addStringCommandHandler('reply', cli_reply)
dp.addUnknownStringCommandHandler(unknown_cli_command)
dp.addStringRegexHandler('[^/].*', cli_noncommand)
2015-11-05 13:52:57 +01:00
2015-11-22 19:15:37 +01:00
dp.addErrorHandler(error)
2015-11-05 13:52:57 +01:00
2015-11-22 19:15:37 +01:00
# Start the Bot and store the update Queue, so we can insert updates
update_queue = updater.start_polling(poll_interval=0.1, timeout=20)
2015-11-17 00:30:21 +01:00
'''
# Alternatively, run with webhook:
2015-11-22 19:15:37 +01:00
update_queue = updater.start_webhook('example.com',
443,
'cert.pem',
'key.key',
listen='0.0.0.0')
2015-11-17 00:30:21 +01:00
'''
2015-11-22 14:47:38 +01:00
2015-11-05 13:52:57 +01:00
# Start CLI-Loop
while True:
2015-11-16 20:35:27 +01:00
try:
2015-11-05 13:52:57 +01:00
text = raw_input()
2015-11-16 20:35:27 +01:00
except NameError:
2015-11-05 13:52:57 +01:00
text = input()
2015-11-15 17:37:01 +01:00
# Gracefully stop the event handler
if text == 'stop':
2015-11-22 19:15:37 +01:00
updater.stop()
2015-11-15 17:37:01 +01:00
break
# else, put the text into the update queue
elif len(text) > 0:
2015-11-05 13:52:57 +01:00
update_queue.put(text) # Put command into queue
if __name__ == '__main__':
main()