This project demonstrates how to create a Telegram bot using Django 5.1.1 and aiogram 3.13.0, utilizing webhooks for efficient communication.
- Features
- Prerequisites
- Installation
- Configuration
- Running the Project
- Setting Up the Webhook
- Testing the Bot
- Deployment Considerations
- Troubleshooting
- Handles
/start
,/help
, and/menu
commands. - Echoes user messages.
- Utilizes aiogram 3.13.0's routers for organizing handlers.
- Integrates with Django 5.1.1 web framework.
- Uses webhooks for efficient message handling.
- Python 3.10+ (Required by Django 5.0)
- Django 5.x
- aiogram 3.x (pre-release)
- ngrok
- Telegram Bot Token from @BotFather
- Git (for cloning the repository)
- Virtualenv or venv (recommended)
git clone https://github.com/yourusername/yourrepository.git
cd yourrepository
Note: Replace https://github.com/murtazox04/django_aiogram3_webhook.git with the actual repository URL if applicable.
Create and activate a virtual environment to isolate the project dependencies.
# For Linux/macOS
python3 -m venv venv
source venv/bin/activate
# For Windows
python -m venv venv
venv\Scripts\activate
pip install --upgrade pip
pip install -r requirements.txt
Create a .env file in the project's root directory to store environment variables.
cp .env.sample .env
Ensure your settings.py includes the environment variables:
# mybot/settings.py
import os
from pathlib import Path
from dotenv import load_dotenv
load_dotenv()
BASE_DIR = Path(__file__).resolve().parent.parent
TELEGRAM_BOT_TOKEN = os.getenv('TELEGRAM_BOT_TOKEN')
WEBHOOK_URL = os.getenv('WEBHOOK_URL')
INSTALLED_APPS = [
# ...
'botapp',
]
ngrok http 8000
python manage.py migrate
uvicorn mybot.asgi:application --host 0.0.0.0 --port 8000
Ensure the management command is correctly set up to close the bot session:
# botapp/management/commands/set_webhook.py
import asyncio
from django.core.management.base import BaseCommand
from django.conf import settings
from aiogram import Bot
class Command(BaseCommand):
help = 'Set the Telegram bot webhook'
def handle(self, *args, **options):
webhook_url = settings.WEBHOOK_URL
asyncio.run(self.set_webhook(webhook_url))
async def set_webhook(self, webhook_url):
bot = Bot(token=settings.TELEGRAM_BOT_TOKEN)
try:
print(f"Setting webhook to: {webhook_url}")
await bot.set_webhook(webhook_url)
self.stdout.write(self.style.SUCCESS(f'Webhook set to {webhook_url}'))
finally:
await bot.session.close()
Run the following command to set the webhook URL with Telegram:
python manage.py set_webhook
You should see a success message confirming the webhook is set.
Interact with your bot on Telegram:
- Send
/start
to receive a welcome message. - Use
/help
to get assistance. - Send any message to see it echoed back.
- Use
/menu
to see an interactive menu.
- HTTPS Requirement: Ensure your webhook URL is accessible over HTTPS with a valid SSL certificate.
- Persistent Server: For production, deploy your app on a server accessible 24/7.
- ASGI Server: Use an ASGI server like uvicorn or daphne for asynchronous support.
- Cause: The webhook URL is not accessible by Telegram.
- Solution:
- Ensure ngrok is running and the URL is correct.
- Upgrade to a paid ngrok plan to remove the interstitial page.
- Verify that the webhook URL is correctly set in the .env file.
- Cause: The aiohttp client session is not properly closed.
- Solution:
- Ensure bot.session.close() is called after setting the webhook.
- Use a try...finally block in your set_webhook.py.
- Cause: The asyncio event loop is closed prematurely.
- Solution:
- Properly await all asynchronous functions.
- Ensure all tasks are completed before the loop closes.
- Access the webhook URL in a browser:
https://your_ngrok_subdomain.ngrok.io/webhook/
. - Use
curl
to test:A 200 OK response indicates the endpoint is accessible.curl -k https://your_ngrok_subdomain.ngrok.io/webhook/
This project is licensed under the MIT License.