python-telegram-bot/examples/clibot.py

178 lines
5.8 KiB
Python
Raw Normal View History

2015-11-05 13:52:57 +01:00
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
2015-12-22 13:23:59 +01:00
# Example Bot to show some of the functionality of the library
# This program is dedicated to the public domain under the CC0 license.
2015-11-05 13:52:57 +01:00
"""
2015-11-24 21:06:55 +01:00
This Bot uses the Updater class to handle the bot.
2015-11-05 13:52:57 +01:00
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:
2015-12-22 13:23:59 +01:00
Repeats messages with a delay.
Reply to last chat from the command line by typing "/reply <text>"
2015-11-15 20:13:03 +01:00
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
2015-12-22 13:23:59 +01:00
# Enable Logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
2015-11-15 19:21:35 +01:00
2015-12-22 13:23:59 +01:00
logger = logging.getLogger(__name__)
2015-11-05 13:52:57 +01:00
2015-12-22 13:23:59 +01:00
# We use this var to save the last chat id, so we can reply to it
2015-11-05 13:52:57 +01:00
last_chat_id = 0
2015-11-24 21:06:55 +01:00
2015-12-22 13:23:59 +01:00
# Define a few (command) handlers. These usually take the two arguments bot and
# update. Error handlers also receive the raised TelegramError object in error.
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-12-21 19:36:17 +01:00
def message(bot, update, **kwargs):
2015-11-05 16:01:25 +01:00
"""
Example for an asynchronous handler. It's not guaranteed that replies will
2015-12-21 19:36:17 +01:00
be in order when using @run_async. Also, you have to include **kwargs in
2015-12-22 13:23:59 +01:00
your parameter list. The kwargs contain all optional parameters that are
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-12-22 13:23:59 +01:00
# These handlers are for updates of type str. We use them to react to inputs
# on the command line interface
2015-11-22 19:15:37 +01:00
def cli_reply(bot, update, args):
2015-11-22 13:58:40 +01:00
"""
2015-12-22 13:23:59 +01:00
For any update of type telegram.Update or str that contains a command, 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-12-22 13:23:59 +01:00
To learn more about those optional handler parameters, read:
http://python-telegram-bot.readthedocs.org/en/latest/telegram.dispatcher.html
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-12-22 13:23:59 +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
def main():
2015-11-15 17:37:01 +01:00
# Create the EventHandler and pass it your bot's token.
2015-12-22 13:23:59 +01:00
token = 'TOKEN'
updater = Updater(token, workers=10)
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-12-22 13:23:59 +01:00
# This is how we add handlers for Telegram messages
2015-11-22 19:15:37 +01:00
dp.addTelegramCommandHandler("start", start)
dp.addTelegramCommandHandler("help", help)
dp.addUnknownTelegramCommandHandler(unknown_command)
2015-12-22 13:23:59 +01:00
# Message handlers only receive updates that don't contain commands
2015-11-22 19:15:37 +01:00
dp.addTelegramMessageHandler(message)
2015-12-22 13:23:59 +01:00
# Regex handlers will receive all updates on which their regex matches
2015-11-22 19:15:37 +01:00
dp.addTelegramRegexHandler('.*', any_message)
2015-11-15 17:37:01 +01:00
2015-12-22 13:23:59 +01:00
# String handlers work pretty much the same
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-12-22 13:23:59 +01:00
# All TelegramErrors are caught for you and delivered to the error
# handler(s). Other types of Errors are not caught.
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
2015-12-22 13:23:59 +01:00
update_queue = updater.start_polling(poll_interval=0.1, timeout=10)
2015-12-01 18:06:42 +01:00
2015-11-17 00:30:21 +01:00
'''
# Alternatively, run with webhook:
2015-12-01 18:06:42 +01:00
updater.bot.setWebhook(webhook_url='https://example.com/%s' % token,
certificate=open('cert.pem', 'rb'))
2015-12-01 18:06:42 +01:00
update_queue = updater.start_webhook('0.0.0.0',
2015-11-22 19:15:37 +01:00
443,
2015-12-01 18:06:42 +01:00
url_path=token,
cert='cert.pem',
key='key.key')
# Or, if SSL is handled by a reverse proxy, the webhook URL is already set
# and the reverse proxy is configured to deliver directly to port 6000:
update_queue = updater.start_webhook('0.0.0.0',
6000)
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
2015-12-22 13:23:59 +01:00
# else, put the text into the update queue to be handled by our handlers
2015-11-15 17:37:01 +01:00
elif len(text) > 0:
2015-12-22 13:23:59 +01:00
update_queue.put(text)
2015-11-05 13:52:57 +01:00
if __name__ == '__main__':
main()