python-telegram-bot/examples/eventhandler_bot.py

156 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
the Broadcaster and registered at their respective places.
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
"""
import sys
2015-11-05 16:01:25 +01:00
from telegram import BotEventHandler
2015-11-11 13:32:11 +01:00
from telegram.broadcaster 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)
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
root.addHandler(ch)
2015-11-05 13:52:57 +01:00
last_chat_id = 0
2015-11-11 13:32:11 +01:00
2015-11-05 13:52:57 +01:00
def removeCommand(text):
return ' '.join(text.split(' ')[1:])
2015-11-11 13:32:11 +01:00
# Command Handlers
2015-11-05 13:52:57 +01:00
def startCommandHandler(bot, update):
bot.sendMessage(update.message.chat_id, text='Hi!')
2015-11-11 13:32:11 +01:00
2015-11-05 13:52:57 +01:00
def helpCommandHandler(bot, update):
bot.sendMessage(update.message.chat_id, text='Help!')
2015-11-11 13:32:11 +01:00
2015-11-05 13:52:57 +01:00
def anyMessageHandler(bot, update):
print("chat_id: %d\nFrom: %s\nText: %s" %
(update.message.chat_id, str(update.message.from_user),
update.message.text))
2015-11-11 13:32:11 +01:00
2015-11-05 13:52:57 +01:00
def unknownCommandHandler(bot, update):
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-05 13:52:57 +01:00
def messageHandler(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
"""
# Save last chat_id to use in reply handler
2015-11-05 13:52:57 +01:00
global last_chat_id
last_chat_id = update.message.chat_id
2015-11-05 16:01:25 +01:00
sleep(2) # IO-heavy operation here
2015-11-05 13:52:57 +01:00
bot.sendMessage(update.message.chat_id, text=update.message.text)
2015-11-11 13:32:11 +01:00
2015-11-15 19:14:12 +01:00
def errorHandler(bot, update, error):
print('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-05 13:52:57 +01:00
def CLIReplyCommandHandler(bot, update):
if last_chat_id is not 0:
bot.sendMessage(chat_id=last_chat_id, text=removeCommand(update))
2015-11-11 13:32:11 +01:00
2015-11-15 17:37:01 +01:00
def anyCLIHandler(bot, update, update_queue):
"""
You can get the update queue as an argument in any handler just by adding
it to the argument list. Be careful with this though.
"""
update_queue.put('/%s' % update)
2015-11-05 13:52:57 +01:00
def unknownCLICommandHandler(bot, update):
print("Command not found: %s" % update)
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.
eh = BotEventHandler("TOKEN", workers=2)
2015-11-05 13:52:57 +01:00
2015-11-11 13:32:11 +01:00
# Get the broadcaster to register handlers
bc = eh.broadcaster
2015-11-05 13:52:57 +01:00
# on different commands - answer in Telegram
2015-11-11 13:32:11 +01:00
bc.addTelegramCommandHandler("start", startCommandHandler)
bc.addTelegramCommandHandler("help", helpCommandHandler)
2015-11-05 13:52:57 +01:00
# on regex match - print all messages to stdout
2015-11-15 17:37:01 +01:00
bc.addTelegramRegexHandler('.*', anyMessageHandler)
2015-11-05 13:52:57 +01:00
# on CLI commands - type "/reply text" in terminal to reply to the last
# active chat
2015-11-11 13:32:11 +01:00
bc.addStringCommandHandler('reply', CLIReplyCommandHandler)
2015-11-05 13:52:57 +01:00
# on unknown commands - answer on Telegram
2015-11-11 13:32:11 +01:00
bc.addUnknownTelegramCommandHandler(unknownCommandHandler)
2015-11-05 13:52:57 +01:00
# on unknown CLI commands - notify the user
2015-11-11 13:32:11 +01:00
bc.addUnknownStringCommandHandler(unknownCLICommandHandler)
2015-11-05 13:52:57 +01:00
2015-11-15 17:37:01 +01:00
# on any CLI message that is not a command - resend it as a command
bc.addStringRegexHandler('[^/].*', anyCLIHandler)
2015-11-05 13:52:57 +01:00
# on noncommand i.e message - echo the message on Telegram
2015-11-11 13:32:11 +01:00
bc.addTelegramMessageHandler(messageHandler)
2015-11-05 13:52:57 +01:00
# on error - print error to stdout
2015-11-11 13:32:11 +01:00
bc.addErrorHandler(errorHandler)
2015-11-05 13:52:57 +01:00
# Start the Bot and store the update Queue,
# so we can insert updates ourselves
update_queue = eh.start_polling(poll_interval=0.1, timeout=20)
2015-11-17 00:30:21 +01:00
'''
# Alternatively, run with webhook:
update_queue = eh.start_webhook('example.com', 443, 'cert.pem', 'key.key',
listen='0.0.0.0')
'''
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':
eh.stop()
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()