fix command permission handling and push discord to v10 (#640)

Co-authored-by: Max Isom <hi@maxisom.me>
This commit is contained in:
Kevin Kendzia 2022-05-14 02:44:14 +02:00 committed by GitHub
parent 1ef05aba9d
commit eb2885b206
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
38 changed files with 1214 additions and 644 deletions

View file

@ -1,5 +1,5 @@
import getYouTubeID from 'get-youtube-id';
import {MessageEmbed} from 'discord.js';
import {EmbedBuilder} from 'discord.js';
import Player, {MediaSource, QueuedSong, STATUS} from '../services/player.js';
import getProgressBar from './get-progress-bar.js';
import {prettyTime} from './time.js';
@ -50,7 +50,7 @@ const getPlayerUI = (player: Player) => {
return `${button} ${progressBar} \`[${elapsedTime}]\` 🔉`;
};
export const buildPlayingMessageEmbed = (player: Player): MessageEmbed => {
export const buildPlayingMessageEmbed = (player: Player): EmbedBuilder => {
const currentlyPlaying = player.getCurrent();
if (!currentlyPlaying) {
@ -58,10 +58,9 @@ export const buildPlayingMessageEmbed = (player: Player): MessageEmbed => {
}
const {artist, thumbnailUrl, requestedBy} = currentlyPlaying;
const message = new MessageEmbed();
const message = new EmbedBuilder();
message
.setColor(player.status === STATUS.PLAYING ? 'DARK_GREEN' : 'DARK_RED')
.setColor(player.status === STATUS.PLAYING ? 'DarkGreen' : 'DarkRed')
.setTitle(player.status === STATUS.PLAYING ? 'Now Playing' : 'Paused')
.setDescription(`
**${getSongTitle(currentlyPlaying)}**
@ -77,7 +76,7 @@ export const buildPlayingMessageEmbed = (player: Player): MessageEmbed => {
return message;
};
export const buildQueueEmbed = (player: Player, page: number): MessageEmbed => {
export const buildQueueEmbed = (player: Player, page: number): EmbedBuilder => {
const currentlyPlaying = player.getCurrent();
if (!currentlyPlaying) {
@ -108,7 +107,7 @@ export const buildQueueEmbed = (player: Player, page: number): MessageEmbed => {
const playlistTitle = playlist ? `(${playlist.title})` : '';
const totalLength = player.getQueue().reduce((accumulator, current) => accumulator + current.length, 0);
const message = new MessageEmbed();
const message = new EmbedBuilder();
let description = `**${getSongTitle(currentlyPlaying)}**\n`;
description += `Requested by: <@${requestedBy}>\n\n`;
@ -121,11 +120,11 @@ export const buildQueueEmbed = (player: Player, page: number): MessageEmbed => {
message
.setTitle(player.status === STATUS.PLAYING ? 'Now Playing' : 'Queued songs')
.setColor(player.status === STATUS.PLAYING ? 'DARK_GREEN' : 'NOT_QUITE_BLACK')
.setColor(player.status === STATUS.PLAYING ? 'DarkGreen' : 'NotQuiteBlack')
.setDescription(description)
.addField('In queue', getQueueInfo(player), true)
.addField('Total length', `${totalLength > 0 ? prettyTime(totalLength) : '-'}`, true)
.addField('Page', `${page} out of ${maxQueuePage}`, true)
.addFields([{name: 'In queue', value: getQueueInfo(player), inline: true}, {
name: 'Total length', value: `${totalLength > 0 ? prettyTime(totalLength) : '-'}`, inline: true,
}, {name: 'Page', value: `${page} out of ${maxQueuePage}`, inline: true}])
.setFooter({text: `Source: ${artist} ${playlistTitle}`});
if (thumbnailUrl) {
@ -134,3 +133,4 @@ export const buildQueueEmbed = (player: Player, page: number): MessageEmbed => {
return message;
};

View file

@ -1,9 +1,9 @@
import {Guild, VoiceChannel, User, GuildMember} from 'discord.js';
import {ChannelType, Guild, GuildMember, User, VoiceChannel} from 'discord.js';
export const isUserInVoice = (guild: Guild, user: User): boolean => {
let inVoice = false;
guild.channels.cache.filter(channel => channel.type === 'GUILD_VOICE').forEach(channel => {
guild.channels.cache.filter(channel => channel.type === ChannelType.GuildVoice).forEach(channel => {
if ((channel as VoiceChannel).members.find(member => member.id === user.id)) {
inVoice = true;
}
@ -22,7 +22,7 @@ export const getSizeWithoutBots = (channel: VoiceChannel): number => channel.mem
export const getMemberVoiceChannel = (member?: GuildMember): [VoiceChannel, number] | null => {
const channel = member?.voice?.channel;
if (channel && channel.type === 'GUILD_VOICE') {
if (channel && channel.type === ChannelType.GuildVoice) {
return [
channel,
getSizeWithoutBots(channel),
@ -41,7 +41,7 @@ export const getMostPopularVoiceChannel = (guild: Guild): [VoiceChannel, number]
const voiceChannels: PopularResult[] = [];
for (const [_, channel] of guild.channels.cache) {
if (channel.type === 'GUILD_VOICE') {
if (channel.type === ChannelType.GuildVoice) {
const size = getSizeWithoutBots(channel);
voiceChannels.push({

View file

@ -1,4 +1,4 @@
import {ApplicationCommandOptionChoice} from 'discord.js';
import {APIApplicationCommandOptionChoice} from 'discord-api-types/v10';
import SpotifyWebApi from 'spotify-web-api-node';
import getYouTubeSuggestionsFor from './get-youtube-suggestions-for.js';
@ -14,7 +14,7 @@ const filterDuplicates = <T extends {name: string}>(items: T[]) => {
return results;
};
const getYouTubeAndSpotifySuggestionsFor = async (query: string, spotify: SpotifyWebApi, limit = 10): Promise<ApplicationCommandOptionChoice[]> => {
const getYouTubeAndSpotifySuggestionsFor = async (query: string, spotify: SpotifyWebApi, limit = 10): Promise<APIApplicationCommandOptionChoice[]> => {
const [youtubeSuggestions, spotifyResults] = await Promise.all([
getYouTubeSuggestionsFor(query),
spotify.search(query, ['track', 'album'], {limit: 5}),
@ -35,7 +35,7 @@ const getYouTubeAndSpotifySuggestionsFor = async (query: string, spotify: Spotif
const maxYouTubeSuggestions = limit - numOfSpotifySuggestions;
const numOfYouTubeSuggestions = Math.min(maxYouTubeSuggestions, totalYouTubeResults);
const suggestions: ApplicationCommandOptionChoice[] = [];
const suggestions: APIApplicationCommandOptionChoice[] = [];
suggestions.push(
...youtubeSuggestions

View file

@ -0,0 +1,19 @@
import {REST} from '@discordjs/rest';
import {Routes} from 'discord-api-types/v10';
import Command from '../commands';
interface RegisterCommandsOnGuildOptions {
rest: REST;
applicationId: string;
guildId: string;
commands: Array<Command['slashCommand']>;
}
const registerCommandsOnGuild = async ({rest, applicationId, guildId, commands}: RegisterCommandsOnGuildOptions) => {
await rest.put(
Routes.applicationGuildCommands(applicationId, guildId),
{body: commands.map(command => command.toJSON())},
);
};
export default registerCommandsOnGuild;

View file

@ -1,53 +0,0 @@
import {ApplicationCommandPermissionData, Guild} from 'discord.js';
import {prisma} from './db.js';
const COMMANDS_TO_LIMIT_TO_GUILD_OWNER = ['config'];
const updatePermissionsForGuild = async (guild: Guild) => {
const settings = await prisma.setting.findUnique({
where: {
guildId: guild.id,
},
});
if (!settings) {
throw new Error('could not find settings for guild');
}
const permissions: ApplicationCommandPermissionData[] = [
{
id: guild.ownerId,
type: 'USER',
permission: true,
},
{
id: guild.roles.everyone.id,
type: 'ROLE',
permission: false,
},
];
if (settings.invitedByUserId) {
permissions.push({
id: settings.invitedByUserId,
type: 'USER',
permission: true,
});
}
const commands = await guild.commands.fetch();
await guild.commands.permissions.set({fullPermissions: commands.map(command => ({
id: command.id,
permissions: COMMANDS_TO_LIMIT_TO_GUILD_OWNER.includes(command.name) ? permissions : [
...permissions,
...(settings.roleId ? [{
id: settings.roleId,
type: 'ROLE' as const,
permission: true,
}] : []),
],
}))});
};
export default updatePermissionsForGuild;