You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Telethon脚本定期更换Telegram头像时提示无效图片文件

解决Telegram头像更换脚本的参数错误问题

问题根源分析

你遇到的UploadProfilePhotoRequest参数错误,主要来自三个核心问题:

  • 重复执行客户端登录流程,导致会话状态异常
  • 调用UploadProfilePhotoRequest时参数格式不匹配
  • 图片处理后保存环节存在隐性格式问题

具体修复步骤

1. 移除重复的登录代码

change_avatar函数内的await client.start()和await client.sign_in(phone_number)完全多余——main函数已经完成客户端初始化和登录流程,重复调用会引发会话冲突,干扰文件上传逻辑。

2. 修正UploadProfilePhotoRequest的参数传递

Telethon的UploadProfilePhotoRequest需要明确指定file参数,而非直接传入上传后的对象。或者可以使用更简洁的client.edit_profile()方法,它对参数的兼容性更好。

3. 确保图片保存格式正确

用PIL修改图片后,显式指定PNG格式保存,避免因默认格式不匹配导致文件损坏。

4. 调整触发逻辑(可选)

原脚本依赖新消息事件触发头像更换,若需要定期自动更换,可直接在main函数中调用change_avatar,无需绑定消息事件。

修改后的完整代码

import asyncio
import os
from telethon import TelegramClient, functions
from PIL import Image

api_id = ''
api_hash = ''
phone_number = ''
avatars = ['C:/AvatarMasterTg/avatar1.png', 'C:/AvatarMasterTg/avatar2.png', 'C:/AvatarMasterTg/avatar3.png']

client = TelegramClient('session_name', api_id, api_hash,
                        device_model="iPhone",
                        system_version="14.8.1",
                        app_version="8.4",
                        lang_code="en",
                        system_lang_code="en-US")

async def change_avatar():
    for avatar in avatars:
        try:
            # 调整图片尺寸,使用LANCZOS插值保证画质
            image = Image.open(avatar)
            if image.width < 200 or image.height < 200:
                image = image.resize((200, 200), Image.Resampling.LANCZOS)
            if image.width > 10000 or image.height > 10000:
                image = image.resize((10000, 10000), Image.Resampling.LANCZOS)
            
            # 显式指定PNG格式保存,避免格式异常
            image.save(avatar, format='PNG')

            # 上传并更换头像
            print(f"切换头像至: {avatar}")
            photo = await client.upload_file(avatar)
            # 方法1:使用UploadProfilePhotoRequest并指定file参数
            await client(functions.photos.UploadProfilePhotoRequest(file=photo))
            # 方法2:更简洁的edit_profile(二选一即可)
            # await client.edit_profile(photo=photo)
            print("头像切换成功!")

            await asyncio.sleep(30)
        except Exception as e:
            print(f"切换头像出错: {e}")

async def main():
    await client.start()
    confirmation_code = input('输入验证码: ')
    await client.sign_in(phone_number, confirmation_code)
    await client.get_dialogs()
    
    # 直接调用头像更换函数,无需消息事件触发
    await change_avatar()
    await client.run_until_disconnected()

if __name__ == '__main__':
    asyncio.run(main())

额外注意事项

  • 确保api_id和api_hash已正确填写,可从Telegram官方开发者后台获取
  • 图片路径优先使用绝对路径,避免相对路径带来的文件查找问题
  • 若仍报错,可临时注释图片处理代码,直接上传原始图片,排查是否是图片处理环节导致的文件损坏

内容的提问来源于stack exchange,提问作者DMG DMG

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 07:53:13