Skip to content

Commit

Permalink
fix(network): profanity uncensored in replies
Browse files Browse the repository at this point in the history
  • Loading branch information
dev-737 committed Oct 6, 2023
1 parent 71b2ade commit 224f588
Show file tree
Hide file tree
Showing 7 changed files with 72 additions and 55 deletions.
20 changes: 13 additions & 7 deletions src/Commands/Information/help.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { SlashCommandBuilder, ChatInputCommandInteraction, ActionRowBuilder, Interaction, StringSelectMenuBuilder, EmbedBuilder, APISelectMenuOption, ApplicationCommandType, ComponentType, Client, chatInputApplicationCommandMention, User } from 'discord.js';
import { SlashCommandBuilder, ChatInputCommandInteraction, ActionRowBuilder, Interaction, StringSelectMenuBuilder, EmbedBuilder, APISelectMenuOption, ApplicationCommandType, ComponentType, Client, chatInputApplicationCommandMention, User, ButtonBuilder, ButtonStyle } from 'discord.js';
import { checkIfStaff, constants, getCredits } from '../../Utils/utils';
import { InterchatCommand } from '../../../typings/discord';
import emojis from '../../Utils/JSON/emoji.json';
import { stripIndents } from 'common-tags';
import emojis from '../../Utils/JSON/emoji.json';

export default {
data: new SlashCommandBuilder()
Expand All @@ -14,13 +14,13 @@ export default {
.setThumbnail(interaction.client.user.avatarURL())
.setFooter({ text: `Requested by @${interaction.user.username}`, iconURL: interaction.user.avatarURL() || interaction.user.defaultAvatarURL })
.setDescription(stripIndents`
### InterChat Help
## InterChat Help
InterChat is a powerful discord bot that enables effortless cross-server chatting! Get started by looking at the categories below.
### Categories:
- ⚙️ [**Setting up InterChat**](https://discord-interchat.github.io/docs/setup)
- ${emojis.normal.slashCommand} [**All Commands**](https://discord-interchat.github.io/docs/category/commands)
- 👥 [**InterChat Hubs**](https://discord-interchat.github.io/docs/hub/joining)
- ⚙️ [**Setting up InterChat**](https://discord-interchat.github.io/docs/setup)
- 💬 [**Messaging & Network**](https://discord-interchat.github.io/docs/messaging)
- 👥 [**Hubs**](https://discord-interchat.github.io/docs/hub/joining)
`);

const selects = new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(
Expand Down Expand Up @@ -59,11 +59,17 @@ export default {
},

],
placeholder: 'Select a Category',
placeholder: 'Select a Category...',
}),
);

const firstReply = await interaction.reply({ embeds: [embed], components: [selects] });
const linkButtons = new ActionRowBuilder<ButtonBuilder>().addComponents(
new ButtonBuilder().setStyle(ButtonStyle.Link).setLabel('Invite').setURL('https://discord.com/application-directory/769921109209907241'),
new ButtonBuilder().setStyle(ButtonStyle.Link).setLabel('Support Server').setURL('https://discord.gg/6bhXQynAPs'),
new ButtonBuilder().setStyle(ButtonStyle.Link).setLabel('Vote me!').setURL('https://top.gg/bot/769921109209907241/vote'),
);

