首页 > 解决方案 > 如何将频道/服务器 ID 转换为其名称?

问题描述

我正在尝试为我的不和谐机器人创建更详细的控制台日志,并且我想记录机器人可以看到的所有消息。到目前为止,我这样做了:

client.on('message', message => {
    const User = client.users.cache.get(message.author.id); // Getting the user by ID.
    const Channel = client.channels.cache.get(message.channel.id); //getting the channel ID
    console.log(User.tag + " in " + message.channel + " of " + message.guild + " said: " + message.content);

    // rest of my code
});

client.login(token);

我能够弄清楚如何将用户 ID 转换为用户名,但我无法对频道 ID 和服务器 ID 做同样的事情。我通过对频道的用户名使用相同的代码,对频道 ID 尝试了类似的方法,但它仍然给了我数字。

在控制台中,显示如下:

Kingamezz#0218 in 763786268181397527 of 763786268181397524 said: message text

我的目标是尝试将 ID 转换为正确的名称,因此我得到的结果如下所示:

Kingamezz#0218 in #general of Testing Server said: message text

标签: javascriptnode.jsdiscorddiscord.js

解决方案


如果您想发送一个可点击的链接作为响应,您可以使用对象本身(message.author, message.channel, message.guild)。但是,如果要将它们记录在控制台上或保存到文件中,则需要使用author.tagchannel.nameguild.name.

以下应该有效:

client.on('message', (message) => {
  if (message.author.bot) return;

  message.channel.send(
    `${message.author} in ${message.channel} of ${message.guild} said _${message.content}_`,
  );
  
  console.log(
    `${message.author.tag} in #${message.channel.name} of ${message.guild.name} said ${message.content}`,
  );
});

在此处输入图像描述


推荐阅读