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

discord.py使用when_mentioned_or搭配自定义前缀报错如何解决?

问题原因

报错根源是commands.when_mentioned_or()仅接收字符串类型的前缀参数,不能直接传入自定义前缀获取函数get_prefix,你当前的写法相当于把函数对象本身塞到了前缀列表里,触发了类型错误。

修复方案

你需要把「@提及生效」的逻辑合并到自定义前缀函数中,修改后的完整代码如下:

import json
import discord
from discord.ext import commands

def get_prefix(bot, message):
    # 处理私聊无服务器场景,设置兜底默认前缀
    if not message.guild:
        return commands.when_mentioned_or("!")(bot, message)
    with open('prefixes.json', 'r') as f:
        prefixes = json.load(f)
    # 读取服务器存储的前缀,未存储过的服务器默认给!前缀
    guild_prefix = prefixes.get(str(message.guild.id), "!")
    # 包裹when_mentioned_or实现@机器人也能触发命令
    return commands.when_mentioned_or(guild_prefix)(bot, message)

intents = discord.Intents.default()
intents.members = True
# command_prefix直接传入自定义前缀函数即可
bot = commands.Bot(command_prefix = get_prefix, help_command=None, intents=intents)
bot.remove_command("help")
补充注意点
  • 原代码中的get_prefix函数存在缩进错误,修改后函数体内的代码需要保持统一缩进
  • 新增的兜底逻辑可以避免私聊、未存储前缀的服务器触发KeyError报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 04:45:02