python-telegram-bot/examples/eventhandler_simplebot.py

77 lines
1.8 KiB
Python
Raw Normal View History

2015-11-15 20:02:09 +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
2015-11-22 14:47:38 +01:00
the Dispatcher and registered at their respective places.
2015-11-15 20:02:09 +01:00
Then, the bot is started and the CLI-Loop is entered.
2015-11-15 20:13:03 +01:00
Usage:
Basic Echobot example, repeats messages.
Type 'stop' on the command line to stop the bot.
2015-11-15 20:02:09 +01:00
"""
2015-11-22 19:15:37 +01:00
from telegram import Updater
2015-11-15 20:02:09 +01:00
import logging
import sys
2015-11-22 19:15:37 +01:00
from time import sleep
2015-11-15 20:02:09 +01:00
# Enable logging
root = logging.getLogger()
root.setLevel(logging.INFO)
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.DEBUG)
2015-11-22 19:15:37 +01:00
formatter = \
logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
2015-11-15 20:02:09 +01:00
ch.setFormatter(formatter)
root.addHandler(ch)
2015-11-22 19:20:16 +01:00
logger = logging.getLogger(__name__)
2015-11-15 20:02:09 +01:00
# Command Handlers
def start(bot, update):
bot.sendMessage(update.message.chat_id, text='Hi!')
def help(bot, update):
bot.sendMessage(update.message.chat_id, text='Help!')
def echo(bot, update):
bot.sendMessage(update.message.chat_id, text=update.message.text)
def error(bot, update, error):
2015-11-22 19:20:16 +01:00
logger.warn('Update "%s" caused error "%s"' % (update, error))
2015-11-15 20:02:09 +01:00
def main():
# Create the EventHandler and pass it your bot's token.
2015-11-22 19:15:37 +01:00
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
2015-11-22 14:47:38 +01:00
dp.addTelegramCommandHandler("start", start)
dp.addTelegramCommandHandler("help", help)
2015-11-15 20:02:09 +01:00
# on noncommand i.e message - echo the message on Telegram
2015-11-22 14:47:38 +01:00
dp.addTelegramMessageHandler(echo)
2015-11-15 20:02:09 +01:00
# on error - print error to stdout
2015-11-22 14:47:38 +01:00
dp.addErrorHandler(error)
2015-11-15 20:02:09 +01:00
# Start the Bot
2015-11-22 19:15:37 +01:00
updater.start_polling(timeout=5)
2015-11-23 17:40:39 +01:00
# Run the bot until the user presses Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT
2015-11-22 19:15:37 +01:00
updater.idle()
2015-11-15 20:02:09 +01:00
if __name__ == '__main__':
main()