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.


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

BASE_URL = '' + TOKEN + '/'

class SetWebhookHandler(webapp2.RequestHandler):
    def get(self):
        url = self.request.get('url')
        if url:
            requestUrl = BASE_URL + 'setWebhook'
            requestParam = urllib.urlencode({'url': url})
            response = urllib2.urlopen(requestUrl, requestParam)
            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):
        requestUrl = BASE_URL + 'getWebhookInfo'
        response = urllib2.urlopen(requestUrl)

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