我知道如何使用 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)
我希望它在服务器端发送带有触发器的消息,而不是在我向机器人发送命令时。
最佳答案
代码中的以下行:
@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
,让 Bot 轮询回复或类似内容。
运行脚本后的可视化结果:
关于python - pyTelegramBotAPI - 如何发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68209399/