mirror of
https://github.com/BluemediaDev/muse.git
synced 2025-05-10 04:01:37 +02:00
Migrate play command to slash command
This commit is contained in:
parent
fa4ba0bb9a
commit
dcb1351791
9 changed files with 153 additions and 172 deletions
90
src/bot.ts
90
src/bot.ts
|
@ -1,113 +1,91 @@
|
|||
import {Client, Message, Collection} from 'discord.js';
|
||||
import {Client, Collection, User} from 'discord.js';
|
||||
import {inject, injectable} from 'inversify';
|
||||
import {TYPES} from './types.js';
|
||||
import {Settings, Shortcut} from './models/index.js';
|
||||
import container from './inversify.config.js';
|
||||
import Command from './commands/index.js';
|
||||
import debug from './utils/debug.js';
|
||||
import NaturalLanguage from './services/natural-language-commands.js';
|
||||
import handleGuildCreate from './events/guild-create.js';
|
||||
import handleVoiceStateUpdate from './events/voice-state-update.js';
|
||||
import errorMsg from './utils/error-msg.js';
|
||||
import {isUserInVoice} from './utils/channels.js';
|
||||
import Config from './services/config.js';
|
||||
import {generateDependencyReport} from '@discordjs/voice';
|
||||
import {REST} from '@discordjs/rest';
|
||||
import {Routes} from 'discord-api-types/v9';
|
||||
|
||||
@injectable()
|
||||
export default class {
|
||||
private readonly client: Client;
|
||||
private readonly naturalLanguage: NaturalLanguage;
|
||||
private readonly token: string;
|
||||
private readonly commands!: Collection<string, Command>;
|
||||
|
||||
constructor(@inject(TYPES.Client) client: Client, @inject(TYPES.Services.NaturalLanguage) naturalLanguage: NaturalLanguage, @inject(TYPES.Config) config: Config) {
|
||||
constructor(@inject(TYPES.Client) client: Client, @inject(TYPES.Config) config: Config) {
|
||||
this.client = client;
|
||||
this.naturalLanguage = naturalLanguage;
|
||||
this.token = config.DISCORD_TOKEN;
|
||||
this.commands = new Collection();
|
||||
}
|
||||
|
||||
public async listen(): Promise<string> {
|
||||
public async listen(): Promise<void> {
|
||||
// Load in commands
|
||||
container.getAll<Command>(TYPES.Command).forEach(command => {
|
||||
const commandNames = [command.name, ...command.aliases];
|
||||
|
||||
commandNames.forEach(commandName => this.commands.set(commandName, command));
|
||||
// TODO: remove !
|
||||
if (command.slashCommand?.name) {
|
||||
this.commands.set(command.slashCommand.name, command);
|
||||
}
|
||||
});
|
||||
|
||||
this.client.on('messageCreate', async (msg: Message) => {
|
||||
// Get guild settings
|
||||
if (!msg.guild) {
|
||||
// Register event handlers
|
||||
this.client.on('interactionCreate', async interaction => {
|
||||
if (!interaction.isCommand()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const settings = await Settings.findByPk(msg.guild.id);
|
||||
const command = this.commands.get(interaction.commandName);
|
||||
|
||||
if (!settings) {
|
||||
// Got into a bad state, send owner welcome message
|
||||
this.client.emit('guildCreate', msg.guild);
|
||||
if (!command) {
|
||||
return;
|
||||
}
|
||||
|
||||
const {prefix, channel} = settings;
|
||||
|
||||
if (!msg.content.startsWith(prefix) && !msg.author.bot && msg.channel.id === channel && await this.naturalLanguage.execute(msg)) {
|
||||
// Natural language command handled message
|
||||
return;
|
||||
}
|
||||
|
||||
if (!msg.content.startsWith(prefix) || msg.author.bot || msg.channel.id !== channel) {
|
||||
return;
|
||||
}
|
||||
|
||||
let args = msg.content.slice(prefix.length).split(/ +/);
|
||||
const command = args.shift()!.toLowerCase();
|
||||
|
||||
// Get possible shortcut
|
||||
const shortcut = await Shortcut.findOne({where: {guildId: msg.guild.id, shortcut: command}});
|
||||
|
||||
let handler: Command;
|
||||
|
||||
if (this.commands.has(command)) {
|
||||
handler = this.commands.get(command)!;
|
||||
} else if (shortcut) {
|
||||
const possibleHandler = this.commands.get(shortcut.command.split(' ')[0]);
|
||||
|
||||
if (possibleHandler) {
|
||||
handler = possibleHandler;
|
||||
args = shortcut.command.split(/ +/).slice(1);
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
if (!interaction.guild) {
|
||||
await interaction.reply(errorMsg('you can\'t use this bot in a DM'));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (handler.requiresVC && !isUserInVoice(msg.guild, msg.author)) {
|
||||
await msg.channel.send(errorMsg('gotta be in a voice channel'));
|
||||
if (command.requiresVC && !isUserInVoice(interaction.guild, interaction.member.user as User)) {
|
||||
await interaction.reply({content: errorMsg('gotta be in a voice channel'), ephemeral: true});
|
||||
return;
|
||||
}
|
||||
|
||||
await handler.execute(msg, args);
|
||||
if (command.executeFromInteraction) {
|
||||
await command.executeFromInteraction(interaction);
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
debug(error);
|
||||
await msg.channel.send(errorMsg((error as Error).message.toLowerCase()));
|
||||
await interaction.reply({content: errorMsg(error as Error), ephemeral: true});
|
||||
}
|
||||
});
|
||||
|
||||
this.client.on('ready', async () => {
|
||||
this.client.once('ready', async () => {
|
||||
debug(generateDependencyReport());
|
||||
console.log(`Ready! Invite the bot with https://discordapp.com/oauth2/authorize?client_id=${this.client.user?.id ?? ''}&scope=bot&permissions=36752448`);
|
||||
console.log(`Ready! Invite the bot with https://discordapp.com/oauth2/authorize?client_id=${this.client.user?.id ?? ''}&scope=bot&permissions=2184236096`);
|
||||
});
|
||||
|
||||
this.client.on('error', console.error);
|
||||
this.client.on('debug', debug);
|
||||
|
||||
// Register event handlers
|
||||
this.client.on('guildCreate', handleGuildCreate);
|
||||
this.client.on('voiceStateUpdate', handleVoiceStateUpdate);
|
||||
|
||||
return this.client.login(this.token);
|
||||
// Update commands
|
||||
await this.client.login(this.token);
|
||||
|
||||
const rest = new REST({version: '9'}).setToken(this.token);
|
||||
|
||||
await rest.put(
|
||||
Routes.applicationGuildCommands(this.client.user!.id, this.client.guilds.cache.first()!.id),
|
||||
// TODO: remove
|
||||
{body: this.commands.map(command => command.slashCommand ? command.slashCommand.toJSON() : null)},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,66 +0,0 @@
|
|||
import {Message, Util} from 'discord.js';
|
||||
import {injectable} from 'inversify';
|
||||
import Command from '.';
|
||||
import {TYPES} from '../types.js';
|
||||
import {Settings} from '../models/index.js';
|
||||
import container from '../inversify.config.js';
|
||||
|
||||
@injectable()
|
||||
export default class implements Command {
|
||||
public name = 'help';
|
||||
public aliases = ['h'];
|
||||
public examples = [
|
||||
['help', 'you don\'t need a description'],
|
||||
];
|
||||
|
||||
private commands: Command[] = [];
|
||||
|
||||
public async execute(msg: Message, _: string []): Promise<void> {
|
||||
if (this.commands.length === 0) {
|
||||
// Lazy load to avoid circular dependencies
|
||||
this.commands = container.getAll<Command>(TYPES.Command);
|
||||
}
|
||||
|
||||
const settings = await Settings.findOne({where: {guildId: msg.guild!.id}});
|
||||
|
||||
if (!settings) {
|
||||
return;
|
||||
}
|
||||
|
||||
const {prefix} = settings;
|
||||
|
||||
const res = Util.splitMessage(this.commands.sort((a, b) => a.name.localeCompare(b.name)).reduce((content, command) => {
|
||||
const aliases = command.aliases.reduce((str, alias, i) => {
|
||||
str += alias;
|
||||
|
||||
if (i !== command.aliases.length - 1) {
|
||||
str += ', ';
|
||||
}
|
||||
|
||||
return str;
|
||||
}, '');
|
||||
|
||||
if (aliases === '') {
|
||||
content += `**${command.name}**:\n`;
|
||||
} else {
|
||||
content += `**${command.name}** (${aliases}):\n`;
|
||||
}
|
||||
|
||||
command.examples.forEach(example => {
|
||||
content += `- \`${prefix}${example[0]}\`: ${example[1]}\n`;
|
||||
});
|
||||
|
||||
content += '\n';
|
||||
|
||||
return content;
|
||||
}, ''));
|
||||
|
||||
for (const r of res) {
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
await msg.author.send(r);
|
||||
}
|
||||
|
||||
await msg.react('🇩');
|
||||
await msg.react('🇲');
|
||||
}
|
||||
}
|
|
@ -1,9 +1,12 @@
|
|||
import {Message} from 'discord.js';
|
||||
import {SlashCommandBuilder} from '@discordjs/builders';
|
||||
import {CommandInteraction} from 'discord.js';
|
||||
|
||||
export default interface Command {
|
||||
name: string;
|
||||
aliases: string[];
|
||||
examples: string[][];
|
||||
// TODO: remove
|
||||
name?: string;
|
||||
aliases?: string[];
|
||||
examples?: string[][];
|
||||
slashCommand?: Partial<SlashCommandBuilder> & Pick<SlashCommandBuilder, 'toJSON'>;
|
||||
requiresVC?: boolean;
|
||||
execute: (msg: Message, args: string[]) => Promise<void>;
|
||||
executeFromInteraction?: (interaction: CommandInteraction) => Promise<void>;
|
||||
}
|
||||
|
|
|
@ -1,31 +1,27 @@
|
|||
import {TextChannel, Message} from 'discord.js';
|
||||
import {CommandInteraction, GuildMember} from 'discord.js';
|
||||
import {URL} from 'url';
|
||||
import {Except} from 'type-fest';
|
||||
import {TYPES} from '../types.js';
|
||||
import {SlashCommandBuilder} from '@discordjs/builders';
|
||||
import {inject, injectable} from 'inversify';
|
||||
import Command from '.';
|
||||
import {TYPES} from '../types.js';
|
||||
import {QueuedSong, STATUS} from '../services/player.js';
|
||||
import PlayerManager from '../managers/player.js';
|
||||
import {getMostPopularVoiceChannel, getMemberVoiceChannel} from '../utils/channels.js';
|
||||
import LoadingMessage from '../utils/loading-message.js';
|
||||
import errorMsg from '../utils/error-msg.js';
|
||||
import Command from '.';
|
||||
import GetSongs from '../services/get-songs.js';
|
||||
|
||||
@injectable()
|
||||
export default class implements Command {
|
||||
public name = 'play';
|
||||
public aliases = ['p'];
|
||||
public examples = [
|
||||
['play', 'resume paused playback'],
|
||||
['play https://www.youtube.com/watch?v=dQw4w9WgXcQ', 'plays a YouTube video'],
|
||||
['play cool music', 'plays the first search result for "cool music" from YouTube'],
|
||||
['play https://www.youtube.com/watch?list=PLi9drqWffJ9FWBo7ZVOiaVy0UQQEm4IbP', 'adds the playlist to the queue'],
|
||||
['play https://open.spotify.com/track/3ebXMykcMXOcLeJ9xZ17XH?si=tioqSuyMRBWxhThhAW51Ig', 'plays a song from Spotify'],
|
||||
['play https://open.spotify.com/album/5dv1oLETxdsYOkS2Sic00z?si=bDa7PaloRx6bMIfKdnvYQw', 'adds all songs from album to the queue'],
|
||||
['play https://open.spotify.com/playlist/37i9dQZF1DX94qaYRnkufr?si=r2fOVL_QQjGxFM5MWb84Xw', 'adds all songs from playlist to the queue'],
|
||||
['play cool music immediate', 'adds the first search result for "cool music" to the front of the queue'],
|
||||
['play cool music i', 'adds the first search result for "cool music" to the front of the queue'],
|
||||
];
|
||||
public readonly slashCommand = new SlashCommandBuilder()
|
||||
.setName('play')
|
||||
.setDescription('Play a song')
|
||||
.addStringOption(option => option
|
||||
.setName('query')
|
||||
.setDescription('YouTube URL, Spotify URL, or search query'))
|
||||
.addBooleanOption(option => option
|
||||
.setName('immediate')
|
||||
.setDescription('adds track to the front of the queue'));
|
||||
|
||||
public requiresVC = true;
|
||||
|
||||
|
@ -38,43 +34,43 @@ export default class implements Command {
|
|||
}
|
||||
|
||||
// eslint-disable-next-line complexity
|
||||
public async execute(msg: Message, args: string[]): Promise<void> {
|
||||
const [targetVoiceChannel] = getMemberVoiceChannel(msg.member!) ?? getMostPopularVoiceChannel(msg.guild!);
|
||||
|
||||
const res = new LoadingMessage(msg.channel as TextChannel);
|
||||
await res.start();
|
||||
|
||||
const player = this.playerManager.get(msg.guild!.id);
|
||||
public async executeFromInteraction(interaction: CommandInteraction): Promise<void> {
|
||||
const [targetVoiceChannel] = getMemberVoiceChannel(interaction.member as GuildMember) ?? getMostPopularVoiceChannel(interaction.guild!);
|
||||
|
||||
const player = this.playerManager.get(interaction.guild!.id);
|
||||
const wasPlayingSong = player.getCurrent() !== null;
|
||||
|
||||
if (args.length === 0) {
|
||||
const query = interaction.options.getString('query');
|
||||
|
||||
if (!query) {
|
||||
if (player.status === STATUS.PLAYING) {
|
||||
await res.stop(errorMsg('already playing, give me a song name'));
|
||||
await interaction.reply({content: errorMsg('already playing, give me a song name'), ephemeral: true});
|
||||
return;
|
||||
}
|
||||
|
||||
// Must be resuming play
|
||||
if (!wasPlayingSong) {
|
||||
await res.stop(errorMsg('nothing to play'));
|
||||
await interaction.reply({content: errorMsg('nothing to play'), ephemeral: true});
|
||||
return;
|
||||
}
|
||||
|
||||
await player.connect(targetVoiceChannel);
|
||||
await player.play();
|
||||
|
||||
await res.stop('the stop-and-go light is now green');
|
||||
await interaction.reply('the stop-and-go light is now green');
|
||||
return;
|
||||
}
|
||||
|
||||
const addToFrontOfQueue = args[args.length - 1] === 'i' || args[args.length - 1] === 'immediate';
|
||||
const addToFrontOfQueue = interaction.options.getBoolean('immediate');
|
||||
|
||||
const newSongs: Array<Except<QueuedSong, 'addedInChannelId'>> = [];
|
||||
let extraMsg = '';
|
||||
|
||||
await interaction.deferReply();
|
||||
|
||||
// Test if it's a complete URL
|
||||
try {
|
||||
const url = new URL(args[0]);
|
||||
const url = new URL(query);
|
||||
|
||||
const YOUTUBE_HOSTS = [
|
||||
'www.youtube.com',
|
||||
|
@ -96,12 +92,12 @@ export default class implements Command {
|
|||
if (song) {
|
||||
newSongs.push(song);
|
||||
} else {
|
||||
await res.stop(errorMsg('that doesn\'t exist'));
|
||||
await interaction.editReply(errorMsg('that doesn\'t exist'));
|
||||
return;
|
||||
}
|
||||
}
|
||||
} else if (url.protocol === 'spotify:' || url.host === 'open.spotify.com') {
|
||||
const [convertedSongs, nSongsNotFound, totalSongs] = await this.getSongs.spotifySource(args[0]);
|
||||
const [convertedSongs, nSongsNotFound, totalSongs] = await this.getSongs.spotifySource(query);
|
||||
|
||||
if (totalSongs > 50) {
|
||||
extraMsg = 'a random sample of 50 songs was taken';
|
||||
|
@ -123,25 +119,23 @@ export default class implements Command {
|
|||
}
|
||||
} catch (_: unknown) {
|
||||
// Not a URL, must search YouTube
|
||||
const query = addToFrontOfQueue ? args.slice(0, args.length - 1).join(' ') : args.join(' ');
|
||||
|
||||
const song = await this.getSongs.youtubeVideoSearch(query);
|
||||
|
||||
if (song) {
|
||||
newSongs.push(song);
|
||||
} else {
|
||||
await res.stop(errorMsg('that doesn\'t exist'));
|
||||
await interaction.editReply(errorMsg('that doesn\'t exist'));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (newSongs.length === 0) {
|
||||
await res.stop(errorMsg('no songs found'));
|
||||
await interaction.editReply(errorMsg('no songs found'));
|
||||
return;
|
||||
}
|
||||
|
||||
newSongs.forEach(song => {
|
||||
player.add({...song, addedInChannelId: msg.channel.id}, {immediate: addToFrontOfQueue});
|
||||
player.add({...song, addedInChannelId: interaction.channel?.id}, {immediate: addToFrontOfQueue ?? false});
|
||||
});
|
||||
|
||||
const firstSong = newSongs[0];
|
||||
|
@ -173,9 +167,9 @@ export default class implements Command {
|
|||
}
|
||||
|
||||
if (newSongs.length === 1) {
|
||||
await res.stop(`u betcha, **${firstSong.title}** added to the${addToFrontOfQueue ? ' front of the' : ''} queue${extraMsg}`);
|
||||
await interaction.editReply(`u betcha, **${firstSong.title}** added to the${addToFrontOfQueue ? ' front of the' : ''} queue${extraMsg}`);
|
||||
} else {
|
||||
await res.stop(`u betcha, **${firstSong.title}** and ${newSongs.length - 1} other songs were added to the queue${extraMsg}`);
|
||||
await interaction.editReply(`u betcha, **${firstSong.title}** and ${newSongs.length - 1} other songs were added to the queue${extraMsg}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -18,7 +18,6 @@ import Clear from './commands/clear.js';
|
|||
import Config from './commands/config.js';
|
||||
import Disconnect from './commands/disconnect.js';
|
||||
import ForwardSeek from './commands/fseek.js';
|
||||
import Help from './commands/help.js';
|
||||
import Pause from './commands/pause.js';
|
||||
import Play from './commands/play.js';
|
||||
import QueueCommand from './commands/queue.js';
|
||||
|
@ -59,7 +58,6 @@ container.bind<NaturalLanguage>(TYPES.Services.NaturalLanguage).to(NaturalLangua
|
|||
Config,
|
||||
Disconnect,
|
||||
ForwardSeek,
|
||||
Help,
|
||||
Pause,
|
||||
Play,
|
||||
QueueCommand,
|
||||
|
|
|
@ -21,7 +21,7 @@ export interface QueuedSong {
|
|||
length: number;
|
||||
playlist: QueuedPlaylist | null;
|
||||
isLive: boolean;
|
||||
addedInChannelId: Snowflake;
|
||||
addedInChannelId?: Snowflake;
|
||||
}
|
||||
|
||||
export enum STATUS {
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue