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

Discord机器人使用Keyv+MongoDB时设置前缀;未生效回退为!问题

问题根因
  • 变量拼写错误:代码中定义的动态前缀变量为commandprefix,但setprefix命令判断逻辑中错误写为commandPrefix(大小写不匹配),导致自定义前缀的修改命令无法被触发,只有环境变量中配置的前缀能命中修改逻辑
  • 空值未初始化:数据库首次运行时不存在prefix键,keyv.get('prefix')返回null,直接给null赋值prefixMap[msg.guild.id]会抛出异常,导致数据库写入操作静默失败
  • 参数边界缺失:用户执行setprefix未携带新前缀参数时,newPrefix为undefined,调用newPrefix.length会抛出错误,后续写入逻辑中断
  • 硬编码命令问题:ping命令写死了前缀为!,未使用动态获取的服务器前缀,不符合自定义前缀的设计逻辑
修复后的代码
const { Client, Intents, MessageEmbed, Collection } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS,Intents.FLAGS.GUILD_MESSAGES] });
const dotenv = require('dotenv');
const Keyv = require('keyv');
const keyv = new Keyv('mongodb://user:password@cluster0-shard-00-00.auifa.mongodb.net:27017,cluster0-shard-00-01.auifa.mongodb.net:27017,cluster0-shard-00-02.auifa.mongodb.net:27017/Discord?ssl=true&replicaSet=atlas-bs4dwb-shard-0&authSource=admin&retryWrites=true&w=majority', { collection: 'Discord' });
keyv.on('error', err => console.error('Keyv connection error:', err));
dotenv.config();

client.on('ready', () => {
    console.log(`Logged in as ${client.user.tag}!`);
});
    
client.on('messageCreate', async (msg) => {
    if (msg.author.bot) return;
    // 初始化前缀映射,空值默认给空对象避免赋值报错
    const prefixMap = await keyv.get('prefix') || {};
    const getGuildPrefix = () => {
        return prefixMap?.[msg.guild.id] || "!"
    }
    const setGuildPrefix = async (prefix) => {
        prefixMap[msg.guild.id] = prefix;
        await keyv.set('prefix', prefixMap);
    }
    const commandprefix = getGuildPrefix();

    // 动态前缀ping命令
    if (msg.content === `${commandprefix}ping`) {
        msg.channel.send('ping!')
    }

    // 获取当前前缀命令
    if ((msg.content === `${process.env.prefix}prefix`) || (msg.content === `${commandprefix}prefix`)) {
        msg.channel.send(`Your server prefix is ${commandprefix}`)
    }

    // 修改前缀命令,修复变量拼写错误
    if ((msg.content.startsWith(`${process.env.prefix}setprefix`)) || (msg.content.startsWith(`${commandprefix}setprefix`))) {
        const newPrefix = msg.content.split(' ')[1];
        // 修复参数为空的报错问题
        if (!newPrefix || newPrefix.length === 0) {
            msg.channel.send(`Please enter a valid prefix`);
            return;
        }
        await setGuildPrefix(newPrefix)
        msg.channel.send(`Your server prefix is now '${newPrefix}'`);
    }
})

client.login(process.env.token);

内容的提问来源于stack exchange,提问作者Amrit R Asher

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 22:45:02