aboutsummaryrefslogtreecommitdiff
path: root/src/utils/channels.ts
blob: f4e576a77d4fc3676ce8491e6aaa7108eb2bf5ca (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import {Guild, VoiceChannel, User, GuildMember} from 'discord.js';

export const isUserInVoice = (guild: Guild, user: User): boolean => {
  let inVoice = false;

  guild.channels.cache.filter(channel => channel.type === 'GUILD_VOICE').forEach(channel => {
    if ((channel as VoiceChannel).members.find(member => member.id === user.id)) {
      inVoice = true;
    }
  });

  return inVoice;
};

export const getSizeWithoutBots = (channel: VoiceChannel): number => channel.members.reduce((s, member) => {
  if (!member.user.bot) {
    s++;
  }

  return s;
}, 0);

export const getMemberVoiceChannel = (member?: GuildMember): [VoiceChannel, number] | null => {
  const channel = member?.voice?.channel;
  if (channel && channel.type === 'GUILD_VOICE') {
    return [
      channel,
      getSizeWithoutBots(channel),
    ];
  }

  return null;
};

export const getMostPopularVoiceChannel = (guild: Guild): [VoiceChannel, number] => {
  interface PopularResult {
    n: number;
    channel: VoiceChannel | null;
  }

  const voiceChannels: PopularResult[] = [];

  for (const [_, channel] of guild.channels.cache) {
    if (channel.type === 'GUILD_VOICE') {
      const size = getSizeWithoutBots(channel);

      voiceChannels.push({
        channel,
        n: size,
      });
    }
  }

  // Find most popular channel
  const popularChannel = voiceChannels.reduce((popular: PopularResult, elem: PopularResult) => {
    if (elem.n > popular.n) {
      return elem;
    }

    return popular;
  }, {n: -1, channel: null});

  if (popularChannel.channel) {
    return [popularChannel.channel, popularChannel.n];
  }

  throw new Error();
};