【问题标题】:PyTelegramBotApi doesn't react to messagesPyTelegramBotApi 不对消息做出反应
【发布时间】:2019-07-01 22:55:10
【问题描述】:

我正在 vultr vps 上开发电报机器人。我使用的软件包:

  • Python 3.6.8
  • PyTelegramBotApi
  • 小马奥姆
  • CherryPy

我设置了 webhook,它返回成功,但我的机器人对命令、消息等没有反应。我正在使用来自 pytelegrambotapi here 的指南

这是我的代码:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# This is a simple echo bot using decorators and webhook with CherryPy
# It echoes any incoming text messages and does not use the polling method.

import cherrypy
import telebot
import logging


API_TOKEN = '<api_token>'

WEBHOOK_HOST = 'here is my host'
WEBHOOK_PORT = 8443  # 443, 80, 88 or 8443 (port need to be 'open')
WEBHOOK_LISTEN = '0.0.0.0'  # In some VPS you may need to put here the IP addr

WEBHOOK_SSL_CERT = './webhook_cert.pem'  # Path to the ssl certificate
WEBHOOK_SSL_PRIV = './webhook_pkey.pem'  # Path to the ssl private key

# Quick'n'dirty SSL certificate generation:
#
# openssl genrsa -out webhook_pkey.pem 2048
# openssl req -new -x509 -days 3650 -key webhook_pkey.pem -out webhook_cert.pem
#
# When asked for "Common Name (e.g. server FQDN or YOUR name)" you should reply
# with the same value in you put in WEBHOOK_HOST

WEBHOOK_URL_BASE = "https://%s:%s" % (WEBHOOK_HOST, WEBHOOK_PORT)
WEBHOOK_URL_PATH = "/%s/" % (API_TOKEN)


logger = telebot.logger
telebot.logger.setLevel(logging.INFO)

bot = telebot.TeleBot(API_TOKEN)


# WebhookServer, process webhook calls
class WebhookServer(object):
    @cherrypy.expose
    def index(self):
        if 'content-length' in cherrypy.request.headers and \
           'content-type' in cherrypy.request.headers and \
           cherrypy.request.headers['content-type'] == 'application/json':
            length = int(cherrypy.request.headers['content-length'])
            json_string = cherrypy.request.body.read(length)
            update = telebot.types.Update.de_json(json_string)
            bot.process_new_messages([update.message])
            return ''
        else:
            raise cherrypy.HTTPError(403)


# Handle '/start' and '/help'
@bot.message_handler(commands=['help', 'start'])
def send_welcome(message):
    bot.reply_to(message,
                 ("Hi there, I am EchoBot.\n"
                  "I am here to echo your kind words back to you."))


# Handle all other messages
@bot.message_handler(func=lambda message: True, content_types=['text'])
def echo_message(message):
    bot.reply_to(message, message.text)


# Remove webhook, it fails sometimes the set if there is a previous webhook
bot.remove_webhook()

# Set webhook
bot.set_webhook(url=WEBHOOK_URL_BASE+WEBHOOK_URL_PATH,
                certificate=open(WEBHOOK_SSL_CERT, 'r'))

# Start cherrypy server
cherrypy.config.update({
    'server.socket_host': WEBHOOK_LISTEN,
    'server.socket_port': WEBHOOK_PORT,
    'server.ssl_module': 'builtin',
    'server.ssl_certificate': WEBHOOK_SSL_CERT,
    'server.ssl_private_key': WEBHOOK_SSL_PRIV
})

cherrypy.quickstart(WebhookServer(), WEBHOOK_URL_PATH, {'/': {}})

我从我提到的指南中复制了它,但我的代码完全一样。我有letsencrypt生成的SSL证书。没有错误,什么都没有。想提一下,我设置了正确的权限,没有权限错误。

