aws lambda使用_使用AWS Lambda构建一个简单的电报机器人

aws lambda使用

Recently, I just launched a small business, which is a local service to help customers order and ship their goods from the USA to VN. In the beginning, I tend to use a Google sheet to build a service price calculator, so every time my customers need to know the final price for a product, I can quickly check and answer. After doing that way for a while, I recognize that it is not useful sometimes. For example, when I was outside, I can not open the Google Sheet on the laptop to check, or even I can do it on my smartphone, it’s still very slow. I need a fast and clean solution. Thus I came up with the final choice, the Telegram Bot

最近,我刚开办了一家小型企业,这是一项本地服务,可帮助客户从美国订购商品并将其运送到VN。 一开始,我倾向于使用Google工作表来构建服务价格计算器,因此,每当客户需要了解产品的最终价格时,我都可以快速进行检查和回答。 这样做一段时间后,我认识到有时它没有用。 例如,当我在外面时,无法打开笔记本电脑上的Google表格进行检查,甚至无法在智能手机上进行操作,但它仍然非常缓慢。 我需要一个快速干净的解决方案。 因此,我想到了最终的选择,即电报机器人

什么是电报?(What is Telegram?)

Telegram is an online messaging app, working like Facebook Messenger, Whatsapp… It is cloud-based and well-known for its security and speed. The telegram was founded by Pavel Durov, who’s also behind Russia’s largest social network VKontakte (VK). It has many cool features and is continuing to improve

Telegram是一个在线消息传递应用程序,类似于Facebook Messenger,Whatsapp等。它基于云,并且以安全性和速度而闻名。 该电报由Pavel Durov创建,他也是俄罗斯最大的社交网络VKontakte(VK)的幕后黑手。 它具有许多很酷的功能,并且正在不断改进

什么是AWS Lambda?(What is AWS Lambda?)

AWS Lambda is a computing service provided by Amazon Web Services. It is an event-driven computing platform, which means that it runs code as a response to an event and automatically manage the computing resources required by your code

AWS Lambda是Amazon Web Services提供的计算服务。 它是一个事件驱动的计算平台,这意味着它运行代码作为对事件的响应,并自动管理代码所需的计算资源

什么是Amazon API Gateway概念?(Whats is Amazon API Gateway concepts?)

It is also an AWS service that supports to expose the AWS Lambda function or any backend HTTP endpoint to the URL format

它也是一项AWS服务,支持将AWS Lambda函数或任何后端HTTP终端节点公开为URL格式。

电报机器人如何与AWS API Gateway交互? (How can the telegram bot interact with AWS API Gateway?)

Telegram bot is an application hosted on your server. It uses the Telegram bot API to connect to the Telegram Messenger clients. There are 2 ways for your server and the Telegram server to communicate:

Telegram bot是服务器上托管的应用程序。 它使用Telegram bot API连接到Telegram Messenger客户端。 服务器和Telegram服务器有两种通信方式:

  1. Long polling mechanism: your server keeps asking the Telegram server “Hey is there anything new?“

    长轮询机制:您的服务器不断询问Telegram服务器“嘿,有什么新东西吗?”
  2. Webhook: Anytime Telegram server has any updates, it will call that webhook URL

    Webhook:每当Telegram服务器有任何更新时,它将调用该Webhook URL

Because my first priority is simplicity. I need a solution that I just need to write code for business logic and run. I do not want to be bordered by any complicated deploy options. Compare with the 2 communication method above, I figured out:

因为我的首要任务是简单。 我需要一个解决方案,我只需要编写用于业务逻辑的代码并运行即可。 我不想被任何复杂的部署选项所困扰。 与上面的两种通信方式相比,我发现:

  1. For the long-polling method, I need to use a framework/library to code from scratch and host that script on AWS EC2 or some other cloud services. It takes a little more times

    对于长轮询方法,我需要使用框架/库从头开始编写代码并将该脚本托管在AWS EC2或某些其他云服务上。 需要更多时间
  2. For webhook, I just code the logic on AWS Lambda, expose an API Gateway endpoint, configured the webhook for a telegram bot. It’s much simpler and scalable

    对于Webhook,我只是在AWS Lambda上编写逻辑,公开API Gateway终端节点,为电报机器人配置了Webhook。 它更加简单和可扩展

实施计划:(Implementation plan:)

在Telegram上注册机器人: (Register a bot on Telegram:)

Registering a bot on Telegram can be known as the easiest task in the world. Since we have @BotFather, just following his instruction. Let’s start by typing “/newbot” in the chat with @BotFather

在Telegram上注册机器人可以称为世界上最简单的任务。 由于我们有@BotFather,因此请按照他的指示进行操作。 让我们从与@BotFather的聊天中键入“ / newbot”开始

Image for post

创建AWS API网关(Create AWS API Gateway)

  • In this step, I assumed that you have already registered for an AWS account ID. If you did not have, please open Google and type “Sign up AWS account”.

    在此步骤中,我假设您已经注册了一个AWS账户ID。 如果您还没有,请打开Goog​​le并输入“注册AWS账户”。
  • If you already had an account, sign in and go to “AWS Management Console” and choose “API Gateway” from the list ( or using Find Services bar for a quick)

    如果您已经有一个帐户,请登录并转到“ AWS管理控制台”,然后从列表中选择“ API网关”(或快速使用“查找服务”栏)
Image for post
AWS Management Console screen
AWS管理控制台屏幕
  • In the API Gateway main page, choose “Create API”

    在API网关主页中,选择“创建API”
