Skip to content

Commit

Permalink
Update to new discord username system
Browse files Browse the repository at this point in the history
  • Loading branch information
JulianVennen committed Aug 1, 2023
1 parent fe02986 commit 863016d
Show file tree
Hide file tree
Showing 33 changed files with 217 additions and 265 deletions.
266 changes: 101 additions & 165 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
"@googleapis/youtube": "^8.0.2",
"diff": "^5.1.0",
"discord-api-types": "^0.37.37",
"discord.js": "^14.9.0",
"discord.js": "^14.12.1",
"fuse.js": "^6.6.2",
"got": "^12.6.0",
"mysql2": "^3.2.0",
Expand Down
3 changes: 2 additions & 1 deletion src/commands/guild/GuildInfoCommand.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ export default class GuildInfoCommand extends Command {
.setColor(colors.RED)
.setThumbnail(guild.iconURL({size: 2048}))
.addPairIf(guild.description, 'Description', guild.description)
.addPair('Owner', `${userMention(owner.id)} (${owner.user.tag})`)
.addPair('Owner', userMention(owner.id))
.addPair('Owner ID', owner.id)
.addPair('Created', time(guild.createdAt, TimestampStyles.LongDateTime))
.addPair('Guild ID', guild.id)
.newLine()
Expand Down
39 changes: 17 additions & 22 deletions src/commands/guild/IDCommand.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,29 +14,21 @@ export default class IDCommand extends Command {

buildOptions(builder) {
builder.addStringOption(option => option
.setName('username')
.setDescription('(partial) username to search for')
.setName('query')
.setDescription('Username to search for (you can also provide a discrim for legacy users using #)')
.setRequired(true)
.setMinLength(2)
.setMaxLength(32));
builder.addIntegerOption(option => option
.setName('discriminator')
.setDescription('Full discriminator to search for')
.setRequired(false)
.setMinValue(1)
.setMaxValue(9999));
.setMaxLength(37));
return super.buildOptions(builder);
}

async execute(interaction) {
const name = interaction.options.getString('username', true),
discrim = interaction.options.getInteger('discriminator'),
query = `${name}${discrim ? '#' + discrim : ''}`;
const query = interaction.options.getString('query', true);

await interaction.deferReply({ephemeral: true});

/** @type {Collection<import('discord.js').Snowflake, (import('discord.js').GuildMember|import('discord.js').GuildBan)>} */
const users = await interaction.guild.members.fetch({query: name});
const users = await interaction.guild.members.fetch({query});

if (users.size) {
await interaction.editReply(this.#generateResultEmbed(
Expand All @@ -46,7 +38,7 @@ export default class IDCommand extends Command {
));
}

const bans = await this.#fetchAndFilterBans(interaction, name, discrim?.toString?.());
const bans = await this.#fetchAndFilterBans(interaction, query);
if (!bans.size && !users.size) {
return await interaction.editReply(ErrorEmbed.message('No users found'));
}
Expand All @@ -70,7 +62,7 @@ export default class IDCommand extends Command {
}

for (const result of results) {
embed.addLine(`${escapeMarkdown(result.user.tag)}: ${result.user.id}`);
embed.addLine(`${escapeMarkdown(result.user.displayName)}: ${result.user.id}`);
}

const count = embed.getLineCount(), complete = count === results.length;
Expand All @@ -82,12 +74,11 @@ export default class IDCommand extends Command {
/**
* @param {import('discord.js').Interaction} interaction
* @param {string} user
* @param {string} discrim
* @return {Promise<Collection<import('discord.js').Snowflake, import('discord.js').GuildBan>>}
*/
async #fetchAndFilterBans(interaction, user, discrim) {
async #fetchAndFilterBans(interaction, user) {
return (await this.#fetchAllBans(interaction))
.filter(banInfo => this.#matches(banInfo.user, user, discrim));
.filter(banInfo => this.#matches(banInfo.user, user));
}

/**
Expand Down Expand Up @@ -120,13 +111,17 @@ export default class IDCommand extends Command {
/**
*
* @param {User} user
* @param {string} name
* @param {string} discriminator
* @param {string} query
* @returns {boolean}
* @private
*/
#matches(user, name, discriminator) {
return user.username.toLowerCase().includes(name.toLowerCase()) && (!discriminator || user.discriminator === discriminator);
#matches(user, query) {
let names = [
user.tag,
user.globalName,
].filter(name => name).map(name => name.toLowerCase());

return names.some(name => name.includes(query));
}

getDescription() {
Expand Down
2 changes: 1 addition & 1 deletion src/commands/moderation/CompletingModerationCommand.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export default class CompletingModerationCommand extends SubCommand {
]);

options.push({
name: `#${moderation.id} - ${moderation.action} ${user?.tag ?? 'unknown'} by ${moderator?.tag ?? 'unknown'}`,
name: `#${moderation.id} - ${moderation.action} ${user?.displayName ?? 'unknown'} by ${moderator?.displayName ?? 'unknown'}`,
value: moderation.id
});
}
Expand Down
2 changes: 1 addition & 1 deletion src/commands/moderation/ModerationClearCommand.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export default class ModerationClearCommand extends SubCommand {

const confirmation = new Confirmation({user: user.id}, timeAfter('15 minutes'));
await interaction.editReply(new ConfirmationEmbed('moderation:clear', await confirmation.save(), ButtonStyle.Danger)
.setDescription(`Delete ${moderationCount} Moderations for ${escapeMarkdown(user.tag)}`)
.setDescription(`Delete ${moderationCount} Moderations for ${escapeMarkdown(user.displayName)}?`)
.toMessage());
}

Expand Down
13 changes: 7 additions & 6 deletions src/commands/user/AvatarCommand.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ import {ALLOWED_SIZES, EmbedBuilder, escapeMarkdown} from 'discord.js';
import MemberWrapper from '../../discord/MemberWrapper.js';
import GuildWrapper from '../../discord/GuildWrapper.js';

/**
* @type {import('discord.js').ImageURLOptions}
*/
const IMAGE_OPTIONS = {
size: ALLOWED_SIZES.at(-1),
};
Expand Down Expand Up @@ -54,17 +57,15 @@ export default class AvatarCommand extends Command {
async buildMessage(user, guild, useServerProfile = true) {
let url = user.displayAvatarURL(IMAGE_OPTIONS);

if (guild && useServerProfile) {
const member = await (new MemberWrapper(user, new GuildWrapper(guild))).fetchMember();
if (member) {
url = member.displayAvatarURL(IMAGE_OPTIONS);
}
const member = new MemberWrapper(user, new GuildWrapper(guild));
if (guild && useServerProfile && await member.fetchMember()) {
url = member.member.displayAvatarURL(IMAGE_OPTIONS);
}

return {
embeds: [
new EmbedBuilder()
.setTitle(`Avatar of ${escapeMarkdown(user.tag)}`)
.setTitle(`Avatar of ${escapeMarkdown(user.displayName)}`)
.setImage(url),
],
ephemeral: true,
Expand Down
2 changes: 1 addition & 1 deletion src/commands/user/BanCommand.js
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ export default class BanCommand extends UserCommand {
}

await interaction.showModal(new ModalBuilder()
.setTitle(`Ban ${member.user.tag}`.substring(0, MODAL_TITLE_LIMIT))
.setTitle(`Ban ${await member.displayName()}`.substring(0, MODAL_TITLE_LIMIT))
.setCustomId(`ban:${member.user.id}`)
.addComponents(
/** @type {*} */
Expand Down
2 changes: 1 addition & 1 deletion src/commands/user/KickCommand.js
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ export default class KickCommand extends UserCommand {
}

await interaction.showModal(new ModalBuilder()
.setTitle(`Kick ${member.user.tag}`.substring(0, MODAL_TITLE_LIMIT))
.setTitle(`Kick ${await member.displayName()}`.substring(0, MODAL_TITLE_LIMIT))
.setCustomId(`kick:${member.user.id}`)
.addComponents(
/** @type {*} */
Expand Down
2 changes: 1 addition & 1 deletion src/commands/user/MuteCommand.js
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ export default class MuteCommand extends UserCommand {
}

await interaction.showModal(new ModalBuilder()
.setTitle(`Mute ${member.user.tag}`.substring(0, MODAL_TITLE_LIMIT))
.setTitle(`Mute ${await member.displayName()}`.substring(0, MODAL_TITLE_LIMIT))
.setCustomId(`mute:${member.user.id}`)
.addComponents(
/** @type {*} */
Expand Down
6 changes: 3 additions & 3 deletions src/commands/user/PardonCommand.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ export default class PardonCommand extends Command {
if (count === 0) {
await replyOrEdit(interaction, new EmbedWrapper()
.setDescription(inlineEmojiIfExists('pardon') +
`${bold(escapeMarkdown(member.user.tag))} has no strikes to pardon`)
`${bold(escapeMarkdown(await member.displayName))} has no strikes to pardon`)
.setColor(colors.RED)
.toMessage()
);
Expand All @@ -83,7 +83,7 @@ export default class PardonCommand extends Command {
await member.pardon(reason, moderator, count);
await replyOrEdit(interaction, new EmbedWrapper()
.setDescription(inlineEmojiIfExists('pardon') +
`${formatNumber(count, 'strike')} were pardoned for ${bold(escapeMarkdown(member.user.tag))}: ${reason}`)
`${formatNumber(count, 'strike')} were pardoned for ${bold(escapeMarkdown(await member.displayName))}: ${reason}`)
.setColor(colors.GREEN)
.toMessage()
);
Expand All @@ -104,7 +104,7 @@ export default class PardonCommand extends Command {
}

await interaction.showModal(new ModalBuilder()
.setTitle(`Pardon ${member.user.tag}`.substring(0, MODAL_TITLE_LIMIT))
.setTitle(`Pardon ${await member.displayName()}`.substring(0, MODAL_TITLE_LIMIT))
.setCustomId(`pardon:${member.user.id}`)
.addComponents(
/** @type {*} */
Expand Down
2 changes: 1 addition & 1 deletion src/commands/user/SoftBanCommand.js
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ export default class SoftBanCommand extends UserCommand {
}

await interaction.showModal(new ModalBuilder()
.setTitle(`Soft-ban ${member.user.tag}`.substring(0, MODAL_TITLE_LIMIT))
.setTitle(`Soft-ban ${await member.displayName()}`.substring(0, MODAL_TITLE_LIMIT))
.setCustomId(`soft-ban:${member.user.id}`)
.addComponents(
/** @type {*} */
Expand Down
4 changes: 2 additions & 2 deletions src/commands/user/StrikeCommand.js
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ export default class StrikeCommand extends UserCommand {
await member.strike(reason, interaction.user, count);
await replyOrEdit(interaction, new EmbedWrapper()
.setDescription(inlineEmojiIfExists('strike') +
`${bold(escapeMarkdown(member.user.tag))} has received ${formatNumber(count, 'strike')}: ${reason}`)
`${bold(escapeMarkdown(await member.displayName))} has received ${formatNumber(count, 'strike')}: ${reason}`)
.setColor(colors.RED)
.toMessage()
);
Expand Down Expand Up @@ -136,7 +136,7 @@ export default class StrikeCommand extends UserCommand {
}

await interaction.showModal(new ModalBuilder()
.setTitle(`Strike ${member.user.tag}`.substring(0, MODAL_TITLE_LIMIT))
.setTitle(`Strike ${await member.displayName()}`.substring(0, MODAL_TITLE_LIMIT))
.setCustomId(`strike:${member.user.id}`)
.addComponents(
/** @type {*} */
Expand Down
2 changes: 1 addition & 1 deletion src/commands/user/StrikePurgeCommand.js
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ export default class StrikePurgeCommand extends StrikeCommand {
}

await interaction.showModal(new ModalBuilder()
.setTitle(`Strike-purge ${member.user.tag}`.substring(0, MODAL_TITLE_LIMIT))
.setTitle(`Strike-purge ${await member.displayName()}`.substring(0, MODAL_TITLE_LIMIT))
.setCustomId(`strike-purge:${member.user.id}`)
.addComponents(
/** @type {*} */
Expand Down
2 changes: 1 addition & 1 deletion src/commands/user/UnbanCommand.js
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ export default class UnbanCommand extends Command {
}

await interaction.showModal(new ModalBuilder()
.setTitle(`Unban ${member.user.tag}`.substring(0, MODAL_TITLE_LIMIT))
.setTitle(`Unban ${await member.displayName()}`.substring(0, MODAL_TITLE_LIMIT))
.setCustomId(`unban:${member.user.id}`)
.addComponents(
/** @type {*} */
Expand Down
2 changes: 1 addition & 1 deletion src/commands/user/UnmuteCommand.js
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ export default class UnmuteCommand extends Command {
}

await interaction.showModal(new ModalBuilder()
.setTitle(`Unmute ${member.user.tag}`.substring(0, MODAL_TITLE_LIMIT))
.setTitle(`Unmute ${await member.displayName()}`.substring(0, MODAL_TITLE_LIMIT))
.setCustomId(`unmute:${member.user.id}`)
.addComponents(
/** @type {*} */
Expand Down
5 changes: 3 additions & 2 deletions src/commands/user/UserCommand.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,14 +84,15 @@ export default class UserCommand extends Command {
const confirmation = new Confirmation(data, Math.floor(Date.now() / 1000) + CONFIRMATION_DURATION);
const embed = new ConfirmationEmbed(this.getName(), await confirmation.save())
.setAuthor({
name: `${member.user.tag} has already been moderated in the last ${formatTime(MODERATION_WARN_DURATION)}.`,
name: `${await member.displayName()} has already been moderated in the last ${formatTime(MODERATION_WARN_DURATION)}.`,
iconURL: member.user.avatarURL()
});

for (const result of results.slice(-3)) {
const moderator = await new UserWrapper(result.moderator).fetchUser();
embed
.addPairIf(moderator, 'Moderator', moderator.tag)
.addPairIf(moderator, 'Moderator', moderator.displayName)
.addPairIf(moderator, 'Moderator ID', moderator.id)
.addPair('Type', toTitleCase(result.action))
.addPair('Timestamp', time(result.created, TimestampStyles.ShortTime))
.addPairIf(result.expireTime, 'Duration', formatTime(result.getDuration()))
Expand Down
2 changes: 1 addition & 1 deletion src/commands/user/UserInfoCommand.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export default class UserInfoCommand extends Command {
async generateUserMessage(user, interaction) {
const memberWrapper = new MemberWrapper(user, new GuildWrapper(interaction.guild));
const member = await memberWrapper.fetchMember();
const embed = new UserEmbed(user)
const embed = new UserEmbed(member ?? user)
.setColor(colors.GREEN)
.addPair(inlineEmojiIfExists('userId') + 'Discord ID', user.id)
.addPair(inlineEmojiIfExists('userCreated') + 'Created', time(user.createdAt, TimestampStyles.LongDate));
Expand Down
8 changes: 6 additions & 2 deletions src/database/Moderation.js
Original file line number Diff line number Diff line change
Expand Up @@ -236,17 +236,21 @@ export default class Moderation {
*/
async log(total = null) {
const user = await this.getUser();
const moderator = await this.getModerator();

return (await this.getGuildWrapper()).log({
embeds: [
new KeyValueEmbed()
.setColor(resolveColor(this.action))
.setAuthor({
name: `Case ${this.id} | ${toTitleCase(this.action)} | ${user.tag}`,
name: `Case ${this.id} | ${toTitleCase(this.action)} | ${user.displayName}`,
iconURL: user.avatarURL()
})
.setFooter({text: user.id})
.addPair('User', userMention(user.id))
.addPair('Moderator', userMention((await this.getModerator()).id))
.addPair('User ID', user.id)
.addPair('Moderator', userMention(moderator.id))
.addPair('Moderator ID', moderator.id)
.addPairIf(this.expireTime, 'Duration', formatTime(this.expireTime - this.created))
.addPairIf(this.value, 'Amount', this.value)
.addPairIf(total, 'Total Strikes', total)
Expand Down
21 changes: 15 additions & 6 deletions src/discord/MemberWrapper.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,15 @@ export default class MemberWrapper {
return this.member;
}

/**
* get the display name of this member
* @return {Promise<string>}
*/
async displayName() {
if (!this.member) await this.fetchMember();
return this.member?.displayName ?? this.user.displayName;
}

/**
* get all moderations for this member
* @return {Promise<Moderation[]>}
Expand Down Expand Up @@ -357,7 +366,7 @@ export default class MemberWrapper {

await this.dmPunishedUser('banned', reason, duration, 'from');
await this.guild.guild.members.ban(this.user.id, {
reason: this._shortenReason(`${moderator.tag} ${duration ? `(${formatTime(duration)}) ` : ''}| ${reason}`),
reason: this._shortenReason(reason),
deleteMessageSeconds,
});
await (await this.createModeration('ban', reason, duration, moderator.id)).log();
Expand All @@ -372,7 +381,7 @@ export default class MemberWrapper {
async unban(reason, moderator){
await this.disableActiveModerations('ban');
try {
await this.guild.guild.members.unban(this.user, this._shortenReason(`${moderator.tag} | ${reason}`));
await this.guild.guild.members.unban(this.user, this._shortenReason(reason));
}
catch (e) {
if (e.code !== RESTJSONErrorCodes.UnknownBan) {
Expand All @@ -398,7 +407,7 @@ export default class MemberWrapper {
await this.dmPunishedUser('softbanned', reason, null, 'from');
await this.guild.guild.members.ban(this.user.id, {
deleteMessageSeconds,
reason: this._shortenReason(`${moderator.tag} | ${reason}`)
reason: this._shortenReason(reason)
});
await this.guild.guild.members.unban(this.user.id, 'softban');
await (await this.createModeration('softban', reason, null, moderator.id)).log();
Expand All @@ -413,7 +422,7 @@ export default class MemberWrapper {
async kick(reason, moderator){
await this.dmPunishedUser('kicked', reason, null, 'from');
if (!this.member && await this.fetchMember() === null) return;
await this.member.kick(this._shortenReason(`${moderator.tag} | ${reason}`));
await this.member.kick(this._shortenReason(reason));
await (await this.createModeration('kick', reason, null, moderator.id)).log();
}

Expand All @@ -436,7 +445,7 @@ export default class MemberWrapper {
await this.dmPunishedUser('muted', reason, duration, 'in');
if (!this.member) await this.fetchMember();
if (this.member) {
const shortedReason = this._shortenReason(`${moderator.tag} ${duration ? `(${formatTime(duration)}) ` : ''}| ${reason}`);
const shortedReason = this._shortenReason(reason);
if (timeout) {
await this.member.timeout(duration*1000, shortedReason);
} else {
Expand All @@ -457,7 +466,7 @@ export default class MemberWrapper {
if (this.member) {
const mutedRole = await this.getMutedRole();
if (mutedRole && this.member.roles.cache.has(mutedRole.id)) {
await this.member.roles.remove(mutedRole, this._shortenReason(`${moderator.tag} | ${reason}`));
await this.member.roles.remove(mutedRole, this._shortenReason(reason));
}
await this.member.timeout(null);
}
Expand Down
4 changes: 2 additions & 2 deletions src/embeds/MessageDeleteEmbed.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ export default class MessageDeleteEmbed extends EmbedWrapper {
}
else {
this.setAuthor({
name: `Message by ${escapeMarkdown(message.author.tag)} was deleted in #${message.channel.name}`,
iconURL: message.author.avatarURL()
name: `Message by ${escapeMarkdown(message.member.displayName)} was deleted in #${message.channel.name}`,
iconURL: message.member.avatarURL()
}).setFooter({text:
`Message ID: ${message.id}\n` +
`Channel ID: ${message.channel.id}\n` +
Expand Down
Loading

0 comments on commit 863016d

Please sign in to comment.