Saturday, March 18, 2017
Python Telegram Bot
Installation
pip3 install python-telegram-bot
Get Access token
- Talk to @botfather
- ...
Introduction to Library
Updater: fetch update from telegram and forwards to dispatcher
Updater object
- Dispatcher object
- link with Queue
Import stuffs
from telegram.ext import Updater
from telegram.ext import CommandHandler, MessageHandler, Filters
import logging
Make Updater and Dispatcher
updater = Updater(token='TOKEN')
dispatcher = updater.dispatcher
Start and Stop Updater
updater.start_polling()
updater.stop()
Make Logs, To know the progress
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
Define a function to process /start command
def start(bot, update):
bot.sendMessage(chat_id=update.message.chat_id, text="I'm a bot")
Register the function to a Handler, and assign to Dispatcher in Updater
start_handler = CommandHandler('start', start)
dispatcher.add_handler(start_handler)
Define a function to echo non-command messages
def echo(bot, update):
bot.sendMessage(chat_id=update.message.chat_id, text=update.message.text)
Register the function to a Handler, and assign to Dispatcher in Updater
echo_handler = MessageHandler(Filters.text, echo)
dispatcher.add_handler(echo_handler)
Define a function to /caps the message
def caps(bot, update, args):
text_caps = ' '.join(args).upper()
bot.sendMessage(chat_id=update.message.chat_id, text=text_caps)
Register the function to a Handler, and assign to Dispatcher in Updater
caps_handler = CommandHandler('caps', caps, pass_args=True)
dispatcher.add_handler(caps_handler)
Define a function for /unknown commands
def unknown(bot, update):
bot.sendMessage(chat_id=update.message.chat_id, text="Sorry, i don't understand")
Register the function to a Handler, and assign to Dispatcher in Updater
unknown_handler = MessageHandler(Filters.command, unknown)
dispatcher.add_handler(caps_handler)
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment