from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from telegram import Bot, Update
from telegram.ext import Dispatcher, CommandHandler
from telegram.error import BadRequest
# Create a Telegram Bot instance with your bot token
bot_token = 'your_bot_token_here'
bot = Bot(token=bot_token)
# Create a Dispatcher to handle updates
dispatcher = Dispatcher(bot, None)
# Define a command handler for /start command
@csrf_exempt
def start_command_handler(update: Update, context):
"""Handle the /start command"""
chat_id = update.effective_chat.id
message = 'Hello! This is your bot.'
try:
bot.send_message(chat_id=chat_id, text=message)
except BadRequest as e:
# Handle any error while sending message
print(f'Error while sending message: {e}')
return HttpResponse(status=200)
# Register the command handler
dispatcher.add_handler(CommandHandler('start', start_command_handler))
# Define a view function for Telegram bot webhook
@csrf_exempt
def telegram_webhook(request):
"""Handle incoming Telegram updates"""
if request.method == 'POST':
# Retrieve the JSON data from the request
data = request.body.decode('utf-8')
# Create an Update object from the JSON data
update = Update.de_json(data, bot)
# Process the update using the Dispatcher
dispatcher.process_update(update)
return HttpResponse(status=200)