banner
zhxy-CN

zhxy-CN

email
github

AWS Lambda Exploration: Building a Telegram Bot on Lambda

Original Text: https://owo.cab/106, also published on xLog

Introduction#

What is AWS Lambda#

AWS Lambda is a computing service that lets you run code without provisioning or managing servers. Lambda runs your code on a high-availability compute infrastructure and performs all the management of the compute resources, including server and operating system maintenance, capacity provisioning, and automatic scaling, as well as logging. With Lambda, you can run code for virtually any type of application or backend service, and you only need to provide your code in one of the languages supported by Lambda.
You can organize your code into Lambda functions. Lambda runs your functions only when needed and automatically scales them from a few requests per day to thousands of requests per second. You pay only for the compute time that you consume—there is no charge when your code is not running.

Why Use AWS Lambda#

  1. No Server Management
    AWS Lambda is a serverless computing service that automatically scales and manages the infrastructure, eliminating the need for server management and maintenance. You just need to write your code and upload it to Lambda.
  2. Cost-effective
    Previous bots ran on servers that would continue running regardless of whether the bot was being used, increasing operational costs. As mentioned above, with Lambda, you only pay for the actual runtime of your code, significantly reducing operational costs.
  3. Quick Deployment
    You can deploy your code to a production environment in minutes.

I couldn't find any relevant Chinese tutorials, so I decided to write one myself (

Let's Get Started#

Creating a Telegram Bot#

Search for @BotFather in Telegram and follow the prompts to create a bot.
image
After creating the bot, you will receive a token (highlighted in red). Keep this token for future bot operations.

Creating a Lambda Function#

Go to the AWS Lambda Functions Console and select Create Function to create a new function.
Enter any function name, choose Python 3.10 as the runtime, and click Create Function.
image
After creation, you will see some sample code.

Creating an API#

Go to the API Gateway Console and click Build in the REST API section.
Here, select REST API, or you can choose HTTP API.
image
Click Create Method in the Actions menu.
image
For simplicity, select ANY method.
image
Check Use Lambda Proxy integration, enter the Lambda Function, and click Save.
image
Click Deploy API in the Actions menu.
image
Select New Stage in the Deployment stage and enter any name, then click Deploy.
image
After completion, you will get the Invoke URL.
image
You can try accessing the Invoke URL. If it returns "Hello from Lambda!", it means that the Lambda and API have been successfully created.

Building a Simple Bot#

Go back to the Lambda console, click the Configuration tab, and create an environment variable to store the Bot Token, as shown in the image.
image
Create a folder on your local computer and create a lambda_function.py file to store the code for the Lambda function.
Declare a variable to use the Bot Token from the environment variable.

import os

BOT_TOKEN = os.environ['BOT_TOKEN']

Create a function to send messages.

import requests

def send_message(chat_id, text):
    params = {
        "text": text,
        "chat_id": chat_id,
        "parse_mode": "MarkdownV2"
    }
    requests.get(
        f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage",
        params=params
    )

Create a simple function to handle the bot's messages. Of course, you can add more functionality based on your needs. Here, we create an echo bot (?

import json

def process_event(event):
    message = json.loads(event['body']['message'])
    chat_id = message['chat']['id']
    text = message['text']
    if text:
        send_message(chat_id, text) # Repeat the message when received

Finally, create the entry function for the Lambda function.
Note: Be sure to return a status code of 200; otherwise, the Telegram server will continue sending the same content, thinking that the bot did not receive the message. Then (manually funny

def lambda_handler(event, context):
    process_event(event)
    return {
        'statusCode': 200 # Return a status code of 200
    }

Complete code:

import os
import json
import requests

BOT_TOKEN = os.environ['BOT_TOKEN']


def send_message(chat_id, text):
    params = {
        "text": text,
        "chat_id": chat_id,
        "parse_mode": "MarkdownV2"
    }
    requests.get(
        f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage",
        params=params
    )


def process_event(event):
    message = json.loads(event['body']['message'])
    chat_id = message['chat']['id']
    text = message['text']
    if text:
        send_message(chat_id, text)


def lambda_handler(event, context):
    process_event(event)
    return {
        'statusCode': 200
    }

Installing Dependencies#

Since Lambda does not provide all dependencies, you need to install them yourself.
Go to the folder you created earlier and use pip to install requests to that folder.

pip install --target ./ requests

Package all the contents in that folder (including lambda_function.py) into a .zip file.
In the AWS Lambda console, select the Code tab and click Upload a .zip file.
image

Setting Telegram Bot Webhook#

API Gateway acts as a bridge between the Lambda function and the Telegram server. By setting up a webhook, the content of each user's message to the bot is passed to the API Gateway for Lambda to use.
You can set the webhook by sending a request to the Telegram Bot API.

curl https://api.telegram.org/bot{BOT_TOKEN}/setWebhook?url={GATEWAY_URL}

Note: Replace <BOT_TOKEN> and <API_ENDPOINT_URL> accordingly. For example:

curl https://api.telegram.org/bot5653724882:AAHcfYeYzEDfcg2svKzO9ZpiAFPKl4ulKuQ/setWebhook?url=https://6sgwszwmw0.execute-api.ap-southeast-1.amazonaws.com/Test

If the response is {"ok":true,"result":true,"description":"Webhook is already set"}, it means the webhook has been successfully set.
image

Completion#

Send any message to the bot in Telegram, and the bot will repeat your message. Congratulations!
image

Conclusion#

In this section, ChatGPT generated the content.
In conclusion, AWS Lambda is a serverless computing service that allows you to run code without provisioning or managing servers. This sample project serves as a starting point for using AWS Lambda and the Telegram API, demonstrating how to deploy code to a production environment in minutes and interact with users through a Telegram bot. Additionally, with AWS Lambda's automatic scaling and infrastructure management, operational costs can be significantly reduced when using the service.
If you want to learn more about AWS Lambda or other AWS services, it is recommended to visit the AWS official website for more related documentation and tutorials.

References#

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.