首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当某人加入特定的语音频道时,向文本频道发送消息

问当某人加入特定的语音频道时,向文本频道发送消息
EN

Stack Overflow用户
提问于 2022-01-13 16:39:42
回答 1查看 349关注 0票数 1

当有人进入话音支援候诊室时,我正试图让我的机器人在特定的文本通道中通知我的服务器工作人员。

不幸的是,我只找到了一些不和谐版本12的例子,而在第13版中,它并不适用于我,我不知道如何修改该代码。

没有错误信息或其他任何信息,只是当有人加入语音频道时,它不会发送消息。

代码语言:javascript
复制
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();
});
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-13 17:18:52

首先,确保添加了GUILD_VOICE_STATES意图。

最好是fetch通道,而不是依赖缓存。如果通道已经被缓存,fetch将使用它,不会对不和谐的API提出请求,但是如果它没有缓存,channels.cache.get将找不到它。

我做了一些修改,并在下面的代码中添加了一些注释:

代码语言:javascript
复制
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;
    }
  }
});
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70700068

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档