python-telegram-bot/examples/clibot.py

172 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
"""
2016-04-16 19:25:08 +02:00
from telegram.ext import Updater, StringCommandHandler, StringRegexHandler, \
MessageHandler, CommandHandler, RegexHandler, filters
2016-03-19 16:39:35 +01:00
from telegram.ext.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
2016-04-16 19:25:08 +02:00
# Define a few (command) handler callback functions. 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-05 16:01:25 +01:00
@run_async
2016-04-16 19:25:08 +02: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-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
2016-04-16 19:25:08 +02:00
To learn more about those optional handler parameters, read the
documentation of the Handler classes.
2015-11-15 17:37:01 +01:00
"""
update_queue.put('/%s' % update)
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
2016-04-16 19:25:08 +02:00
dp.addHandler(CommandHandler("start", start))
dp.addHandler(CommandHandler("help", help))
2015-12-22 13:23:59 +01:00
# Message handlers only receive updates that don't contain commands
2016-04-16 19:25:08 +02:00
dp.addHandler(MessageHandler([filters.TEXT], message))
# Regex handlers will receive all updates on which their regex matches,
# but we have to add it in a separate group, since in one group,
# only one handler will be executed
dp.addHandler(RegexHandler('.*', any_message), group='log')
# String handlers work pretty much the same. Note that we have to tell
# the handler to pass the args or update_queue parameter
dp.addHandler(StringCommandHandler('reply', cli_reply, pass_args=True))
dp.addHandler(StringRegexHandler('[^/].*', cli_noncommand,
pass_update_queue=True))
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
2016-04-16 19:25:08 +02:00
update_queue = updater.start_polling(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
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',
2016-04-16 19:25:08 +02:00
key='key.key',
webhook_url='https://example.com/%s'
% token)
2015-12-01 18:06:42 +01:00
# 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:
2016-04-16 19:25:08 +02:00
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()