首页 > 解决方案 > 电报机器人无法发送直接消息

问题描述

我正在使用pytelegrambotapi. 但是当我测试代码时,我的 Telegram Bot 总是回复这样引用我的输入,我不希望它引用我的输入消息,而是直接发送消息。

另外,我怎样才能通过使用简单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)

标签: botstelegramphp-telegram-botpy-telegram-bot-apitelegram-api

解决方案


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

bot.reply_to回复消息本身。如果您想发送单独的消息,请使用bot.send_message. 您需要传递您希望向其发送消息的用户的 ID。您可以在上面找到此 ID,message.chat.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 来获得回复。

代替使用 a 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 reply')

    # Send message to person
    bot.send_message(message.chat.id, '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()

视觉结果: 在此处输入图像描述


推荐阅读