Python Telebot无法与其他用户一起使用

问题描述

我也是开发和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()

解决方法

您需要将以下代码移至顶级缩进。否则,它将无法正常工作。

    @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')
,

我也遇到了类似的问题。

  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,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')
    

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...