node.js - How get usernames from IDs in discord.js
问题描述
i stored ids or nicknames(string only because are not discord users). Now i want to get the usernames from users that are part of discord. Tho i get a [promise object] and i cant access. I read something about .then but not success. I dont know how the structure would be in this case:
for (var i = 0; i < ids.length; i++){
let tag = client.fetchUser(ids[i]);
if(tag.username){
//if exist put his username
title.push(tag.username);
info += icons[i] + ' = ' + tag.username + ' \n';
}else{
//if not exist, means we saved the nickname only (string)
title.push(size[i]);
info += icons[i] + ' = ' + size[i] + ' \n';
}
}
const embed = new Discord.RichEmbed()
.setTitle(title.join(' - '))
.setColor(0x00AE86)
.setDescription(info)
.setFooter("none")
.setTimestamp()
.setURL("https://discord.gg/sHanmsPX")
.addField("-", "-", true);
解决方案
请使用 Discord.JS v12 与 v11 相比
请阅读以下内容:当您发布问题时,请务必删除 discord.gg 邀请或使其无效!这适用于任何敏感信息!
不和谐 v11 版本
因此,该fetchUser
函数返回一个包装在承诺中的用户。如果您的for
代码在函数内,请制作asynchronous
并制作:
let tag = client.fetchUser(ids[i]);
进入:
let tag = await client.fetchUser(ids[i]);
你也可以这样做,它不需要 async/await:
let tag = client.fetchUser(ids[i]).then(u=>{
// your code here...
});
不和谐 v12 版本
使用 v12,它已更新,但该fetchUser
方法不再存在。你必须使用这个:
let tag = client.users.fetch(ids[i]);
// this is a promise! Use async/await or .then after.
您可以使用缓存,但这适用于机器人看到或与之交互的用户:
let tag = client.users.cache.get(ids[i]);
// this is not a promise.
推荐阅读
- python - vec4的多个mat4,然后在Python中使其成为vec3
- arrays - 如何在 Swift 的数组中找到多个峰值和谷值元素?
- cmd - 如何从 Windows 注册表中获取 Windows 的产品名称?
- angular - 如何对 NGXS 异步 http 请求进行单元测试?
- python - 使用 az cli 或 python sdk 检索 blob 存储连接字符串?
- python - 将沿 ND 数组的特定轴的选定索引/行的数组与其总和组合/替换
- javascript - 如何使用由模型属性组成的参数创建自定义验证属性
- sql - MariaDB 给我一个错误,在 ctf 中显示 'WHERE '1'='1''
- pandas - 尝试在 h5py 中打开由 pandas 创建的 hdf 时缺少列
- angular8 - 空 URL 没有返回,因为我从 app-routing.module 设置