Python PyTapi不';不要对信息做出反应

Python PyTapi不';不要对信息做出反应,python,telegram-bot,cherrypy,py-telegram-bot-api,Python,Telegram Bot,Cherrypy,Py Telegram Bot Api,我正在vultr vps上开发电报机器人。我使用的软件包: Python 3.6.8 皮博塔皮 小马蚁 樱桃味 我设置了webhook,它返回成功,但我的机器人不会对命令、消息等做出反应。我使用的是pytelegrambotapi 这是我的代码: #!/usr/bin/env python3 # -*- coding: utf-8 -*- # This is a simple echo bot using decorators and webhook with CherryPy # It

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

  • Python 3.6.8
  • 皮博塔皮
  • 小马蚁
  • 樱桃味
我设置了webhook,它返回成功,但我的机器人不会对命令、消息等做出反应。我使用的是
pytelegrambotapi

这是我的代码:

#!/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, {'/': {}})
#/usr/bin/env蟒蛇3
#-*-编码:utf-8-*-
#这是一个简单的echo机器人,使用decorators和带有CherryPy的webhook
#它回显任何传入的文本消息,并且不使用轮询方法。
进口樱桃
进口遥控机器人
导入日志记录
API_标记=“”
WEBHOOK_HOST='这是我的主机'
WEBHOOK_PORT=8443#443、80、88或8443(端口需要“打开”)
WEBHOOK_LISTEN='0.0.0.0'#在某些VPS中,您可能需要将IP地址放在这里
WEBHOOK_SSL_CERT='./WEBHOOK_CERT.pem'#SSL证书的路径
WEBHOOK_SSL_PRIV='./WEBHOOK_pkey.pem'#SSL私钥的路径
#快速“n”脏SSL证书生成:
#
#openssl genrsa-out webhook_pkey.pem 2048
#openssl请求-新建-x509-第3650天-密钥webhook_pkey.pem-输出webhook_cert.pem
#
#当被问及“通用名称(例如服务器FQDN或您的名称)”时,您应该回答
#在WEBHOOK\u主机中输入相同的值
WEBHOOK\u URL\u BASE=“https://%s:%s”%(WEBHOOK\u主机,WEBHOOK\u端口)
WEBHOOK_URL_PATH=“/%s/”%(API_令牌)
logger=telebot.logger
telebot.logger.setLevel(logging.INFO)
bot=telebot.telebot(API_令牌)
#WebhookServer,处理webhook调用
类WebhookServer(对象):
@樱桃树
def索引(自):
如果cherrypy.request.headers中的“内容长度”为\
cherrypy.request.headers中的“内容类型”和\
cherrypy.request.headers['content-type']='application/json':
length=int(cherrypy.request.headers['content-length'])
json_string=cherrypy.request.body.read(长度)
update=telebot.types.update.de_json(json_字符串)
bot.process\u新消息([update.message])
返回“”
其他:
raise cherrypy.HTTPError(403)
#处理“/start”和“/help”
@消息处理程序(命令=['help','start'])
def发送_欢迎(信息):
bot.回复(消息、,
(“你好,我是EchoBot。\n”
“我在这里是为了回应你的好话。”)
#处理所有其他消息
@消息处理程序(func=lambda消息:True,内容类型=['text']))
def回显_消息(消息):
bot.reply_to(message,message.text)
#移除webhook,如果存在以前的webhook,则设置有时会失败
bot.remove_webhook()
#设置webhook
bot.set\u webhook(url=webhook\u url\u BASE+webhook\u url\u PATH,
证书=打开(WEBHOOK\u SSL\u CERT,'r'))
#启动cherrypy服务器
cherrypy.config.update({
“server.socket\u host”:WEBHOOK\u侦听,
'server.socket_-port':WEBHOOK_-port,
'server.ssl_module':'builtin',
“server.ssl\u证书”:WEBHOOK\u ssl\u证书,
'server.ssl\u private\u key':WEBHOOK\u ssl\u PRIV
})
quickstart(WebhookServer(),WEBHOOK_URL_路径,{'/':{})

我从我提到的指南中复制了它,但我的代码与此完全相同。我有由letsencrypt生成的SSL证书。没有错误,什么都没有。我想说的是,我设置了正确的权限,没有权限错误。

我找到了一个解决方案。如果您不知道该做什么,请使用
getWebhookInfo
。我不知道为什么,但在示例中,
json\u字符串
变量没有解码。。。因此,我使用了
json\u string.decode(“utf-8”)
,最终我开始从电报机器人获取消息。在修复之前,我还删除了bot.set_webhook()的第二个参数,因为Telegrame不想验证letsencrypt证书。因此,对我来说,最终的工作代码是:

#!/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, {'/': {}})
#/usr/bin/env蟒蛇3
#-*-编码:utf-8-*-
#这是一个简单的echo机器人,使用decorators和带有CherryPy的webhook
#它回显任何传入的文本消息,并且不使用轮询方法。
进口樱桃
进口遥控机器人
导入日志记录
API_标记=“”
WEBHOOK_HOST='这是我的主机'
WEBHOOK_PORT=8443#443、80、88或8443(端口需要“打开”)
WEBHOOK_LISTEN='0.0.0.0'#在某些VPS中,您可能需要将IP地址放在这里
WEBHOOK_SSL_CERT='./WEBHOOK_CERT.pem'#SSL证书的路径
WEBHOOK_SSL_PRIV='./WEBHOOK_pkey.pem'#SSL私钥的路径
#快速“n”脏SSL证书生成:
#
#openssl genrsa-out webhook_pkey.pem 2048
#openssl请求-新建-x509-第3650天-密钥webhook_pkey.pem-输出webhook_cert.pem
#
#当被问及“通用名称(例如服务器FQDN或您的名称)”时,您应该回答
#在WEBHOOK\u主机中输入相同的值
WEBHOOK\u URL\u BASE=“https://%s:%s”%(WEBHOOK\u主机,WEBHOOK\u端口)
WEBHOOK_URL_PATH=“/%s/”%(API_令牌)
logger=telebot.logger
telebot.logger.setLevel(logging.INFO)
bot=telebot.telebot(API_令牌)
#WebhookServer,处理webhook调用
类WebhookServer(对象):
@樱桃树
def索引(自):
如果cherrypy.request.headers中的“内容长度”为\
cherrypy.request.headers中的“内容类型”和\
cherrypy.request.headers['content-type']='application/json':
length=int(cherrypy.request.headers['content-length'])
json_string=cherrypy.request.body.read(长度)
update=telebot.types.update.de_json(json_string.decode(“utf-8”))
bot.process\u新消息([update.message])
返回“”
其他:
raise cherrypy.HTTPError(403)
#处理“/start”和“/help”
@消息处理程序(命令=['help','start'])
def发送_欢迎(信息):
bot.回复(消息、,
(“你好,我是EchoBot。\n”
“我在这里是为了回应你的好话。”)
#处理所有其他消息
@消息处理程序(func=lambda消息:True,内容类型=['text']))
def回显_消息(消息):
bot.reply_to(message,message.text)
#移除webhook,有时设置失败