Telegram chatbot is easy and fun

This evening I tried the Telegram chatbot API. I came to know about Telegram and their API quite long time ago and at last I was able to make some time to play with it. I found is super easy and fun to use. I implemented and run my first chatbot in less than 10 minutes. The code looks so good to me that I decided to make it a boilerplate so that I can make and run new future chatbots without any delay. The chatbot boilerplate is available on github.

from telegram.ext import Updater
from telegram.ext import CommandHandler
from telegram.ext import MessageHandler, Filters
from datetime import datetime
import logging


updater = Updater(token=TOKEN)
dispatcher = updater.dispatcher

logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)

# Will be called everytime /start command is received
def start(bot, update):
    bot.send_message(chat_id=update.message.chat_id, text='So, you have cravings for movie?')

# The real chat method which will reply acccordingly
def chat(bot, update):
    # TODO implement get_reply
    # reply = get_reply(update.message.text)
    reply = 'I have received: {}'.format(update.message.text)
    bot.send_message(chat_id=update.message.chat_id, text=reply)

# A command method to capitalize the message
def caps(bot, update, args):
    text_caps = ' '.join(args).upper()
    bot.send_message(update.message.chat_id, text=text_caps)

# A command method to return current datetime
def date(bot, update):
    curr_time ='%B %d, %Y %H:%M')
    bot.send_message(update.message.chat_id, text=curr_time)

# Unknown command handler
def unknown(bot, update):
    bot.send_message(chat_id=update.message.chat_id, text="Sorry, I didn't understand that command")

start_handler = CommandHandler('start', start)

chat_handler = MessageHandler(Filters.text, chat)

caps_handler = CommandHandler('caps', caps, pass_args=True)

date_handler = CommandHandler('date', date)

unknown_handler = MessageHandler(Filters.command, unknown)


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Back To Top