Compare commits

...

55 Commits

Author SHA1 Message Date
b485b5d420 Merge pull request 'dev' (#26) from dev into main
Reviewed-on: #26
2023-09-16 15:39:32 +02:00
1c50e818b0 Merge pull request 'feature/uptime-kuma-heartbeat' (#25) from feature/uptime-kuma-heartbeat into dev
Reviewed-on: #25
2023-09-16 15:38:58 +02:00
8cb74a1291
Bump version 2023-09-16 15:35:30 +02:00
4bf782cddf
Add version scripts 2023-09-16 15:34:34 +02:00
c6a4577872
Implement push monitoring 2023-09-16 15:33:16 +02:00
3594c2ea8c Merge pull request 'hotfix/db-race' (#23) from hotfix/db-race into dev
Reviewed-on: #23
2023-09-16 11:20:08 +02:00
538d039c5c Merge branch 'dev' into hotfix/db-race 2023-09-16 11:19:12 +02:00
da1996f2ff Merge pull request 'Fix db race condition' (#20) from hotfix/db-race into main
Reviewed-on: #20
2023-09-16 11:14:33 +02:00
d5b75b12c8
Fix db race condition
- Fixed a bug where the bot would crash if the db connection took too long
- Updated packages to latest version
- Bumped version to 1.1.1
2023-09-16 11:12:43 +02:00
Lukas | AstroGD
a71dbecf8c
Merge pull request #19 from r-Overwatch2/main 2022-11-29 21:38:32 +01:00
Lukas | AstroGD
f528d107da
Merge pull request #18 from r-Overwatch2/release/1.1.0 2022-11-29 21:37:08 +01:00
9510116a37
Update lockfile 2022-11-29 21:36:18 +01:00
b8508a4a82
Adjust changelog 2022-11-29 21:34:02 +01:00
ccf2fd9361
Bump version number 2022-11-29 21:33:13 +01:00
cb4bddf983
Bump version number 2022-11-29 21:00:36 +01:00
b1b087e32c
Update reportEmbed wording 2022-11-29 21:00:09 +01:00
451b414fba
Bump version number 2022-11-29 20:55:03 +01:00
Lukas | AstroGD
b53c08a553
Merge pull request #17 from r-Overwatch2/feature/16-send-dm-to-user-that-used-blocked-word-in-channel
closes https://github.com/r-Overwatch2/eu.astrogd.white-leopard/issues/16
2022-11-29 19:40:29 +01:00
f34e06d31f
Format Readme 2022-11-29 19:38:18 +01:00
173438395e
Update env variable documentation 2022-11-29 19:30:25 +01:00
59429ea548
Removed unused import 2022-11-29 19:26:28 +01:00
dbb64baae3
Send message to user when their channel gets deleted 2022-11-29 19:22:11 +01:00
eccb379b51 Update user report embed 2022-11-29 19:21:00 +01:00
cb5516246f
Add user report Embed 2022-11-29 19:05:24 +01:00
Lukas | AstroGD
63c67f4992
Merge pull request #15 from r-Overwatch2/main 2022-11-29 03:22:52 +01:00
Lukas | AstroGD
b24cc4eba8
Merge pull request #14 from r-Overwatch2/release/1.0.0 2022-11-29 03:21:56 +01:00
4466c138ab
Update changelog 2022-11-29 03:20:59 +01:00
44e5cc8c91
Bump fs-extra to @^11 2022-11-29 03:20:48 +01:00
fc9f1c7c4c
Update packages 2022-11-29 03:19:07 +01:00
6be983b217
Bump version number 2022-11-29 03:13:51 +01:00
Lukas | AstroGD
781d2e547e
Merge pull request #13 from r-Overwatch2/feature/12-show-warning-if-logchannel-is-unreachable
closes https://github.com/r-Overwatch2/eu.astrogd.white-leopard/issues/12
2022-11-29 03:07:01 +01:00
ddf28c1612
Show missing permissions when using /showsettings 2022-11-29 03:04:29 +01:00
5fb9ad1e12
Push data model changes 2022-11-29 02:44:54 +01:00
bfabd62674
Detect blocked words on channel creation 2022-11-29 02:40:55 +01:00
5eb56efb79
Fetch target user from audit log 2022-11-29 02:36:46 +01:00
1c6c79dacf
Simplify fetching client member 2022-11-29 02:25:08 +01:00
f4b7685f94
Remove unused import 2022-11-29 01:58:08 +01:00
c3b0a4316b
[BREAKING] Switch from rename channel to delete channel
Reason: rate limits by Discord suck :(
2022-11-29 01:57:34 +01:00
ee9039c239
Remove premium features 2022-11-29 01:56:51 +01:00
361326c31e
Fix: Add empty function to catch clauses 2022-11-29 00:23:19 +01:00
f7c878854b
Warn if logchannel is misconfigured 2022-11-29 00:22:50 +01:00
a8cd924e18
Check for Logchannel permissions before accepting it 2022-11-29 00:22:33 +01:00
3a6641be86
Add start:rebuild script 2022-11-29 00:15:28 +01:00
c9df84b255
Fix crash when getting a channel that doesn't exist 2022-11-29 00:06:57 +01:00
0d69cf3e7b
Add channel permission getter 2022-11-29 00:05:04 +01:00
730151e34b
Update packages 2022-11-29 00:03:19 +01:00
Lukas | AstroGD
d4457e89ce
Merge pull request #11 from r-Overwatch2/release/1.0.0-beta.3
Release/1.0.0 beta.3
2022-11-25 19:52:25 +01:00
Lukas | AstroGD
11845cae42
Merge pull request #10 from r-Overwatch2/release/1.0.0-beta.3
Release/1.0.0 beta.3
2022-11-25 19:49:57 +01:00
d853fa55d3
Add changelog 2022-11-25 19:47:52 +01:00
88834703ef
Bump version number 2022-11-25 19:47:41 +01:00
Lukas | AstroGD
9cbb7799e9
Merge pull request #9 from r-Overwatch2/feature/6-add-a-way-to-view-current-settings
Feature/6 add a way to view current settings
2022-11-25 19:37:49 +01:00
005b9bd69c
Update embed color for /showsettings 2022-11-25 19:30:57 +01:00
21812157f8
/showsettings 2022-11-25 19:28:05 +01:00
Lukas | AstroGD
fb2e3c4f11
Merge pull request #2 from r-Overwatch2/dev
Version 1.0.0-beta.2
2022-11-24 23:30:25 +01:00
Lukas | AstroGD
c8ed870fec
Merge pull request #1 from r-Overwatch2/dev
V1.0.0-beta.1
2022-11-24 21:29:42 +01:00
28 changed files with 1507 additions and 590 deletions

3
.npmrc Normal file
View File

@ -0,0 +1,3 @@
@astrogd:registry=https://git.astrogd.cloud/api/packages/packages/npm/
@internal:registry=https://git.astrogd.cloud/api/packages/internal/npm/
//git.astrogd.cloud/api/packages/internal/npm/:_authToken=${NPM_TOKEN}

43
Changelog.md Normal file
View File

@ -0,0 +1,43 @@
# Changelog
This file is used to list changes made to this software.
_Current development release: 1.1.1_
## V1.1.1 [2023-09-16]
### Updates
- Updated packages to latest versions
### Bugfixes
- Fixed a bug where the bot would crash on startup if the database connection establishment took too long
### Other
- Renamed db service in docker compose file from database to db
## V1.1.0 [2022-11-29]
### Features
- If a channel gets deleted and the responsible user has been detected, a message will be sent to that user informing him of the deletion
## V1.0.0 [2022-11-29]
### Features
- /info
- /logchannel
- /blocklist get
- /blocklist add
- /blocklist remove
- /preservesettings
- /showblocklist
- /showsettings
- Data will be deleted by default when the bot leaves the server
- Server admins can change the behaviour of the bot when it leaves the server to keep the data persistent
- Scans for blocked words in channel names and deletes the channel if found
- Gets the user creating or renaming a channel to a blocked word
- When settings are changed or channels are deleted, notifications to a logchannel can be enabled
- CLI to change settings and get information during runtime by attaching to the apps docker container
- API for automated uptime checks to prevent the bot from going offline unnoticed
- Bot notifies admins via /showsettings when it lacks permissions needed for its functionality

View File

@ -1,37 +1,53 @@
# eu.astrogd.white-leopard # eu.astrogd.white-leopard
A Discord bot that checks Discord channel names for banned words and prevents renaming of them A Discord bot that checks Discord channel names for banned words and prevents renaming of them
## Commands ## Commands
### /logchanel [channel?] `Permission: MANAGE_GUILD` ### /logchanel [channel?] `Permission: MANAGE_GUILD`
Sets the channel where the bot will log if a channel meets the banned word criteria. If channel is omitted, the log channel will be disabled. Sets the channel where the bot will log if a channel meets the banned word criteria. If channel is omitted, the log channel will be disabled.
### /blocklist `Permission: MANAGE_GUILD` ### /blocklist `Permission: MANAGE_GUILD`
#### /blocklist get #### /blocklist get
Gets the global and server specific banned word list and returns it (Same behaviour as /showblocklist)
Returns the global and server specific banned word list and returns it (Same behaviour as /showblocklist)
#### /blocklist add [word] #### /blocklist add [word]
Adds the word to the server specific blocklist Adds the word to the server specific blocklist
#### /blocklist remove [word] #### /blocklist remove [word]
Removes the word from the server specific blocklist Removes the word from the server specific blocklist
### /info `Permission: EVERYONE` ### /info `Permission: EVERYONE`
Returns general information about the bot and the servers stats Returns general information about the bot and the servers stats
### /preservesettings `Permission: ADMINISTRATOR` ### /preservesettings `Permission: ADMINISTRATOR`
Changes the behaviour when the bot leaves the server. Changes the behaviour when the bot leaves the server.
Options are: Options are:
- Keep settings persistent even if the bot leaves - Keep settings persistent even if the bot leaves
- Delete setting when the bot leaves the server [default] - Delete setting when the bot leaves the server [default]
### /showblocklist `Permission: MANAGE_CHANNELS` ### /showblocklist `Permission: MANAGE_CHANNELS`
Gets the global and server specific banned word list and returns it
Returns the global and server specific banned word list and returns it
### /showsettings `Permission: MANAGE_GUILD`
Returns the current settings for the server
## Environment variables ## Environment variables
| Name | Description | Required | Example | | Name | Description | Required | Example |
| :--------------- | :------------------------------------------------------------------------------ | :------: | :------------------ | | :--------------- | :------------------------------------------------------------------------------ | :------: | :------------------ |
| TOKEN | Discord bot token to log into the API with | ▶️/🚀 | NzYzMDP3MzE1Mzky... | | TOKEN | Discord bot token to log into the API with | ▶️/🚀 | NzYzMDP3MzE1Mzky... |
| DB_HOST | Hostname of the database | ▶️ | 127.0.0.1:3546 | | DB_HOST | Hostname of the database | ▶️ | 127.0.0.1 |
| DB_USERNAME | Username of the database | ▶️ | root | | DB_USERNAME | Username of the database | ▶️ | root |
| DB_PASSWORD | Password of the database | ▶️ | abc123 | | DB_PASSWORD | Password of the database | ▶️ | abc123 |
| DB_DATABASE | Database name | ▶️ | white-leopard | | DB_DATABASE | Database name | ▶️ | white-leopard |
@ -39,6 +55,7 @@ Gets the global and server specific banned word list and returns it
| DEPLOY_TOKEN | Production Discord bot token to log into the API with | 🚀 | NzYzMDP3MzE1Mzky... | | DEPLOY_TOKEN | Production Discord bot token to log into the API with | 🚀 | NzYzMDP3MzE1Mzky... |
| DEPLOY_CLIENT_ID | Production Client ID of the Discord appication associated with the deploy token | 🚀 | 763035392692274 | | DEPLOY_CLIENT_ID | Production Client ID of the Discord appication associated with the deploy token | 🚀 | 763035392692274 |
### Icon explanation: ### Icon explanation
- ▶️ = Required in runtime - ▶️ = Required in runtime
- 🚀 = Required during CI/CD - 🚀 = Required during CI/CD

View File

@ -8,15 +8,16 @@ services:
tty: true tty: true
stdin_open: true stdin_open: true
depends_on: depends_on:
- database - db
restart: unless-stopped restart: unless-stopped
environment: environment:
- TOKEN=$TOKEN - TOKEN=$TOKEN
- DB_HOST=database - DB_HOST=db
- DB_USERNAME=$DB_USERNAME - DB_USERNAME=$DB_USERNAME
- DB_PASSWORD=$DB_PASSWORD - DB_PASSWORD=$DB_PASSWORD
- DB_DATABASE=$DB_DATABASE - DB_DATABASE=$DB_DATABASE
database: - MONITOR_URL=$MONITOR_URL
db:
image: postgres:latest image: postgres:latest
restart: unless-stopped restart: unless-stopped
ports: ports:

1447
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,21 +1,27 @@
{ {
"name": "eu.astrogd.white-leopard", "name": "eu.astrogd.white-leopard",
"version": "1.0.0-alpha.7", "version": "1.2.0",
"description": "A Discord bot that checks channel names for blacklisted words and reverts the changes if necessary", "description": "A Discord bot that checks channel names for blacklisted words and reverts the changes if necessary",
"main": "build/index.js", "main": "build/index.js",
"scripts": { "scripts": {
"test": "echo \"Error: no test specified\" && exit 1", "test": "echo \"Error: no test specified\" && exit 1",
"build": "tsc && shx cp package-lock.json build/package-lock.json", "build": "tsc && shx cp package-lock.json build/package-lock.json",
"start:rebuild": "npm run build && node --enable-source-maps .",
"version:dev": "npm version prerelease --preid dev --no-commit-hooks --no-git-tag-version",
"version:patch": "npm version prepatch --preid dev --no-commit-hooks --no-git-tag-version",
"version:minor": "npm version preminor --preid dev --no-commit-hooks --no-git-tag-version",
"version:major": "npm version premajor --preid dev --no-commit-hooks --no-git-tag-version",
"version:release": "npm version patch --no-commit-hooks --no-git-tag-version",
"deploy-commands:dev": "ts-node ci/devDeploy.ts", "deploy-commands:dev": "ts-node ci/devDeploy.ts",
"deploy-commands:prod": "ts-node ci/deploy.ts", "deploy-commands:prod": "ts-node ci/deploy.ts",
"deploy:dev": "npm run build && npm run deploy-commands:dev && docker compose build && docker compose up -d", "deploy:dev": "npm run build && npm run deploy-commands:dev && docker compose build && docker compose up -d",
"deploy:prod": "rimraf build && npm run build && npm run deploy-commands:prod && docker build -t astrogd/white-leopard:latest . && docker push astrogd/white-leopard:latest", "deploy:prod": "rimraf build && npm run build && npm run deploy-commands:prod && docker build -t astrogd/white-leopard:latest . && docker push astrogd/white-leopard:latest",
"start": "npm run build && npm run deploy-commands:dev && docker-compose up --no-start && docker compose start database && node --enable-source-maps .", "start": "npm run build && npm run deploy-commands:dev && docker-compose up -d db && node --enable-source-maps .",
"migration:create": "node --require ts-node/register ./node_modules/typeorm/cli.js migration:generate -d src/data/dataSource.ts -p src/data/migrations/data", "migration:create": "node --require ts-node/register ./node_modules/typeorm/cli.js migration:generate -d src/data/dataSource.migration.ts -p src/data/migrations/data",
"migration:run": "node --require ts-node/register ./node_modules/typeorm/cli.js migration:run -d src/data/dataSource.ts", "migration:run": "node --require ts-node/register ./node_modules/typeorm/cli.js migration:run -d src/data/dataSource.migration.ts",
"migration:revert": "node --require ts-node/register ./node_modules/typeorm/cli.js migration:revert -d src/data/dataSource.ts", "migration:revert": "node --require ts-node/register ./node_modules/typeorm/cli.js migration:revert -d src/data/dataSource.migration.ts",
"migration:show": "node --require ts-node/register ./node_modules/typeorm/cli.js migration:show -d src/data/dataSource.ts", "migration:show": "node --require ts-node/register ./node_modules/typeorm/cli.js migration:show -d src/data/dataSource.migration.ts",
"migration:check": "node --require ts-node/register ./node_modules/typeorm/cli.js migration:generate --check -d src/data/dataSource.ts src/data/migrations/data" "migration:check": "node --require ts-node/register ./node_modules/typeorm/cli.js migration:generate --check -d src/data/dataSource.migration.ts src/data/migrations/data"
}, },
"repository": { "repository": {
"type": "git", "type": "git",
@ -29,18 +35,19 @@
"homepage": "https://github.com/r-Overwatch2/eu.astrogd.white-leopard#readme", "homepage": "https://github.com/r-Overwatch2/eu.astrogd.white-leopard#readme",
"devDependencies": { "devDependencies": {
"@types/express": "^4.17.14", "@types/express": "^4.17.14",
"@types/fs-extra": "^9.0.13", "@types/fs-extra": "^11.0.2",
"@types/node": "^18.11.9", "@types/node": "^18.17.17",
"rimraf": "^3.0.2", "rimraf": "^5.0.1",
"shx": "^0.3.4", "shx": "^0.3.4",
"ts-node": "^10.9.1", "ts-node": "^10.9.1",
"typescript": "^4.9.3" "typescript": "^5.2.2"
}, },
"dependencies": { "dependencies": {
"discord.js": "^14.6.0", "@astrogd/eu.astrogd.uptime-kuma-push-monitor": "^1.0.0-dev.3",
"discord.js": "^14.13.0",
"dotenv": "^16.0.3", "dotenv": "^16.0.3",
"express": "^4.18.2", "express": "^4.18.2",
"fs-extra": "^10.1.0", "fs-extra": "^11.0.0",
"moment": "^2.29.4", "moment": "^2.29.4",
"pg": "^8.8.0", "pg": "^8.8.0",
"typeorm": "^0.3.10" "typeorm": "^0.3.10"

View File

@ -1,5 +1,4 @@
import { getGuildSetting, isPremiumActive } from "../tools/data"; import { getGuildSetting } from "../tools/data";
import moment from "moment";
import { Badword, database, GuildSetting } from "../data"; import { Badword, database, GuildSetting } from "../data";
import { Console } from "console"; import { Console } from "console";
@ -13,7 +12,6 @@ export default async function execute(args: string[]) {
case "info": { case "info": {
if (!args[1]) return printHelp(); if (!args[1]) return printHelp();
const settings = await getGuildSetting(args[1]); const settings = await getGuildSetting(args[1]);
const isPremium = isPremiumActive(settings.isPremiumUntil);
const wordCount = await database.getRepository(Badword).count({ const wordCount = await database.getRepository(Badword).count({
where: { where: {
guildID: args[1] guildID: args[1]
@ -21,36 +19,12 @@ export default async function execute(args: string[]) {
}); });
console.log(`Guild ${args[1]}: console.log(`Guild ${args[1]}:
- Premium: ${isPremium ? `ACTIVE for ${moment(settings.isPremiumUntil).fromNow(true)}` : "INACTIVE"}
- Preserve Settings: ${settings.preserveDataOnGuildLeave ? "ENABLED" : "DISABLED"} - Preserve Settings: ${settings.preserveDataOnGuildLeave ? "ENABLED" : "DISABLED"}
- Logchannel: ${settings.notificationChannelID ? `ENABLED (${settings.notificationChannelID})` : "DISABLED"} - Logchannel: ${settings.notificationChannelID ? `ENABLED (${settings.notificationChannelID})` : "DISABLED"}
- blocked Words: ${wordCount}`); - blocked Words: ${wordCount}`);
break; break;
} }
case "setpremium": {
if (!args[1] || !args[2]) return printHelp();
const settings = await getGuildSetting(args[1]);
if (args[2].toLowerCase() === "null") {
settings.isPremiumUntil = null;
await database.getRepository(GuildSetting).save(settings);
console.log("Premium status removed for guild " + args[1]);
break;
}
const date = new Date(args[2]);
if (isNaN(Number(date))) return printHelp();
const now = new Date();
if (now > date) return console.log("Date lies in the past");
settings.isPremiumUntil = date;
await database.getRepository(GuildSetting).save(settings);
console.log(`Premium status for guild ${args[1]} is now active for ${moment(date).fromNow(true)}`);
break;
}
case "words": { case "words": {
if (!args[1] || !args[2]) return printWordHelp(); if (!args[1] || !args[2]) return printWordHelp();
@ -152,7 +126,6 @@ function printHelp() {
console.log(`Usage "guild": console.log(`Usage "guild":
guild info [GUILDID] guild info [GUILDID]
guild setPremium [GUILDID] [YYYY-MM-DD or NULL]
guild words [get|add|remove|clear] guild words [get|add|remove|clear]
guild delete [GUILDID]`); guild delete [GUILDID]`);
} }

View File

@ -1,13 +1,25 @@
import { runCleanup } from "../service"; import { runCleanup } from "../service";
import client from "./index"; import client from "./index";
import { initPromise } from "../data/dataSource";
import pushMonitor from "@astrogd/eu.astrogd.uptime-kuma-push-monitor";
const token = process.env["TOKEN"]; const token = process.env["TOKEN"];
if (!token) throw new ReferenceError("TOKEN environment variable is missing"); if (!token) throw new ReferenceError("TOKEN environment variable is missing");
client.login(token); async function run() {
console.log("Establishing database connection");
await initPromise;
console.log("Connection established\nAuthenticating with Discord API");
client.login(token);
}
client.on("ready", () => { client.on("ready", async () => {
console.log(`Connected to Discord API. Bot account is ${client.user?.tag} (${client.user?.id})`); console.log(`Connected to Discord API. Bot account is ${client.user?.tag} (${client.user?.id})`);
if (process.env["MONITOR_URL"]) pushMonitor.register(process.env["MONITOR_URL"], 120);
pushMonitor.enableShutdownNotifications();
pushMonitor.setPerformanceHandler(() => client.ws.ping);
runCleanup(); runCleanup();
}); });
run();

View File

@ -1,7 +1,7 @@
import { ChatInputCommandInteraction, PermissionFlagsBits, SlashCommandBuilder } from "discord.js"; import { ChatInputCommandInteraction, PermissionFlagsBits, SlashCommandBuilder } from "discord.js";
import { database, Badword } from "../data"; import { database, Badword } from "../data";
import { IsNull } from "typeorm"; import { IsNull } from "typeorm";
import { getGuildSetting, isPremiumActive } from "../tools/data"; import { getGuildSetting } from "../tools/data";
import getDefaultEmbed, { getFailedEmbed, getSuccessEmbed } from "../tools/defaultEmbeds"; import getDefaultEmbed, { getFailedEmbed, getSuccessEmbed } from "../tools/defaultEmbeds";
import { getGuildChannel } from "../tools/discord"; import { getGuildChannel } from "../tools/discord";
import { Color, Emoji } from "../tools/design"; import { Color, Emoji } from "../tools/design";
@ -46,7 +46,6 @@ async function execute(interaction: ChatInputCommandInteraction): Promise<void>
if (!interaction.guildId) throw new Error("Command was executed in DM context"); if (!interaction.guildId) throw new Error("Command was executed in DM context");
const settings = await getGuildSetting(interaction.guildId); const settings = await getGuildSetting(interaction.guildId);
const isPremium = isPremiumActive(settings.isPremiumUntil);
const logChannel = settings.notificationChannelID ? await getGuildChannel(interaction.guildId, settings.notificationChannelID) : null; const logChannel = settings.notificationChannelID ? await getGuildChannel(interaction.guildId, settings.notificationChannelID) : null;
@ -63,14 +62,14 @@ async function execute(interaction: ChatInputCommandInteraction): Promise<void>
} }
}); });
const limit = isPremium ? 100 : 10; const limit = 100;
if (count >= limit) { if (count >= limit) {
const embed = getFailedEmbed(); const embed = getFailedEmbed();
embed.setDescription(`You reached the word limit for your guild. Please delete a word before adding a new one`); embed.setDescription(`You reached the word limit for your guild. Please delete a word before adding a new one`);
interaction.reply({ interaction.reply({
embeds: [embed], embeds: [embed],
ephemeral: true ephemeral: true
}).catch(); }).catch(() => {});
return; return;
} }
@ -89,7 +88,7 @@ async function execute(interaction: ChatInputCommandInteraction): Promise<void>
interaction.reply({ interaction.reply({
embeds: [embed], embeds: [embed],
ephemeral: true ephemeral: true
}).catch(); }).catch(() => {});
return; return;
} }
@ -117,7 +116,7 @@ async function execute(interaction: ChatInputCommandInteraction): Promise<void>
if (logChannel && logChannel.isTextBased()) { if (logChannel && logChannel.isTextBased()) {
logChannel.send({ logChannel.send({
embeds: [logMessage] embeds: [logMessage]
}).catch(); }).catch(() => {});
} }
break; break;
} }
@ -138,7 +137,7 @@ async function execute(interaction: ChatInputCommandInteraction): Promise<void>
interaction.reply({ interaction.reply({
embeds: [embed], embeds: [embed],
ephemeral: true ephemeral: true
}).catch(); }).catch(() => {});
return; return;
} }
@ -151,7 +150,7 @@ async function execute(interaction: ChatInputCommandInteraction): Promise<void>
interaction.reply({ interaction.reply({
embeds: [embed], embeds: [embed],
ephemeral: true ephemeral: true
}).catch(); }).catch(() => {});
const logMessage = getDefaultEmbed(); const logMessage = getDefaultEmbed();
logMessage.setTitle(`${Emoji.SETTINGS} Word removed`); logMessage.setTitle(`${Emoji.SETTINGS} Word removed`);
@ -164,7 +163,7 @@ async function execute(interaction: ChatInputCommandInteraction): Promise<void>
if (logChannel && logChannel.isTextBased()) { if (logChannel && logChannel.isTextBased()) {
logChannel.send({ logChannel.send({
embeds: [logMessage] embeds: [logMessage]
}).catch(); }).catch(() => {});
} }
break; break;
} }

View File

@ -3,8 +3,17 @@ import * as blocklist from "./blocklist";
import * as info from "./info"; import * as info from "./info";
import * as preserveSettings from "./preserveSettings"; import * as preserveSettings from "./preserveSettings";
import * as showBlocklist from "./showblocklist"; import * as showBlocklist from "./showblocklist";
import * as showSettings from "./showSettings";
const array = [notification.builder.toJSON(), blocklist.builder.toJSON(), info.builder.toJSON(), preserveSettings.builder.toJSON(), showBlocklist.builder.toJSON()]; const commands = [];
commands.push(notification);
commands.push(blocklist);
commands.push(info);
commands.push(preserveSettings);
commands.push(showBlocklist);
commands.push(showSettings);
const array = commands.map((command) => command.builder.toJSON());
export { export {
array array

View File

@ -4,6 +4,7 @@ import * as blocklist from "./blocklist";
import * as info from "./info"; import * as info from "./info";
import * as preserveSettings from "./preserveSettings"; import * as preserveSettings from "./preserveSettings";
import * as showBlocklist from "./showblocklist"; import * as showBlocklist from "./showblocklist";
import * as showSettings from "./showSettings";
import client from "../client"; import client from "../client";
import getDefaultEmbed from "../tools/defaultEmbeds"; import getDefaultEmbed from "../tools/defaultEmbeds";
@ -13,6 +14,7 @@ commands.set(blocklist.builder.name, blocklist);
commands.set(info.builder.name, info); commands.set(info.builder.name, info);
commands.set(preserveSettings.builder.name, preserveSettings); commands.set(preserveSettings.builder.name, preserveSettings);
commands.set(showBlocklist.builder.name, showBlocklist); commands.set(showBlocklist.builder.name, showBlocklist);
commands.set(showSettings.builder.name, showSettings);
client.on(Events.InteractionCreate, async (interaction) => { client.on(Events.InteractionCreate, async (interaction) => {
if (!interaction.isChatInputCommand()) return; if (!interaction.isChatInputCommand()) return;
@ -42,6 +44,6 @@ client.on(Events.InteractionCreate, async (interaction) => {
await interaction.reply({ await interaction.reply({
embeds: [embed], embeds: [embed],
ephemeral: true ephemeral: true
}).catch(); }).catch(() => {});
} }
}); });

View File

@ -1,7 +1,6 @@
import { ChatInputCommandInteraction, SlashCommandBuilder } from "discord.js"; import { ChatInputCommandInteraction, SlashCommandBuilder } from "discord.js";
import { IsNull } from "typeorm"; import { IsNull } from "typeorm";
import { Badword, database } from "../data"; import { Badword, database } from "../data";
import { getGuildSetting, isPremiumActive } from "../tools/data";
import getDefaultEmbed from "../tools/defaultEmbeds"; import getDefaultEmbed from "../tools/defaultEmbeds";
import pack from "../../package.json"; import pack from "../../package.json";
import { Color, Emoji } from "../tools/design"; import { Color, Emoji } from "../tools/design";
@ -14,8 +13,6 @@ builder.setDMPermission(false);
async function execute(interaction: ChatInputCommandInteraction): Promise<void> { async function execute(interaction: ChatInputCommandInteraction): Promise<void> {
if (!interaction.inGuild()) throw new Error("Command was executed outside guild context"); if (!interaction.inGuild()) throw new Error("Command was executed outside guild context");
const settings = await getGuildSetting(interaction.guildId);
const isPremium = isPremiumActive(settings.isPremiumUntil);
const globalBlockedWordsCount = await database.getRepository(Badword).count({ const globalBlockedWordsCount = await database.getRepository(Badword).count({
where: { where: {
guildID: IsNull() guildID: IsNull()
@ -30,17 +27,13 @@ async function execute(interaction: ChatInputCommandInteraction): Promise<void>
const embed = getDefaultEmbed(); const embed = getDefaultEmbed();
embed.setTitle(`${Emoji.SECURITY_CHALLENGE} Channel filter V${pack.version} by AstroGD®`); embed.setTitle(`${Emoji.SECURITY_CHALLENGE} Channel filter V${pack.version} by AstroGD®`);
embed.setDescription(`Codename eu.astrogd.white-leopard`); embed.setDescription(`Codename eu.astrogd.white-leopard`);
embed.setColor(isPremium ? Color.PREMIUM_ORANGE : Color.INFORMING_BLUE); embed.setColor(Color.INFORMING_BLUE);
embed.addFields({ embed.addFields({
name: "What does this bot do?", name: "What does this bot do?",
value: "This bot checks for blocked words contained in channel names and reverts the changes if found." value: "This bot checks for blocked words contained in channel names and reverts the changes if found."
},{ },{
name: "Author", name: "Author",
value: `This bot was created by AstroGD#0001 ${Emoji.ASTROGD} mainly for the official r/Overwatch2 Subreddit Discord server` value: `This bot was created by AstroGD#0001 ${Emoji.ASTROGD} mainly for the official r/Overwatch2 Subreddit Discord server`
},{
name: "Server status",
value: `${isPremium ? Emoji.PREMIUM : Emoji.SWITCH_OFF} Premium features are ${isPremium ? "enabled" : "disabled"} on this server`,
inline: true
},{ },{
name: "Global word count", name: "Global word count",
value: globalBlockedWordsCount.toString(), value: globalBlockedWordsCount.toString(),
@ -57,7 +50,7 @@ async function execute(interaction: ChatInputCommandInteraction): Promise<void>
interaction.reply({ interaction.reply({
embeds: [embed], embeds: [embed],
ephemeral: true ephemeral: true
}).catch(); }).catch(() => {});
} }
export { export {

View File

@ -1,8 +1,8 @@
import { SlashCommandBuilder, PermissionFlagsBits, ChannelType, ChatInputCommandInteraction, NewsChannel, TextBasedChannel, CategoryChannel, StageChannel, TextChannel, PrivateThreadChannel, PublicThreadChannel, VoiceChannel, APIInteractionDataResolvedChannel, ForumChannel } from "discord.js"; import { SlashCommandBuilder, PermissionFlagsBits, ChannelType, ChatInputCommandInteraction, NewsChannel, TextBasedChannel, CategoryChannel, StageChannel, TextChannel, PrivateThreadChannel, PublicThreadChannel, VoiceChannel, APIInteractionDataResolvedChannel, ForumChannel } from "discord.js";
import getDefaultEmbed, { getSuccessEmbed } from "../tools/defaultEmbeds"; import getDefaultEmbed, { getFailedEmbed, getSuccessEmbed } from "../tools/defaultEmbeds";
import { database, GuildSetting } from "../data"; import { database, GuildSetting } from "../data";
import { getGuildSetting } from "../tools/data"; import { getGuildSetting } from "../tools/data";
import { getGuildChannel } from "../tools/discord"; import { getGuildChannel, getChannelPermission } from "../tools/discord";
import { Emoji } from "../tools/design"; import { Emoji } from "../tools/design";
const builder = new SlashCommandBuilder(); const builder = new SlashCommandBuilder();
@ -35,7 +35,7 @@ async function resetNotificationChannel(guildSetting: GuildSetting, interaction:
if (logChannel && logChannel.isTextBased()) { if (logChannel && logChannel.isTextBased()) {
logChannel.send({ logChannel.send({
embeds: [logEmbed] embeds: [logEmbed]
}).catch(); }).catch(() => {});
} }
const embed = getSuccessEmbed(); const embed = getSuccessEmbed();
@ -43,7 +43,7 @@ async function resetNotificationChannel(guildSetting: GuildSetting, interaction:
interaction.reply({ interaction.reply({
embeds: [embed], embeds: [embed],
ephemeral: true ephemeral: true
}).catch(); }).catch(() => {});
} }
const execute = async (interaction: ChatInputCommandInteraction) => { const execute = async (interaction: ChatInputCommandInteraction) => {
@ -55,6 +55,20 @@ const execute = async (interaction: ChatInputCommandInteraction) => {
if (!optionVal) return await resetNotificationChannel(guildSetting, interaction); if (!optionVal) return await resetNotificationChannel(guildSetting, interaction);
const channel = getTextBasedChannel(optionVal); const channel = getTextBasedChannel(optionVal);
if (channel.isDMBased()) return;
const permissions = await getChannelPermission(channel);
if (!permissions || !permissions.has(PermissionFlagsBits.ViewChannel) || !permissions.has(PermissionFlagsBits.SendMessages)) {
const embed = getFailedEmbed();
embed.setDescription(`Bot doesn't have permission to view and/or write in channel <#${channel.id}>`);
interaction.reply({
embeds: [ embed ],
ephemeral: true
}).catch(() => {});
return;
}
if (guildSetting.notificationChannelID) { if (guildSetting.notificationChannelID) {
const oldLogChannel = await getGuildChannel(guildSetting.id, guildSetting.notificationChannelID); const oldLogChannel = await getGuildChannel(guildSetting.id, guildSetting.notificationChannelID);
const embed = getDefaultEmbed(); const embed = getDefaultEmbed();
@ -68,7 +82,7 @@ const execute = async (interaction: ChatInputCommandInteraction) => {
if (oldLogChannel && oldLogChannel.isTextBased()) { if (oldLogChannel && oldLogChannel.isTextBased()) {
oldLogChannel.send({ oldLogChannel.send({
embeds: [embed] embeds: [embed]
}).catch(); }).catch(() => {});
} }
} }
@ -84,16 +98,16 @@ const execute = async (interaction: ChatInputCommandInteraction) => {
}); });
channel.send({ channel.send({
embeds: [ embed ] embeds: [embed]
}).catch(); }).catch(() => {});
const reply = getSuccessEmbed(); const reply = getSuccessEmbed();
reply.setDescription(`Log channel was set to <#${channel.id}>`); reply.setDescription(`Log channel was set to <#${channel.id}>`);
interaction.reply({ interaction.reply({
embeds: [ reply ], embeds: [reply],
ephemeral: true ephemeral: true
}).catch(); }).catch(() => {});
return; return;
} }

View File

@ -42,7 +42,7 @@ async function execute(interaction: ChatInputCommandInteraction): Promise<void>
interaction.reply({ interaction.reply({
embeds: [embed], embeds: [embed],
ephemeral: true ephemeral: true
}).catch(); }).catch(() => {});
if (!settings.notificationChannelID) return; if (!settings.notificationChannelID) return;
const logChannel = await getGuildChannel(interaction.guildId, settings.notificationChannelID); const logChannel = await getGuildChannel(interaction.guildId, settings.notificationChannelID);
@ -57,7 +57,7 @@ async function execute(interaction: ChatInputCommandInteraction): Promise<void>
logChannel.send({ logChannel.send({
embeds: [logEmbed] embeds: [logEmbed]
}).catch(); }).catch(() => {});
} }
export { export {

View File

@ -0,0 +1,110 @@
import { ChatInputCommandInteraction, Guild, PermissionFlagsBits, SlashCommandBuilder } from "discord.js";
import client from "../client";
import { Badword, database } from "../data";
import { getGuildSetting } from "../tools/data";
import getDefaultEmbed from "../tools/defaultEmbeds";
import { Color, Emoji } from "../tools/design";
import { getGuildChannel, getChannelPermission } from "../tools/discord";
const builder = new SlashCommandBuilder();
builder.setName("showsettings");
builder.setDescription("Show the current settings of this guild");
builder.setDMPermission(false);
builder.setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild);
async function execute(interaction: ChatInputCommandInteraction): Promise<void> {
if (!interaction.inGuild()) throw new Error("Interaction was performed outside guild context");
const guild = await new Promise<null | Guild>((resolve) => {
client.guilds.fetch(interaction.guildId).catch(() => {resolve(null)}).then((guild) => {resolve(guild || null)});
});
if (!guild) throw new Error("Guild is unavailable");
const settings = await getGuildSetting(interaction.guildId);
const wordCount = await database.getRepository(Badword).count({
where: {
guildID: interaction.guildId
}
});
const logChannel = settings.notificationChannelID ? await getGuildChannel(interaction.guildId, settings.notificationChannelID) : null;
const embed = getDefaultEmbed();
embed.setTitle(`Settings from guild ${interaction.guild?.name || ""} (${interaction.guildId})`);
embed.setDescription("Thanks for using this bot");
embed.setColor(Color.INFORMING_BLUE);
embed.addFields({
name: "Logchannel",
value: settings.notificationChannelID ? `<#${settings.notificationChannelID}>` : "Not configured",
inline: true
}, {
name: "Words in Blocklist",
value: `${wordCount}/100`,
inline: true
}, {
name: `Preserve data on server leave is ${settings.preserveDataOnGuildLeave ? "active" : "inactive"}`,
value: settings.preserveDataOnGuildLeave ? "Your settings will be saved even if the bot gets kicked" : "Your settings will be deleted as soon as the bot leaves this server"
}, {
name: `${Emoji.WAVING} Found a bug? Want to request a feature? Say hello?`,
value: "Join the support server at https://go.astrogd.eu/discord"
});
const embeds = [];
embeds.push(embed);
const invalidLogChannelEmbed = getDefaultEmbed();
invalidLogChannelEmbed.setColor(Color.WARNING_YELLOW);
invalidLogChannelEmbed.setTitle(`${Emoji.CHAT_DENY} Logchannel is misconfigured!`);
invalidLogChannelEmbed.setDescription("The bot is unable to read and/or write in the configured logChannel. Please adjust your permissions.");
const missingPermissionEmbed = getDefaultEmbed();
missingPermissionEmbed.setColor(Color.WARNING_YELLOW);
missingPermissionEmbed.setTitle(`${Emoji.CHAT_DENY} Bot is missing permissions to function properly!`);
missingPermissionEmbed.setDescription("Without these missing Permissions, the bot won't work properly and might lead to unexpected behavior");
if (logChannel && logChannel.isTextBased()) {
const permissions = await getChannelPermission(logChannel);
if (!permissions || !permissions.has(PermissionFlagsBits.ViewChannel) || !permissions.has(PermissionFlagsBits.SendMessages)) {
embeds.push(invalidLogChannelEmbed);
}
}
if ((!logChannel || !logChannel.isTextBased()) && settings.notificationChannelID) {
embeds.push(invalidLogChannelEmbed);
}
const member = await guild.members.fetchMe();
if (!member.permissions.has(PermissionFlagsBits.ViewAuditLog)) {
missingPermissionEmbed.addFields({
name: "View Audit Logs",
value: "With this permission the bot can determine who created or updated a channel with a blocked word"
});
}
if (!member.permissions.has(PermissionFlagsBits.ViewChannel)) {
missingPermissionEmbed.addFields({
name: "View Channels",
value: "If the bot can't see a channel, it won't be able to detect blocked words in it"
});
}
if (!member.permissions.has(PermissionFlagsBits.ManageChannels)) {
missingPermissionEmbed.addFields({
name: "Manage Channels",
value: "If the bot can't delete a channel, it can't protect your server from channels with blocked words"
});
}
if (missingPermissionEmbed.data.fields?.length || 0 > 0) embeds.push(missingPermissionEmbed);
interaction.reply({
embeds: embeds,
ephemeral: true
}).catch(() => {});
}
export {
builder,
execute
}

View File

@ -1,7 +1,6 @@
import { ChatInputCommandInteraction, PermissionFlagsBits, SlashCommandBuilder } from "discord.js"; import { ChatInputCommandInteraction, PermissionFlagsBits, SlashCommandBuilder } from "discord.js";
import { IsNull } from "typeorm"; import { IsNull } from "typeorm";
import { Badword, database } from "../data"; import { Badword, database } from "../data";
import { getGuildSetting, isPremiumActive } from "../tools/data";
const builder = new SlashCommandBuilder(); const builder = new SlashCommandBuilder();
builder.setName("showblocklist"); builder.setName("showblocklist");
@ -12,9 +11,6 @@ builder.setDefaultMemberPermissions(PermissionFlagsBits.ManageChannels);
async function execute(interaction: ChatInputCommandInteraction): Promise<void> { async function execute(interaction: ChatInputCommandInteraction): Promise<void> {
if (!interaction.inGuild()) throw new Error("Command was executed outside guild context"); if (!interaction.inGuild()) throw new Error("Command was executed outside guild context");
const settings = await getGuildSetting(interaction.guildId);
const isPremium = isPremiumActive(settings.isPremiumUntil);
const guildBadWords = await database.getRepository(Badword).find({ const guildBadWords = await database.getRepository(Badword).find({
select: { select: {
value: true value: true
@ -30,9 +26,9 @@ async function execute(interaction: ChatInputCommandInteraction): Promise<void>
}); });
interaction.reply({ interaction.reply({
content: `\`\`\`Global bad word list\`\`\`\n||${globalBadWords.map((word) => word.value).reduce((prev, next) => prev + ", " + next, "").slice(2)} ||\n\`\`\`Local server bad word list (${guildBadWords.length}/${isPremium ? 100 : 10})\`\`\`\n||${guildBadWords.map((word) => word.value).reduce((prev, next) => prev + ", " + next, "").slice(2)} ||`, content: `\`\`\`Global bad word list\`\`\`\n||${globalBadWords.map((word) => word.value).reduce((prev, next) => prev + ", " + next, "").slice(2)} ||\n\`\`\`Local server bad word list (${guildBadWords.length}/100)\`\`\`\n||${guildBadWords.map((word) => word.value).reduce((prev, next) => prev + ", " + next, "").slice(2)} ||`,
ephemeral: true ephemeral: true
}).catch(); }).catch(() => {});
} }
export { export {

View File

@ -0,0 +1,3 @@
import dataSource from "./dataSource";
export default dataSource;

View File

@ -28,6 +28,9 @@ const dataSource = new DataSource({
migrationsTransactionMode: "each" migrationsTransactionMode: "each"
}); });
dataSource.initialize(); const initPromise = dataSource.initialize();
export default dataSource; export default dataSource;
export {
initPromise
}

View File

@ -0,0 +1,19 @@
import { MigrationInterface, QueryRunner } from "typeorm";
export class data1669686263307 implements MigrationInterface {
name = 'data1669686263307'
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`
ALTER TABLE "guild_setting" DROP COLUMN "isPremiumUntil"
`);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`
ALTER TABLE "guild_setting"
ADD "isPremiumUntil" TIMESTAMP
`);
}
}

View File

@ -8,9 +8,6 @@ export class GuildSetting {
@Column("varchar", { nullable: true, default: null }) @Column("varchar", { nullable: true, default: null })
notificationChannelID!: string | null; notificationChannelID!: string | null;
@Column("timestamp", { nullable: true, default: null })
isPremiumUntil!: Date | null;
@Column("boolean", { default: false }) @Column("boolean", { default: false })
preserveDataOnGuildLeave!: boolean preserveDataOnGuildLeave!: boolean
} }

116
src/events/channelCreate.ts Normal file
View File

@ -0,0 +1,116 @@
import client from "../client";
import { AuditLogEvent, Events, GuildAuditLogsEntry, PermissionFlagsBits, User } from "discord.js";
import { getGuildSetting } from "../tools/data";
import { Badword, database } from "../data";
import { IsNull } from "typeorm";
import getDefaultEmbed, { getFailedEmbed, getUserReportEmbed } from "../tools/defaultEmbeds";
import { getGuildChannel } from "../tools/discord";
import { Color, Emoji } from "../tools/design";
client.on(Events.ChannelCreate, async (newChannel) => {
if (newChannel.isDMBased()) return;
const name = newChannel.name.toLowerCase();
const guild = newChannel.guild;
const settings = await getGuildSetting(guild.id);
const globalBlocklist = await database.getRepository(Badword).find({
where: {
guildID: IsNull()
}
});
const localBlocklist = await database.getRepository(Badword).find({
where: {
guildID: guild.id
}
});
const blocklist = [...globalBlocklist, ...localBlocklist];
let found: string | null = null;
for (let i = 0; i < blocklist.length; i++) {
const word = blocklist[i];
if (!word) continue;
if (!name.includes(word.value)) continue;
found = word.value;
break;
}
if (found === null) return;
let responsibleUser: User | null;
try {
const clientMember = await guild.members.fetchMe();
const canSeeAuditLog = clientMember.permissions.has(PermissionFlagsBits.ViewAuditLog);
const auditLogs = canSeeAuditLog ? await guild.fetchAuditLogs({
type: AuditLogEvent.ChannelCreate,
limit: 50
}) : undefined;
const change = auditLogs?.entries.filter((entry) => {
if (entry.target.id !== newChannel.id) return false;
return entry.changes.filter((change) => {
return change.key === "name" && change.new === newChannel.name;
}).length > 0;
}).reduce<null | GuildAuditLogsEntry<AuditLogEvent.ChannelCreate, "Create", "Channel", AuditLogEvent.ChannelCreate>>((unknown, curr) => {
if (!unknown) return curr;
const prev = unknown as GuildAuditLogsEntry<AuditLogEvent.ChannelCreate, "Create", "Channel", AuditLogEvent.ChannelCreate>
return curr.createdTimestamp > prev.createdTimestamp ? curr : prev;
}, null);
responsibleUser = change?.executor || null;
} catch (error) {
responsibleUser = null;
}
const logChannel = settings.notificationChannelID ? await getGuildChannel(guild.id, settings.notificationChannelID) : null;
try {
if (!newChannel.deletable) throw new Error("Missing permissions to delete channel");
await newChannel.delete("[Automated] Detected blocked word in channel name");
} catch (error) {
if (!logChannel || !logChannel.isTextBased()) return;
const embed = getFailedEmbed();
embed.setDescription(`Couldn't delete <#${newChannel.id}> (${newChannel.id}): ${error instanceof Error ? error.message : error}`);
embed.addFields({
name: "Detected banned word:",
value: `||${found}||`
}, {
name: "Channel created by:",
value: responsibleUser ? `${responsibleUser.tag} (${responsibleUser.id})` : "`Couldn't detect responsible user :(`"
});
logChannel.send({
embeds: [embed]
}).catch(() => {});
return;
}
if (responsibleUser) {
const embed = getUserReportEmbed(guild.name, newChannel.name);
responsibleUser.send({
embeds: [embed]
}).catch(() => {});
}
if (!logChannel || !logChannel.isTextBased()) return;
const embed = getDefaultEmbed();
embed.setTitle(`${Emoji.SECURITY_CHALLENGE_FAILED} Blocked word detected`);
embed.setDescription(`||#${newChannel.name}|| (${newChannel.id}) has been deleted because its name contained a blocked word.`);
embed.setColor(Color.WARNING_YELLOW);
embed.addFields({
name: "Detected banned word:",
value: `||${found}||`,
inline: true
}, {
name: "Channel created by:",
value: responsibleUser ? `${responsibleUser.tag} (${responsibleUser.id})` : "`Couldn't detect responsible user :(`"
});
logChannel.send({
embeds: [embed]
}).catch(() => {});
});

View File

@ -1,20 +1,18 @@
import client from "../client"; import client from "../client";
import { Events } from "discord.js"; import { AuditLogEvent, Events, GuildAuditLogsEntry, PermissionFlagsBits, User } from "discord.js";
import { getGuildSetting, isPremiumActive } from "../tools/data"; import { getGuildSetting } from "../tools/data";
import { Badword, database } from "../data"; import { Badword, database } from "../data";
import { IsNull } from "typeorm"; import { IsNull } from "typeorm";
import getDefaultEmbed, { getFailedEmbed } from "../tools/defaultEmbeds"; import getDefaultEmbed, { getFailedEmbed, getUserReportEmbed } from "../tools/defaultEmbeds";
import { getGuildChannel } from "../tools/discord"; import { getGuildChannel } from "../tools/discord";
import { Color, Emoji } from "../tools/design"; import { Color, Emoji } from "../tools/design";
client.on(Events.ChannelUpdate, async (oldChannel, newChannel) => { client.on(Events.ChannelUpdate, async (oldChannel, newChannel) => {
if (oldChannel.isDMBased() || newChannel.isDMBased()) return; if (oldChannel.isDMBased() || newChannel.isDMBased()) return;
const name = newChannel.name.toLowerCase(); const name = newChannel.name.toLowerCase();
if (name === "censored") return;
const guild = oldChannel.guild; const guild = oldChannel.guild;
const settings = await getGuildSetting(guild.id); const settings = await getGuildSetting(guild.id);
const isPremium = isPremiumActive(settings.isPremiumUntil);
const globalBlocklist = await database.getRepository(Badword).find({ const globalBlocklist = await database.getRepository(Badword).find({
where: { where: {
@ -41,45 +39,78 @@ client.on(Events.ChannelUpdate, async (oldChannel, newChannel) => {
if (found === null) return; if (found === null) return;
let responsibleUser: User | null;
try {
const clientMember = await guild.members.fetchMe();
const canSeeAuditLog = clientMember.permissions.has(PermissionFlagsBits.ViewAuditLog);
const auditLogs = canSeeAuditLog ? await guild.fetchAuditLogs({
type: AuditLogEvent.ChannelUpdate,
limit: 50
}) : undefined;
const change = auditLogs?.entries.filter((entry) => {
if (entry.target.id !== newChannel.id) return false;
return entry.changes.filter((change) => {
return change.key === "name" && change.new === newChannel.name;
}).length > 0;
}).reduce<null | GuildAuditLogsEntry<AuditLogEvent.ChannelUpdate, "Update", "Channel", AuditLogEvent.ChannelUpdate>>((unknown, curr) => {
if (!unknown) return curr;
const prev = unknown as GuildAuditLogsEntry<AuditLogEvent.ChannelUpdate, "Update", "Channel", AuditLogEvent.ChannelUpdate>
return curr.createdTimestamp > prev.createdTimestamp ? curr : prev;
}, null);
responsibleUser = change?.executor || null;
} catch (error) {
responsibleUser = null;
}
const logChannel = settings.notificationChannelID ? await getGuildChannel(guild.id, settings.notificationChannelID) : null; const logChannel = settings.notificationChannelID ? await getGuildChannel(guild.id, settings.notificationChannelID) : null;
try { try {
await newChannel.setName("CENSORED", `[Automated] Detected blocked word in channel name. Name has been censored`); if (!newChannel.deletable) throw new Error("Missing permissions to delete channel");
await newChannel.delete("[Automated] Detected blocked word in channel name");
} catch (error) { } catch (error) {
if (!logChannel || !logChannel.isTextBased()) return; if (!logChannel || !logChannel.isTextBased()) return;
const embed = getFailedEmbed(); const embed = getFailedEmbed();
embed.setDescription(`Couldn't censor <#${newChannel.id}> (${newChannel.id}): ${error instanceof Error ? error.message : error}`); embed.setDescription(`Couldn't delete <#${newChannel.id}> (${newChannel.id}): ${error instanceof Error ? error.message : error}`);
if (isPremium) embed.addFields({ embed.addFields({
name: "Detected banned word:", name: "Detected banned word:",
value: `||${found}||` value: `||${found}||`
},{ }, {
name: "Old channel name:", name: "Channel renamed by:",
value: `||${name}||`, value: responsibleUser ? `${responsibleUser.tag} (${responsibleUser.id})` : "`Couldn't detect responsible user :(`"
inline: true
}); });
logChannel.send({ logChannel.send({
embeds: [embed] embeds: [embed]
}).catch(); }).catch(() => {});
return; return;
} }
if (responsibleUser) {
const embed = getUserReportEmbed(guild.name, newChannel.name);
responsibleUser.send({
embeds: [embed]
}).catch(() => {});
}
if (!logChannel || !logChannel.isTextBased()) return; if (!logChannel || !logChannel.isTextBased()) return;
const embed = getDefaultEmbed(); const embed = getDefaultEmbed();
embed.setTitle(`${Emoji.SECURITY_CHALLENGE_FAILED} Blocked word detected`); embed.setTitle(`${Emoji.SECURITY_CHALLENGE_FAILED} Blocked word detected`);
embed.setDescription(`<#${newChannel.id}> (${newChannel.id}) has been renamed because its name contained a blocked word.`); embed.setDescription(`||#${newChannel.name}|| (${newChannel.id}) has been deleted because its name contained a blocked word.`);
embed.setColor(Color.WARNING_YELLOW); embed.setColor(Color.WARNING_YELLOW);
if (isPremium) embed.addFields({ embed.addFields({
name: "Detected banned word:", name: "Detected banned word:",
value: `||${found}||`, value: `||${found}||`,
inline: true inline: true
},{ }, {
name: "Old channel name:", name: "Channel renamed by:",
value: `||${name}||`, value: responsibleUser ? `${responsibleUser.tag} (${responsibleUser.id})` : "`Couldn't detect responsible user :(`"
inline: true
}); });
logChannel.send({ logChannel.send({
embeds: [embed] embeds: [embed]
}).catch(); }).catch(() => {});
}); });

View File

@ -1,2 +1,3 @@
import "./channelUpdate"; import "./channelUpdate";
import "./guildDelete"; import "./guildDelete";
import "./channelCreate";

View File

@ -1,4 +1,3 @@
import "./uptime";
import runCleanup from "./cleanup"; import runCleanup from "./cleanup";
export { export {

View File

@ -1,19 +0,0 @@
import express from "express";
import pack from "../../package.json";
import startupTime from "../tools/startupTime";
const app = express();
app.get("/", (_req, res) => {
res.status(200).json({
running: true,
version: pack.version,
runningSince: startupTime.toISOString()
});
});
app.all("*", (_req, res) => {
res.status(404).end();
});
app.listen(80);

View File

@ -10,18 +10,9 @@ export async function getGuildSetting(guildID: string): Promise<GuildSetting> {
if (!guildSetting) { if (!guildSetting) {
guildSetting = new GuildSetting(); guildSetting = new GuildSetting();
guildSetting.id = guildID; guildSetting.id = guildID;
guildSetting.isPremiumUntil = null;
guildSetting.notificationChannelID = null; guildSetting.notificationChannelID = null;
guildSetting.preserveDataOnGuildLeave = false; guildSetting.preserveDataOnGuildLeave = false;
} }
return guildSetting; return guildSetting;
} }
export function isPremiumActive(timestamp: Date | null): boolean {
if (timestamp === null) return false;
const now = Number(new Date());
const activeUntil = Number(timestamp);
return now < activeUntil;
}

View File

@ -30,3 +30,14 @@ export function getFailedEmbed(): EmbedBuilder {
embed.setColor(Color.STOPSIGN_RED); embed.setColor(Color.STOPSIGN_RED);
return embed; return embed;
} }
export function getUserReportEmbed(guildName: string, channelName: string): EmbedBuilder {
const embed = getDefaultEmbed();
embed.setColor(Color.STOPSIGN_RED);
embed.setTitle(`${Emoji.SECURITY_CHALLENGE_FAILED} A channel you modified has been deleted`);
embed.setDescription(`Hey there ${Emoji.WAVING}
Your channel (#${channelName}) on the "${guildName}" server contained a blacklisted word and was deleted automatically.
Please make sure to keep channel names friendly for everyone!`);
return embed;
}

View File

@ -1,10 +1,25 @@
import { GuildBasedChannel } from "discord.js"; import { GuildBasedChannel, GuildTextBasedChannel, PermissionsBitField } from "discord.js";
import client from "../client"; import client from "../client";
export async function getGuildChannel(guildID: string, channelID: string): Promise<GuildBasedChannel | null> { export async function getGuildChannel(guildID: string, channelID: string): Promise<GuildBasedChannel | null> {
const guild = await client.guilds.fetch(guildID); try {
if (!guild) return null; const guild = await client.guilds.fetch(guildID);
if (!guild) return null;
const channel = await guild.channels.fetch(channelID); const channel = await guild.channels.fetch(channelID);
return channel; return channel;
} catch (_error) {
return null;
}
}
export async function getChannelPermission(channel: GuildTextBasedChannel): Promise<Readonly<PermissionsBitField> | null> {
try {
const guildMember = await channel.guild.members.fetchMe();
if (!guildMember) return null;
return channel.permissionsFor(guildMember);
} catch (error) {
return null;
}
} }