我刚刚了解 python-telegram-bot,还没有找到向任何用户发送自发消息的方法。我只能找到用户仅由 ID 号定义的示例。我将不胜感激任何能帮助我的人。谢谢
from telegram.ext import Application, CommandHandler, MessageHandler, filters
from telegram.ext import ContextTypes, CallbackContext
async def send_message(context: CallbackContext):
chat_id = 1212121212 (example ID)
"""
here, 1212121212 must be a variable, not just the ID number
"""
text = "Message... "
await context.bot.send_message(chat_id= chat_id, text=text, )
def main() -> None:
token = os.getenv('TELEGRAM_BOT_TOKEN')
app = Application.builder().token(token).build()
app.add_handler(MessageHandler(filters.TEXT, handle_message))
app.job_queue.run_repeating(send_message, interval=20, first=0)
app.add_error_handler(error)
app.run_polling(poll_interval=2, timeout=5)
if __name__ == '__main__':
main()
我只能找到用户仅由 ID 号定义的示例
这是 Telegram 机器人向用户发送消息的唯一方式。但是,机器人可以随时向用户发送消息(如果用户已启动机器人),而不仅仅是对传入消息做出反应。您所需要的只是
telegram.Bot
类的实例。请查看PTB简介以获取更多解释。
免责声明:我目前是
python-telegram-bot
的维护者。