Image for post
API type currently supported by AWS API Gateway
AWS API Gateway当前支持的API类型
  • There are some available API types on the page, you can choose HTTP API or REST API. According to an AWS blog, HTTP APIs are 71% cheaper than REST API. If you are seriously considering using AWS for your business, discover more about HTTP APIs type. In my case, I am familiar with the REST API type so I used it for quick

    页面上有一些可用的API类型,您可以选择HTTP API或REST API。 根据一个AWS博客,HTTP API比REST API便宜71%。 如果您正认真考虑将AWS用于您的业务,请了解有关HTTP API类型的更多信息。 就我而言,我熟悉REST API类型,因此我使用它来快速

Image for post
Fill out some basic information and Create API
填写一些基本信息并创建API

创建AWS Lambda函数 (Create AWS Lambda function)

  • In this part, I will put some business logic inside a lambda function called “calculateFinalPrice”. This will handle the input data from the telegram bot command and return a result. It will be written in Python3.6

    在这一部分中,我将一些业务逻辑放在称为“ calculateFinalPrice”的lambda函数中。 这将处理来自telegram bot命令的输入数据并返回结果。 它将用Python3.6编写
Image for post
  • As you notice, we have a “Permissions” tab. To be simple, you can follow this:

    如您所见,我们有一个“权限”标签。 为简单起见,您可以按照以下步骤操作:
Image for post
  • Click “Create function” and it will let me go to an online editor where I can put my Python code there

    点击“创建函数”,它将使我进入一个在线编辑器,在这里我可以将Python代码放在​​那里
Image for post
  • Sample code with some magical logic :D

    具有神奇逻辑的示例代码:D
import jsonfrom botocore.vendored import requests
TELE_TOKEN='My-bot-token'URL = "https://api.telegram.org/bot{}/".format(TELE_TOKEN)USD_VND_RATE = 23000 #VND
def calculate_final_price(listed_price, item_weight): final_price = (listed_price + item_weight * 0.5) * USD_VND_RATE return final_price_vndef fp_command_handler(arguments, chat_id): listed_price = float(arguments[0]) item_weight = float(arguments[1]) final_price_in_vnd = calculate_final_price(listed_price, item_weight) message = "*Final price*: {:,.2f} VNĐ".format(final_price_in_vnd) send_message(message, chat_id)
def send_message(text, chat_id):
url = URL + "sendMessage?text={}&chat_id={}&parse_mode=Markdown".format(text, chat_id)
requests.get(url)
def lambda_handler(event, context): request_body = json.loads(event['body']) chat_id = request_body['message']['chat']['id'] command_arguments = request_body['message']['text'].split() command = command_arguments[0] arguments = command_arguments[1:] if command == "/fp": fp_command_handler(arguments, chat_id)
else: send_message("Command not support", chat_id)

return { 'statusCode': 200
}

A small note for the above snippet, we should return status code 200 ( stand for successful processing). Otherwise, Telegram will retry to push the update to your webhook and then your bot will make your inbox exploded :D

对于上述摘要,我们应该返回状态码200 (表示成功处理)。 否则,Telegram将重试将更新推送到您的Webhook,然后您的机器人将使您的收件箱爆炸:D

连接AWS Lambda和API网关 (Connect AWS Lambda and API Gateway)

Now it’s time to expose the logic handling every bot command. Let’s go to the AWS console and select the API that has been created earlier from API Gateway service

现在该公开处理每个bot命令的逻辑了。 让我们转到AWS控制台并选择先前通过API Gateway服务创建的API

  • Choose “Create Method”

    选择“创建方法”
Image for post
  • After that, we choose “ANY” method for simplicity. In the scope of this blog, I do not cover the different types of HTTP methods. Because the bot is really simple, so we will set the endpoint to accept any type of method

    之后,为简单起见,我们选择“ ANY ”方法。 在本博客的范围内,我不会介绍不同类型的HTTP方法。 由于bot非常简单,因此我们将设置端点接受任何类型的方法

Image for post
  • Then we will deploy our API ( or simply expose it to a URL format)

    然后,我们将部署我们的API(或简单地将其公开为URL格式)
Image for post
Image for post
Image for post

At this step, the webhook is the Invoke URL like above

在这一步,webhook是上面的调用URL

设置Webhook (Set Webhook)

To set the webhook, it is very simple. All you need to do is copying, editing and pasting the below URL to your browser

要设置网络挂钩,这非常简单。 您需要做的就是将以下URL复制,编辑并粘贴到浏览器中

https://api.telegram.org/bot<bot-token>/setWebHook?url=<webhook-url>

测试机器人 (Test the bot)

Image for post
This is the screenshot from my actual bot
这是我实际机器人的屏幕截图

结论(Conclusion)

Telegram bot is a convenient way to build some quick access tools like above. There are many more use cases where telegram bot was proved to be an efficient tool like a notification system ( often used for trading bots)

Telegram bot是一种构建上述快速访问工具的便捷方式。 在许多用例中,电报机器人被证明是一种有效的工具,例如通知系统(通常用于交易机器人)

The above guide is suitable for someone who does not have or very little coding skill ( for a more complex bot, I will cover in some next articles). In this case, you do not have to care much about how to build a complete webhook with some times including complex deploying processes. Thanks to the AWS powered computing services, all you need now is some Python skill +an AWS free tier account

上面的指南适用于没有或只有很少的编码技能的人(对于更复杂的机器人,我将在接下来的文章中介绍)。 在这种情况下,您不必花太多时间在复杂的部署过程中就如何构建完整的Webhook。 借助AWS驱动的计算服务,您现在所需要的就是一些Python技能和一个AWS免费套餐帐户

Happy Coding

快乐编码

翻译自: https://medium.com/@dtphat/building-a-simple-telegram-bot-with-aws-lambda-c3143e596b3b

aws lambda使用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值