const firstReply = await interaction.reply({ embeds: [embed], components: [selects, linkButtons] });
const collector = firstReply.createMessageComponentCollector({
filter: i => i.user.id === interaction.user.id,
idle: 60000,
Expand Down
31 changes: 22 additions & 9 deletions src/Events/messageCreate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export default {

let replyInDb: messageData | null;
let referredAuthor: User | undefined; // author of the message being replied to
let referredContent: string | undefined; // for compact messages
let referred: { author?: User, censored: string, content: string } | undefined; // for compact messages

if (message.reference) {
const referredMessage = await message.fetchReference().catch(() => null);
Expand All @@ -61,10 +61,15 @@ export default {
where: { channelAndMessageIds: { some: { messageId: referredMessage.id } } },
});

referredContent = messageContentModifiers.getReferredContent(referredMessage);
referredAuthor = replyInDb
? await message.client.users.fetch(replyInDb?.authorId).catch(() => undefined)
: undefined;
const content = messageContentModifiers.getReferredContent(referredMessage);
referred = {
censored: censor(content),
content: content,
author: replyInDb
? await message.client.users.fetch(replyInDb?.authorId).catch(() => undefined)
: undefined,
};

}
}

Expand All @@ -83,8 +88,8 @@ export default {
.setImage(attachmentURL)
.setColor((connection.embedColor as HexColorString) || 'Random')
.setFields(
referredContent
? [{ name: 'Reply to:', value: `> ${referredContent.replaceAll('\n', '\n> ')}` }]
referred
? [{ name: 'Reply to:', value: `> ${referred.content.replaceAll('\n', '\n> ')}` }]
: [],
)
.setAuthor({
Expand All @@ -98,7 +103,13 @@ export default {
});

// profanity censored embed
const censoredEmbed = EmbedBuilder.from(embed).setDescription(message.censored_content || null);
const censoredEmbed = EmbedBuilder.from(embed)
.setDescription(message.censored_content || null)
.setFields(
referred
? [{ name: 'Reply to:', value: `> ${referred.censored.replaceAll('\n', '\n> ')}` }]
: [],
);

// send the message to all connected channels in apropriate format (compact/profanity filter)
const messageResults = connection.hub?.connections?.map(async (connected) => {
Expand All @@ -118,11 +129,13 @@ export default {
: null;

let webhookMessage: WebhookMessageCreateOptions;

if (connected.compact) {
const referredContent = connected.profFilter ? referred?.censored : referred?.content;
const replyEmbed = replyLink && referredContent
? new EmbedBuilder()
.setColor('Random')
.setDescription(`[**Reply to:**](${replyLink}) ${referredContent.length >= 80 ? referredContent.slice(0, 80) + '...' : referredContent}`)
.setDescription(`[**Reply to:**](${replyLink}) ${referredContent.length >= 80 ? referredContent.slice(0, 80) + '...' : referred}`)
.setAuthor({
name: `${referredAuthor?.username}`,
iconURL: referredAuthor?.avatarURL() || undefined,
Expand Down
5 changes: 2 additions & 3 deletions src/Utils/deploy-commands.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import { REST } from '@discordjs/rest';
import { Routes } from 'discord.js';
import { RESTPostAPIApplicationCommandsJSONBody, RESTPostAPIApplicationGuildCommandsJSONBody, Routes } from 'discord.js';
import { stripIndent } from 'common-tags';
import { constants } from './utils';

import fs from 'fs';
import logger from './logger';
import 'dotenv/config';
import { InterchatCommand } from '../../typings/discord';

const clientID = process.env.CLIENT_ID as string;
const server = process.argv[3]?.toLowerCase() || constants.guilds.cbhq;
Expand All @@ -16,7 +15,7 @@ const commandsPath = 'build/Commands';
const rest = new REST({ version: '10' }).setToken(process.env.TOKEN as string);

function deployCommands(staff = false) {
const commands: InterchatCommand[] = [];
const commands: RESTPostAPIApplicationCommandsJSONBody | RESTPostAPIApplicationGuildCommandsJSONBody[] = [];

fs.readdirSync(commandsPath).forEach((dir) => {
// Only proceed if dir is inside staffCommands array (for deploying only staff commands)
Expand Down
19 changes: 2 additions & 17 deletions src/Utils/network.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { connectedList, hubs } from '@prisma/client';
import { getDb } from './utils';
import { ChannelType, Guild, TextChannel, ThreadChannel, WebhookClient, WebhookMessageCreateOptions } from 'discord.js';
import { getDb, getOrCreateWebhook } from './utils';
import { Guild, TextChannel, ThreadChannel, WebhookClient, WebhookMessageCreateOptions } from 'discord.js';
import { stripIndents } from 'common-tags';
import emojis from './JSON/emoji.json';

Expand Down Expand Up @@ -87,19 +87,4 @@ export async function createConnection(guild: Guild, hub: hubs, networkChannel:
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 };
4 changes: 1 addition & 3 deletions src/Utils/paginator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { ActionRowBuilder, ButtonBuilder, ButtonStyle, EmbedBuilder, CommandInte
import emojis from './JSON/emoji.json';

export interface PaginatorOptions {
/** Number in milliseconds */
stopAfter?: number;
/** only supports buttons at the moment */
extraComponent?: {
Expand All @@ -16,9 +17,6 @@ export interface PaginatorOptions {
};
}

/**
* @param stopAfter - Number in milliseconds
*/
export async function paginate(interaction: CommandInteraction, pages: EmbedBuilder[], options?: PaginatorOptions) {
if (pages.length < 1) {
interaction.reply({ content: `${emojis.normal.tick} No more pages to display!`, ephemeral: true });
Expand Down
46 changes: 31 additions & 15 deletions src/Utils/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,24 @@ export const constants = {
export const topgg = new Api(process.env.TOPGG as string);
const _prisma = new PrismaClient();

export const rulesEmbed = new discord.EmbedBuilder()
.setColor(constants.colors.interchatBlue)
.setImage('https://i.imgur.com/D2pYagc.png')
.setDescription(stripIndents`
### 📜 InterChat Network Rules
1. **Use Common Sense:** Be considerate of others and their views. No slurs, derogatory language or any actions that can disrupt the chat's comfort.
2. **No Spamming or Flooding:** Avoid repeated, nonsensical, or overly lengthy messages.
3. **Keep Private Matters Private:** Avoid sharing personal information across the network.
4. **No Harassment:** Trolling, insults, or harassment of any kind are not tolerated.
5. **No NSFW/NSFL Content:** Posting explicit NSFW/NSFL content will result in immediate blacklist.
6. **Respect Sensitive Topics:** Do not trivialize self-harm, suicide, violence, or other offensive topics.
7. **Report Concerns:** If you observe a violation of these rules, report it to the appropriate hub moderator or InterChat staff for further action.
Any questions? Join our [support server](https://discord.gg/6bhXQynAPs).
`,
);

export function replaceLinks(string: string, replaceText = '`[LINK HIDDEN]`') {
const urlRegex = /https?:\/\/(?!tenor\.com|giphy\.com)\S+/g;
return string.replaceAll(urlRegex, replaceText);
Expand Down Expand Up @@ -200,20 +218,18 @@ export async function deleteHubs(ids: string[]) {
await _prisma.hubs.deleteMany({ where: { id: { in: ids } } });
}

export const rulesEmbed = new discord.EmbedBuilder()
.setColor(constants.colors.interchatBlue)
.setImage('https://i.imgur.com/D2pYagc.png')
.setDescription(stripIndents`
### 📜 InterChat Network Rules
export async function getOrCreateWebhook(channel: discord.TextChannel | discord.ThreadChannel, avatar: string | null) {
const channelOrParent = channel.type === discord.ChannelType.GuildText ? channel : channel.parent;
const webhooks = await channelOrParent?.fetchWebhooks();
const existingWebhook = webhooks?.find((w) => w.owner?.id === channel.client.user?.id);

1. **Use Common Sense:** Be considerate of others and their views. No slurs, derogatory language or any actions that can disrupt the chat's comfort.
2. **No Spamming or Flooding:** Avoid repeated, nonsensical, or overly lengthy messages.
3. **Keep Private Matters Private:** Avoid sharing personal information across the network.
4. **No Harassment:** Trolling, insults, or harassment of any kind are not tolerated.
5. **No NSFW/NSFL Content:** Posting explicit NSFW/NSFL content will result in immediate blacklist.
6. **Respect Sensitive Topics:** Do not trivialize self-harm, suicide, violence, or other offensive topics.
7. **Report Concerns:** If you observe a violation of these rules, report it to the appropriate hub moderator or InterChat staff for further action.
if (existingWebhook) {
return existingWebhook;
}

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

Any questions? Join our [support server](https://discord.gg/6bhXQynAPs).
`,
);
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
"esModuleInterop": true,
"strict": true,
"sourceMap": true,
// "inlineSources": true,
"inlineSources": true,
"forceConsistentCasingInFileNames": true,
"skipLibCheck": true
},
Expand Down

0 comments on commit 224f588

Please sign in to comment.