telegram 机器人
by Moses Soh
通过摩西·苏(Moses Soh)
我在周末构建了一个无服务器的Telegram机器人。 这是我学到的。 (I built a serverless Telegram bot over the weekend. Here’s what I learned.)
I built a Telegram chatbot that sends out a SOS to rescuers when someone is stranded in the rain. It’s written in Python using AWS Lambda, Zappa and Flask.
我建立了一个Telegram聊天机器人,当有人被困在雨中时,它会向救援人员发送SOS。 它是使用AWS Lambda,Zappa和Flask用Python编写的。
You can try it here. I haven’t added in persistence yet ? but I think some of this here might be useful to anyone else interested in a similar project.
您可以在这里尝试。 我还没有添加持久性吗? 但我认为这里的某些内容可能对其他对类似项目感兴趣的人有用。
I normally have a hard time getting my fiancée to discuss technology. It’s come to a point where she can’t help but stifle a yawn once I say “code”.
我通常很难让未婚夫讨论技术。 当我说“代码”时,她忍不住打了个哈欠。
Imagine my surprise this weekend when she asked me — pretty much out of the blue — how much it would cost to make a mobile app.
想象一下这个周末,当她问我-出乎意料的时候-制作一个移动应用程序要花多少钱时,我感到惊讶。
After losing it for a bit, here’s what I found out.
在失去了一点之后,这就是我发现的东西。
问题 (The problem)
My fiancée’s workplace is close to two MRT stations but there aren’t any covered paths from the MRT stations to her building. When it rains, people without umbrellas get stranded at the stations. She and her colleagues often head down to help friends out, but there are often more people stranded there than they expected.
未婚夫的工作场所靠近两个捷运站,但从捷运站到她的大楼没有遮盖的路径。 下雨时,没有雨伞的人会被困在车站。 她和她的同事经常低头去帮助朋友,但经常有更多的人滞留在那里,比他们预期的要多。
Her colleagues were discussing if an app could help solve this. Well, I thought that a chatbot might be able to have the same functions (such as sending out request for umbrellas, location sharing, getting replies). And you could avoid convincing people to download another app.
她的同事们正在讨论一个应用程序是否可以解决这个问题。 好吧,我认为聊天机器人也许可以具有相同的功能(例如发出请求,共享位置,获取回复)。 而且您可以避免说服人们下载另一个应用程序。
Since I’d been meaning to try out Telegram’s bot APIs for awhile now, I volunteered to help build out a prototype so we could see how interesting this might actually be.
由于我本来打算试用一下Telegram的机器人API,所以我自愿帮助构建了一个原型,以便我们可以看到这实际上是多么有趣。
聊天机器人 (The chatbot)
I started working on this on Saturday afternoon and went to bed at 2am on Sunday. But I’m really happy to have gone from knowing nothing about the bot APIs to being able to make something like this.
我从周六下午开始进行这项工作,并于周日凌晨2点上床睡觉。 但是我真的很高兴,从对机器人API一无所知,到能够做出类似的事情。
Anyone can request an umbrella. The bot asks where the person is, how many umbrellas he/she might need, and when they’d like to be picked up (the options are limited so we don’t tax our rescuers too much).
任何人都可以要求一把雨伞。 机器人会询问该人在哪里,他/她可能需要多少把雨伞,以及何时需要拿起雨伞(选择有限,因此我们不会对救援人员征税过多)。
People can register to be rescuers. A little good karma goes a long way ?
人们可以注册成为救援人员。 一点善业能走很长一段路?
Rescuers get notified whenever someone near them is stranded in the rain. I wanted to make it clear to rescuers whether they were responsible for the request once they had pressed “Yes”.
每当附近有人被困在雨中时,救援人员都会收到通知。 我想向救援人员表明,一旦按下“是”,他们是否应对请求负责。
In the process I learned a few tricks about making the development a lot faster. I spent almost six hours before I managed to find the right tools and a development workflow that worked for me. Building the bot logic took me a much shorter time.
在此过程中,我学到了一些使开发更快的技巧。 我花了将近六个小时的时间才设法找到适合我的工具和开发工作流程。 构建机器人逻辑使我花了更短的时间。
我用了什么 (What I used)
AWS Lambda (AWS Lambda)
Instead of running a server 24/7, you can host functions in Lambda so that the server only lasts for the lifecycle of the request. It’s great for prototypes since you get 1 million free requests a month.
您可以在Lambda中托管功能,而不是运行24/7全天候服务器,以便该服务器仅在请求的生命周期内持续有效。 这对于原型非常有用,因为您每月可获得100万个免费请求。
扎帕 (Zappa)
This automates the steps needed to get your local Python code onto AWS Lambda. It also configures Amazon’s API Gateway so you have a nice HTTPS endpoint to host your chatbot functions.
这将自动执行将本地Python代码放入AWS Lambda所需的步骤。 它还配置了Amazon的API网关,因此您拥有一个不错的HTTPS终端节点来托管您的聊天机器人功能。
恩格罗克 (ngrok)
This makes any local servers reachable via the internet. It’s a great way to prototype web-hooks before actually deploying them to the cloud.
这样就可以通过Internet访问任何本地服务器。 这是在实际将Web挂钩部署到云之前对其进行原型制作的好方法。
These tools helped me avoid a lot of the headache that goes into making a chatbot (e.g. renting a server, configuring it for HTTPS, figuring out how to make the server non-blocking since this is a chatbot).
这些工具帮助我避免了制作聊天机器人时遇到的许多麻烦(例如,租用服务器,为HTTPS配置服务器,弄清如何使服务器成为非阻塞服务器,因为这是聊天机器人)。
Today I’ll show you how I used these tools to develop the chatbot above. Hope this will help someone else on a similar journey.
今天,我将向您展示如何使用这些工具来开发上面的聊天机器人。 希望这将对其他类似旅程的人有所帮助。
演练 (Walkthrough)
This tutorial assumes that you’re making a chatbot with no knowledge of how Telegram’s bot API works, but with a working knowledge of Flask and Python. If anything seems too simple for you, feel free to skip ahead!
本教程假定您是在不了解Telegram的bot API如何工作的情况下创建聊天机器人,但具有Flask和Python的工作知识。 如果您觉得任何事情都太简单了,请随时跳过!
创建一个电报机器人 (Create a Telegram bot)
Visit the Botfather. Type /newbot
and follow his instructions to set up a new bot.
参观Botfather 。 输入/newbot
并按照他的指示设置新的机器人。
⚡ Pro tip: save the token somewhere, we’ll be using it soon!
⚡ 专家提示:将令牌保存在某个地方,我们将很快使用它!
Feel free to play around with the bot’s profile picture, about text, and description to give it whatever personality you want. Typing /help
with the Botfather gives you the full list of settings you can tweak for your bot.
随意玩转机器人的个人资料图片,文字和说明,以赋予其所需的个性。 在Botfather中键入/help
会为您提供可以为您的机器人调整的完整设置列表。
使用Flask设置开发服务器 (Set up a development server with Flask)
I worked with pipenv to manage my project’s Python dependencies. If you’re still using pip and virtualenv I encourage you guys to give this a try. There’s installation instructions at the link.
我与pipenv一起管理项目的Python依赖项。 如果您仍在使用pip和virtualenv,我鼓励大家尝试一下。 链接中有安装说明。
Next we’ll install Flask. We’ll also use the awesome requests library. In your command line type:
接下来,我们将安装Flask 。 我们还将使用很棒的请求库。 在命令行中输入:
pipenv install flaskpipenv install requests
After flask is installed, we’ll set up a basic server to test our bot. Copy the following text into a file called server.py
.
在安装flask之后,我们将设置一个基本服务器来测试我们的机器人。 将以下文本复制到名为server.py
的文件中。
⚡ Pro tip: Make sure you replace <your-bot-tok
en> with the API token we got from the Botfather.
⚡ 专家提示:确保用我们从Botfather获得的API令牌替换<your-bot-tok
en>。
Let’s break down what this is doing. Telegram’s API works this way. Firstly, when someone sends your bot a message, that message gets sent to Telegram’s servers. Telegram then forwards us that message to whatever we specify as our web-hook as a POST request.
让我们分解一下这是做什么的。 Telegram的API以这种方式工作。 首先,当有人向您的漫游器发送消息时,该消息将发送到Telegram的服务器。 然后,Telegram将该消息转发给我们指定为POST请求的任何网络挂钩。
The function process_update()
and the decorator above it says that when anyone POSTs to the domain http://127.0.0.1:5000/<your-bot-tok
en> , we will extract the JSON data from it. If it’s a normal text message, it will have the key m
essage in the JSON. We check for that and if it’s a normal message, we reply using process_message(u
pdate) .
函数process_update()
及其上方的修饰符表示,当任何人发布到域http://127.0.0.1:5000 /<your-bot-tok
en>时,我们都会从中提取JSON数据。 如果是普通文本消息,它将在JSON中具有e key m
消息。 我们检查该消息是否正常,然后using process_message(u
pdate)进行回复。
The function process_message()
constructs the payload that the Telegram API is expecting if we want to reply to the message. We basically need to specify our reply text in data["text"]
and the chat we’re replying to in data["chat_id"]
.
如果我们想回复消息,函数process_message()
构造Telegram API期望的有效负载。 我们基本上需要在data["text"]
指定回复文本,并在data["chat_id"]
要回复的聊天。
Finally, we send a POST request with this payload to the Telegram API endpoint for the sendMessage
method. This allows us to send a message programmatically.
最后,我们将带有此有效负载的POST请求发送到Telegram API端点的sendMessage
方法 。 这使我们能够以编程方式发送消息。
Time to run the server. Now in your command prompt type:
是时候运行服务器了。 现在在命令提示符下键入:
pipenv shell
This activates the virtual environment and gives us access to Flask. Now we need to run the server locally. Type in the command prompt:
这将激活虚拟环境,并使我们能够访问Flask。 现在我们需要在本地运行服务器。 在命令提示符下键入:
export FLASK_APP=server.pyflask run
We have a running server! If you didn’t mess with the defaults, this is running at http://127.0.0.1:5000/.
我们有一台正在运行的服务器! 如果您不使用默认值,那么它将在http://127.0.0.1:5000 /上运行。
Read more at the Flask documentation and quick-start.
在Flask文档和快速入门中阅读更多内容。
But this is running locally, and Telegram’s bot API can’t send its POST requests to a local URL. Hence we’ll use ngrok to expose this local server to the internet.
但这是在本地运行的,Telegram的bot API无法将其POST请求发送到本地URL。 因此,我们将使用ngrok将此本地服务器公开到Internet。
使用ngrok使本地服务器可以在Internet上访问 (Use ngrok to make the local server accessible on the internet)
Get the package for your operating system from this link on the ngrok website. Once you’ve downloaded and installed it, go to the directory that you unzipped the file into and run the following command in the command prompt.
从ngrok网站上的此链接获取适用于您的操作系统的软件包。 下载并安装后,转到将文件解压缩到的目录,然后在命令提示符下运行以下命令。
./ngrok http 5000
You’ll see something similar in your command prompt. Now whatever server you’re running on localhost:5000 is exposed at the following URLs.
您将在命令提示符下看到类似的内容。 现在,您在localhost:5000上运行的任何服务器都会在以下URL中公开。
⚡ Pro tip: Copy the https url, we’re going to use it soon.
⚡ 专家提示:复制https url,我们将很快使用它。
Time to let Telegram know what our web-hook address is. We’ll use the Telegram API again to set our web-hook.
是时候让Telegram知道我们的网络挂钩地址了。 我们将再次使用Telegram API来设置网络挂钩。
Create a file called webhook.py
with the following content:
创建一个名为webhook.py
的文件,其内容如下:
⚡ Pro tip: Remember to replace <your-bot-tok
en>; and <your-h
ttps-url> !
⚡ 专家提示:记住要替换<your-bot-tok
en> ; and <your-h
; and <your-h
ttps-url>!
pprint
lets us print out nicely formatted JSON data. We send our web-hook URL as a POST request to the setWebhook
endpoint of the Telegram API. Now run the following lines in your command prompt:
pprint
使我们可以打印出格式正确的JSON数据。 我们将Web钩URL作为POST请求发送到Telegram API的setWebhook
端点 。 现在,在命令提示符下运行以下行:
pipenv install pprintpython webhook.py
You should see 200
and a JSON block with 'ok': True
.
您应该看到200
和一个带有'ok': True
的JSON块'ok': True
。
测试您的聊天机器人 (Test out your chatbot)
Now we’re done with setting up our server. Head over to your bot in Telegram, and say hello! If everything’s been set up correctly, you’ll see it reply I can hear you!
现在我们完成了设置服务器的工作。 前往Telegram中的机器人,打个招呼! 如果一切设置正确,您会看到它的回复, I can hear you!
In the next part of this tutorial, we’ll learn how to deploy this server onto the internet using Zappa and AWS Lambda. Give this a couple of claps if this was helpful for you — I’d love to know if it was. Thanks ?
在本教程的下一部分中,我们将学习如何使用Zappa和AWS Lambda将此服务器部署到Internet上。 如果这对您有帮助,请给我一些鼓掌-我很想知道是否有帮助。 谢谢 ?
翻译自: https://www.freecodecamp.org/news/how-to-build-a-server-less-telegram-bot-227f842f4706/
telegram 机器人