Skip to content

Commit

Permalink
fix: move createConnection to network utils
Browse files Browse the repository at this point in the history
  • Loading branch information
dev-737 committed Oct 4, 2023
1 parent f2a852b commit 71b2ade
Show file tree
Hide file tree
Showing 5 changed files with 70 additions and 89 deletions.
6 changes: 1 addition & 5 deletions src/Commands/Apps/deleteMsg.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { ContextMenuCommandBuilder, ApplicationCommandType, MessageContextMenuCommandInteraction } from 'discord.js';
import { getDb, checkIfStaff } from '../../Utils/utils';
import { networkMessageDelete } from '../../Scripts/networkLogs/msgDelete';
import { captureException } from '@sentry/node';
import emojis from '../../Utils/JSON/emoji.json';


Expand Down Expand Up @@ -45,10 +44,7 @@ export default {
// finally, delete the message
return await webhook?.deleteMessage(element.messageId, channel.isThread() ? channel.id : undefined)
.then(() => true)
.catch((e) => {
captureException(e, { user: { username: interaction.user.username, extra: { action: 'networkMessageDelete ' } } });
return false;
});
.catch(() => false);
});

const resultsArray = await Promise.all(results);
Expand Down
4 changes: 2 additions & 2 deletions src/Scripts/hub/browse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ import { calculateAverageRating, createHubListingsEmbed, getDb } from '../../Uti
import { paginate } from '../../Utils/paginator';
import { hubs } from '@prisma/client';
import { captureException } from '@sentry/node';
import createConnection from '../network/createConnection';
import logger from '../../Utils/logger';
import emojis from '../../Utils/JSON/emoji.json';
import onboarding from '../network/onboarding';
import { createConnection } from '../../Utils/network';

export default {
async execute(interaction: ChatInputCommandInteraction) {
Expand Down Expand Up @@ -275,7 +275,7 @@ export default {
// if user cancelled onboarding or didn't click any buttons, stop here
if (!onboardingStatus) return interaction.deleteReply().catch(() => null);

createConnection.execute(response, hubDetails, channel).then((success) => {
createConnection(response.guild, hubDetails, channel).then((success) => {
if (success) {
response.editReply({
content: `Successfully joined hub ${hubDetails.name} from ${channel}! Use \`/network manage\` to manage your connection. And \`/hub leave\` to leave the hub.`,
Expand Down
15 changes: 7 additions & 8 deletions src/Scripts/hub/join.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { ChatInputCommandInteraction, ChannelType } from 'discord.js';
import { getDb } from '../../Utils/utils';
import createConnection from '../network/createConnection';
import displaySettings from '../network/displaySettings';
import emojis from '../../Utils/JSON/emoji.json';
import onboarding from '../network/onboarding';
import { fetchServerBlacklist, fetchUserBlacklist } from '../../Utils/blacklist';
import { createConnection } from '../../Utils/network';

export default {
async execute(interaction: ChatInputCommandInteraction) {
Expand Down Expand Up @@ -107,15 +107,14 @@ export default {

if (!await onboarding.execute(interaction, hubExists.name, channel.id)) return interaction.deleteReply().catch(() => null);

const created = await createConnection.execute(interaction, hubExists, channel).catch(() => null);
if (!created) {
return await interaction.reply({
const created = await createConnection(interaction.guild, hubExists, channel).catch(() => {
interaction.reply({
content: `${emojis.normal.no} An error occured while connecting this channel to the hub! Please make sure I have the [required permissions](https://discord-interchat.github.io/docs/#adding-interchat-to-your-server) and try again.`,
ephemeral: true,
});
}
else {
await displaySettings.execute(interaction, created.channelId);
}
return null;
});

if (created) await displaySettings.execute(interaction, created.channelId);
},
};
71 changes: 0 additions & 71 deletions src/Scripts/network/createConnection.ts

This file was deleted.

63 changes: 60 additions & 3 deletions src/Utils/network.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { connectedList } from '@prisma/client';
import { connectedList, hubs } from '@prisma/client';
import { getDb } from './utils';
import { WebhookClient, WebhookMessageCreateOptions } from 'discord.js';
import { ChannelType, Guild, TextChannel, ThreadChannel, WebhookClient, WebhookMessageCreateOptions } from 'discord.js';
import { stripIndents } from 'common-tags';
import emojis from './JSON/emoji.json';

const { connectedList } = getDb();

Expand Down Expand Up @@ -45,4 +47,59 @@ export async function sendInNetwork(message: WebhookMessageCreateOptions, hubId:
});
}

export default { reconnect, disconnect, sendInNetwork };
export async function createConnection(guild: Guild, hub: hubs, networkChannel: TextChannel | ThreadChannel) {
const webhook = await getOrCreateWebhook(networkChannel, guild.client.user?.displayAvatarURL());
if (!webhook) return;

const emoji = emojis.normal;
const createdConnection = await connectedList.create({
data: {
channelId: networkChannel.id,
parentId: networkChannel.isThread() ? networkChannel.id : undefined,
serverId: networkChannel.guild.id,
webhookURL: webhook.url,
connected: true,
profFilter: true,
compact: false,
hub: { connect: { id: hub.id } },
},
});


const numOfConnections = await connectedList.count({ where: { hubId: hub.id } });
await networkChannel?.send(
`This channel has been connected with **${hub.name}**. ${
numOfConnections > 1
? `You are currently with ${numOfConnections - 1} other servers, Enjoy! ${emoji.clipart}`
: `It seems no one else is there currently... *cricket noises* ${emoji.clipart}`
}`,
);

sendInNetwork({
content: stripIndents`
A new server has joined us! ${emoji.clipart}
**Server Name:** __${guild.name}__
**Member Count:** __${guild.memberCount}__
` }, hub.id);

// return the created connection so we can use it in the next step
return createdConnection;
}

export async function getOrCreateWebhook(channel: TextChannel | ThreadChannel, avatar: string | null) {
const channelOrParent = channel.type === ChannelType.GuildText ? channel : channel.parent;
const webhooks = await channelOrParent?.fetchWebhooks();
const existingWebhook = webhooks?.find((w) => w.owner?.id === channel.client.user?.id);

if (existingWebhook) {
return existingWebhook;
}

return await channelOrParent?.createWebhook({
name: 'InterChat Network',
avatar,
});
}

export default { reconnect, disconnect, sendInNetwork, createConnection, getOrCreateWebhook };

0 comments on commit 71b2ade

Please sign in to comment.