【问题讨论】:

    标签: python telegram-bot cherrypy py-telegram-bot-api


    【解决方案1】:

    我找到了解决方案。如果您不知道该怎么做,请使用getWebhookInfo。我不知道为什么,但在示例中,json_string 变量没有解码......所以我使用了json_string.decode("utf-8"),我终于开始从电报机器人接收消息。在我修复之前,我还删除了 bot.set_webhook() 的第二个参数,因为电报不想验证 letencrypt 证书。所以对我来说最终的工作代码是:

    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    
    # This is a simple echo bot using decorators and webhook with CherryPy
    # It echoes any incoming text messages and does not use the polling method.
    
    import cherrypy
    import telebot
    import logging
    
    
    API_TOKEN = '<api_token>'
    
    WEBHOOK_HOST = 'here is my host'
    WEBHOOK_PORT = 8443  # 443, 80, 88 or 8443 (port need to be 'open')
    WEBHOOK_LISTEN = '0.0.0.0'  # In some VPS you may need to put here the IP addr
    
    WEBHOOK_SSL_CERT = './webhook_cert.pem'  # Path to the ssl certificate
    WEBHOOK_SSL_PRIV = './webhook_pkey.pem'  # Path to the ssl private key
    
    # Quick'n'dirty SSL certificate generation:
    #
    # openssl genrsa -out webhook_pkey.pem 2048
    # openssl req -new -x509 -days 3650 -key webhook_pkey.pem -out webhook_cert.pem
    #
    # When asked for "Common Name (e.g. server FQDN or YOUR name)" you should reply
    # with the same value in you put in WEBHOOK_HOST
    
    WEBHOOK_URL_BASE = "https://%s:%s" % (WEBHOOK_HOST, WEBHOOK_PORT)
    WEBHOOK_URL_PATH = "/%s/" % (API_TOKEN)
    
    
    logger = telebot.logger
    telebot.logger.setLevel(logging.INFO)
    
    bot = telebot.TeleBot(API_TOKEN)
    
    
    # WebhookServer, process webhook calls
    class WebhookServer(object):
        @cherrypy.expose
        def index(self):
            if 'content-length' in cherrypy.request.headers and \
               'content-type' in cherrypy.request.headers and \
               cherrypy.request.headers['content-type'] == 'application/json':
                length = int(cherrypy.request.headers['content-length'])
                json_string = cherrypy.request.body.read(length)
                update = telebot.types.Update.de_json(json_string.decode("utf-8"))
                bot.process_new_messages([update.message])
                return ''
            else:
                raise cherrypy.HTTPError(403)
    
    
    # Handle '/start' and '/help'
    @bot.message_handler(commands=['help', 'start'])
    def send_welcome(message):
        bot.reply_to(message,
                     ("Hi there, I am EchoBot.\n"
                      "I am here to echo your kind words back to you."))
    
    
    # Handle all other messages
    @bot.message_handler(func=lambda message: True, content_types=['text'])
    def echo_message(message):
        bot.reply_to(message, message.text)
    
    
    # Remove webhook, it fails sometimes the set if there is a previous webhook
    bot.remove_webhook()
    
    # Set webhook
    bot.set_webhook(url=WEBHOOK_URL_BASE+WEBHOOK_URL_PATH)
    
    # Start cherrypy server
    cherrypy.config.update({
        'server.socket_host': WEBHOOK_LISTEN,
        'server.socket_port': WEBHOOK_PORT,
        'server.ssl_module': 'builtin',
        'server.ssl_certificate': WEBHOOK_SSL_CERT,
        'server.ssl_private_key': WEBHOOK_SSL_PRIV
    })
    
    cherrypy.quickstart(WebhookServer(), WEBHOOK_URL_PATH, {'/': {}})
    

    【讨论】:

      猜你喜欢
      • 2021-03-05
      • 2021-08-14
      • 1970-01-01
      • 2019-05-24
      • 2021-05-14
      • 1970-01-01
      • 1970-01-01
      • 2021-05-08
      • 2021-08-08
      相关资源
      最近更新 更多