如何将Emoji设为Discord角色图标?遇TypeError报错求助
问题场景
想要将Emoji设置为Discord服务器角色的图标,尝试代码如下:
if role.name == "RoleName": await role.edit(icon="Pink Heart")
触发TypeError报错:
Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/client.py", line 378, in _run_event await coro(*args, **kwargs) File "/Users/admin/Downloads/files/color.py", line 28, in on_ready await role.edit(icon="Pink Heart") File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/role.py", line 473, in edit payload["icon"] = _bytes_to_base64_data(icon) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/utils.py", line 658, in _bytes_to_base64_data mime = _get_mime_type_for_image(data) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/utils.py", line 644, in _get_mime_type_for_image if data.startswith(b"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a"): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: startswith first arg must be str or a tuple of str, not bytes
报错原因
根据Discord.py文档,role.edit()的icon参数接受两种类型:
display_icon (Optional[Union[bytes, str]]) – A bytes-like object representing the icon or str representing unicode emoji that should be used as a role icon. Could be None to denote removal of the icon. Only PNG/JPEG is supported. This is only available to guilds that contain ROLE_ICONS in Guild.features.
原代码中传入的"Pink Heart"是Emoji的名称,不是Unicode Emoji字符,Discord.py会将其误判为图片字节流处理,进而触发字符串与字节类型不匹配的错误。
正确实现方法
1. 确认服务器支持角色图标功能
先检查目标服务器是否开启了角色图标功能:
if "ROLE_ICONS" in guild.features: # 服务器支持角色图标,执行后续操作 else: print("当前服务器不支持角色图标功能")
2. 使用Unicode Emoji字符作为参数
直接传入对应Emoji的Unicode字符,而非名称。比如粉色爱心的Unicode是💖,修改后的代码:
@client.event async def on_ready(): guild = client.get_guild(你的服务器ID) if guild and "ROLE_ICONS" in guild.features: role = discord.utils.get(guild.roles, name="RoleName") if role: # 使用Unicode Emoji字符 await role.edit(icon="💖") print("角色图标设置成功")
3. 获取Emoji的Unicode字符
可以通过以下方式获取:
- 直接从系统表情键盘复制Emoji字符
- 搜索对应Emoji的Unicode编码(如搜索“Pink Heart emoji unicode”)
报错解决方案
核心修复点:将icon参数的值从Emoji名称(如"Pink Heart")替换为对应的Unicode Emoji字符,确保Discord.py识别为Emoji而非图片数据,即可解决类型不匹配的TypeError。
内容的提问来源于stack exchange,提问作者Abraya

