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

discord.py报错求助:None类型无法赋值给User类型参数

解决discord.py中"Expression of type 'None' cannot be assigned to parameter of type 'User'"报错

问题原因

  1. 缺失discord模块导入:代码里用到了discord.User类型,但只导入了discord.ext.commands,没导入核心的discord模块,导致类型无法被识别。
  2. 类型提示不规范:参数默认值设为None,但直接标注类型为discord.User,类型检查器会认为这个参数只能是User对象,不能是None,从而抛出错误。

修正步骤

  1. 补充导入discord模块和typing.Optional(Python 3.9及以下);Python 3.10+可直接用联合类型语法,无需导入Optional。
  2. 修正参数的类型提示,明确允许参数为None。
  3. 删掉冗余的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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 21:44:57