如何使用Python的Telethon模块将单个目标实体改为列表
解决Telethon脚本批量向多个Telegram群组/频道发送消息的问题
你的代码目前只能发送到单个目标,核心问题有两个:一是错误覆盖了InputPeerChannel类型,二是缺少多目标的遍历逻辑。下面是修改后的实现方案:
关键修改点
- 取消对
InputPeerChannel类型的错误赋值,正确构建多目标实体列表 - 遍历目标列表逐个发送文件,添加异常处理避免单个目标失败导致脚本中断
修改后的完整代码
from telethon import TelegramClient from telethon.tl.types import InputPeerChannel api_id = xxxxxxxx # 替换为你的api_id api_hash = 'xxxxxxx' # 替换为你的api_hash client = TelegramClient('user', api_id, api_hash).start() # 构建多目标列表,每个元素为频道/群组的实体对象或ID # 私有频道需使用InputPeerChannel(需提供channel_id和access_hash) target_channels = [ InputPeerChannel(channel_id=-123456, access_hash=1234567890), # 替换为实际频道ID和access_hash InputPeerChannel(channel_id=-789012, access_hash=0987654321), # 公开频道/群组可直接用ID或用户名,比如: # -456789, # '@public_group_username' ] async def main(): for channel in target_channels: try: await client.send_file(channel, 'imgurl.jpg', caption="It's me!") print(f"消息已成功发送到目标: {channel}") except Exception as e: print(f"发送到目标 {channel} 失败: {str(e)}") with client: client.loop.run_until_complete(main())
补充说明
- 获取access_hash:如果是私有频道,需要获取对应的access_hash,可以临时添加以下代码获取:
async def get_channel_hash(channel_id): entity = await client.get_entity(channel_id) print(f"频道 {channel_id} 的access_hash: {entity.access_hash}") # 在main函数中调用或者单独运行 # with client: # client.loop.run_until_complete(get_channel_hash(-123456))
- 简化目标设置:公开频道/群组无需构建
InputPeerChannel,直接使用频道ID(整数)或用户名(字符串,以@开头)即可。 - 异常处理:添加try-except块可以确保某个目标发送失败时,脚本继续处理下一个目标。
内容的提问来源于stack exchange,提问作者SMariePython
相关产品推荐
相关产品推荐

