discord.py报错求助:None类型无法赋值给User类型参数
解决discord.py中"Expression of type 'None' cannot be assigned to parameter of type 'User'"报错
问题原因
- 缺失discord模块导入:代码里用到了
discord.User类型,但只导入了discord.ext.commands,没导入核心的discord模块,导致类型无法被识别。 - 类型提示不规范:参数默认值设为
None,但直接标注类型为discord.User,类型检查器会认为这个参数只能是User对象,不能是None,从而抛出错误。
修正步骤
- 补充导入
discord模块和typing.Optional(Python 3.9及以下);Python 3.10+可直接用联合类型语法,无需导入Optional。 - 修正参数的类型提示,明确允许参数为
None。 - 删掉冗余的
elif判断(user=user完全没必要)。
修正后的代码
# Python 3.9及以下版本 import discord from typing import Optional from discord.ext import commands class Cog(commands.Cog): @commands.command(aliases=["l", "lvl", "rank", "r"]) async def level(self, ctx, user: Optional[discord.User] = None): if user is None: user = ctx.author # 这里写你的后续逻辑
# Python 3.10+版本(支持联合类型语法) import discord from discord.ext import commands class Cog(commands.Cog): @commands.command(aliases=["l", "lvl", "rank", "r"]) async def level(self, ctx, user: discord.User | None = None): if user is None: user = ctx.author # 这里写你的后续逻辑
内容的提问来源于stack exchange,提问作者bigman
相关产品推荐
相关产品推荐

