From 2a2b679362e57f7fbf740281573ab71fd4e49a2a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jannes=20H=C3=B6ke?= Date: Tue, 22 Dec 2015 13:23:59 +0100 Subject: [PATCH] improved and renamed examples --- README.rst | 22 ++++-- examples/{updater_bot.py => clibot.py} | 67 ++++++++++--------- .../{updater_simplebot.py => echobot2.py} | 30 ++++----- examples/{ => legacy}/echobot.py | 0 examples/{ => legacy}/roboed.py | 0 5 files changed, 65 insertions(+), 54 deletions(-) rename examples/{updater_bot.py => clibot.py} (75%) rename examples/{updater_simplebot.py => echobot2.py} (74%) rename examples/{ => legacy}/echobot.py (100%) rename examples/{ => legacy}/roboed.py (100%) diff --git a/README.rst b/README.rst index a4d0c1dcf..8388ef302 100644 --- a/README.rst +++ b/README.rst @@ -155,9 +155,9 @@ _`Getting started` View the last release API documentation at: https://core.telegram.org/bots/api ------- +-------------------- _`The Updater class` ------- +-------------------- The ``Updater`` class is the new way to create bots with ``python-telegram-bot``. It provides an easy-to-use interface to the ``telegram.Bot`` by caring about getting new updates from telegram and forwarding them to the ``Dispatcher`` class. We can register handler functions in the ``Dispatcher`` to make our bot react to Telegram commands, messages and even arbitrary updates. @@ -298,9 +298,9 @@ There are many more API methods, to read the full API documentation:: $ pydoc telegram.Bot ------------ +---------- _`Logging` ------------ +---------- You can get logs in your main application by calling `logging` and setting the log level you want:: @@ -318,14 +318,24 @@ _`Examples` Here follows some examples to help you to get your own Bot up to speed: -- `echobot `_ replies back messages. +- `echobot2 `_ replies back messages. -- `roboed `_ talks to `Robô Ed `_. +- `clibot `_ has a command line interface. + +- `Welcome Bot `_ greets everyone who joins a group chat. + +Legacy examples (pre-3.0): + +- `echobot `_ replies back messages. + +- `roboed `_ talks to `Robô Ed `_. - `Simple-Echo-Telegram-Bot `_ simple Python Telegram bot that echoes your input with Flask microframework, setWebhook method, and Google App Engine (optional) - by @sooyhwang. - `DevOps Reaction Bot `_ sends latest or random posts from `DevOps Reaction `_. Running on `Google App Engine `_ (billing has to be enabled for fully Socket API support). +Other notable examples: + - `TwitterForwarderBot `_ forwards you tweets from people that you have subscribed to. ================ diff --git a/examples/updater_bot.py b/examples/clibot.py similarity index 75% rename from examples/updater_bot.py rename to examples/clibot.py index ad87503e0..81ccf81e2 100644 --- a/examples/updater_bot.py +++ b/examples/clibot.py @@ -1,7 +1,7 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- # -# Simple Bot to reply to Telegram messages +# Example Bot to show some of the functionality of the library # Copyright (C) 2015 Leandro Toledo de Souza # # This program is free software: you can redistribute it and/or modify @@ -27,8 +27,8 @@ 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. Usage: -Basic Echobot example, repeats messages. Reply to last chat from the command -line by typing "/reply " +Repeats messages with a delay. +Reply to last chat from the command line by typing "/reply " Type 'stop' on the command line to stop the bot. """ @@ -36,24 +36,20 @@ from telegram import Updater from telegram.dispatcher import run_async from time import sleep import logging -import sys -root = logging.getLogger() -root.setLevel(logging.INFO) - -ch = logging.StreamHandler(sys.stdout) -ch.setLevel(logging.INFO) -formatter = \ - logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') -ch.setFormatter(formatter) -root.addHandler(ch) - -last_chat_id = 0 +# Enable Logging +logging.basicConfig( + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + level=logging.INFO) logger = logging.getLogger(__name__) +# We use this var to save the last chat id, so we can reply to it +last_chat_id = 0 -# Command Handlers + +# Define a few (command) handlers. These usually take the two arguments bot and +# update. Error handlers also receive the raised TelegramError object in error. def start(bot, update): """ Answer in Telegram """ bot.sendMessage(update.message.chat_id, text='Hi!') @@ -87,25 +83,20 @@ def message(bot, update, **kwargs): """ Example for an asynchronous handler. It's not guaranteed that replies will be in order when using @run_async. Also, you have to include **kwargs in - your parameter list. + your parameter list. The kwargs contain all optional parameters that are """ - print(kwargs) - sleep(2) # IO-heavy operation here bot.sendMessage(update.message.chat_id, text='Echo: %s' % update.message.text) -def error(bot, update, error): - """ Print error to console """ - logger.warn('Update %s caused error %s' % (update, error)) - - +# These handlers are for updates of type str. We use them to react to inputs +# on the command line interface def cli_reply(bot, update, args): """ - For any update of type telegram.Update or str, you can get the argument - list by appending args to the function parameters. + 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. Here, we reply to the last active chat with the text after the command. """ if last_chat_id is not 0: @@ -117,6 +108,9 @@ def cli_noncommand(bot, update, update_queue): 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. Here, we put the input string back into the queue, but as a command. + + To learn more about those optional handler parameters, read: + http://python-telegram-bot.readthedocs.org/en/latest/telegram.dispatcher.html """ update_queue.put('/%s' % update) @@ -125,28 +119,39 @@ def unknown_cli_command(bot, update): logger.warn("Command not found: %s" % update) +def error(bot, update, error): + """ Print error to console """ + logger.warn('Update %s caused error %s' % (update, error)) + + def main(): # Create the EventHandler and pass it your bot's token. - token = 'token' - updater = Updater(token, workers=2) + token = 'TOKEN' + updater = Updater(token, workers=10) # Get the dispatcher to register handlers dp = updater.dispatcher + # This is how we add handlers for Telegram messages dp.addTelegramCommandHandler("start", start) dp.addTelegramCommandHandler("help", help) dp.addUnknownTelegramCommandHandler(unknown_command) + # Message handlers only receive updates that don't contain commands dp.addTelegramMessageHandler(message) + # Regex handlers will receive all updates on which their regex matches dp.addTelegramRegexHandler('.*', any_message) + # String handlers work pretty much the same dp.addStringCommandHandler('reply', cli_reply) dp.addUnknownStringCommandHandler(unknown_cli_command) dp.addStringRegexHandler('[^/].*', cli_noncommand) + # All TelegramErrors are caught for you and delivered to the error + # handler(s). Other types of Errors are not caught. dp.addErrorHandler(error) # Start the Bot and store the update Queue, so we can insert updates - update_queue = updater.start_polling(poll_interval=0.1, timeout=20) + update_queue = updater.start_polling(poll_interval=0.1, timeout=10) ''' # Alternatively, run with webhook: @@ -178,9 +183,9 @@ def main(): updater.stop() break - # else, put the text into the update queue + # else, put the text into the update queue to be handled by our handlers elif len(text) > 0: - update_queue.put(text) # Put command into queue + update_queue.put(text) if __name__ == '__main__': main() diff --git a/examples/updater_simplebot.py b/examples/echobot2.py similarity index 74% rename from examples/updater_simplebot.py rename to examples/echobot2.py index 16144226f..8fab75902 100644 --- a/examples/updater_simplebot.py +++ b/examples/echobot2.py @@ -23,32 +23,27 @@ This Bot uses the Updater class to handle the bot. First, a few handler functions are defined. Then, those functions are passed to the Dispatcher and registered at their respective places. -Then, the bot is started and the CLI-Loop is entered. +Then, the bot is started and runs until we press Ctrl-C on the command line. Usage: Basic Echobot example, repeats messages. -Type 'stop' on the command line to stop the bot. +Press Ctrl-C on the command line or send a signal to the process to stop the +bot. """ from telegram import Updater import logging -import sys # Enable logging -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) +logging.basicConfig( + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + level=logging.INFO) logger = logging.getLogger(__name__) -# Command Handlers +# Define a few command handlers. These usually take the two arguments bot and +# update. Error handlers also receive the raised TelegramError object in error. def start(bot, update): bot.sendMessage(update.message.chat_id, text='Hi!') @@ -79,14 +74,15 @@ def main(): # on noncommand i.e message - echo the message on Telegram dp.addTelegramMessageHandler(echo) - # on error - print error to stdout + # log all errors dp.addErrorHandler(error) # Start the Bot - updater.start_polling(timeout=5) + updater.start_polling() - # Run the bot until the user presses Ctrl-C or the process receives SIGINT, - # SIGTERM or SIGABRT + # 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__': diff --git a/examples/echobot.py b/examples/legacy/echobot.py similarity index 100% rename from examples/echobot.py rename to examples/legacy/echobot.py diff --git a/examples/roboed.py b/examples/legacy/roboed.py similarity index 100% rename from examples/roboed.py rename to examples/legacy/roboed.py