点击按钮后我的电报机器人没有响应

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

我有一个与 Firebase(特别是 Firestore 数据库)集成的电报机器人(我正在使用 telebot 库)。机器人会询问用户是否想知道房间内消耗的电量或房间内特定设备的电量——设备功能尚未实现。当您单击 Room 时,它会找到所有房间(集合中的文档)并为它找到的每个房间发送一个按钮。

问题是,当您选择一个房间时,机器人应该向您发送在该房间内找到的所有子集合和文档的字段“potencia”的总和,但机器人从未响应,我发现这是因为它从未进入回调功能,但我不知道为什么。

这是我正在使用的代码 TOKEN 和 fire_add 是具有机器人令牌和带有 Firebase 凭据的 .json 文件地址的变量

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
@bot.callback_query_handler(func=lambda call: True)
def callback_query(call):
    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):
    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()

我在回调函数中添加了一些打印件,但它没有进入 def room_query(call)

python firebase google-cloud-firestore python-telegram-bot telebot
© www.soinside.com 2019 - 2024. All rights reserved.