python-telegram-bot/examples/echobot2.py

81 lines
2.3 KiB
Python
Raw Normal View History

2015-11-15 20:02:09 +01:00
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Simple Bot to reply to Telegram messages.
This program is dedicated to the public domain under the CC0 license.
2015-11-24 21:06:55 +01:00
This Bot uses the Updater class to handle the bot.
2015-11-15 20:02:09 +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-12-22 13:23:59 +01:00
Then, the bot is started and runs until we press Ctrl-C on the command line.
2015-11-15 20:02:09 +01:00
2015-11-15 20:13:03 +01:00
Usage:
Basic Echobot example, repeats messages.
2015-12-22 13:23:59 +01:00
Press Ctrl-C on the command line or send a signal to the process to stop the
bot.
2015-11-15 20:02:09 +01:00
"""
Context based callbacks (#1100) See https://github.com/python-telegram-bot/python-telegram-bot/wiki/Transition-guide-to-Version-11.0 under Context based callbacks and Filters in handlers for a good guide on the changes in this commit. * Change handlers so context is supported * Attempt to make parameter "guessing" work on py < 3.5 * Document use_context in all handlers * Add Context to docs * Minor fixes to context handling * Add tests for context stuff * Allow the signature check to work on py<3.5 with methods * Fix order of operations * Address most issues raised in CR * Make CommandHandler no longer support filter lists * Fix indent (pycharm can be an arse sometimes) * Improve readability in conversationhandler * Make context have Match instead of groups & groupdict * Remove filter list support from messagehandler too * Small fix to StringCommandHandler * More small fixes to handlers * Amend CHANGES * Fix tests and fix bugs raised by tests * Don't allow users to ignore errors without messing with the warning filters themselves * Ignore our own deprecation warnings when testing * Skipping deprecationwarning test on py2 * Forgot some changes * Handler: Improved documentation and text of deprecation warnings * HandlerContext: Keep only dispatcher and use properties; improved doc * Complete fixing the documentation. - Fixes per Eldinnie's comments. - Fixes per warnings when running sphinx. * Some small doc fixes (interlinks and optionals) * Change add_error_handler to use HandlerContext too * More context based changes Context Based Handlers -> Context Based Callbacks No longer use_context args on every single Handler Instead set dispatcher/updater .use_context=True to use Works with - Handler callbacks - Error handler callbacks - Job callbacks Change examples to context based callbacks so new users are not confused Rename and move the context object from Handlers.HandlerContext to CallbackContext, since it doesn't only apply to handlers anymore. Fix tests by adding a new fixture `cpd` which is a dispatcher with use_context=True * Forgot about conversationhandler * Forgot jobqueue * Add tests for callbackcontext & for context based callback job * Fix as per review :)
2018-05-21 15:00:47 +02:00
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import logging
Context based callbacks (#1100) See https://github.com/python-telegram-bot/python-telegram-bot/wiki/Transition-guide-to-Version-11.0 under Context based callbacks and Filters in handlers for a good guide on the changes in this commit. * Change handlers so context is supported * Attempt to make parameter "guessing" work on py < 3.5 * Document use_context in all handlers * Add Context to docs * Minor fixes to context handling * Add tests for context stuff * Allow the signature check to work on py<3.5 with methods * Fix order of operations * Address most issues raised in CR * Make CommandHandler no longer support filter lists * Fix indent (pycharm can be an arse sometimes) * Improve readability in conversationhandler * Make context have Match instead of groups & groupdict * Remove filter list support from messagehandler too * Small fix to StringCommandHandler * More small fixes to handlers * Amend CHANGES * Fix tests and fix bugs raised by tests * Don't allow users to ignore errors without messing with the warning filters themselves * Ignore our own deprecation warnings when testing * Skipping deprecationwarning test on py2 * Forgot some changes * Handler: Improved documentation and text of deprecation warnings * HandlerContext: Keep only dispatcher and use properties; improved doc * Complete fixing the documentation. - Fixes per Eldinnie's comments. - Fixes per warnings when running sphinx. * Some small doc fixes (interlinks and optionals) * Change add_error_handler to use HandlerContext too * More context based changes Context Based Handlers -> Context Based Callbacks No longer use_context args on every single Handler Instead set dispatcher/updater .use_context=True to use Works with - Handler callbacks - Error handler callbacks - Job callbacks Change examples to context based callbacks so new users are not confused Rename and move the context object from Handlers.HandlerContext to CallbackContext, since it doesn't only apply to handlers anymore. Fix tests by adding a new fixture `cpd` which is a dispatcher with use_context=True * Forgot about conversationhandler * Forgot jobqueue * Add tests for callbackcontext & for context based callback job * Fix as per review :)
2018-05-21 15:00:47 +02:00
2015-11-15 20:02:09 +01:00
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
2015-11-15 20:02:09 +01:00
2015-11-22 19:20:16 +01:00
logger = logging.getLogger(__name__)
2015-11-15 20:02:09 +01:00
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.
def start(bot, update):
"""Send a message when the command /start is issued."""
update.message.reply_text('Hi!')
2015-11-15 20:02:09 +01:00
def help(bot, update):
"""Send a message when the command /help is issued."""
update.message.reply_text('Help!')
2015-11-15 20:02:09 +01:00
def echo(bot, update):
"""Echo the user message."""
update.message.reply_text(update.message.text)
2015-11-15 20:02:09 +01:00
def error(bot, update, error):
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, error)
2015-11-15 20:02:09 +01:00
def main():
"""Start the bot."""
# Create the EventHandler and pass it your bot's token.
updater = Updater("TOKEN")
2015-11-15 20:02:09 +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-15 20:02:09 +01:00
# on different commands - answer in Telegram
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", help))
2015-11-15 20:02:09 +01:00
# on noncommand i.e message - echo the message on Telegram
2016-10-25 19:51:56 +02:00
dp.add_handler(MessageHandler(Filters.text, echo))
2015-11-15 20:02:09 +01:00
2015-12-22 13:23:59 +01:00
# log all errors
dp.add_error_handler(error)
2015-11-15 20:02:09 +01:00
# Start the Bot
2015-12-22 13:23:59 +01:00
updater.start_polling()
2015-11-22 19:15:37 +01:00
# Run the bot until you press Ctrl-C or the process receives SIGINT,
2015-12-22 13:23:59 +01:00
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
2015-11-22 19:15:37 +01:00
updater.idle()
2015-11-15 20:02:09 +01:00
2015-11-15 20:02:09 +01:00
if __name__ == '__main__':
main()