如何获取可用报告机器人列表?iter_dialogs失效求替代方案
问题解决方案
替代iter_dialogs的方案
如果之前使用的是Telethon或Pyrogram库,iter_dialogs方法失效后,可替换为官方推荐的get_dialogs()方法,该方法支持异步迭代获取聊天列表,同时支持分页处理避免加载过多数据。
Telethon示例代码
from telethon import TelegramClient async def fetch_chat_list(client): chat_list = [] # 异步迭代获取所有对话 async for dialog in client.get_dialogs(): chat_info = { "chat_id": dialog.id, "chat_title": dialog.title, "chat_type": dialog.chat.type.name } chat_list.append(chat_info) return chat_list
Pyrogram示例代码
from pyrogram import Client async def fetch_chat_list(client): chat_list = [] # 异步迭代获取所有对话 async for dialog in client.get_dialogs(): chat_info = { "chat_id": dialog.chat.id, "chat_title": dialog.chat.title, "chat_type": dialog.chat.type.name } chat_list.append(chat_info) return chat_list
获取报告机器人列表并交互
方法1:从对话列表中筛选报告机器人
通过遍历对话列表,筛选标记为机器人且名称/用户名包含报告相关关键词的账号:
Telethon示例
async def fetch_report_bots(client): report_bots = [] async for dialog in client.get_dialogs(): chat = dialog.chat # 判断是否为机器人,且名称含"report"关键词 if chat.bot and ("report" in chat.title.lower() or "report" in chat.username.lower()): bot_info = { "bot_id": chat.id, "bot_username": chat.username, "bot_title": chat.title } report_bots.append(bot_info) return report_bots
Pyrogram示例
async def fetch_report_bots(client): report_bots = [] async for dialog in client.get_dialogs(): chat = dialog.chat # 判断是否为机器人,且名称含"report"关键词 if chat.is_bot and ("report" in chat.title.lower() or "report" in chat.username.lower()): bot_info = { "bot_id": chat.id, "bot_username": chat.username, "bot_title": chat.title } report_bots.append(bot_info) return report_bots
方法2:直接获取官方报告机器人
如果需要特定官方报告机器人(如Telegram官方的@ReportBot、@SpamBot),可通过用户名直接查询:
Telethon示例
async def get_official_report_bots(client): official_bot_usernames = ["ReportBot", "SpamBot"] bots = [] for username in official_bot_usernames: try: bot = await client.get_users(username) bots.append({ "bot_id": bot.id, "bot_username": bot.username, "bot_name": bot.first_name }) except Exception as e: print(f"获取机器人 {username} 失败: {str(e)}") return bots
Pyrogram示例
async def get_official_report_bots(client): official_bot_usernames = ["ReportBot", "SpamBot"] bots = [] for username in official_bot_usernames: try: bot = await client.get_users(username) bots.append({ "bot_id": bot.id, "bot_username": bot.username, "bot_name": bot.first_name }) except Exception as e: print(f"获取机器人 {username} 失败: {str(e)}") return bots
与机器人交互示例
获取机器人信息后,可通过send_message方法直接发送消息交互:
# Telethon示例 await client.send_message(bot_id, "这里是要发送的报告内容") # Pyrogram示例 await client.send_message(bot_id, "这里是要发送的报告内容")
内容的提问来源于stack exchange,提问作者jaglug
相关产品推荐
相关产品推荐

