-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
310 lines (272 loc) · 9.68 KB
/
index.js
File metadata and controls
310 lines (272 loc) · 9.68 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
/**
* @fileoverview Initializes the MooSaurus Discord bot client.
* Loads commands and events, sets up DisTube with yt-dlp and cookies.txt,
* and exports an async factory function to return the fully initialized client.
*
* @author DJ Stomp <85457381+DJStompZone@users.noreply.github.com>
* @license MIT
* @see {@link https://github.com/StompZone/MooSaurus}
* @since 2025-08-06
*/
const { execFile } = require("child_process");
const { promisify } = require("util");
const execFileAsync = promisify(execFile);
const { Client, Collection, GatewayIntentBits, Partials, Colors, EmbedBuilder } = require("discord.js");
const { DisTube } = require("distube");
const { SoundCloudPlugin } = require("@distube/soundcloud");
const { YtDlpPlugin } = require("@distube/yt-dlp");
const path = require("path");
const fs = require("fs");
const { registerCustomFonts } = require("./src/utils/registerFonts");
const config = require("./config.js");
const sodium = require("libsodium-wrappers");
const Localization = require("./src/utils/localization");
/**
* @function createClient
* @name createClient
* @async
* @description
* Sets up and initializes the MooSaurus Discord bot client.
*
* - Loads and prepares the Discord client with required intents and partials.
* - Registers custom fonts for canvas-based rendering (e.g., music cards).
* - Injects config, localization, and command handling.
* - Loads all command files from `src/commands`.
* - Loads all event files from `src/events` and attaches them to the client.
* - Sets up the DisTube music system with YouTube cookies support via yt-dlp.
* - Authenticates and logs in using the bot token in config.
*
* @returns {Promise<import("discord.js").Client>} Fully initialized and authenticated Discord.js client.
*
* @example
* const createClient = require('./index');
* (async () => {
* const client = await createClient();
* console.log(`Logged in as ${client.user.tag}`);
* })();
*/
async function createClient() {
await sodium.ready;
registerCustomFonts();
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildVoiceStates,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
],
partials: [Partials.Channel],
});
client.config = config;
client.localization = new Localization(client);
client.commands = new Collection();
loadCommands(client);
loadEvents(client);
initDisTube(client);
await client.login(client.config.token);
console.log("🚀 Bot is online!");
return client;
}
/**
* @function loadCommands
* @name loadCommands
* @description
* Loads all command modules from the `src/commands` directory and registers them to the client's command map.
* Also registers any aliases listed in the config under `config.aliases`.
*
* @param {import("discord.js").Client} client - The Discord client instance.
*/
function loadCommands(client) {
const commandsPath = path.join(__dirname, "src", "commands");
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith(".js"));
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
if ("name" in command && "execute" in command) {
client.commands.set(command.name, command);
const aliases = client.config.aliases[command.name];
if (aliases && Array.isArray(aliases)) {
aliases.forEach(alias => client.commands.set(alias, command));
}
} else {
console.warn(`⚠️ Command ${filePath} missing "name" or "execute"`);
}
}
}
/**
* @function loadEvents
* @name loadEvents
* @description
* Loads all event handlers from the `src/events` directory and attaches them to the client.
* Supports both persistent and `once` events.
*
* @param {import("discord.js").Client} client - The Discord client instance.
*/
function loadEvents(client) {
const eventsPath = path.join(__dirname, "src", "events");
const eventFiles = fs.readdirSync(eventsPath).filter(file => file.endsWith(".js"));
for (const file of eventFiles) {
const filePath = path.join(eventsPath, file);
const event = require(filePath);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args, client));
} else {
client.on(event.name, (...args) => event.execute(...args, client));
}
}
}
const { Readable } = require("stream");
class PatchedYtDlpPlugin extends YtDlpPlugin {
async resolve(url, options) {
// to preserve my sanity, fix later
const ytDlpPath = "/home/moo9xi/MooSaurus/node_modules/@distube/yt-dlp/bin/yt-dlp";
const cookiesPath = "/home/moo9xi/MooSaurus/cookies.txt";
const args = [
"--cookies", cookiesPath,
"--no-playlist",
"-f", "bestaudio",
"-g", // Get the direct audio stream URL
url
];
const { stdout } = await execFileAsync(ytDlpPath, args);
const streamURL = stdout.trim();
const result = {
stream: streamURL,
name: `YouTube Stream (${url})`,
isLive: false,
type: "youtube",
source: "youtube",
url: url
};
console.log(result)
return result;
/*
try {
const { stdout } = await execFileAsync(ytDlpPath, args);
const streamURL = stdout.trim();
// Just return the original URL, but inject metadata to patch the stream later
return {
url,
metadata: { forceStreamURL: streamURL }
};
} catch (err) {
console.error("❌ Failed to run yt-dlp manually:", err.stderr || err);
throw new Error("Custom yt-dlp downloader failed");
}
}
}
// Its getting late and I am all out of fucks to give.
class PatchedYtDlpPlugin extends YtDlpPlugin {
constructor(options = {}) {
super(options)
// Monkeypatch YouTubePlugin inside DisTube to support forceStreamURL
this.name = "PatchedYtDlpPlugin"
}
patchYouTubePlugin(distube) {
const youtubePlugin = distube.handler.plugins.find(
(p) => p.constructor?.name === "YouTubePlugin"
)
if (!youtubePlugin || typeof youtubePlugin.getStreamURL !== "function") {
console.warn("⚠️ Could not find YouTubePlugin to patch.")
return
}
const original = youtubePlugin.getStreamURL.bind(youtubePlugin)
youtubePlugin.getStreamURL = (song) => {
if (song.metadata?.forceStreamURL) {
return song.metadata.forceStreamURL
}
return original(song)
}
console.log("✅ Patched YouTubePlugin to support forceStreamURL")
}
/** @override */
/*async resolve(url, options) {
const result = await super.resolve(url, options)
// Patch happens once on demand
if (!this._patched && options?.manager?.distube) {
this.patchYouTubePlugin(options.manager.distube)
this._patched = true
}
// Inject the custom stream into metadata
if (result && typeof result === "object" && result.stream) {
return {
url: url, // original URL so DisTube processes it normally
metadata: {
forceStreamURL: result.stream
}
}
}
return result // fuck it
}
}
*/
}}
/**
* @function initDisTube
* @name initDisTube
* @description
* Initializes DisTube and configures its plugins, including yt-dlp with cookies.txt support.
* Also sets up event listeners for "playSong" and "addSong" events to handle playback messaging.
*
* @param {import("discord.js").Client} client - The Discord client instance.
*/
function initDisTube(client) {
client.distube = new DisTube(client, {
emitNewSongOnly: true,
emitAddSongWhenCreatingQueue: false,
emitAddListWhenCreatingQueue: false,
plugins: [
new SoundCloudPlugin(),
new PatchedYtDlpPlugin()
]
});
client.distube
.on("playSong", async (queue, song) => {
if (!queue.textChannel && song.metadata?.message?.channel) {
queue.textChannel = song.metadata.message.channel;
}
if (client.config.enableLogging) {
console.log(client.localization.get('events.playSong', {
song: song.name,
user: song.user.tag,
}));
}
if (queue.currentMessage) {
await queue.currentMessage.delete().catch(() => {});
queue.currentMessage = undefined;
}
await require("./src/utils/sendMusicCard")(queue, song, client.localization);
})
.on("addSong", (queue, song) => {
const embed = new EmbedBuilder()
.setColor(Colors.Blue)
.setDescription(client.localization.get('events.addSong', {
song: song.name,
duration: formatTime(song.duration),
user: song.user.tag,
}));
queue.textChannel?.send({ embeds: [embed] }).catch(() => {});
});
}
/**
* @function formatTime
* @name formatTime
* @description Converts seconds into "mm:ss" format for display in embeds or logs.
*
* @param {number} seconds - The number of seconds to format.
* @returns {string} Formatted time string.
*/
function formatTime(seconds) {
const mins = Math.floor(seconds / 60);
const secs = Math.floor(seconds % 60).toString().padStart(2, '0');
return `${mins}:${secs}`;
}
process.on("uncaughtException", err => console.error("Uncaught Exception:", err));
process.on("unhandledRejection", err => console.error("Unhandled Rejection:", err));
module.exports = createClient;
if (require.main === module) {
createClient().catch(err => {
console.error("❌ Failed to start MooSaurus:", err);
process.exit(1);
});
}