in Automation, Programming

Playing with Telegram and Python

Telegram is a popular application for instant messaging.
Thanks to its new release, it can runs chat bots which can be used to create different services.

The concept is simple, you subscribe to a chat with a bot and then you can send command to the bot itself.

In this post I’ll show you how to create a bot in Python which tells you if a number is odd or even.

Just a simple example to demonstrate all the possible uses.

The basics

Obtaining API KEY

To obtain your API key you need to chat with a bot called “BotFather”: search it on Telegram, start a new chat and type “/newbot”.

The bot will ask you the name of the bot you want to create and a username you want to use.

At this point the bot will assign you the API KEY: write it somewhere.

Installing Telepot

As usual, type:

$> sudo pip install telepot

The code

Of course, remember to insert the API KEY you get two steps before!

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
import telepot
def handle(message):
    chatid  =   message['from']['id']
    cmd, payload     =   message['text'].split(' ')[0], " ".join(message['text'].split(" ")[1:]).strip()
    
    if (cmd in ["/odd","/even"]):
        odd = bool(int(payload)%2)
        out = odd if (cmd=="/odd") else not odd
    else:
        out = """These are all the available commands:
        /odd [number] ==> check if a number is odd;
        /even [number] ==> check if a number is even;
        """
    bot.sendMessage(chatid,out)
    

bot = telepot.Bot('<<INSERT YOUR API KEY HERE>>')
bot.notifyOnMessage(handle)
print "Alive and listening..."

while 1:
    print "Up"
    time.sleep(5)

… and that’s all!