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

Discord lottery命令运行报DiscordAPIError: Cannot send an empty message问题问询

错误原因
  • text.js未配置模块导出规则,Node.js中require()引入未显式导出的模块时,默认返回空对象{},此时读取lottery.length为undefined,生成的随机索引为NaN,最终取到的item是undefined,调用message.channel.send(undefined)就会触发Discord API的空消息报错。
  • 即便补全导出逻辑,你当前直接对多行字符串做索引取值,只会拿到单个字符,无法获取完整的4位中奖编码,不符合功能需求。
  • 若你使用Discord.js v13及以上版本,消息发送接口不支持直接传入字符串作为参数,需要传入带content字段的配置对象,否则也会触发空消息错误。
  • message.channel.send()是异步方法返回Promise,你没有添加错误捕获逻辑,所以发送失败时会抛出UnhandledPromiseRejectionWarning警告。
修复方案

第一步:修改text.js

两种方案二选一即可:

方案A:直接导出编码数组(更推荐)

module.exports = [
  'w2H1',
  'DmKS',
  'wSLS',
  'yRpQ',
  '8J57',
  '0qlq',
  'hRRc',
  'Cn8G',
  'B0FL',
  'D2H0',
  'k3dD',
  'jchM',
  'MWyN',
  'VK5m',
  'NllW',
  'CKxJ',
  '0mKq',
  'b4rR',
  'Bl5t',
  'dDdt',
  '5MT0',
  '84s1',
  '7DwG',
  'mzDW',
  '06rl',
  'R3Hl',
  'fG82',
  'tnbt',
  'lc02',
  '6TDh',
  'MySv',
  'FgBq',
  '3g30',
  'qB6B',
  'QQyq',
  'wQMr',
  'nMg5',
  'PvK9',
  'jL72',
  'zZ8z'
]

方案B:导出字符串后分割

module.exports = `w2H1
DmKS
wSLS
yRpQ
8J57
0qlq
hRRc
Cn8G
B0FL
D2H0
k3dD
jchM
MWyN
VK5m
NllW
CKxJ
0mKq
b4rR
Bl5t
dDdt
5MT0
84s1
7DwG
mzDW
06rl
R3Hl
fG82
tnbt
lc02
6TDh
MySv
FgBq
3g30
qB6B
QQyq
wQMr
nMg5
PvK9
jL72
zZ8z`

第二步:修改lottery.js

适配导出逻辑、高版本Discord.js接口,添加错误捕获和重复定时器拦截:

const Discord = require('discord.js');
// 存储定时器ID,避免多次调用命令启动多个发送进程
let lotteryTimer = null;

module.exports = {
    name: 'lottery',
    async execute(message, args) {
        // 先清掉之前运行的定时器
        if (lotteryTimer) clearInterval(lotteryTimer);

        const lottery = require('../text.js');
        // 如果用的是方案B导出字符串,就先按换行分割为数组
        // const lotteryList = lottery.split('\n');
        // 如果用的是方案A导出数组,直接赋值即可
        const lotteryList = lottery;

        lotteryTimer = setInterval(async () => {
            const item = lotteryList[Math.floor(Math.random() * lotteryList.length)];
            try {
                // 适配高版本Discord.js的发送格式
                await message.channel.send({
                    content: item
                });
            } catch (e) {
                console.error('中奖编码发送失败:', e);
            }
        }, 5 * 1000);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 07:45:04