We will write handler class to process user message and return a response.

WebhookHandler Route

Receive/Reply message from/to Telegram user.

class WebhookHandler(webapp2.RequestHandler):
    def post(self):

        def generateReply(tBody=None):
            if tBody:
                try:
                    message = body['message']
                except:
                    message = body['edited_message']
                if message:
                    chat = message['chat']
                    chat_id = chat['id']
                    text = message.get('text')
                    fr = message.get('from')
                    msg = 'Yo '+fr['username']+' I got your message: '+text
                    return urllib.urlencode({
                        'chat_id': str(chat_id),
                        'text': msg.encode('utf-8'),
                        'disable_web_page_preview': 'true',
                    })
                else:
                    logging.info('fail to generate reply')
                    return None
            else:
                logging.info('no body from telegram update')
                return None

        def sendReply(data=None):
            if data:
                requestUrl = BASE_URL + 'sendMessage'
                resp = urllib2.urlopen(requestUrl, data).read()
            else:
                logging.info('fail to reply')
                resp = None
            logging.info('sendReply response:')
            logging.info(resp)

        urlfetch.set_default_fetch_deadline(60)
        body = json.loads(self.request.body)
        logging.info('Telegram update body:')
        logging.info(body)
        replyData = generateReply(body)
        sendReply(replyData)

app = webapp2.WSGIApplication([
    ('/webhook', WebhookHandler)
], debug=True)

Deploy App

Run this command to deploy your app.

gcloud app deploy

Set your Webhook for Telegram bot

Open your browser and run this URL

https://[YOUR_WEBSITE]/set_webhook?url=https://[YOUR_WEBSITE]/webhook

DONE

You can start message your bot and see the reply.

Your bot is running