Python telebot不能与不同的用户一起工作

2024-06-28 14:44:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我在开发和python方面也是新手。我试着用Telebot编写一个简单的电报机器人。该场景是在用户单击按钮执行某些逻辑时向用户显示内联键盘。在下面的示例中,我剪切了代码,但它显示了问题。问题是: 当第一个用户开始工作时,他会得到正确的和所有的通知。但当第二个用户开始使用bot时,他得到了正确的键盘,但通知将发送给第一个用户

下面是一个代码示例:

import telebot
import datetime

bot = telebot.TeleBot(insert_token_here)

keyboard1 = telebot.types.ReplyKeyboardMarkup(True)
keyboard1.row('Choose date', 'dont push it')

@bot.message_handler(commands=['start'])
def start_message(message):
    bot.send_message(message.chat.id, 'Welcome', reply_markup=keyboard1)


def dates_inline():
    current_date = datetime.datetime.today()

    # Inline keyboard
    keyboard_dates = telebot.types.InlineKeyboardMarkup()
    key_now = telebot.types.InlineKeyboardButton(text=current_date.strftime('%d.%m.%Y') + ' (Today)',
                                                 callback_data=current_date.strftime('%Y-%m-%d'))
    keyboard_dates.add(key_now)

    return keyboard_dates
@bot.message_handler(content_types=['text'])
def choose_message(message):

    if message.text == "Choose date":

        bot.send_message(message.chat.id, 'Choose date:', reply_markup=dates_inline())

        @bot.callback_query_handler(func=lambda call: True)
        def choose_date(call):
            dt = call.data
            print('chose_date dt: %s' % dt)
            bot.send_message(message.chat.id, 'All done')
        print('end')
    else:
        print('smth else')



def main():

    bot.polling(none_stop=True)


if __name__ == '__main__':
    main()

Tags: 用户sendtruemessagedatetimedatedefbot
3条回答

我也面临着类似的问题

  1. 不要在另一个处理器/装饰器中创建处理器/装饰器。它不是那样工作的。我对python也比较陌生,所以我不知道确切的原因。我也从我的错误中学到了这一点
  2. 不要将消息发送回message.chat.id。将其发送到call.from_user.id,以便它始终将回复发送回呼叫来源的用户
@bot.message_handler(content_types=['text'])
def choose_message(message):

    if message.text == "Choose date":
        bot.send_message(message.chat.id, 'Choose date:', reply_markup=dates_inline())
    else:
        print('smth else')


@bot.callback_query_handler(func=lambda call: True)
    def choose_date(call):
        dt = call.data
        print('chose_date dt: %s' % dt)
        bot.send_message(call.from_user.id, 'All done')
        print('end')
    

我现在也在开发机器人,这对我来说很好

您需要将以下代码移动到顶级缩进。否则,它将无法按预期工作

    @bot.callback_query_handler(func=lambda call: True)
    def choose_date(call):
        dt = call.data
        print('chose_date dt: %s' % dt)
        bot.send_message(message.chat.id, 'All done')

@wowkin2以下是一个示例代码:

@bot.message_handler(content_types=['text'])
def choose_message(message):

    if message.text == "Choose date":
        bot.send_message(message.chat.id, 'Choose date:', reply_markup=dates_inline())
        print('end')

    else:
        print('smth else')
        
    @bot.callback_query_handler(func=lambda call: True)
    def choose_date(call):
        dt = call.data
        bot.send_message(message.chat.id, 'All done')

相关问题 更多 >