如何通过Telethon向@PostBot执行发送帖子操作?
通过Telethon触发PostBot发送帖子的正确方法
直接发送@PostBot ...这类普通文本无法触发发送帖子的操作,因为机器人需要的是特定交互(内联查询或回调按钮点击),而非纯文本消息。以下是两种常见场景的实现方式:
场景1:使用内联查询触发发送
如果“发送帖子”是通过内联模式实现的,可通过以下代码调用:
from telethon import TelegramClient async def send_post(client, target_chat, post_content): # 向PostBot发起内联查询,传入帖子内容 inline_results = await client.inline_query('PostBot', post_content) # 选择第一个查询结果发送到目标聊天(根据实际情况调整索引) if inline_results: await inline_results[0].click(target_chat) # 初始化客户端(替换为你的API信息) client = TelegramClient('my_session', 12345, 'your_api_hash_here') client.start() # 执行发送操作 client.loop.run_until_complete(send_post(client, 'your_chat_id', '测试帖子内容'))
场景2:模拟回调按钮点击
如果“发送帖子”是Bot回复消息中的按钮,需要先触发Bot弹出按钮,再模拟点击:
from telethon import TelegramClient, events async def trigger_and_click_button(client): # 发送触发按钮的命令(比如/start,根据Bot实际逻辑调整) await client.send_message('PostBot', '/start') # 监听Bot的回复,获取按钮 @client.on(events.NewMessage(from_users='PostBot')) async def handle_bot_reply(event): if event.message.buttons: # 点击第一个按钮(对应“发送帖子”的按钮,根据实际位置调整) await event.message.buttons[0][0].click() # 触发后移除监听 client.remove_event_handler(handle_bot_reply) # 初始化客户端 client = TelegramClient('my_session', 12345, 'your_api_hash_here') client.start() client.loop.run_until_complete(trigger_and_click_button(client))
注意事项
- 先手动在Telegram客户端操作一遍,确认和PostBot的交互流程:是内联查询还是按钮触发?再对应调整代码。
- 替换代码中的
api_id、api_hash、chat_id等参数为你自己的信息。
内容的提问来源于stack exchange,提问作者Frit Rose
相关产品推荐
相关产品推荐

