Telegram 机器人不响应命令

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

Telegram 机器人不响应命令。根据日志,webhook 已正常安装,机器人已启动。但它完全忽略机器人中的任何消息,不记录任何内容。您能帮我找出问题所在吗?

import telebot
from telebot.types import InlineKeyboardButton, InlineKeyboardMarkup, CallbackQuery
import logging
from datetime import datetime, timezone
from flask import Flask, request, abort

# Enable logging
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.DEBUG
)
logger = logging.getLogger(__name__)

# Your token
TOKEN = "YOUR_BOT_TOKEN"
# Use the full URL of the webhook provided by Make
WEBHOOK_URL = "YOUR_WEBHOOK_URL"

# Create a bot object
bot = telebot.TeleBot(TOKEN)

# Handler for the /start command
@bot.message_handler(commands=['start'])
def send_welcome(message):
    logger.info(f"Received /start command from user {message.from_user.id}")

    keyboard = InlineKeyboardMarkup()
    keyboard.add(InlineKeyboardButton("Choose time", callback_data='choose_time'))

    bot.send_message(
        message.chat.id,
        "Hello! This bot will send you a word and its definition once a day. Choose a time when it will be convenient for you to read and remember it!",
        reply_markup=keyboard
    )

# Function to determine the user's time zone
def get_user_timezone(message):
    # Get UTC time from the message timestamp
    utc_time = datetime.fromtimestamp(message.date, tz=timezone.utc)
    
    # Determine the offset from UTC in hours
    user_time = utc_time.astimezone()
    offset_seconds = user_time.utcoffset().total_seconds()
    offset_hours = int(offset_seconds // 3600)
    
    user_timezone = f"UTC{'+' if offset_hours >= 0 else ''}{offset_hours}"
    return user_timezone

# Handler for inline buttons
@bot.callback_query_handler(func=lambda call: True)
def callback_query(call: CallbackQuery):
    logger.info(f"Button pressed with callback data: {call.data}")

    if call.data == 'choose_time':
        keyboard = InlineKeyboardMarkup()
        keyboard.add(InlineKeyboardButton("Morning", callback_data='morning'))
        keyboard.add(InlineKeyboardButton("Afternoon", callback_data='afternoon'))
        keyboard.add(InlineKeyboardButton("Evening", callback_data='evening'))
        keyboard.add(InlineKeyboardButton("Night", callback_data='night'))
        bot.edit_message_text(
            chat_id=call.message.chat.id,
            message_id=call.message.message_id,
            text="Choose the time of day:",
            reply_markup=keyboard
        )

    elif call.data in ['morning', 'afternoon', 'evening', 'night']:
        times = {
            'morning': ["06:00", "07:00", "08:00", "09:00", "10:00", "11:00"],
            'afternoon': ["12:00", "13:00", "14:00", "15:00", "16:00", "17:00"],
            'evening': ["18:00", "19:00", "20:00", "21:00", "22:00", "23:00"],
            'night': ["00:00", "01:00", "02:00", "03:00", "04:00", "05:00"]
        }
        chosen_times = times[call.data]
        keyboard = InlineKeyboardMarkup()
        for time in chosen_times:
            keyboard.add(InlineKeyboardButton(time, callback_data=f"time_{time}"))
        bot.edit_message_text(
            chat_id=call.message.chat.id,
            message_id=call.message.message_id,
            text="Choose a specific time:",
            reply_markup=keyboard
        )

    elif call.data.startswith('time_'):
        chosen_time = call.data.split('_')[1]
        
        # Get the user's time zone
        user_timezone = get_user_timezone(call.message)
        
        bot.edit_message_text(
            chat_id=call.message.chat.id,
            message_id=call.message.message_id,
            text=f"You chose the time {chosen_time}, {user_timezone}"
        )

# Create a Flask object
app = Flask(__name__)

# Flask route for handling webhooks
@app.route("/", methods=['POST'])
def webhook():
    logger.info("Received a webhook request to Flask app")
    logger.info(f"Headers: {request.headers}")
    
    if request.headers.get('content-type') == 'application/json':
        json_string = request.get_data().decode('utf-8')
        logger.debug(f"Received JSON string: {json_string}")
        update = telebot.types.Update.de_json(json_string)
        logger.debug(f"Update object: {update}")
        bot.process_new_updates([update])
        logger.info("Update processed successfully by Flask app")
        return 'OK', 200
    else:
        logger.warning("Invalid request received by Flask app")
        abort(400)

# Set the webhook when the app starts
if __name__ == '__main__':
    bot.remove_webhook()
    bot.set_webhook(url=WEBHOOK_URL)
    webhook_info = bot.get_webhook_info()
    logger.info(f"Webhook info: {webhook_info}")

    logger.info("Webhook set. Bot started.")
    app.run(host='0.0.0.0', port=8443)
python flask telegram-bot
1个回答
0
投票

原因是我尝试使用Make创建的webhook。不允许对两个端点使用 webhook。

当我将 Make webhook url 更改为另一个时 – 机器人启动了

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