Basic understand about Telegram Bot.

  1. Telegram Bots are simply Telegram accounts operated by software.
  2. Everytime a user send message to it, the message will be forwarded to a bot server.
  3. The bot server will process and send back the response to all the messages.

We are going to create a bot server.

Reading

Telegram Webhook

Webhook URL

  1. Telegram user send our bot a message. (ex: “/echo hello world”)
  2. Telegram will forward the message to a bot server using pre-registered Webhook URL.
  3. Bot server will process and response to all messages

Webhook URL acts like our bot server registered address. So Telegram knows where to forward user message for processing and responding.

SetWebhookHandler Route

Register/Update our server address with Telegram Webhook.

This handler can’t be tested on your localhost. Telegram won’t accept your localhost URL and error code 500 will return.

import json
import logging
import urllib2
import urllib

from google.appengine.api import urlfetch
import webapp2

TOKEN = 'xxxxxx:YOUR_TELEGRAM_BOT_TOKEN'
BASE_URL = 'https://api.telegram.org/bot' + TOKEN + '/'

class SetWebhookHandler(webapp2.RequestHandler):
    def get(self):
        urlfetch.set_default_fetch_deadline(60)
        url = self.request.get('url')
        if url:
            requestUrl = BASE_URL + 'setWebhook'
            requestParam = urllib.urlencode({'url': url})
            response = urllib2.urlopen(requestUrl, requestParam)
            self.response.write(json.dumps(json.load(response)))
        else:
            self.response.write('Invalid webhook URL: ' + url + '<br>')

app = webapp2.WSGIApplication([
    ('/set_webhook', SetWebhookHandler),
], debug=True)

GetWebhookHandler Route

Get current Telegram webhook status.

class GetWebhookHandler(webapp2.RequestHandler):
    def get(self):
        urlfetch.set_default_fetch_deadline(60)
        requestUrl = BASE_URL + 'getWebhookInfo'
        response = urllib2.urlopen(requestUrl)
        self.response.write(json.dumps(json.load(response)))

app = webapp2.WSGIApplication([
    ('/get_webhook', GetWebhookHandler),
], debug=True)