微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

电报机器人无法发送直接消息

如何解决电报机器人无法发送直接消息

我正在使用 pytelegrambotapi 创建一个 Telegram 机器人。但是当我测试代码时,我的 Telegram Bot 总是回复引用我的输入 like this,我不希望它引用我的输入消息而是直接发送消息。

另外,我如何通过使用简单的 HiHello 而不是 /hi/hello 来获得回复

我的代码

import telebot
import time
bot_token = ''

bot= telebot.TeleBot(token=bot_token)

@bot.message_handler(commands=['start'])
def send_welcome(message):
    bot.reply_to(message,'Hi')

@bot.message_handler(commands=['help'])
def send_welcome(message):
    bot.reply_to(message,'Read my description')

while True:
    try:
        bot.polling()
    except Exception:
        time.sleep(10)

解决方法

我不希望它引用我的输入消息,而是直接发送消息。

bot.reply_to 回复消息本身。如果您希望发送单独的消息,请使用 bot.send_message。您需要传递您希望向其发送消息的用户的 ID。您可以在 message.chat.id 上找到此 ID,以便将消息发送到同一个聊天室。

@bot.message_handler(commands=['help'])
def send_welcome(message):

    # Reply to message
    bot.reply_to(message,'This is a reply')

    # Send message to person
    bot.send_message(message.chat.id,'This is a seperate message')

另外,我如何通过使用简单的 Hi 或 Hello 而不是 /hi 或 /hello 来获得回复。

不要使用带有 message_handlercommands=['help'],您可以删除参数以捕获未被任何命令消息处理程序捕获的每条消息。


上面实现的例子:

import telebot

bot_token = '12345'

bot = telebot.TeleBot(token=bot_token)


# Handle /help
@bot.message_handler(commands=['help'])
def send_welcome(message):

    # Reply to message
    bot.reply_to(message,'This is a seperate message')


# Handle normal messages
@bot.message_handler()
def send_normal(message):

    # Detect 'hi'
    if message.text == 'hi':
        bot.send_message(message.chat.id,'Reply on hi')

    # Detect 'help'
    if message.text == 'help':
        bot.send_message(message.chat.id,'Reply on help')


bot.polling()

视觉效果: enter image description here

,

如果我理解正确: cid = message.chat.id bot.send_message(cid,"你好")

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。