Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Hosted-services / serverless

Creating an AWS Lambda Powered Telegram Bot

4.89/5 (7 votes)
14 Jul 2023CPOL3 min read 7K  
Create a simple but scalable Telegram bot using AWS Lambda and the python-telegram-bot library
This tutorial demonstrates how to create a Telegram bot using AWS Lambda and the python-telegram-bot library. It provides a step-by-step guide for setting up an AWS Lambda function and configuring it to act as a Telegram bot. By following the instructions, readers will be able to build a fully functional and scalable bot capable of processing incoming messages and commands.

Introduction

This is a small tutorial on creating a very simple bot using AWS Lambda and the Python library, https://python-telegram-bot.org.

Step 1

Let's begin with AWS-related tasks. Firstly, you'll need an account (which you can create for free here). After successfully signing in, navigate to the Lambda service and click on Create function.

Image 1

Image 2

Step 2

In the Create function dialog, select the Python 3 runtime and choose any desired function name. You can leave everything else as it is. Click on the Create function button at the bottom and proceed.

Image 3

Step 3

Now we need to create a layer with our Python dependencies to use them inside our newly created Lambda function. The Python dependencies should be packed as a zip archive to be imported into the Lambda function's environment. While you can try to do this on your own laptop, there is a possibility of encountering different problems that will result in non-working dependencies. To ensure that the Python dependencies will work as expected, it's better to launch an EC2 instance and perform all the required actions there and then copy-paste the archive from the EC2 instance to your Lambda environment.

Here's the plan:

  • Launch an EC2 instance.
  • Connect to the instance via SSH.
  • Install the required Python dependencies and pack them into a zip archive.

Go to the EC2 service, navigate to Instances, and select Launch instances:

Image 4

Choose all the defaults (Amazon Linux 2 image, x86_64 architecture, and the micro instance type is what we need here). Don't forget to select a key pair, as it is necessary for logging in. Click on Launch instance.

Image 5

Go to the instance summary and obtain the public IPv4 DNS to establish a connection.

Image 6

Connect to the created VM using SSH:

BAT
ssh -i "default.pem" ec2-user@ec2-54-86-3-144.compute-1.amazonaws.com

By default, Python 3.7 is installed. Let's update it to Python 3.9 by running the following commands:

Bash
sudo yum install gcc openssl-devel bzip2-devel libffi-devel
cd /opt
sudo wget https://www.python.org/ftp/python/3.9.6/Python-3.9.6.tgz
sudo tar xzf Python-3.9.6.tgz
cd Python-3.9.6
sudo ./configure --enable-optimizations
sudo make altinstall
sudo rm -f /opt/Python-3.9.6.tgz

Now that you have Python 3.9 installed on your VM, you can verify it by using the following command:

Bash
python3.9 -V

It's time to install our dependencies and create a zip archive with them.

Bash
cd /home/ec2-user/
python3.9 -m venv env
source env/bin/activate
mkdir python
cd python
pip3 install -t . python-telegram-bot
rm -r *dist-info
cd ..
zip -r deployment_package.zip python

You now have the deployment_package.zip file containing all the dependencies needed for a new Lambda layer. Copy this zip file to your computer using scp command:

Bash
scp -i "default.pem" 
ec2-user@ec2-54-86-3-144.compute-1.amazonaws.com:/home/ec2-user/deployment_package.zip .

Next, navigate to the Lambda service, then go to Layers and click on Create layer:

Image 7

Image 8

Upload your local zip file containing the dependencies. The compatible architectures and runtimes will be used to determine if the layer is suitable for a specific function.

Return to your function, click on Layers, and select Add a layer.

Image 9

Image 10

Choose Custom layers and select the layer you created:

Image 11

That's it! We have successfully created a layer with all our dependencies. Now, within our Lambda function, we will have access to the external libraries that we provided in the zip archive. If there are any issues with the archive, you won't be able to access the dependencies and may encounter errors indicating that the module does not exist.

Step 4

Now it's time to create a Telegram bot using BotFather. Obtain the token and add it to the environment variables of your Lambda function.

Image 12

Now, return to the Code tab and paste it inside:

Python
import asyncio
import json
import os
import traceback

from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes

bot_app = ApplicationBuilder().token(os.getenv('TELEGRAM_TOKEN')).build()

async def hello(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    await update.message.reply_text(f'Hello {update.effective_user.first_name}')

bot_app.add_handler(CommandHandler("hello", hello))

async def tg_bot_main(bot_app, event):
    async with bot_app:
        await bot_app.process_update(
            Update.de_json(json.loads(event["body"]), bot_app.bot)
        )

def lambda_handler(event, context):
    try:
        asyncio.run(tg_bot_main(bot_app, event))
    except Exception as e:
        traceback.print_exc()
        print(e)
        return {"statusCode": 500}

    return {"statusCode": 200}

Click on Deploy, and you are all set! Go to your bot and enter /hello.

The code above is quite simple and can be used as is, with the addition of required handlers for different types of commands. For more complex tasks, refer to the documentation at https://python-telegram-bot.org.

One important note: To view logs, navigate to the Monitor tab of your Lambda function.

Image 13

It usually takes some time for logs to appear, so please be patient. They should arrive within approximately two minutes.

History

  • 14th July, 2023: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)