【问题标题】:discord.js: Issue with adding usernames to stringdiscord.js:将用户名添加到字符串的问题
【发布时间】:2018-10-11 01:54:48
【问题描述】:

我使用 discord.js 为 Discord 机器人编写了以下代码。我尝试编写的代码的目的是让机器人回复一个用户名列表,这些用户名的 id 在另一个 .json 文件中指定。这是我写的。

if(command === "privlist")
{
    var msg = ""
    msg += "[Privileged Users]\n"

    // iterate through the array of id's
    config.privileged.forEach(function(item, index) {
        msg += index + ": ";

        // fetch the user associated with the id in the array
        client.fetchUser(item).then(User => {
            // add the name of the user into the string to be outputted
            msg += User.username + "#" + User.discriminator;
        });

        // include the user id as well
        msg += " <" + item + ">\n";
    });

    // send the message
    message.channel.send(msg);
}

机器人的预期回复应该是这样的。

[Privileged Users]
0: Merlin#8474 <172734241136836608>
1: Spring Voltage#2118 <255109013383938048>
2: masterhunter56#2561 <243167201471889409>
3: brett#4582 <123957558133129217>

但是,这就是我得到的。

[Privileged Users]
0:  <172734241136836608>
1:  <255109013383938048>
2:  <243167201471889409>
3:  <123957558133129217>

我尝试在msg += User.username + "#" + User.discriminator; 行之后添加console.log(User.username),这会使名称正确显示在控制台中。

我什至可以在msg += User.username + "#" + User.discriminator; 之后执行message.channel.send(User.username),这会将每个名称作为它自己的消息发送。

我似乎无法将 User.username + "#" + User.discriminator 连接到 msg 字符串。

【问题讨论】:

  • client.fetchUser(item).then(User 是异步的

标签: javascript promise concatenation discord.js


【解决方案1】:

正如Jaromanda X 所说,您使用了异步函数。这意味着这一行: msg += " &lt;" + item + "&gt;\n"; 不会等待  client.fetchUser(item).then(User 结束继续。

我认为这应该可行:

if(command === "privlist")
{
    var msg = ""
    msg += "[Privileged Users]\n"

    // iterate through the array of id's
    config.privileged.forEach(function(item, index) {
        msg += index + ": ";

        // fetch the user associated with the id in the array
        client.fetchUser(item).then(User => {
            // add the name of the user into the string to be outputted
            msg += User.username + "#" + User.discriminator;
            // include the user id as well
            msg += " <" + item + ">\n";
        });
    });

    // send the message
    message.channel.send(msg);
}

【讨论】:

    猜你喜欢
    • 2017-03-10
    • 2020-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-15
    • 1970-01-01
    • 1970-01-01
    • 2023-01-11
    相关资源
    最近更新 更多