@bot.command(name='role')
async def role(ctx, role_id, new_icon_url):
new_icon_url = str(new_icon_url)
if new_icon_url.count('<:') != 0:
new_icon_url = new_icon_url.split(':')
new_icon_url = new_icon_url[2]
new_icon_url = new_icon_url.replace('>', '')
new_icon_url = 'https://cdn.discordapp.com/emojis/%{placeholder}%.png'.replace('%{placeholder}%', new_icon_url)
role = discord.utils.get(ctx.guild.roles, id=int(role_id))
if role is not None:
try:
await role.edit(display_icon=new_icon_url)
await ctx.send(f"Role icon for {role.name} has been updated.")
except discord.errors.Forbidden:
await ctx.send("I don't have the required permissions to edit role icons.")
else:
await ctx.send(f"Role with ID {role_id} not found.")
错误信息:
Traceback (most recent call last):
File "C:\Users\VosQu\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\ext\commands\core.py", line 235, in wrapped
ret = await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\VosQu\OneDrive\Desktop\Brewy Poo\brew.py", line 271, in role
new_icon_url = bytes(new_icon_url)
^^^^^^^^^^^^^^^^^^^
TypeError: string argument without an encoding
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\VosQu\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\VosQu\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\ext\commands\core.py", line 1029, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\VosQu\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\ext\commands\core.py", line 244, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: string argument without an encoding
我本以为它会更改角色图标,但它只是返回了一个错误。
正如错误所示,您需要随字符串一起传递编码系统。例如,使用
utf-8
作为我们的编码系统,它看起来像 bytes(url, "utf-8")
发生此错误是因为
discord.py
模块希望您将 bytes
对象传递给 display_icon
参数,而不是包含图像 url 的字符串。
开发命令的更合适方法是接收图像文件(附加到命令消息中):
import discord
from discord.ext import commands
@bot.command(name='roleicon')
async def role(ctx: commands.Context, role: discord.Role, new_icon: discord.Attachment):
try:
await role.edit(display_icon=await new_icon.read())
except discord.errors.Forbidden:
await ctx.send("I don't have the required permissions to edit role icons.")
else:
await ctx.send(f"Role icon for {role.name} has been updated.")
备注:
- 不要接收角色 ID,而是使用
,库将进行自动转换。此参数表示法还允许用户输入角色的名称或提及;role: discord.Role
- 输入变量是良好的编程习惯。这将使您的 IDE 能够检查您的代码并指出可能的错误。