diff --git a/src/commandDetails/admin/ban.ts b/src/commandDetails/admin/ban.ts index 8a44aaf3..bd609799 100644 --- a/src/commandDetails/admin/ban.ts +++ b/src/commandDetails/admin/ban.ts @@ -8,6 +8,7 @@ import { } from '../../codeyCommand'; import { banUser } from '../../components/admin'; import { vars } from '../../config'; +import { pluralize } from '../../utils/pluralize'; // Ban a user const banExecuteCommand: SapphireMessageExecuteType = async (client, messageFromUser, args) => { @@ -31,13 +32,11 @@ const banExecuteCommand: SapphireMessageExecuteType = async (client, messageFrom ); } const days = args['days']; - // Get the GuildMember object corresponding to the user in the guild - // This is needed because we can only ban GuildMembers, not Users + // get Guild object corresponding to server const guild = await client.guilds.fetch(vars.TARGET_GUILD_ID); - const memberInGuild = await guild.members.fetch({ user }); - if (await banUser(memberInGuild, reason, days)) { + if (await banUser(guild, user, reason, days)) { return `Successfully banned user ${user.tag} (id: ${user.id}) ${ - days ? `and deleted their messages in the past ${days} days ` : `` + days ? `and deleted their messages in the past ${days} ${pluralize('day', days)} ` : `` }for the following reason: ${reason}`; } else { throw new CodeyUserError( diff --git a/src/components/admin.ts b/src/components/admin.ts index d003633f..f54f43d2 100644 --- a/src/components/admin.ts +++ b/src/components/admin.ts @@ -1,4 +1,4 @@ -import { GuildMember } from 'discord.js'; +import { Guild, User } from 'discord.js'; import { vars } from '../config'; import { logger } from '../logger/default'; import { pluralize } from '../utils/pluralize'; @@ -19,16 +19,28 @@ a reason why you think you should be unbanned. `; /* Ban a user, returns whether ban was successful */ +// Bans user from guild even if they are not in server +// makeBanMessage is only sent to User if they are in server (in Discord, you cannot send direct messages to users who are not in any mutual servers) export const banUser = async ( - member: GuildMember, + guild: Guild, + user: User, reason: string, days?: number, ): Promise => { let isSuccessful = false; try { - const user = member.user; - await user.send(makeBanMessage(reason, days)); - await member.ban({ reason, deleteMessageDays: days }); + try { + await user.send(makeBanMessage(reason, days)); + } catch (err) { + logger.error({ + event: "Can't send message to user not in server", + error: (err as Error).toString(), + }); + } + await guild.members.ban(user, { + reason: reason, + deleteMessageSeconds: days == null ? 0 : days * 86400, + }); isSuccessful = true; } catch (err) { logger.error({