如何在Python中的Telebot API中执行命令后回复消息

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

我有这个代码..

import telebot

#telegram API 
api_key = os.environ['Tele_API_key']
bot = telebot.TeleBot(api_key)

@bot.message_handler(commands=['start'])
def help_command(message):
    bot.send_message(chat.id,"send a message")

@bot.message_handler(func = lambda msg: msg.text is not None and '/' not in msg.text)
    if message.text == "Hi":
        bot.send_message(chat.id,"Hello!")

每次我发送“嗨”时,它都会向我发送“你好”

我希望它是这样的, 在我做/开始之后 它应该询问“发送消息” 当我发送“你好”时 它应该发送“嗨”

但问题是,每次我发送“Hello”它都会发送“Hi”

但我只希望它在发送 /start 后说“Hello”,然后发送“Hi”消息

我是初学者,感谢您的帮助

python python-3.x telegram-bot py-telegram-bot-api telebot
2个回答
0
投票

您在 @message_handler 中创建了对象 msg ,但尚未使用它。

这些都是愚蠢的错误

  • 消息.文本
  • 聊天ID

正确✅

  • msg.text
  • msg.聊天.id

最终代码

@bot.message_handler(func = lambda msg: msg.text is not None and '/' not in msg.text)
if msg.text == "Hi":
    bot.send_message(msg.chat.id,"Hello!")

0
投票

你可以这样做

@bot.message_handler(commands=[all_commands['start']])
def say(message):
    bot.send_message(message.chat.id, "send a message")

@bot.message_handler(func=lambda msg: msg.text is not None and '/' not in msg.text)
def sayHi(message):
    if message.text == "Hi":
         bot.reply_to(message, "Hello!")

您可以通过

reply_to(message, "your reply text")

回复消息
© www.soinside.com 2019 - 2024. All rights reserved.