Skip to content

Production-grade serverless Telegram bot (aiogram) with Lambda, API Gateway, env-managed config, and streamlined DX for fast iteration as plus small bots can run for free forever πŸš€

Notifications You must be signed in to change notification settings

aoulaa/aiogram-lambda-template

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

4 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Telegram Bot AWS Lambda Template

A robust and scalable template for creating Telegram bots deployed on AWS Lambda using aiogram. This template provides a solid foundation with a clean project structure, local development support, and a flexible, automated deployment pipeline.

Features

  • Asynchronous with aiogram 3.x
  • Serverless on AWS Lambda (API Gateway webhook)
  • Clean project structure (core, handlers, utils)
  • Local development via polling (main.py)
  • Automated deployment script with optional manual upload (deploy.sh)
  • Secure webhook management via Lambda "Test" or deploy script
  • Environment-based configuration (.env.dev, .env.prod)
  • Makefile shortcuts for common tasks

Project Structure

.
β”œβ”€β”€ core/               # Core application logic (bot instance, config)
β”œβ”€β”€ handlers/           # Message and command handlers
β”œβ”€β”€ states/             # FSM states (if used)
β”œβ”€β”€ keyboards/          # Reply/inline keyboards
β”œβ”€β”€ utils/              # Utility functions (e.g., logging)
β”œβ”€β”€ docs/imgs/          # Documentation images
β”œβ”€β”€ .env.example        # Example environment file
β”œβ”€β”€ .gitignore
β”œβ”€β”€ README.md
β”œβ”€β”€ deploy.sh           # Automated deployment script
β”œβ”€β”€ lambda_function.py  # AWS Lambda handler entry point
β”œβ”€β”€ main.py             # Local development (polling)
β”œβ”€β”€ makefile            # Makefile for common commands
└── requirements.txt

Prerequisites

  • Python 3.11+ (Lambda runtime 3.11 or 3.13)
  • AWS account with the AWS CLI configured
  • A Telegram Bot Token from @BotFather

Quickstart

  • Local dev (polling):
    python -m venv .venv && source .venv/bin/activate
    make install-req
    cp .env.example .env.dev  # fill BOT_TOKEN for dev
    make run                  # starts bot locally
  • Deploy to Lambda (interactive):
    cp .env.example .env.prod  # fill BOT_TOKEN, LAMBDA_URL, SECRET_KEY
    make deploy                # choose auto or manual upload

Configuration

This template uses separate env files for dev and prod.

  • .env.dev (local polling):
    BOT_TOKEN="your_development_bot_token"
  • .env.prod (deployed Lambda):
    BOT_TOKEN="your_production_bot_token"
    LAMBDA_URL="https://<api-id>.execute-api.<region>.amazonaws.com/<stage>/webhook"
    SECRET_KEY="a_very_long_and_random_secret"
    • LAMBDA_URL must be the full public API Gateway URL that maps to your Lambda webhook route, including /webhook.
    • SECRET_KEY is used to authorize management commands (e.g., set/delete webhook) via Lambda.

Local Development

To run the bot locally using long polling, simply run:

make run

This uses .env.dev and starts polling via main.py.

Deployment to AWS Lambda

The deploy.sh script handles packaging and (optionally) deployment.

  1. Run the script:
    make deploy
  2. The script will create deployment.zip, then ask: "Do you want to deploy to AWS now? (y/n)"
    • Press y for automated deployment:
      1. Uploads code to Lambda
      2. Updates Lambda environment variables using prod .env credentials
      3. Prompts to set the webhook via a secure Lambda invocation
    • Press n for manual deployment:
      • deployment.zip is left in the project directory for manual upload in the AWS Console

Create Lambda and API Gateway (AWS Console)

  1. Go to Lambda Functions and click Create function
  2. Increase timeout and memory in Configuration if needed
    • Edit memory/timeout
  3. Add a trigger: API Gateway β†’ Create new API
    • Choose a deployment stage (e.g., dev)
    • Use an open security mode for simplicity (you can harden later)
    • Add trigger
  4. In API Gateway, create a route /webhook
    • Create route
  5. Attach the Lambda integration to that route
    • Attach integration
  6. Copy the final webhook URL from API Gateway triggers
    • Format: https://<api-id>.execute-api.<region>.amazonaws.com/<stage>/webhook
    • Webhook endpoint
  7. Add environment variables to Lambda β†’ Configuration β†’ Environment variables
    • Set BOT_TOKEN, LAMBDA_URL, SECRET_KEY
    • Environment variables
  8. Upload the deployment package
    • Click "Upload from" and select deployment.zip
    • Upload from
  9. Set the webhook (two options):
    • Using Lambda Test (manual):
      • Open the Test tab β†’ Create an event with payload:
        {
          "command": "set_webhook",
          "secret": "your_very_secret_key_here"
        }
      • Click Test
      • Invoke test
    • Using the deploy script (automated):
      • When prompted, choose to set the webhook β†’ it will invoke the Lambda with a secure payload
  10. Wait up to a few minutes for the webhook to propagate, then send /start to your bot.

Manual Webhook Management

You can also manage the webhook at any time via the Lambda Test tab using the same JSON payload as above, or via the AWS CLI:

aws lambda invoke \
  --function-name <your-function-name> \
  --payload '{"command":"set_webhook","secret":"<SECRET_KEY>"}' \
  --cli-binary-format raw-in-base64-out \
  --region <region> \
  response.json

To delete the webhook, use "command":"delete_webhook".

Troubleshooting

  • Event loop is closed (Lambda):
    • The template uses a safe pattern that closes the bot session after each invocation in lambda_function.py. Ensure your deployment uses the latest version.
  • 401 Unauthorized from Telegram:
    • Check BOT_TOKEN in Lambda env vars (Configuration β†’ Environment variables).
  • 403 when setting webhook:
    • Ensure LAMBDA_URL is the full API Gateway URL including /webhook and that API Gateway route is deployed.
  • 502/Integration errors in API Gateway:
    • Re-check that the route is integrated with the correct Lambda in the same region and stage is deployed.
  • No messages arriving:
    • Confirm webhook is set (getWebhookInfo via Bot API), and view CloudWatch logs (Lambda β†’ Monitor β†’ Logs).

Security Notes

  • Never commit secrets. .gitignore excludes .env files and build artifacts (build, deployment.zip).
  • Rotate your BOT_TOKEN if it is ever exposed.
  • Choose a strong, random SECRET_KEY and keep it only in Lambda env or .env.prod locally.

Makefile Commands

  • make install-req β€” Installs dependencies from requirements.txt
  • make run β€” Runs the bot locally via polling
  • make deploy β€” Builds deployment.zip and interactively deploys/sets webhook

About

Production-grade serverless Telegram bot (aiogram) with Lambda, API Gateway, env-managed config, and streamlined DX for fast iteration as plus small bots can run for free forever πŸš€

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published