This project deploys a Telegram chatbot on AWS using Infrastructure as Code (Terraform). It provisions S3 buckets for storing archived chat history, DynamoDB tables for managing user sessions, Lambda for serverless processing, and API Gateway for real-time webhook integration with Telegram.
⚠️ Status: Currently in development. Ollama AI integration (backend models) is not yet implemented. Session management, commands, archive features, and Telegram connectivity are fully functional.
- Overview
- Architecture
- Features
- Prerequisites
- AWS Academy Setup
- Deployment
- Telegram Webhook Setup
- Bot Commands
- Project Structure
- Data Storage
- Verification
- Troubleshooting
- Cleanup
- License
This project creates a serverless Telegram bot running on AWS. When users send messages to the bot, Telegram forwards them to an API Gateway endpoint, which triggers a Lambda function to process the message and respond.
Key Features:
- ✅ Real-time message handling via API Gateway webhook
- ✅ User session creation and management
- ✅ Command handling (
/help,/newsession,/listsessions,/switch,/history,/echo) - ✅ Archive system (
/archive,/listarchives,/export, file import) - ✅ DynamoDB for live session storage
- ✅ S3 for archived session storage
- ⏳ Ollama AI integration (planned for next phase)
┌─────────────┐ ┌─────────────────┐ ┌────────────────┐
│ Telegram │─────▶│ API Gateway │─────▶│ Lambda │
│ User │◀─────│ (webhook) │◀─────│ (handler.py) │
└─────────────┘ └─────────────────┘ └────────────────┘
│
┌───────────────────────┴───────────────────────┐
▼ ▼
┌─────────────────┐ ┌─────────────────┐
│ DynamoDB │ │ S3 │
│ (active sessions)│ │ (archived chats)│
└─────────────────┘ └─────────────────┘
Flow:
- User sends a message to the Telegram bot
- Telegram POSTs the update to API Gateway webhook URL
- API Gateway triggers Lambda function
- Lambda processes the message (command or chat)
- Active session data is stored/retrieved from DynamoDB
- Archived sessions are stored in S3
- Lambda sends response back to Telegram
| Command | Purpose | Status |
|---|---|---|
/start or /hello |
Initialize and greet user | ✅ Working |
/help |
Show available commands | ✅ Working |
/newsession |
Create a new chat session | ✅ Working |
/listsessions |
List all user sessions | ✅ Working |
/switch <number> |
Switch to a different session | ✅ Working |
/history |
Show recent messages in session | ✅ Working |
/archive |
List sessions available to archive | ✅ Working |
/archive <number> |
Archive a specific session to S3 | ✅ Working |
/listarchives |
List archived sessions | ✅ Working |
/export <number> |
Export archive as JSON file | ✅ Working |
| Send JSON file | Import archive from file | ✅ Working |
/status |
Check bot status | ✅ Working |
/echo <text> |
Echo back text (test command) | ✅ Working |
| Chat messages | Send to AI model | ⏳ Not implemented |
- AWS Academy Learner Lab access (or AWS account)
- Terraform >= 1.0.0
- AWS CLI configured with credentials
- Python 3.9+ with pip
- Telegram Bot Token (from @BotFather)
- Open AWS Academy and navigate to "Launch AWS Academy Learner Lab"
- Click Start Lab and wait for the status to turn green
- Click AWS Details to view credentials
Click Show next to "AWS CLI" in AWS Details and copy the credentials:
# Edit credentials file
nano ~/.aws/credentialsPaste the credentials:
[default]
aws_access_key_id=ASIA...
aws_secret_access_key=...
aws_session_token=FwoGZX...aws sts get-caller-identityaws iam get-role --role-name LabRole --query 'Role.Arn' --output textOutput: arn:aws:iam::ACCOUNT_ID:role/LabRole
git clone https://github.com/Man2Dev/cloud-Ai.git
cd cloud-Ai
# Create configuration file
cp terraform.tfvars.example terraform.tfvarsEdit terraform.tfvars:
telegram_token = "YOUR_TELEGRAM_BOT_TOKEN"
lab_role_arn = "arn:aws:iam::YOUR_ACCOUNT_ID:role/LabRole"# Clean previous builds
rm -rf package/ lambda_function.zip
# Create package directory
mkdir -p package
# Install dependencies
pip install -r requirements.txt -t ./package
# Copy handler
cp handler.py package/# Initialize Terraform
terraform init
# Preview changes
terraform plan
# Deploy
terraform apply -auto-approveAfter deployment, Terraform will output:
api_gateway_url- Your webhook URLs3_bucket_name- S3 bucket for archivesdynamodb_table_name- DynamoDB table namelambda_function_name- Lambda function name
Replace YOUR_BOT_TOKEN and use the api_gateway_url from Terraform output:
curl "https://api.telegram.org/botYOUR_BOT_TOKEN/setWebhook?url=YOUR_API_GATEWAY_URL"Example:
curl "https://api.telegram.org/bot123456:ABC-DEF/setWebhook?url=https://abc123.execute-api.us-east-1.amazonaws.com/prod/webhook"curl "https://api.telegram.org/botYOUR_BOT_TOKEN/getWebhookInfo"Expected response:
{
"ok": true,
"result": {
"url": "https://abc123.execute-api.us-east-1.amazonaws.com/prod/webhook",
"has_custom_certificate": false,
"pending_update_count": 0
}
}- Open Telegram and find your bot
- Send
/startor/help - The bot should respond instantly!
.
├── provider.tf # AWS provider configuration
├── main.tf # Infrastructure resources (S3, DynamoDB, Lambda, API Gateway)
├── outputs.tf # Terraform outputs (URLs, resource names)
├── terraform.tfvars.example # Example configuration file
├── terraform.tfvars # Your configuration (gitignored)
├── requirements.txt # Python dependencies
├── handler.py # Lambda function code
├── package/ # Lambda deployment package (generated)
├── lambda_function.zip # Zipped Lambda package (generated)
├── .gitignore # Git ignore rules
├── LICENSE # GPL v3 License
└── README.md # This documentation
Table: chatbot-sessions
| Attribute | Type | Purpose |
|---|---|---|
pk |
Number | Telegram user ID (partition key) |
sk |
String | Session identifier (sort key) |
model_name |
String | Selected AI model |
session_id |
String | UUID for the session |
conversation |
List | Array of messages |
is_active |
Number | 1 = active, 0 = inactive |
last_message_ts |
Number | Unix timestamp |
Global Secondary Indexes:
model_index- Query by model across usersactive_sessions_index- Query active sessions
Bucket: chatbot-conversations-{ACCOUNT_ID}
Structure:
chatbot-conversations-123456789/
└── archives/
└── {user_id}/
├── {session_id_1}.json
└── {session_id_2}.json
# Check Lambda
aws lambda get-function --function-name telegram-bot
# Check DynamoDB
aws dynamodb describe-table --table-name chatbot-sessions
# Check S3
aws s3 ls
# Check API Gateway
aws apigateway get-rest-apis
# View Lambda logs
aws logs tail /aws/lambda/telegram-bot --followAccess the console through AWS Academy:
- Click AWS button (green dot) in Vocareum
- Navigate to Lambda, DynamoDB, S3, API Gateway services
- Session tokens expire every few hours
- Refresh credentials from AWS Academy → AWS Details
- AWS Academy restricts IAM role creation
- Use the pre-existing
LabRolevialab_role_arnvariable
- Check CloudWatch logs:
aws logs tail /aws/lambda/telegram-bot --follow - Verify environment variables are set
- Verify API Gateway URL is correct
- Test Lambda directly:
aws lambda invoke --function-name telegram-bot out.json - Check webhook info:
curl "https://api.telegram.org/bot<TOKEN>/getWebhookInfo"
- Bucket names must be globally unique
- The template uses
chatbot-conversations-{ACCOUNT_ID}for uniqueness
terraform destroy -auto-approvecurl "https://api.telegram.org/botYOUR_BOT_TOKEN/deleteWebhook"# Deploy
terraform init && terraform apply -auto-approve
# Get webhook URL
terraform output api_gateway_url
# Set webhook
curl "https://api.telegram.org/bot<TOKEN>/setWebhook?url=<URL>"
# Check webhook
curl "https://api.telegram.org/bot<TOKEN>/getWebhookInfo"
# View logs
aws logs tail /aws/lambda/telegram-bot --follow
# Test Lambda
aws lambda invoke --function-name telegram-bot out.json && cat out.json
# Destroy
terraform destroy -auto-approveThis project is licensed under GNU General Public License v3.0 or later (GPLv3+). See LICENSE for details.