pythonanywhere.com telebot webhook 无法工作

问题描述 投票:0回答:1

我尝试在 pythonanywhere.com 上安装 webhook。

工作正常。运行使用 Telegram API 的远程机器人单元测试后,webhook 停止工作。

我尝试使用新的机器人 API 密钥,但没有成功。 我尝试创建一个新的网络应用程序但无济于事。 当我使用“getWebhookInfo”发布到 telegram api 时,它不显示 webhook 的任何 url。 我在 pythonanywhere 错误日志中没有收到任何错误。 在我的本地计算机上使用轮询时,该机器人运行良好。 我已尝试更新所有源代码文件。


#Oct. 9 2023

#faq_bot.py

import os
from telebot import types
import telebot
from flask import Flask, request
import faq_logging as faq_log
import faq_inline_keyboards
import faq_utils
import faq_data_viz

# Set up Flask app
app = Flask(__name__)

logger = faq_log.set_logging('faq_bot.py', 'faq_bot.log')

# Loads the Telegram API token and the questions and answers from a .json file
logger.info('Loading faq_config.json')
json_file ='faq_config.json'
# Loads teh contact us information
contact_file = 'faq_contact_us.txt'
# Loads the prompts
prompt_file = 'faq_prompts.json'
prompts = faq_utils.get_prompts(prompt_file)

logger.info('Creating data directory if it doesnt exist')
if os.path.isdir('data') is False:
    os.mkdir('data')

token, questions_and_answers = faq_utils.parse_json(json_file)

logger.info('Creating telebot instance')
bot = telebot.TeleBot(token, threaded=False)

# Creates two csv files if they don't exist. One containing user feedback, the other user
# search queries. The values in the dictionary are the csv headers.
logger.info('Creating CSV files if they dont exist')
filenames = {'data/faq_feedback.csv': ['question', 'feedback'], \
'data/faq_search_queries.csv': ['query']}
faq_utils.create_csv(filenames)

# Triggers when the user inputs /FAQ or selects FAQ from the Telegram bot menu
@bot.message_handler(commands=['FAQ', 'ask', 'start'])
def faq_command(message: types.Message):
    """
    Function that displays the main menu to the Telegram user when they request it
    
    Args:
    message (types.Message) : telebot message type object
    
    Returns:
    Does not return
    """
    logger.info('FAQ menu initialized')
    bot.send_message(message.chat.id, prompts[0],
                     reply_markup=faq_inline_keyboards.faq_keyboard(questions_and_answers))

@bot.message_handler(commands=['42hiddenData67'])
def data_viz(message: types.Message):
    """
    Function that sends the data visualization to the Telegram user when they request it
    
    Args:
    message (types.Message) : telebot message type object
    
    Returns:
    Does not return
    """
    data_viz_files = faq_data_viz.create_data_viz(list(filenames.keys()))
    zip_file = faq_data_viz.export_data_viz(data_viz_files)
    logger.info('Sending data visualization')
    bot.send_message(message.chat.id, prompts[1])
    bot.send_document(message.chat.id, open(zip_file, 'rb'))

# Triggers when the user inputs /Contact or selects Contact Us from the Telegram bot menu
@bot.message_handler(commands=['contact'])
def contact_command(message: types.Message):
    """
    Function that displays the company contact information when the user requests it
    
    Args:
    message (types.Message) : telebot message type object
    
    Returns:
    Does not return
    """
    logger.info('Contact info being sent')
    with open(contact_file, 'r') as fn:
        contact_info = fn.read()
    bot.send_message(message.chat.id, prompts[2])
    bot.send_message(message.chat.id, contact_info)

# Handler that processes data returned by the Telegram bot API as callback data
@bot.callback_query_handler(func=lambda call: True)
def keyboard_callback_handle(call: types.CallbackQuery):
    """
    Function that responds to Telegram callback queries
    
    Args:
    call (types.CallbackQuery) : telebot callbackquery type object
    
    Returns:
    Does not return
    """
    # Flattens the questions and answers dictionary so nested questions can be found
    qna_flattened = dict(faq_utils.flatten_dict(questions_and_answers))
    try:
        # Displays the next tier in the nested menu to the user based on their previous selection
        if isinstance(qna_flattened[call.data], dict) == True:
            logger.info('Displaying nested menu')
            bot.send_message(call.from_user.id, prompts[3],
                reply_markup=faq_inline_keyboards.faq_keyboard(qna_flattened[call.data]))
        else:
            # Sends the answer and collects user feedback
            logger.info('Sending answer and asking for feedback')
            bot.send_message(call.from_user.id, qna_flattened[call.data])
            bot.send_message(call.from_user.id, prompts[4],
                               reply_markup=faq_inline_keyboards.feedback(call.data))
    # KeyError will occur when the markup keyboard returns the feedback value, since those
    # values are not in the questions and answers dictionary. This is exploited to process
    # the feedback while handling the exception
    except KeyError:
        logger.info('Adding feedback to csv')
        if call.data[-3:] == 'yes' or call.data[-2:] == 'no':
            # Creates a list that seperates the questions ([:-1]) from the feedback ([-1])
            csv_list = [' '.join(call.data.split()[:-1]), call.data.split()[-1]]
            faq_utils.to_csv(csv_list, list(filenames.keys())[0])
            bot.send_message(call.from_user.id, prompts[5])

# Handler that will respons to any input from the user that isn't handled above
@bot.message_handler(func=lambda message: True)
def handle_message(message: types.Message):
    """
    Function that handles any input from the user that isn't handles by the other handlers. The user input will be used to search the questions from the FAQ
    
    Args:
    message (types.Message) : telebot message type object
    
    Returns:
    Does not return
    """
    logger.info('Collecting questions based on user search query. Adding queries to .csv')
    questions = faq_utils.search_questions(message.text, questions_and_answers)
    # Adds teh search query to the .csv collection of queries
    faq_utils.to_csv([message.text], list(filenames.keys())[1])
    # Displays a set of buttons that contain the quetions relevant to the query
    if len(questions) > 0:
        bot.send_message(message.chat.id, prompts[6],
                           reply_markup=faq_inline_keyboards.faq_keyboard(questions))
    else:
        bot.send_message(message.chat.id, prompts[7])

logger.info('Telebot webhook started')

# Define the webhook route
@app.route('/', methods=['POST'])
def webhook():
    """
    Function that creates the webhook for the Telegram bot API
    
    Returns:
    Does not return
    """
    update = telebot.types.Update.de_json(request.stream.read().decode('utf-8'))
    bot.process_new_updates([update])
    return 'OK'

# Set the webhook URL
bot.remove_webhook()
bot.set_webhook(url='https://shorecode.pythonanywhere.com', drop_pending_updates=True)

WSGI:

# This file contains the WSGI configuration required to serve up your
# web application at http://<your-username>.pythonanywhere.com/
# It works by setting the variable 'application' to a WSGI handler of some
# description.
#
# The below has been auto-generated for your Flask project

import sys

# add your project directory to the sys.path
project_home = '/home/shorecode'
if project_home not in sys.path:
    sys.path = [project_home] + sys.path

# import flask app but need to call it "application" for WSGI to work
from faq_bot import app as application  # noqa

python telegram webhooks pythonanywhere telebot
1个回答
0
投票

通过 pip install -rrequirements.txt 安装依赖项解决了这个问题。错误日志中确定的依赖项是 valdec,其他依赖项也可能丢失。

© www.soinside.com 2019 - 2024. All rights reserved.