music-start-pro
Version:
Music Start Pro is a discord bot that can play YouTube music by slash command.
389 lines (388 loc) • 18.5 kB
JavaScript
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Bucket = void 0;
var discord_js_1 = require("discord.js");
var voice_1 = require("@discordjs/voice");
var musicInfo_1 = require("./musicInfo");
var util_1 = require("./util");
var queue_1 = require("./queue");
var ytdl_core_1 = __importDefault(require("@distube/ytdl-core"));
var language_json_1 = require("./language.json");
var commands_1 = require("./commands");
var fs = __importStar(require("fs"));
/**
* An instance of Bucket represents one guild in Discord.
* Use Bucket.find(`id`) to fetch the instance.
* Bucket.find(`id`) creates new instance if `id` is new one, else returns the instance we created.
*/
var Bucket = /** @class */ (function () {
function Bucket(id) {
this.connection = null;
this.interaction = null;
this.voiceChannel = null;
this.resource = null;
this.player = this.createPlayer();
this.verbose = true; // if set false, the player does not show the information when starting playing song.
this._playerErrorLock = false; // set true when player is error.
this._playerVolume = .64;
this._lang = "en";
this._repeat = false;
this.queue = new queue_1.Queue();
if (id == undefined)
throw ('no guild id when fetch Bucket');
console.log('bucket id:', id);
this.id = id;
Bucket.instant.set(this.id, this);
}
Bucket.disableLog = function () {
Bucket._useLog = false;
};
Bucket.load = function (fn) {
// Even if the file does not exist, set _logFn nonetheless.
Bucket._logFn = fn;
// if the file does not exist, exit
if (!fs.existsSync(fn))
return;
var data = JSON.parse(fs.readFileSync(fn, { encoding: 'utf-8', flag: 'r' }));
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Object.keys(data).forEach(function (k) {
var e = data[k];
var bucket = new Bucket(k);
bucket.lang = e.lang;
bucket.volume = e.volume;
e.queue.forEach(function (f) {
bucket.queue.add(new musicInfo_1.MusicInfo(f.url, f.title, f.likes, f.viewCount, f.playCounter));
});
Bucket.instant.set(k, bucket);
});
};
// store all instance of Bucket when _useLog is true
Bucket.prototype.store = function () {
var _this = this;
if (!Bucket._useLog)
return;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
var ret = {};
Bucket.instant.forEach(function (e) {
ret[e.id] = {
lang: _this.lang,
volume: _this.volume,
queue: _this.queue.toList()
};
});
fs.writeFileSync(Bucket._logFn, JSON.stringify(ret), { flag: 'w' });
};
Bucket.find = function (id) {
var _a;
// https://tutorial.eyehunts.com/js/javascript-double-question-mark-vs-double-pipe-code/
return (_a = Bucket.instant.get(id)) !== null && _a !== void 0 ? _a : new Bucket(id);
};
Object.defineProperty(Bucket.prototype, "playing", {
get: function () {
return this.player.state.status === 'playing';
},
enumerable: false,
configurable: true
});
/**
* Join the bot to the voice channel.
* This method also updates the value of `this.interaction`.
* @param interaction
* @returns true if connect success
*/
Bucket.prototype.connect = function (interaction) {
this.interaction = interaction;
if (interaction.member instanceof discord_js_1.GuildMember && interaction.member.voice.channel) {
var voiceChannel = interaction.member.voice.channel;
this.voiceChannel = voiceChannel;
this.connection = (0, voice_1.joinVoiceChannel)({
channelId: voiceChannel.id,
guildId: voiceChannel.guild.id,
selfDeaf: true,
selfMute: false,
adapterCreator: voiceChannel.guild.voiceAdapterCreator
});
this.connection.subscribe(this.player);
return true;
}
return false;
};
Bucket.prototype.disconnect = function () {
var _a;
(_a = this.connection) === null || _a === void 0 ? void 0 : _a.destroy();
};
/**
* Create a player that automatically plays the next song when finish playing.
* When play the next song, show the information of it if `this.verbose` is true.
*
* @returns an audio player object
*/
Bucket.prototype.createPlayer = function () {
var _this = this;
var player = (0, voice_1.createAudioPlayer)({
debug: true,
behaviors: {
noSubscriber: voice_1.NoSubscriberBehavior.Pause,
}
});
player.on(voice_1.AudioPlayerStatus.Playing, function () {
var _a, _b;
// if there is no one in voice channel when the player is playing, pause.
if (_this.voiceChannel != null && ((_a = _this.voiceChannel) === null || _a === void 0 ? void 0 : _a.members.size) <= 1) {
player.pause();
var channel = (_b = _this.interaction) === null || _b === void 0 ? void 0 : _b.channel;
channel === null || channel === void 0 ? void 0 : channel.send(language_json_1.messages.paused_because_no_one_in_channel[_this.lang]);
}
});
// https://discordjs.guide/voice/audio-player.html#life-cycle
// DEBUG:
// player.on(AudioPlayerStatus.Buffering, () => {
// console.log("buffering");
// });
// When the bot is not in any voice channels, the player is automatically paused.
// player.on(AudioPlayerStatus.AutoPaused, () => {
// console.log("autoPaused");
// });
// player.on(AudioPlayerStatus.Paused, () => {
// console.log("paused");
// });
// player.on(AudioPlayerStatus.Idle, () => {
// console.log("idle");
// });
/**
* 當播放器錯誤發生時,state會依序進入以下狀態:
* 1. onError
* 2. buffering
* 3. onFinish
* Thus, we can set _playerErrorLock to be `true` and fix error in the state of `onFinish`
* Then, set _playerErrorLock to be `false`
*/
player.on('error', function (error) {
var _a;
console.log('播放器發生錯誤!');
console.log(error.message);
console.log(error.name);
console.log(error.stack);
_this._playerErrorLock = true;
var channel = (_a = _this.interaction) === null || _a === void 0 ? void 0 : _a.channel;
channel === null || channel === void 0 ? void 0 : channel.send(util_1.Util.createEmbedMessage(language_json_1.messages.error[_this.lang], "".concat(language_json_1.messages.player_error[_this.lang], " ").concat(util_1.Util.randomCry()), true));
console.log('Reset player');
_this.player = _this.createPlayer();
// disconnect from voice channel
_this.disconnect();
});
// this block handles
// (1) player error
// (2) play next song when player finished
player.on('stateChange', function (oldState, newState) {
// onfinish()
if (newState.status === voice_1.AudioPlayerStatus.Idle && oldState.status !== voice_1.AudioPlayerStatus.Idle) {
// If the Idle state is entered from a non-Idle state, it means that an audio resource has finished playing.
// The queue is then processed to start playing the next track, if one is available.
if (_this._playerErrorLock) {
// error occurred
// fake finish()
console.log('Error line169 bucket.ts');
}
else {
// real finish()
// update play counter
// if call removeAll(), the current will out of bound.
if (!_this.queue.current)
return;
_this.queue.current.playCounter++;
_this.store();
if (!_this._repeat) {
_this.queue.next(1);
}
_this.play(_this.queue.current).then(function () {
var _a;
if (_this.verbose) {
var channel = (_a = _this.interaction) === null || _a === void 0 ? void 0 : _a.channel;
channel === null || channel === void 0 ? void 0 : channel.send(util_1.Util.createMusicInfoMessage(_this.queue.current));
}
});
}
_this._playerErrorLock = false;
}
else if (newState.status === voice_1.AudioPlayerStatus.Playing) {
// onstart()
}
});
return player;
};
/**
* Plays music on `this.player` by given MusicInfo.
* @param music
* @param begin start at `begin` milliseconds
*/
Bucket.prototype.play = function (music, begin) {
return __awaiter(this, void 0, void 0, function () {
var stream, e_1, channel;
var _a, _b, _c;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
if (this.connection === null) {
throw (language_json_1.messages.robot_not_in_voice_channel[this.lang]);
}
stream = (0, ytdl_core_1.default)(music.url, {
quality: 'highestaudio',
filter: 'audioonly',
highWaterMark: 1 << 25, // 32 MB
begin: begin ? begin : 0,
// begin: This option is not very reliable for non-live videos
});
// ytdlInfo seems to be expired after a period of time
// const stream = ytdl.downloadFromInfo(music.ytdlInfo, {...});
// DEBUG
// number - Chunk length in bytes or segment number.
// number - Total bytes or segments downloaded.
// number - Total bytes or segments.
// stream.on('progress', (chunkSize, downloadedSize, totalSize) => {
// this._playerDownloadedChunk = downloadedSize;
// this._playerTotalChunk = totalSize;
// });
this.resource = (0, voice_1.createAudioResource)(stream, {
inputType: voice_1.StreamType.Arbitrary,
inlineVolume: true,
});
(_b = (_a = this.resource) === null || _a === void 0 ? void 0 : _a.volume) === null || _b === void 0 ? void 0 : _b.setVolume(this.volume);
_d.label = 1;
case 1:
_d.trys.push([1, 3, , 4]);
this.player.play(this.resource);
return [4 /*yield*/, (0, voice_1.entersState)(this.player, voice_1.AudioPlayerStatus.Playing, 3e4)];
case 2:
_d.sent();
return [3 /*break*/, 4];
case 3:
e_1 = _d.sent();
channel = (_c = this.interaction) === null || _c === void 0 ? void 0 : _c.channel;
channel === null || channel === void 0 ? void 0 : channel.send(util_1.Util.createEmbedMessage(language_json_1.messages.error[this.lang], "".concat(e_1), true));
console.error("line274 bucket.ts play() error", e_1, "try to reset player");
this.player = this.createPlayer();
if (this.interaction != null) {
this.connect(this.interaction);
}
channel === null || channel === void 0 ? void 0 : channel.send(util_1.Util.createEmbedMessage(language_json_1.messages.error[this.lang], "".concat(language_json_1.messages.player_error[this.lang], " ").concat(util_1.Util.randomCry()), true));
return [3 /*break*/, 4];
case 4: return [2 /*return*/];
}
});
});
};
// play() + edit reply
Bucket.prototype.playAndEditReplyDefault = function (music, interaction) {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
this.play(music).then(function () {
interaction === null || interaction === void 0 ? void 0 : interaction.editReply(util_1.Util.createMusicInfoMessage(music));
}).catch(function (e) {
interaction === null || interaction === void 0 ? void 0 : interaction.editReply(util_1.Util.createEmbedMessage(language_json_1.messages.error[_this.lang], "".concat(e), true));
});
return [2 /*return*/];
});
});
};
// @return final `repeat` state
Bucket.prototype.toggleRepeat = function () {
this._repeat = !this._repeat;
return this._repeat;
};
Object.defineProperty(Bucket.prototype, "volume", {
get: function () {
return this._playerVolume;
},
// @param: volume is in [0, 1]
set: function (vol) {
var _a, _b;
this._playerVolume = vol;
(_b = (_a = this.resource) === null || _a === void 0 ? void 0 : _a.volume) === null || _b === void 0 ? void 0 : _b.setVolume(vol);
},
enumerable: false,
configurable: true
});
Object.defineProperty(Bucket.prototype, "lang", {
get: function () {
return this._lang;
},
// set language and re-register command.
set: function (lang) {
this._lang = lang;
if (this.interaction != null) {
commands_1.Commands.register(this.interaction.guild, this._lang);
}
},
enumerable: false,
configurable: true
});
Bucket._useLog = true;
Bucket._logFn = '';
Bucket.instant = new Map();
return Bucket;
}());
exports.Bucket = Bucket;