pyTelegramBotAPI - 如何发送消息

时间:2021-07-01 11:31:39

标签: python telegram

我知道如何使用 pyTelegramBotAPI 回复命令和消息 但也许你知道如何让它在没有交互的情况下将消息发送到我的聊天 ID?它不会执行 bot.polling() 下的代码行

import telebot
bot=telebot.TeleBot(API_KEY)

@bot.message_handler(content_types=['text'])

def send_text(message):
    bot.send_message(message.chat.id, 'text')

bot.polling(none_stop=True)

我希望它在服务器端发送带有触发器的消息,而不是在我向机器人发送命令时发送。

1 个答案:

答案 0 :(得分:0)

代码中的以下行:

@bot.message_handler(content_types=['text'])

创建一个 message_handler,可用于回复消息。


由于您只想发送常规消息,没有任何回复逻辑,您可以使用 bot.send_message 方法,无需任何处理程序。

示例:

import telebot

# Create bot
bot = telebot.TeleBot(token='ABCDEFHHIJ:AAG2snRwz8jnFtVf8b0eyCueGJRD3hY9AaQ')

# Send message
bot.send_message(123456798, 'Hi! I\'m a Bot!')

如果我运行这个脚本,我的机器人会向我发送消息,然后终止脚本。当然,您可以在底部添加 bot.polling,让机器人轮询回复或类似内容。

运行脚本后的视觉效果:

enter image description here