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

module.exports导出的discord.js用户查询函数返回undefined如何解决

问题原因

  1. 你的user函数没有显式返回值,默认返回undefined。client.api.users().get()是异步Promise操作,then回调内的return只会把结果传递给Promise内部,不会作为外层user函数的返回值。
  2. 你每次调用user函数都会新建一个Discord.Client实例并重复登录,不仅会大幅提升接口报错概率,还有触发Discord限流、机器人token被封禁的风险。

解决方案

第一步:修改function.js代码

将Client实例初始化放在模块顶层只执行一次,同时让user函数直接返回Promise对象:

const Discord = require('discord.js');
// 全局只初始化、登录一次Client
const client = new Discord.Client();
client.login('MyBotToken');

module.exports = {
  user: function(UserID) {
    // 直接返回Promise,供调用方获取异步结果
    return client.api.users(UserID).get();
  }
}

如果需要保证调用接口时Client已经完成登录初始化,可以改成async函数等待ready事件:

const Discord = require('discord.js');
const client = new Discord.Client();
client.login('MyBotToken');

module.exports = {
  user: async function(UserID) {
    // 等待Client完成登录和初始化
    await new Promise(resolve => client.once('ready', resolve));
    return client.api.users(UserID).get();
  }
}

第二步:修改main.js代码

因为返回的是Promise对象,你需要通过.then或者await来拿到最终的用户信息:

方式1:使用.then

const details = require('./function');
details.user('SomeUserID').then(userInfo => {
  console.log(userInfo);
  // 所有需要用到userInfo的逻辑都写在这个回调内
});

方式2:使用async/await

const details = require('./function');

// 用立即执行异步函数包裹逻辑
(async () => {
  const userInfo = await details.user('SomeUserID');
  console.log(userInfo);
  // 所有需要用到userInfo的逻辑都写在这里
})();

注意事项

如果你的项目中不需要用到Client的其他网关功能,只需要拉取用户信息,也可以直接调用Discord的公开用户接口,不用初始化完整的Client实例,性能会更优。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 02:15:03