【问题标题】:Send a message to a text channel when a person joins a specific voice channel当有人加入特定语音频道时向文本频道发送消息
【发布时间】:2022-01-13 16:39:42
【问题描述】:

我正在尝试让我的机器人在有人进入语音支持等候室时通过特定的文本频道通知我的服务器工作人员。

不幸的是,我只找到了 Discord 版本 12 的一些示例,并且在版本 13 中它不适用于我。我不知道该代码中要更改什么。

没有错误信息什么的,只是在有人加入语音频道时不发送信息。

client.on('voiceStateUpdate', (oldState, newState) => {
  const newUserChannel = newState.channelID;
  const textChannel = client.channels.cache.get('931223643362703521');

  if (newUserChannel === '931156705303317013') {
    textChannel.send('Somebody joined');
  }
  console.error();
});

【问题讨论】:

  • 这有什么问题?有什么错误吗?
  • 当有人加入语音频道时,没有错误消息或任何内容,只是没有发送消息

标签: javascript node.js discord.js


【解决方案1】:

首先,确保添加 GUILD_VOICE_STATES 意图。

fetch 频道可能会更好,而不是依赖缓存。如果通道已经被缓存,fetch 将使用它并且不会向 discord API 发出请求,但如果它没有被缓存,channels.cache.get 将找不到它。

我做了一些更改,并在下面的代码中添加了一些 cmets:

const { Client, Intents } = require('discord.js');

const client = new Client({
  intents: [
    Intents.FLAGS.GUILDS,
    Intents.FLAGS.GUILD_MESSAGES,
    Intents.FLAGS.GUILD_VOICE_STATES,
  ],
});

client.on('voiceStateUpdate', async (oldState, newState) => {
  const VOICE_SUPPORT_ID = '931156705303317013';
  const LOG_CHANNEL_ID = '931223643362703521';
  // if there is no newState channel, the user has just left a channel
  const USER_LEFT = !newState.channel;
  // if there is no oldState channel, the user has just joined a channel
  const USER_JOINED = !oldState.channel;
  // if there are oldState and newState channels, but the IDs are different,
  // user has just switched voice channels
  const USER_SWITCHED = newState.channel?.id !== oldState.channel?.id;

  // if a user has just left a channel, stop executing the code 
  if (USER_LEFT)
    return;

  if (
    // if a user has just joined or switched to a voice channel
    (USER_JOINED || USER_SWITCHED) &&
    // and the new voice channel is the same as the support channel
    newState.channel.id === VOICE_SUPPORT_ID
  ) {
    try {
      let logChannel = await client.channels.fetch(LOG_CHANNEL_ID);

      logChannel.send(
        `${newState.member.displayName} joined the support channel`,
      );
    } catch (err) {
      console.error('❌ Error finding the log channel, check the error below');
      console.error(err);
      return;
    }
  }
});

【讨论】:

  • 据我所知,所有公会频道都被缓存了,所以不需要获取
  • @MrMythical 我不确定。我很确定(直到阅读您的评论)我遇到过频道没有被缓存的情况。但是既然你提到了它,我想知道它是不是一个公会?不过,我正在更改答案的措辞:)
  • 默认情况下所有公会也会被缓存...
  • 我知道,它们应该被缓存,但是sometimes they are not
猜你喜欢
  • 2019-04-07
  • 2021-02-28
  • 2021-08-18
  • 2021-07-13
  • 2019-04-07
  • 2021-04-05
  • 2020-07-02
  • 2021-08-21
相关资源
最近更新 更多