Skip to content

Commit

Permalink
fix: remove old non-webhooks network code
Browse files Browse the repository at this point in the history
  • Loading branch information
dev-737 committed Jun 25, 2023
1 parent 44d79d1 commit 6df3928
Show file tree
Hide file tree
Showing 5 changed files with 71 additions and 124 deletions.
12 changes: 10 additions & 2 deletions src/Commands/Network/deleteMsg.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,19 @@ export default {
include: { hub: true },
});

if (!messageInDb) return interaction.reply({ content: 'Unknown message.', ephemeral: true });
if (!messageInDb) {
return interaction.reply({
content: 'Unknown Message. If it has been sent in the past minute, please wait few more seconds and try again.',
ephemeral: true,
});
}

const interchatStaff = checkIfStaff(interaction.user.id);
if (!messageInDb.hub?.moderators.find((m) => m.userId === interaction.user.id) && !interchatStaff && interaction.user.id !== messageInDb.authorId) {
return interaction.reply({ content: `${emoji.no} You are not the author of this message.`, ephemeral: true });
return interaction.reply({
content: `${emoji.no} You are not the author of this message.`,
ephemeral: true,
});
}

await interaction.reply({
Expand Down
35 changes: 18 additions & 17 deletions src/Commands/Network/editMsg.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { ContextMenuCommandBuilder, MessageContextMenuCommandInteraction, Applic
import { networkMsgUpdate } from '../../Scripts/networkLogs/msgUpdate';
import { checkIfStaff, getDb, getGuildName, topgg } from '../../Utils/functions/utils';
import wordFiler from '../../Utils/functions/wordFilter';
import logger from '../../Utils/logger';
import { captureException } from '@sentry/node';

export default {
description: 'Edit a message that was sent in the network.',
Expand All @@ -11,10 +11,8 @@ export default {
.setType(ApplicationCommandType.Message),
async execute(interaction: MessageContextMenuCommandInteraction) {
const target = interaction.targetMessage;
const hasVoted = await topgg.hasVoted(interaction.user.id);
const isStaff = checkIfStaff(interaction.user.id);

if (!hasVoted && !isStaff) {
if (!await topgg.hasVoted(interaction.user.id) && !checkIfStaff(interaction.user.id)) {
await interaction.reply({
content: `${interaction.client.emotes.normal.no} You must [vote](<https://top.gg/bot/${interaction.client.user.id}/vote>) to use this command.`,
ephemeral: true,
Expand All @@ -40,8 +38,6 @@ export default {
return;
}

const placeholder = target.content || target.embeds[0]?.description;

const modal = new ModalBuilder()
.setCustomId(interaction.id)
.setTitle('Edit Message')
Expand All @@ -52,15 +48,15 @@ export default {
.setCustomId('newMessage')
.setStyle(TextInputStyle.Paragraph)
.setLabel('Please enter your new message.')
.setValue(`${placeholder}`)
.setValue(`${target.content || target.embeds[0]?.description}`)
.setMaxLength(950),
),
);

await interaction.showModal(modal);

interaction.awaitModalSubmit({ filter: (i) => i.user.id === interaction.user.id && i.customId === modal.data.custom_id, time: 30_000 })
.then(i => {
.then(async i => {
// get the input from user
const newMessage = i.fields.getTextInputValue('newMessage');
const censoredNewMessage = wordFiler.censor(newMessage);
Expand All @@ -81,10 +77,12 @@ export default {
content: `${interaction.client.emotes.normal.yes} Message Edited. Please give a few seconds for it to reflect in all connections.`,
ephemeral: true,
});
const channelSettingsArr = await db.connectedList.findMany({
where: { channelId: { in: messageInDb.channelAndMessageIds.map(c => c.channelId) } },
});

// loop through all the channels in the network and edit the message
messageInDb.channelAndMessageIds.forEach(async obj => {
const channelSettings = await db.connectedList.findFirst({ where: { channelId: obj.channelId } });
const channelSettings = channelSettingsArr.find(c => c.channelId === obj.channelId);

if (channelSettings) {
const webhook = new WebhookClient({ id: channelSettings.webhook.id, token: channelSettings.webhook.token });
Expand All @@ -97,14 +95,17 @@ export default {
}
});

const newMessageObject = {
id: target.id,
content: newMessage,
timestamp: target.editedAt ?? target.createdAt,
};

interaction.inCachedGuild() ? networkMsgUpdate(interaction.member, target, newMessageObject) : null;
interaction.inCachedGuild()
? networkMsgUpdate(interaction.member, target, {
id: target.id, content: newMessage,
})
: null;

}).catch((reason) => !reason.message.includes('reason: time') ? logger.error(reason) : null);
}).catch((reason) => {
!reason.message.includes('reason: time')
? captureException(reason, { user: { id: interaction.user.id, username: interaction.user.username }, extra: { command: 'Edit Message' } })
: null;
});
},
};
103 changes: 25 additions & 78 deletions src/Events/messageCreate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import checks from '../Scripts/message/checks';
import messageContentModifiers from '../Scripts/message/messageContentModifiers';
import messageFormats from '../Scripts/message/messageFormatting';
import cleanup from '../Scripts/message/cleanup';
import { ActionRowBuilder, APIMessage, ButtonBuilder, ButtonStyle, ChannelType, EmbedBuilder, Message, User, WebhookClient } from 'discord.js';
import { getDb, colors, constants } from '../Utils/functions/utils';
import { ActionRowBuilder, APIMessage, ButtonBuilder, ButtonStyle, EmbedBuilder, Message, User, WebhookClient } from 'discord.js';
import { getDb, colors } from '../Utils/functions/utils';
import { censor } from '../Utils/functions/wordFilter';
import { messageData } from '@prisma/client';

Expand All @@ -16,11 +16,6 @@ export interface NetworkWebhookSendResult {
webhookId: string;
}

export interface NetworkSendResult {
message?: Message | null
channelId: string;
}

export default {
name: 'messageCreate',
async execute(message: NetworkMessage) {
Expand Down Expand Up @@ -88,80 +83,32 @@ export default {
const censoredEmbed = new EmbedBuilder(embed.data).setDescription(message.censored_content || null);
// await addBadges.execute(message, db, embed, censoredEmbed);

// send the message to all connected channels in apropriate format (webhook/compact/normal)
const hubConnections = await db.connectedList.findMany({ where: { hubId: channelInDb.hubId, connected: true } });
const messageResults: Promise<NetworkWebhookSendResult | NetworkSendResult>[] = [];
hubConnections?.forEach((connection) => {
const result = (async () => {
const channelToSend = message.client.channels.cache.get(connection.channelId);
if (!channelToSend || !channelToSend.isTextBased()) return { channelId: connection.channelId } as NetworkSendResult;

const reply = replyInDb?.channelAndMessageIds.find((msg) => msg.channelId === connection.channelId);
const replyButton = reply
? new ActionRowBuilder<ButtonBuilder>().addComponents(new ButtonBuilder()
.setLabel(
(referredAuthor && referredAuthor.tag.length >= 80
? '@' + referredAuthor.tag.slice(0, 76) + '...'
: '@' + referredAuthor?.tag) || 'Jump',
)
.setStyle(ButtonStyle.Link)
.setEmoji(message.client.emotes.normal.reply)
.setURL(`https://discord.com/channels/${connection.serverId}/${reply.channelId}/${reply.messageId}`))
: null;

if (connection?.webhook) {
const webhook = new WebhookClient({ id: `${connection?.webhook?.id}`, token: `${connection?.webhook?.token}` });
const webhookMessage = messageFormats.createWebhookOptions(message, connection, replyButton,
{ censored: censoredEmbed, normal: embed, reply: referedMsgEmbed }, attachment);
const webhookSendRes = await webhook.send(webhookMessage).catch(() => null);
return { webhookId: webhook.id, message: webhookSendRes } as NetworkWebhookSendResult;
}

const guild = message.client.guilds.cache.get(connection.serverId);
const channel = guild?.channels.cache.get(connection.channelId);

if (channel?.type === ChannelType.GuildText) {
try {
channel.send(
message.client.emotes.normal.loading + 'All Networks must now use webhooks for faster performance and to avoid frequent rate limits. Attempting to create webhook...',
).catch(() => null);

const hook = await channel.createWebhook({
name: `${message.author.username} Network`,
avatar: message.client.user.avatarURL(),
reason: 'All networks must use webhooks now.',
});

if (hook.token) {
await db.connectedList.update({
where: { id: connection.id },
data: { webhook: { set: { id: hook.id, token: hook.token, url: hook.url } } },
});
}

}
catch {
channel.send(
message.client.emotes.normal.no + 'Failed to create webhook. Please make sure I have the `Manage Webhooks` permission in this channel and reconnect to the network (`/network manage`).',
).catch(() => null);
const logChannel = message.client.channels.cache.get(constants.channel.networklogs) as any;
logChannel?.send(`Failed to create webhook in \`#${channel.name}\` (${channel.id}) in ${guild} (${guild?.id})`).catch(() => null);
await db.connectedList.update({ where: { id: connection.id }, data: { connected: false } });
}
}

const normalOptions = messageFormats.createEmbedOptions(attachment, replyButton, connection,
{ censored: censoredEmbed, normal: embed });
const sendResult = await channelToSend.send(normalOptions).catch(() => null);
return { channelId: channelToSend.id, message: sendResult } as NetworkSendResult;
})();

messageResults.push(result);

// send the message to all connected channels in apropriate format (compact/profanity filter)
const messageResults = hubConnections?.map(async (connection) => {
const reply = replyInDb?.channelAndMessageIds.find((msg) => msg.channelId === connection.channelId);
const replyButton = reply
? new ActionRowBuilder<ButtonBuilder>().addComponents(new ButtonBuilder()
.setLabel(
(referredAuthor && referredAuthor.tag.length >= 80
? '@' + referredAuthor.tag.slice(0, 76) + '...'
: '@' + referredAuthor?.tag) || 'Jump',
)
.setStyle(ButtonStyle.Link)
.setEmoji(message.client.emotes.normal.reply)
.setURL(`https://discord.com/channels/${connection.serverId}/${reply.channelId}/${reply.messageId}`))
: null;

const webhook = new WebhookClient({ id: `${connection?.webhook.id}`, token: `${connection?.webhook.token}` });
const webhookMessage = messageFormats.createWebhookOptions(message, connection, replyButton,
{ censored: censoredEmbed, normal: embed, reply: referedMsgEmbed }, attachment);
const webhookSendRes = await webhook.send(webhookMessage).catch(() => null);
return { webhookId: webhook.id, message: webhookSendRes } as NetworkWebhookSendResult;
});

// disconnect unknown channels & insert message into messageData collection for future use
const resolvedMessages = await Promise.all(messageResults);
cleanup.execute(message, resolvedMessages, channelInDb.hubId);
message.delete().catch(() => null);
cleanup.execute(message, await Promise.all(messageResults), channelInDb.hubId);
}
},
};
Expand Down
42 changes: 17 additions & 25 deletions src/Scripts/message/cleanup.ts
Original file line number Diff line number Diff line change
@@ -1,38 +1,29 @@
import { Message } from 'discord.js';
import { NetworkSendResult, NetworkWebhookSendResult } from '../../Events/messageCreate';
import { NetworkWebhookSendResult } from '../../Events/messageCreate';
import { getDb } from '../../Utils/functions/utils';

export default {
/**
* Disconnects connections if an errored occured while sending the message to it.
* Otherwise, inserts messages into `messageData` collection for future use.
*/
async execute(
message: Message,
channelAndMessageIds: (NetworkWebhookSendResult | NetworkSendResult)[],
channelAndMessageIds: NetworkWebhookSendResult[],
hubId: string | null,
) {
message.delete().catch(() => null);
// All message data is stored in the database, so we can delete the message from the network later
const messageDataObj: { channelId: string, messageId: string }[] = [];
const invalidChannelIds: string[] = [];
const invalidWebhookIds: string[] = [];

channelAndMessageIds.forEach((result) => {
if (result.message === undefined && 'webhookId' in result) invalidWebhookIds.push(result.webhookId);
else if (result.message === undefined && 'channelId' in result) invalidChannelIds.push(result.channelId);

if (result.message === undefined) invalidWebhookIds.push(result.webhookId);
if (result.message) {
// normal message
if ('channelId' in result) {
messageDataObj.push({
channelId: result.channelId,
messageId: result.message.id,
});
}
// webhook message (channel_id instead of channelId)
else if (result.message.channel_id) {
messageDataObj.push({
channelId: result.message.channel_id,
messageId: result.message.id,
});
}
messageDataObj.push({
channelId: result.message.channel_id,
messageId: result.message.id,
});
}
});

Expand All @@ -51,11 +42,12 @@ export default {
});
}


// disconnect invalid webhooks/channels from the database
await db.connectedList.updateMany({
where: { OR: [{ channelId: { in: invalidChannelIds } }, { webhook: { is: { id: { in: invalidWebhookIds } } } }] },
data: { connected: false },
});
if (invalidWebhookIds.length > 0) {
await db.connectedList.updateMany({
where: { webhook: { is: { id: { in: invalidWebhookIds } } } },
data: { connected: false },
});
}
},
};
3 changes: 1 addition & 2 deletions src/Scripts/networkLogs/msgUpdate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import { constants, getDb } from '../../Utils/functions/utils';
interface messageOptions {
id: string;
content: string;
timestamp: Date;
}

export async function networkMsgUpdate(member: GuildMember, oldMessage: Message, newMessage: messageOptions) {
Expand All @@ -27,7 +26,7 @@ export async function networkMsgUpdate(member: GuildMember, oldMessage: Message,
${emoji.normal.dotYellow} **User:** ${member.user.tag} (${member.id})
${emoji.normal.dotYellow} **Server:** ${member.guild.name} (${member.guild.id})
${emoji.normal.dotYellow} **Attachments:** ${attachmentLink ? `[Click to view](${attachmentLink})` : 'None.'}
${emoji.normal.dotYellow} **Created At:** <t:${Math.round(newMessage.timestamp.getTime() / 1000)}:R>
${emoji.normal.dotYellow} **Created At:** <t:${Math.round(new Date().getTime() / 1000)}:R>
[Jump To Message](https://discord.com/channels/${constants.guilds.cbhq}/${cbhqJumpMsg?.channelId}/${cbhqJumpMsg?.messageId})`)
.addFields(
{ name: 'Before', value: oldMessage.content || oldMessage.embeds[0]?.description || 'None.' },
Expand Down

0 comments on commit 6df3928

Please sign in to comment.