-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
321 lines (269 loc) Β· 11.7 KB
/
index.js
File metadata and controls
321 lines (269 loc) Β· 11.7 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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
require("dotenv").config();
const { Client, GatewayIntentBits, EmbedBuilder, AttachmentBuilder } = require("discord.js");
const fs = require("fs");
const path = require("path");
const { Collection } = require("discord.js");
const { DisTube } = require("distube");
const { YtDlpPlugin } = require("@distube/yt-dlp");
const { SpotifyPlugin } = require("@distube/spotify");
const { YouTubePlugin } = require("@distube/youtube");
const { DirectLinkPlugin } = require("@distube/direct-link");
// process.env.FFMPEG_PATH = require('ffmpeg-static');
const { SoundCloudPlugin } = require("@distube/soundcloud");
// const gTTS = require('gtts');
const { createAudioPlayer, createAudioResource, getVoiceConnection, AudioPlayerStatus } = require('@discordjs/voice');
const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, GatewayIntentBits.GuildVoiceStates],
});
client.distube = new DisTube(client, {
plugins: [
new SpotifyPlugin({
api: {
clientId: process.env.SPOTIFY_CLIENT_ID,
clientSecret: process.env.SPOTIFY_CLIENT_SECRET
}
}),
new YouTubePlugin(),
new SoundCloudPlugin(),
new DirectLinkPlugin(),
new YtDlpPlugin({ update: true }),
]
});
client.distube.setMaxListeners(20); // Increase max listeners to 20
let disconnectTimeout;
const status = queue =>
`π **Volume:** \`${queue.volume}%\` | ποΈ **Filter:** \`${queue.filters.names.join(', ') || 'Inactive'}\` | π **Repeat:** \`${queue.repeatMode ? (queue.repeatMode === 2 ? 'Queue' : 'Track') : 'Off'
}\` | π€ **Autoplay:** \`${queue.autoplay ? 'On' : 'Off'}\``
client.distube
.on('playSong', (queue, song) => {
resetDisconnectTimer()
console.log("Playing song:", song);
if (queue.textChannel) {
queue.textChannel.send({
embeds: [new EmbedBuilder()
.setColor('#a200ff')
.setTitle('πΆ Now Playing')
.setDescription(`**${song.name}** - \`${song.formattedDuration}\`\n\nπ€ **Requested by:** ${song.user}\n\n${status(queue)}`)
.setThumbnail(song.thumbnail)
.setFooter({ text: 'Enjoy the music! π§' })]
});
} else {
console.error('Text channel not found for song playback');
}
})
.on('addSong', async (queue, song) => {
resetDisconnectTimer()
queue.textChannel.send(
{
embeds: [new EmbedBuilder()
.setColor('#a200ff')
.setTitle('πΆ Song Added to Queue')
.setDescription(`**${song.name}** - \`${song.formattedDuration}\`\n\nπ€ **Requested by:** ${song.user}`)
.setThumbnail(song.thumbnail)
.setFooter({ text: 'More tunes coming up! πΆ' })]
}
)
})
.on('addList', (queue, playlist) => {
resetDisconnectTimer()
queue.textChannel.send(
{
embeds: [new EmbedBuilder()
.setColor('#a200ff')
.setTitle('πΆ Playlist Added to Queue')
.setDescription(`**${playlist.name}** - \`${playlist.songs.length} tracks\`\n\n${status(queue)}`)
.setThumbnail(playlist.thumbnail)
.setFooter({ text: 'Let the music play! π΅' })]
}
)
})
.on('error', (error, queue) => {
const textChannel = queue.voiceChannel?.guild.channels.cache.get(queue.textChannel?.id);
if (textChannel?.isTextBased?.()) {
textChannel.send({
embeds: [
new EmbedBuilder()
.setColor('Red')
.setTitle('β Error')
.setDescription(`β οΈ **An error occurred while playing a song:**\n\`${error.message}\``)
.setFooter({ text: 'Try another song or check the bot logs.' })
]
});
} else {
console.error("β Cannot send message: queue.textChannel is missing or invalid.");
}
})
.on('empty', channel => {
if (channel && channel.send) {
channel.send({
embeds: [new EmbedBuilder()
.setColor('Red')
.setTitle('β Voice Channel Empty')
.setDescription('The voice channel is empty! Leaving the channel...')
.setFooter({ text: 'Goodbye for now! π' })]
});
} else {
console.error('Empty channel is not a valid TextChannel');
}
})
.on('searchNoResult', (message, query) =>
message.channel.send(
{
embeds: [new EmbedBuilder()
.setColor('Red')
.setTitle('β No Results Found')
.setDescription(`No results found for: **${query}**`)
.setFooter({ text: 'Try a different search term.' })]
})
)
.on('finish', queue => {
const textChannel = queue.voiceChannel?.guild.channels.cache.get(queue.textChannel?.id);
if (textChannel && textChannel.send) {
textChannel.send({
embeds: [new EmbedBuilder()
.setColor('#a200ff')
.setTitle('πΆ Queue Finished')
.setDescription('The queue has ended. Thanks for listening!')
.setFooter({ text: 'More tunes coming up! πΆ' })]
});
}
const connection = queue.voice.connection;
if (!connection) {
console.error("No active voice connection found.");
return;
}
// Disconnect after 30 sec if no new songs are added
disconnectTimeout = setTimeout(() => {
// console.log("No new songs, playing TTS...");
const ttsFile = 'tts.mp3';
if (!fs.existsSync(ttsFile)) {
console.error("TTS file not found:", ttsFile);
return;
}
const player = createAudioPlayer();
const resource = createAudioResource(ttsFile);
connection.subscribe(player);
player.play(resource);
player.on(AudioPlayerStatus.Idle, () => {
// console.log("Finished playing TTS file.");
if (queue.voice.connection) {
queue.voice.connection.destroy();
}
}); //
}, 30000);
});
const resetDisconnectTimer = () => {
if (disconnectTimeout) {
// console.log("π Clearing previous disconnect timeout.");
clearTimeout(disconnectTimeout);
disconnectTimeout = null;
} else {
// console.log("β
No active disconnect timeout to clear.");
}
// console.log("π Disconnect timer reset! Bot will stay in the VC.");
};
const messageMap = new Map();
const ATTACHMENTS_CHANNEL_ID = process.env.ATTACHMENT_CHANNELS_ID;
const GENERAL_CHANNEL_ID = process.env.GENERAL_CHANNELS_ID;
client.commands = new Collection();
const commandsPath = path.join(__dirname, "commands");
const commandFiles = fs.readdirSync("./commands")
for (const fileOrFolder of commandFiles) {
const fullPath = path.join(commandsPath, fileOrFolder);
if (fs.statSync(fullPath).isDirectory()) {
const subFiles = fs.readdirSync(fullPath).filter(file => file.endsWith(".js"));
for (const file of subFiles) {
const filePath = path.join(fullPath, file);
const command = require(filePath);
if ('data' in command && 'execute' in command) {
client.commands.set(command.data.name, command);
} else {
// console.log(`Command ${file} is missing 'data' or 'execute'`);
}
}
}
else if (fileOrFolder.endsWith(".js")) {
const command = require(fullPath);
if ('data' in command && 'execute' in command) {
client.commands.set(command.data.name, command);
} else {
// console.log(`Command ${file} is missing 'data' or 'execute'`);
}
}
}
const eventsPath = path.join(__dirname, "events");
fs.readdirSync(eventsPath).forEach((file) => {
if (file.endsWith(".js")) {
const event = require(path.join(eventsPath, file));
client.on(event.name, event.execute.bind(null, client));
}
});
client.on("messageCreate", async (message) => {
// Check if the message is in the attachments channel and contains attachments
if (message.channel.id === ATTACHMENTS_CHANNEL_ID && message.attachments.size > 0) {
const generalChannel = await message.guild.channels.fetch(GENERAL_CHANNEL_ID);
message.attachments.forEach(async (attachment) => {
// Check if the attachment is a video
if (attachment.contentType && attachment.contentType.startsWith("video")) {
// Generate a thumbnail using FFmpeg
// Create the embed
const embed = new EmbedBuilder()
.setTitle("π₯ New Video Attachment")
.setDescription(`${message.author} has sent a video in ${message.channel}`)
.setImage(message.author.displayAvatarURL({ size: 512 })) // Use the generated thumbnail
.setFooter({ text: `Author: ${message.author.tag}` })
.setTimestamp();
// Send the embed with the thumbnail
const sentMessage = await generalChannel.send({ embeds: [embed] }).catch(console.error);
messageMap.set(message.id, sentMessage.id);
// Delete the thumbnail file after sending
} else {
// Handle non-video attachments (e.g., images)
const embed = new EmbedBuilder()
.setTitle("π New Attachment")
.setDescription(`${message.author} has sent an image in ${message.channel}`)
.setImage(attachment.url)
.setFooter({ text: `Author: ${message.author.tag}` })
.setTimestamp();
const sentMessage = await generalChannel.send({ embeds: [embed] }).catch(console.error);
messageMap.set(message.id, sentMessage.id);
}
});
}
});
client.on("messageDelete", async (message) => {
if (message.channel.id !== ATTACHMENTS_CHANNEL_ID) return; // Only track attachment channel
const generalChannel = await message.guild.channels.fetch(GENERAL_CHANNEL_ID);
const linkedMessageId = messageMap.get(message.id);
if (linkedMessageId) {
try {
const linkedMessage = await generalChannel.messages.fetch(linkedMessageId);
if (linkedMessage) {
await linkedMessage.delete(); // Delete the copied message
}
} catch (error) {
console.error("Failed to delete linked message:", error);
}
messageMap.delete(message.id); // Remove from map
}
});
// client.distube.on("error", (channel, error) => {
// console.error(`DisTube Error in channel ${channel.id}:`,);
// console.error("Full error details:", error);
// });
client.once("ready", () => {
console.log(`β
Logged in as ${client.user.tag}`);
});
client.on("error", (error) => {
console.error("Client Error:", error);
});
client.on("shardError", (error, shardId) => {
console.error(`Shard ${shardId} Error:`, error);
});
client.on("shardDisconnect", (event, shardId) => {
console.warn(`Shard ${shardId} Disconnected:`, event);
});
client.on("shardReconnecting", (shardId) => {
console.log(`Shard ${shardId} Reconnecting...`);
});
client.login(process.env.DISCORD_TOKEN).catch(console.error);