Skip to content

Commit

Permalink
Handle Discord username changes and ignore unavailable guilds
Browse files Browse the repository at this point in the history
  • Loading branch information
SunburntRock89 committed Jun 9, 2023
1 parent a78aa2e commit 0c0af0d
Show file tree
Hide file tree
Showing 15 changed files with 42 additions and 19 deletions.
3 changes: 2 additions & 1 deletion src/commands/standard/mention remove.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { ActionRowBuilder, StringSelectMenuBuilder, StringSelectMenuOptionBuilder } from "discord.js";
import Command from "../../internals/commandProcessor";
import { getUsername } from "../../internals/utils";

export default class MentionRemove extends Command {
async run(): Promise<void> {
Expand All @@ -22,7 +23,7 @@ export default class MentionRemove extends Command {
const user = await this.client.getUser(i).catch(() => null);
selectMenu.options.push(
new StringSelectMenuOptionBuilder()
.setLabel(`${user?.tag || i}`)
.setLabel(`${user ? getUsername(user) : i}`)
.setValue(i)
.setDescription(i),
);
Expand Down
3 changes: 2 additions & 1 deletion src/commands/standard/mention toggle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ import Command from "../../internals/commandProcessor";

export default class MentionToggle extends Command {
async run(): Promise<void> {
const indexOfMention = this.number!.mentions.indexOf(this.interaction.user.id);
let indexOfMention = this.number!.mentions.indexOf(this.interaction.user.id);
if (indexOfMention === -1) indexOfMention = this.number!.mentions.indexOf(`<@${this.interaction.user.id}>`);

// If they're already being mentioned
if (indexOfMention > -1) {
Expand Down
11 changes: 7 additions & 4 deletions src/commands/standard/pay common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Accounts } from "@prisma/client";
import { ActionRowBuilder, ButtonBuilder, ButtonStyle, ComponentType, EmbedBuilder, User } from "discord.js";
import { PermissionLevel } from "../../interfaces/commandData";
import Command from "../../internals/commandProcessor";
import { formatBalance, upperFirst } from "../../internals/utils";
import { formatBalance, getUsername, upperFirst } from "../../internals/utils";

export default abstract class PayCommonFunctions extends Command {
async payUser(toPay: Accounts, user: User): Promise<void> {
Expand Down Expand Up @@ -42,16 +42,19 @@ export default abstract class PayCommonFunctions extends Command {
return;
}

const authorTag = this.userDisplayName;
const recipientTag = getUsername(user);

const embed = EmbedBuilder.from({
color: this.config.colors.info,
author: {
name: this.interaction.user.tag,
name: authorTag,
icon_url: this.interaction.user.displayAvatarURL(),
},

...this.t("confirmEmbedOptions"),
...this.t("embed", {
displayName: `${user.tag} (${user.id})`,
displayName: `${recipientTag} (${user.id})`,
preFeeToSend: totalCost,
fee: formatBalance(fee),
postFeeCost: formatBalance(totalReceived),
Expand Down Expand Up @@ -154,7 +157,7 @@ export default abstract class PayCommonFunctions extends Command {
});
embed.spliceFields(2, 1, {
name: this.t("sender"),
value: `${this.interaction.user.tag}`,
value: authorTag,
});

// Try to DM the user
Expand Down
5 changes: 3 additions & 2 deletions src/commands/standard/strikes.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { EmbedField } from "discord.js";
import { PermissionLevel } from "../../interfaces/commandData";
import Command from "../../internals/commandProcessor";
import { getUsername } from "../../internals/utils";

export default class Strikes extends Command {
async run() {
Expand Down Expand Up @@ -35,10 +36,10 @@ export default class Strikes extends Command {
const fields: EmbedField[] = [];

for (const strike of strikes) {
const staff = await this.client.users.fetch(strike.created.by).catch(() => null) || { tag: "Unknown#0000" };
const staff = await this.client.users.fetch(strike.created.by).catch(() => null);

fields.push({
name: `Strike \`${strike.id}\` by ${staff.tag}`,
name: `Strike \`${strike.id}\` by ${staff ? getUsername(staff) : `Unknown (${strike.created.by})`}`,
value: `• **Reason**: ${truncate(strike.reason, 800) || "No reason provided"}\n• **ID**: ${strike.id}`,
inline: false,
});
Expand Down
2 changes: 1 addition & 1 deletion src/commands/support/addcredit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export default class AddCredit extends Command {
description: `${addedOrRemoved} ${this.config.dtsEmoji} ${Math.abs(amountOfCredits)} ${creditsAdded ? "to" : "from"} <@${userID}> (${userID})`,
footer: {
icon_url: this.interaction.user.displayAvatarURL(),
text: `${this.interaction.user.tag} (${this.interaction.user.id})`,
text: `${this.userDisplayName} (${this.interaction.user.id})`,
},
}).setTimestamp(new Date());

Expand Down
5 changes: 3 additions & 2 deletions src/commands/support/cinfo.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { ActiveCalls, ArchivedCalls, Numbers } from "@prisma/client";
import { EmbedBuilder } from "discord.js";
import Command from "../../internals/commandProcessor";
import { getUsername } from "../../internals/utils";

type activeOrArchivedCallWithNumbers = (ActiveCalls | ArchivedCalls);

Expand Down Expand Up @@ -71,10 +72,10 @@ export default class CInfo extends Command {
value: [
`**Picked up**:`,
`- At: ${blockFormat(call.pickedUp?.at.toString() || "N/A")}`,
`- By: ${blockFormat(call.pickedUp ? `${pickedUpUser?.tag} (${pickedUpUser?.id})` : "N/A")}`,
`- By: ${blockFormat(call.pickedUp ? `${pickedUpUser ? getUsername(pickedUpUser) : "Unknown"} (${pickedUpUser?.id})` : "N/A")}`,
`**Ended**:`,
`- At: ${blockFormat(call.ended?.at.toString() || "N/A")}`,
`- By: ${blockFormat(call.ended ? `${endedUser?.tag} (${endedUser?.id})` : "N/A")}`,
`- By: ${blockFormat(call.ended ? `${endedUser ? getUsername(endedUser) : "Unknown"} (${endedUser?.id})` : "N/A")}`,
`**Random**: ${blockFormat(call.randomCall ? "Yes" : "No")}`,
// `Transferred by: ${blockFormat(call. ? "Yes" : "No")}`,
`**Started**:`,
Expand Down
2 changes: 1 addition & 1 deletion src/commands/support/deassign.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export default class Deassign extends Command {
embeds: [{
color: this.config.colors.success,
author: {
name: this.interaction.user.tag,
name: this.userDisplayName,
icon_url: this.interaction.user.displayAvatarURL(),
},
title: "R.I.P",
Expand Down
2 changes: 1 addition & 1 deletion src/commands/support/ninfo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ export default class NInfo extends Command {

numberOwner = await this.client.getUser(guild.ownerId);

guildDescription = `${guild.name}\n\`${guild.id}\`\nWhitelisted: ${number.guild?.whitelisted}`;
guildDescription = `${guild.name}\n\`${guild.id}\`\nWhitelisted: ${number.guild?.whitelisted ? "Yes" : "No"}`;
channelDescription = `#${(channel as GuildTextBasedChannel).name}\n\`${channel.id}\``;

let footerImage = this.client.user.displayAvatarURL();
Expand Down
2 changes: 1 addition & 1 deletion src/commands/support/reassign.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ export default class Deassign extends Command {
return;
}

const discordChannel = await this.client.getChannel(newChannel);
const discordChannel = await this.client.getChannel(newChannel).catch(() => null);
if (!discordChannel) {
this.interaction.editReply({
embeds: [this.client.errorEmbed("Couldn't find the new channel.")],
Expand Down
3 changes: 2 additions & 1 deletion src/commands/support/strike remove.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Strikes } from "@prisma/client";
import Command from "../../internals/commandProcessor";
import { getUsername } from "../../internals/utils";

export default class StrikeRemove extends Command {
async run(): Promise<void> {
Expand Down Expand Up @@ -34,7 +35,7 @@ export default class StrikeRemove extends Command {
embeds: [{
color: this.config.colors.success,
title: "✅ Strike removed",
description: `Strike removed from **${offender.user?.tag || offender.guild?.name || "Unknown Offender"}** (${strike.offender})`,
description: `Strike removed from **${(offender.user ? getUsername(offender.user) : null) || offender.guild?.name || "Unknown Offender"}** (${strike.offender})`,
footer: {
text: `They now have ${strikeCount} ${strikeCount > 1 ? "strikes" : "strike"}`,
},
Expand Down
3 changes: 2 additions & 1 deletion src/commands/support/uinfo.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { APIEmbed, User } from "discord.js";
import Command from "../../internals/commandProcessor";
import { getUsername } from "../../internals/utils";
export default class UInfo extends Command {
async run(): Promise<void> {
const toFind = this.interaction.options.getString("user", true);
Expand All @@ -16,7 +17,7 @@ export default class UInfo extends Command {
color: this.config.colors.info,
author: {
icon_url: user.displayAvatarURL(),
name: `${user.tag} (${user.id})`,
name: `${getUsername(user)} (${user.id})`,
},
footer: {
text: `Use /strikes for more information. Server management permissions indicated by red phone..`,
Expand Down
4 changes: 4 additions & 0 deletions src/events/guildDelete.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { Guild } from "discord.js";
import DTelClient from "../internals/client";
import { winston } from "../dtel";

export default async(client: DTelClient, guild: Guild): Promise<void> => {
if (!guild.available) {
winston.error(`Guild ${guild.name} (${guild.id}) is unavailable. Ignoring Guild Delete event.`);
}
client.log(`📤 Left guild \`${guild.name}\` (\`${guild.id}\`). Currently in \`${client.guilds.cache.size}\` servers on Shard ${process.env.SHARDS} and \`${await client.getGuildCount()}\` servers total.`);
};
4 changes: 2 additions & 2 deletions src/internals/callClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import config from "../config/config";
import { APIEmbed, APIMessage, ButtonStyle, RESTGetAPIChannelMessageResult } from "discord-api-types/v10";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import { parseNumber } from "./utils";
import { getUsername, parseNumber } from "./utils";
import { NumbersWithGuilds } from "../interfaces/numbersWithGuilds";
import { winston } from "../dtel";

Expand Down Expand Up @@ -478,7 +478,7 @@ export default class CallClient implements CallsWithNumbers {
async processContent(message: Message, sideToSendTo: ClientCallParticipant): Promise<MessageCreateOptions> {
const userPerms = await this.client.getPerms(message.author.id);

const toSend: MessageCreateOptions = { content: `**${message.author.tag}`, embeds: [] };
const toSend: MessageCreateOptions = { content: `**${getUsername(message.author)}`, embeds: [] };

const thisSide = this.getThisSideByChannel(message.channelId)!;
if (thisSide.vip?.hidden) toSend.content = `**Anonymous#${message.author.id.slice(-4)}`;
Expand Down
6 changes: 5 additions & 1 deletion src/internals/processor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import CommandDataInterface, { CommandType, PermissionLevel } from "../interface
import { Numbers, Accounts, Mailbox } from "@prisma/client";
import { db } from "../database/db";
import CallClient from "./callClient";
import { fetchNumber, formatShardNumber, getOrCreateAccount } from "./utils";
import { fetchNumber, formatShardNumber, getOrCreateAccount, getUsername } from "./utils";
import { getFixedT, TFunction } from "i18next";

export type ChannelBasedInteraction = CommandInteraction|MessageComponentInteraction|ModalSubmitInteraction;
Expand Down Expand Up @@ -156,5 +156,9 @@ abstract class Processor<T extends ChannelBasedInteraction> {
embeds: [this.client.errorEmbed("This command cannot be ran outside of the support server.")],
});
}

get userDisplayName() {
return getUsername(this.interaction.user);
}
}
export default Processor;
6 changes: 6 additions & 0 deletions src/internals/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import { Accounts, Numbers } from "@prisma/client";
import dayjs from "dayjs";
import { db } from "../database/db";
import { User } from "discord.js";

export const formatShardNumber = (shardNumber: number): string => shardNumber < 10 ? `0${shardNumber}` : shardNumber.toString();
export const formatBalance = (balance: number): string => {
Expand Down Expand Up @@ -75,3 +76,8 @@ export const fetchNumber = (input: string): Promise<Numbers | null> => {

export const formatDate = (date: Date) => dayjs(date).format("YYYY-MM-DD");
export const upperFirst = (text: string) => `${text[0].toUpperCase()}${text.slice(1, text.length)}`;

export const getUsername = (user: User) => {
if (user.discriminator == "0") return `${user.username}`;
return `${user.username}#${user.discriminator}}`;
};

0 comments on commit 0c0af0d

Please sign in to comment.