未加星标

Host a python Telegram bot on Azure in < 30 minutes

字体大小 | |
[系统(windows) 所属分类 系统(windows) | 发布者 店小二03 | 时间 2017 | 作者 红领巾 ] 0人收藏点击收藏

Almost two years ago Telegram let developers create bots quite painlessly. You can read an introduction about it on Telegram website . In this article we will create a simple bot in python, it’ll be hosted in Azure using Bottle framework. The bot will not do anything fancy, consider it as a template for your python based bots.

Here are the things which we’ll cover:

Registering your bot in Telegram app Creating a Bottle App in Azure Configuring Bottle server to run as HTTPS (which is required by Telegram) Creating an API endpoint for communication with Telegram

After that, I will also introduce you to inline bots.

Registering bot in Telegramapp

You can do it without leaving the Telegram app. Your contact person is, well, a bot named @BotFather. Start a conversation with him:


Host a python Telegram bot on Azure in < 30 minutes

He’s a really cool guy and I’m sure you’ll not have any problems with creating a new bot. Just write /newbot , then choose a name and username for it (the latter should end with bot ).

If everything goes smoothly, you’ll receive your bot’s token, which we’ll use in the next step.

Creating a Bottle App inAzure

Bottle is a lightweight server framework for python. It’s available in Azure as a Web Application. In order to create it, open Azure Portal, look for bottle” in new app search window.


Host a python Telegram bot on Azure in < 30 minutes

Click on it, then choose a name for your app and resource group.

After about a minute, your app should be ready. You should be able to see it on http://APPNAME.azurewebsites.net

Open it in azure, and search for “Deployment options”.


Host a python Telegram bot on Azure in < 30 minutes

By default azure bottle app is deployed from this git repository . Let’s create a local git repository just for your project. In Deployment options , click Disconnect and confirm. Then, click Setup button, select Local git repository and confirm. This action may take about a minute to reflect in the UI, after that you should see an address to your git repo in Overview screen:


Host a python Telegram bot on Azure in < 30 minutes

Copy that link, then switch to cmd/terminal, go to directory of your choice and clone your repo (I hope you have git installed!):

git clone (repolink)

You will be asked for user password, you can set it up in Deployment Credentials :


Host a python Telegram bot on Azure in < 30 minutes

Let’s take a look at the files:


Host a python Telegram bot on Azure in < 30 minutes

app.py ―this file contains initialization of your bottle server

routes.py ―it specifies logic which should be executed for API routes (and returns data)

requirements.txt ―all python dependencies have to be listed here

.skipPythonDeployment― if this file exists, azure will not proceed with full python deployment each time you commit (you should remove it for commits which add new dependencies)

Other files and folders are less significant for this tutorial, you can figure out their importance by yourself (or ask in comments, I’ll be happy to help).

Configuring Bottle server to run asHTTPS

Telegram doesn’t support HTTP requests for bot API, so we need to make sure our method is reachable using HTTPS. Bottle doesn’t offer HTTPS server out of the box. To archive this, we need to create a ServerAdapter. You can use one of the implementations floating on the Internet, like this .

Copy the code of server class and paste it into your app.py file (right under the imports is fine):

class SSLWSGIRefServer(bottle.ServerAdapter):
def run(self, handler):
from wsgiref.simple_server import make_server, WSGIRequestHandler
import ssl
if self.quiet:class QuietHandler(WSGIRequestHandler): def log_request(*args, **kw): passself.options['handler_class'] = QuietHandler
srv = make_server(self.host, self.port, handler, **self.options)
srv.socket = ssl.wrap_socket (srv.socket,
certfile='server.pem', server_side=True)
srv.serve_forever()

certfile=’server.pem’ is a path to your server certificate. It’s easy to create it using OpenSSL by running the command below, you can provide empty input for all certificate fields except for Common Name , for it you have to use your domain address (APPNAME.azurewebsites.net):

openssl req -new -x509 -keyout server.pem -out server.pem -days 365 -nodes

Place generated server.pem file in the root folder of your app.

Now, let’s switch to using new class. Change your startup code to look like this and remember to use your app’s name:

if __name__ == '__main__':
app = bottle.Bottle()
srv = SSLWSGIRefServer(host="APPNAME.azurewebsites.net", port=80)
bottle.run(server=srv) python-telegram-bot

To communicate with Telegram API, we’ll use a wrapper called python-telegram-bot .

This package is not available in your azure environment. In order to add it, you need to do two things:

add line python-telegram-bot==5.3.0 to requirements.txt remove file.skipPythonDeployment

Azure will make sure all package requirements are met during deployment (which happens after each commit).

Communication between Telegram and our server can be done in 2 different ways:

1. Our server can check for updates from Telegram in a loop using getUpdates method

2. We can hook telegram to our server’s API method, so everytime there is some user message waiting, Telegram will send us an HTTPS POST request with details.

In this tutorial we’ll use thesecond approach.

Creating an API inBottle

Let’s open routes.py file. You can see many routes specified here, all of them useless for our use case, you can safely remove them. We will add two methods:

/botHookwill respond to telegram’s requests. Our bot will take the incoming message, assume it’s in format a+b , split it into 2 ints and answer with the sum of these numbers.

/setWebhookwill be responsible for hooking telegram to our API. You could move this logic to app.py file, so it’d be done with each deployment/server restart, but I prefer to have quick access to it this way. We’ll pass the address of the /bootHook method. It will return a boolean value, which will indicate if the hooking was successful.

Here’s the full code for routes.py which you can use. Make sure to use your app name and bot token:

from bottle import route, view, run, request import telegram TOKEN = 'TO

本文系统(windows)相关术语:三级网络技术 计算机三级网络技术 网络技术基础 计算机网络技术

主题: OpenSSLSGPython
分页:12
转载请注明
本文标题:Host a python Telegram bot on Azure in < 30 minutes
本站链接:http://www.codesec.net/view/524517.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 系统(windows) | 评论(0) | 阅读(137)