-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.ts
More file actions
183 lines (153 loc) · 7.16 KB
/
bot.ts
File metadata and controls
183 lines (153 loc) · 7.16 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
/**
* This file contains the code for a Discord bot that joins a random voice channel in a random guild and plays a random sound file.
* It uses the @discordjs/voice library for voice connections and the node-schedule library for scheduling the next join.
* The bot also starts a web server using the startServer function from the webserver module.
*
* @packageDocumentation
*/
import {
joinVoiceChannel,
createAudioPlayer,
createAudioResource,
entersState,
AudioPlayerStatus,
VoiceConnectionStatus,
VoiceConnection
} from '@discordjs/voice';
import { ChannelType, Collection, GuildBasedChannel, Snowflake, VoiceChannel, VoiceState } from 'discord.js';
import * as dotenv from 'dotenv';
import { startServer as startWebServer } from './client/webserver';
import * as schedule from 'node-schedule';
import { loadAvoidList } from './helpers/load-avoid-list';
import { LoggerColors } from './helpers/logger-colors';
import { getRandomSoundFilePath } from './helpers/get-random-sound-file-path';
import { logger } from './helpers/logger';
import { SetupDiscordCLient } from './helpers/setup-discord-client';
import { convertHoursToMinutes, dateToString } from './helpers/converters';
import { AvoidList } from './models/avoid-list';
dotenv.config();
export var nextPlayBackTime: string = ''; // Export so it can be used in the webserver module aswell.
const minTimeInterval = parseInt(process.env.INTERVALMIN_MINUTES!, 10); // Minimum interval in minutes.
const maxTimeInterval = convertHoursToMinutes(parseFloat(process.env.INTERVALMAX_HOURS!)); // Maximum interval in minutes.
const voiceChannelRetries = parseInt(process.env.VOICECHANNELRETRIES!, 10); // Number of retries to find a voice channel with members in it.
const discordClient = SetupDiscordCLient();
discordClient.on('ready', async () => {
console.log(LoggerColors.Green, `Add to server by: https://discord.com/oauth2/authorize?client_id=${discordClient.application?.id}&permissions=70379584&scope=bot`);
console.log(`Logged in as ${discordClient.user?.tag}!`);
joinRandomChannel(voiceChannelRetries);
startWebServer();
});
/**
* Joins a random voice channel in a random guild and plays a random sound file.
* @param retries - The number of retries to attempt if no voice channels are found.
* @returns Promise<void>
*/
export async function joinRandomChannel(retries = 12) {
if (!discordClient.guilds.cache.size) {
console.log(LoggerColors.Red, 'No guilds found');
scheduleNextJoin();
return;
}
const randomlyPickedDiscordServer = discordClient.guilds.cache.random();
const accessableVoiceChannels = randomlyPickedDiscordServer?.channels.cache.filter(channel =>
channel.type === ChannelType.GuildVoice &&
channel.members.size > 0
);
if (!accessableVoiceChannels?.size) {
if (retries > 0) {
console.log(LoggerColors.Yellow, `No voice channels found, retrying in 5 seconds... (${retries} retries left)`);
setTimeout(() => joinRandomChannel(retries - 1), 5000); // Wait for 5 seconds before retrying
}
if(retries === 0) {
console.log(LoggerColors.Red, 'No voice channels found');
scheduleNextJoin();
}
return;
}
const randomlyPickedVoiceChannel = accessableVoiceChannels.random();
try {
// Join the voice channel
if(isUserFromAvoidListNotInVoiceChannel(randomlyPickedVoiceChannel!)) {
const voiceChannelConnection = joinVoiceChannel({
channelId: randomlyPickedVoiceChannel!.id,
guildId: randomlyPickedVoiceChannel!.guild.id,
adapterCreator: randomlyPickedVoiceChannel!.guild.voiceAdapterCreator,
});
await entersState(voiceChannelConnection, VoiceConnectionStatus.Ready, 30e3);
const soundFilePath = getRandomSoundFilePath();
if(!soundFilePath) {
console.log(LoggerColors.Red, 'No sound files found');
scheduleNextJoin();
return;
}
await playSoundFile(
soundFilePath,
randomlyPickedVoiceChannel,
voiceChannelConnection);
}
} catch (error) {
console.error(error);
}
scheduleNextJoin();
}
/**
* Plays a sound file in a voice channel.
* @param soundFilePath - The path to the sound file to play.
* @param randomlyPickedVoiceChannel - The voice channel to play the sound file in.
* @param voiceChannelConnection - The voice channel connection.
* @returns Promise<void>
*/
async function playSoundFile(
soundFilePath: string,
randomlyPickedVoiceChannel: GuildBasedChannel | undefined,
voiceChannelConnection: VoiceConnection
): Promise<void> {
const audioResource = createAudioResource(soundFilePath);
const audioPlayer = createAudioPlayer();
console.log(LoggerColors.Teal, `Playing ${soundFilePath} in ${randomlyPickedVoiceChannel?.name}...`);
audioPlayer.play(audioResource);
voiceChannelConnection.subscribe(audioPlayer);
await entersState(audioPlayer, AudioPlayerStatus.Idle, 300000);
voiceChannelConnection.destroy();
}
/**
* Schedules the next join to a random channel. Using a random interval between minTime and maxTime.
* It clears the previous schedule before scheduling the next join, to avoid multiple schedules.
* @see minTimeInterval - time in minutes
* @see maxTimeInterval - time in hours as minutes
* @see schedule - node-schedule instance
*/
function scheduleNextJoin(): void {
const randomInterval = Math.floor(Math.random() * (maxTimeInterval - minTimeInterval + 1)) + minTimeInterval;
const minutes = randomInterval % 60;
const hours = Math.floor((randomInterval - minutes) / 60);
schedule.gracefulShutdown().finally(() => {
const jobName = schedule.scheduleJob(`${minutes} ${hours == 0 ? '*' : hours } * * *`, function(){
joinRandomChannel();
}).name;
let nextPlaybackDate = schedule.scheduledJobs[jobName].nextInvocation();
nextPlayBackTime = dateToString(nextPlaybackDate) ?? '';
logger(nextPlaybackDate, hours, minutes);
});
}
function isUserFromAvoidListNotInVoiceChannel(channel: GuildBasedChannel): boolean {
const avoidList: AvoidList = loadAvoidList();
const voiceChannel = channel as VoiceChannel;
const voiceStates: Collection<Snowflake, VoiceState> = voiceChannel.guild.voiceStates.cache;
const membersInVoiceChannel = voiceStates.filter(voiceState => voiceState.channelId === voiceChannel.id);
if(avoidList.avoidUsers.length === 0)
return true;
if (channel.type !== ChannelType.GuildVoice)
return true;
// Check if any member from the avoid list is in the voice channel
for (const voiceState of membersInVoiceChannel.values()) {
if(!voiceState.member)
continue;
if (avoidList.avoidUsers.includes(voiceState.member.user.username)) {
console.log(LoggerColors.Yellow, `${voiceState.member.user.username} is in the avoid list, skipping...`);
return false;
}
}
// No member from the avoid list is in the voice channel
return true;
}