python - pyTelegramBotAPI - 如何发送消息

标签 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)

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

最佳答案

代码中的以下行:

@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 轮询回复或类似内容。

运行脚本后的可视化结果:

enter image description here

关于python - pyTelegramBotAPI - 如何发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68209399/

相关文章:

python - Tkinter Checkbutton 不会在颜色更改后保留其复选标记

python - 如何从 URL 播放 mp3

api - Telegram 机器人 API token 格式

api - Telegram channel 的帖子观看次数

python - 这个 python lxml 库出了什么问题

python - 如何在 matplotlib 中使用多标记、多颜色显示数据

c# - 在哪里可以找到 Telegram Api key

python - 如何通过 python-telegram-bot 接收 file_id ?

python - 如何使用 Telethon 获取 Telegram 私有(private) channel ID

python - Python Opencv控件(自定义)(增加/减少)视频播放速度