I'm developing Telegram bot based on pyTelegramBotAPI and Django. There is initial code:
import json
import time
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import telebot
from django.conf import settings
if settings.DEBUG:
WEBHOOK_HOST = 'https://zzzz.ngrok.io'
bot = telebot.TeleBot('zzzz')
else:
bot = telebot.TeleBot('zzzz')
WEBHOOK_HOST = 'https://example.com'
WEBHOOK_URL = '/telegram_webhook/'
@bot.message_handler(commands=['start'])
def send_welcome(message):
bot.reply_to(
message,
"Привет! Кажется, мы еще незнакомы. Твой номер: "+str(message.chat.id)
)
@bot.message_handler(func=lambda message: True, content_types=['text'])
def echo_message(message):
bot.reply_to(message, message.text)
@csrf_exempt
def webhook(request):
print(request.body.decode('utf-8'))
update = telebot.types.Update.de_json(json.loads(request.body.decode('utf-8')))
bot.process_new_updates([update])
return JsonResponse({'message': 'OK'}, status=200)
bot.remove_webhook()
time.sleep(1)
bot.set_webhook(
url = WEBHOOK_HOST + WEBHOOK_URL,
)
When I running code locally with ngrok it works well, but when I run it on production server, bot just dont answer on messages.
https://api.telegram.org/botZZZZ/getWebhookInfo returns
{"ok":true,"result":{"url":"https://example.com/telegram_webhook/","has_custom_certificate":false,"pending_update_count":0,"max_connections":40,"ip_address":"194.0.0.0"}}
But if I curl production enpoint with request:
curl --tlsv1.2 -v -k -X POST -H "Content-Type: application/json" -H "Cache-Control: no-cache" -d '{
"update_id":10000,
"message":{
"date":1441645532,
"chat":{
"last_name":"Test Lastname",
"id":1111111,
"first_name":"Test",
"username":"Test"
},
"message_id":1365,
"from":{
"last_name":"Test Lastname",
"id":1111111,
"first_name":"Test",
"username":"Test"
},
"text":"/start"
}
}', "https://example.com/telegram_webhook/"
I will receive some answers from telegram bot and error:
Traceback (most recent call last):
File "/usr/lib/python3.8/json/decoder.py", line 340, in decode
raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 20 column 2 (char 332)
request.body.decode('utf-8')
contains:
{"update_id":337121814,
"message":{"message_id":9,"from":{"id":1000009,"is_bot":false,"first_name":"Boris","last_name":"P","username":"zzzzz","language_code":"ru"},"chat":{"id":124450879,"first_name":"Boris","last_name":"P","username":"zzzzz","type":"private"},"date":1630415986,"text":"hello"}}
Now I have no idea where to dig for the problem. Any thoughts?