如何向仅含@用户名的Telegram机器人定时发送两条循环消息?
解决方案:Telegram机器人定时循环发送消息
方法一:Python + Telethon 脚本(推荐,稳定灵活)
通过Telegram官方的API工具库Telethon,直接调用接口发送消息,无需依赖界面操作,支持通过机器人用户名定位对话对象。
步骤:
- 获取Telegram API凭证
访问my.telegram.org注册账号,创建一个新App,记录下api_id和api_hash。 - 安装依赖
在终端执行:pip install telethon - 编写运行脚本
创建telegram_sender.py文件,填入以下代码(替换占位符为你的信息):from telethon import TelegramClient import time # 替换为你的API信息 API_ID = 123456 API_HASH = '你的api_hash字符串' BOT_USERNAME = '@目标机器人用户名' MESSAGE1 = 'I AM READY' MESSAGE2 = 'YOU CAN SEND NOW' MSG_DELAY = 5 # 两条消息间隔秒数 LOOP_INTERVAL = 600 # 10分钟=600秒 client = TelegramClient('telegram_session', API_ID, API_HASH) async def send_recurring_messages(): while True: # 通过用户名获取机器人对话实体 bot_entity = await client.get_entity(BOT_USERNAME) # 发送第一条消息 await client.send_message(bot_entity, MESSAGE1) time.sleep(MSG_DELAY) # 发送第二条消息 await client.send_message(bot_entity, MESSAGE2) # 等待10分钟后重复 time.sleep(LOOP_INTERVAL) with client: client.loop.run_until_complete(send_recurring_messages()) - 运行脚本
首次运行会要求输入手机号和验证码完成登录,之后会话会自动保存,后续直接运行即可。如果需要后台持续运行,可使用nohup(Linux/macOS)或设置Windows服务。
方法二:桌面自动化脚本(适合无代码基础用户)
通过模拟人工操作Telegram客户端实现消息发送,依赖客户端界面,适合临时场景。
Windows(AutoHotkey脚本)
- 安装AutoHotkey,创建
telegram_auto_send.ahk文件:#Persistent ; 每10分钟触发一次(600000毫秒) SetTimer, SendMsgLoop, 600000 return SendMsgLoop: ; 激活Telegram窗口 WinActivate, ahk_exe Telegram.exe Sleep, 500 ; 打开搜索框输入机器人用户名 Send, ^k Sleep, 300 Send, 目标机器人用户名{Enter} Sleep, 500 ; 发送第一条消息 Send, I AM READY{Enter} Sleep, 5000 ; 发送第二条消息 Send, YOU CAN SEND NOW{Enter} return - 双击脚本运行,保持Telegram在后台即可。
Mac(Automator 快速操作)
创建一个定时触发的Automator工作流,通过AppleScript模拟输入:
tell application "Telegram" activate delay 0.5 tell application "System Events" keystroke "k" using command down delay 0.3 keystroke "目标机器人用户名" keystroke return delay 0.5 keystroke "I AM READY" keystroke return delay 5 keystroke "YOU CAN SEND NOW" keystroke return end tell end tell
通过系统自带的「日历」App设置每10分钟触发该工作流。
内容的提问来源于stack exchange,提问作者rsRudy
相关产品推荐
相关产品推荐

