首页 > 解决方案 > 生产服务器上的 Telegram webhook 问题

问题描述

我正在开发基于pyTelegramBotAPI和 Django 的 Telegram 机器人。有初始代码:

    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,
)

当我使用ngrok在本地运行代码时,它运行良好,但是当我在生产服务器上运行它时,机器人只是不回答消息。

https://api.telegram.org/botZZZZ/getWebhookInfo返回

{"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"}}

但是,如果我根据要求卷曲生产点:

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/"

我将从电报机器人和错误中收到一些答案:

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')包含:

{"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"}}

现在我不知道在哪里挖掘问题。有什么想法吗?

标签: python-3.xdjangotelegram-bottelegram-webhookpy-telegram-bot-api

解决方案


推荐阅读