You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Telegram Bot点击房间按钮无响应:回调函数未触发问题排查

问题解决:Telegram Bot点击房间按钮无响应

核心原因

你的代码中第一个callback_query_handler使用了func=lambda call: True,这个条件会匹配所有回调请求。Telebot的回调处理器按注册顺序匹配,只要第一个处理器满足条件就会执行,导致后面的room_query处理器永远不会被触发。

解决方案

修改第一个回调处理器的匹配条件,让它只处理初始的Room和Device选择请求,不拦截后续的房间具体回调。同时建议在所有回调处理中添加bot.answer_callback_query(call.id),避免Telegram客户端一直显示加载状态。

修改后的完整代码

import firebase_admin
from firebase_admin import credentials, firestore
import telebot
from telebot import types
from datetime import datetime

# Initialize the connection to Firebase
cred = credentials.Certificate(fire_add)
firebase_admin.initialize_app(cred)
db = firestore.client()

# Initialize the connection to Telegram
bot = telebot.TeleBot(TOKEN)

# Handle the /start command
@bot.message_handler(commands=['start'])
def start(message):
    markup = types.InlineKeyboardMarkup()
    markup.row(types.InlineKeyboardButton('Room', callback_data='Room'),
               types.InlineKeyboardButton('Device', callback_data='Device'))
    bot.send_message(message.chat.id, "Do you want to know the power consumption of a room or a specific device?", reply_markup=markup)

# Handle the selection of Room or Device (仅匹配初始的Room/Device回调)
@bot.callback_query_handler(func=lambda call: call.data in ['Room', 'Device'])
def callback_query(call):
    bot.answer_callback_query(call.id)  # 回复回调,消除加载状态
    if call.data == 'Room':
        markup = types.InlineKeyboardMarkup()
        # Get all the rooms from the 'vivienda1' collection
        rooms = db.collection('vivienda1').get()
        # Create a button for each room
        for room in rooms:
            markup.row(types.InlineKeyboardButton(room.id, callback_data='Room:' + room.id))
        bot.send_message(call.message.chat.id, "Which room do you want to know the power consumption of?", reply_markup=markup)
    elif call.data == 'Device':
        bot.send_message(call.message.chat.id, "Functionality not yet implemented")

# Handle the selection of a specific room
@bot.callback_query_handler(func=lambda call: call.data.startswith('Room:'))
def room_query(call):
    bot.answer_callback_query(call.id)  # 回复回调,消除加载状态
    room = call.data.split(':')[1]
    total_power = 0
    today = datetime.now().strftime('%Y-%m-%d')
    # Get all the subcollections within the selected room
    subcollections = db.collection('vivienda1').document(room).collections()
    # Sum the power consumption of all subcollections for today
    for subcollection in subcollections:
        docs = subcollection.where('fecha', '==', today).get()
        for doc in docs:
            total_power += doc.to_dict().get('potencia', 0)
    # Return an array with the name of the room and the total power consumption for today
    array = [{'room': room}, {'total_power': total_power}]
    bot.send_message(call.message.chat.id, str(array))

# Start the bot
bot.polling()

额外说明

  • 回调处理器的匹配顺序很重要,注册在前的处理器会优先匹配
  • 所有回调都应该调用bot.answer_callback_query(call.id),否则用户端会一直显示"加载中"的状态
  • 如果后续需要添加更多回调逻辑,建议按回调数据的前缀或类型划分处理器,避免出现全局匹配的情况

内容的提问来源于stack exchange,提问作者Aitana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 19:47:02