Skip to content

Commit 3b06833

Browse files
committed
feat(bot): add GuildDelete handler
1 parent b1b4efc commit 3b06833

File tree

7 files changed

+58
-10
lines changed

7 files changed

+58
-10
lines changed

api/db/init.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@ export async function initTables() {
99
members INT,
1010
cooldown INT DEFAULT 30000,
1111
updates_enabled BOOLEAN DEFAULT FALSE,
12-
updates_channel_id VARCHAR(255) DEFAULT NULL
12+
updates_channel_id VARCHAR(255) DEFAULT NULL,
13+
is_in_guild BOOLEAN DEFAULT TRUE
1314
)
1415
`;
1516
const createUsersTable = `

api/db/queries/guilds.ts

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ export interface Guild {
1414

1515
export async function getGuild(guildId: string): Promise<[QueryError, null] | [null, Guild | null]> {
1616
return new Promise((resolve, reject) => {
17-
pool.query("SELECT * FROM guilds WHERE id = ?", [guildId], (err, results) => {
17+
pool.query("SELECT * FROM guilds WHERE id = ? AND is_in_guild = ?", [guildId, true], (err, results) => {
1818
if (err) {
1919
reject([err, null]);
2020
} else {
@@ -28,18 +28,20 @@ export async function updateGuild(guild: Omit<Guild, "cooldown" | "updates_enabl
2828
return new Promise((resolve, reject) => {
2929
pool.query(
3030
`
31-
INSERT INTO guilds (id, name, icon, members)
32-
VALUES (?, ?, ?, ?)
31+
INSERT INTO guilds (id, name, icon, members, is_in_guild)
32+
VALUES (?, ?, ?, ?, ?)
3333
ON DUPLICATE KEY UPDATE
3434
name = VALUES(name),
3535
icon = VALUES(icon),
36-
members = VALUES(members)
36+
members = VALUES(members),
37+
is_in_guild = VALUES(is_in_guild)
3738
`,
3839
[
3940
guild.id,
4041
guild.name,
4142
guild.icon,
4243
guild.members,
44+
true,
4345
],
4446
(err, results) => {
4547
if (err) {
@@ -52,6 +54,18 @@ export async function updateGuild(guild: Omit<Guild, "cooldown" | "updates_enabl
5254
});
5355
}
5456

57+
export async function removeGuild(guildId: string): Promise<[QueryError, null] | [null, true]> {
58+
return new Promise((resolve, reject) => {
59+
pool.query("UPDATE guilds SET is_in_guild = ? WHERE id = ?", [false, guildId], (err) => {
60+
if (err) {
61+
reject([err, null]);
62+
} else {
63+
resolve([null, true]);
64+
}
65+
});
66+
});
67+
}
68+
5569
export async function setCooldown(guildId: string, cooldown: number): Promise<[QueryError, null] | [null, Guild]> {
5670
return new Promise((resolve, reject) => {
5771
pool.query("UPDATE guilds SET cooldown = ? WHERE id = ?", [cooldown, guildId], (err, results) => {

api/index.ts

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import express, { type NextFunction, type Request, type Response } from "express";
22
import cors from "cors";
33
import path from "path";
4-
import { getBotInfo, getGuild, getUser, getUsers, initTables, pool, updateGuild, enableUpdates, disableUpdates, setCooldown, setUpdatesChannel, setXP, setLevel } from "./db";
4+
import { getBotInfo, getGuild, getUser, getUsers, initTables, pool, updateGuild, enableUpdates, disableUpdates, setCooldown, setUpdatesChannel, setXP, setLevel, removeGuild } from "./db";
55

66
const app = express();
77
const PORT = 18103;
@@ -43,6 +43,17 @@ app.post("/post/:guild", authMiddleware, async (req, res) => {
4343
}
4444
});
4545

46+
app.post('/post/:guild/remove', authMiddleware, async (req, res) => {
47+
const { guild } = req.params;
48+
const [err, results] = await removeGuild(guild);
49+
50+
if (err) {
51+
res.status(500).json({ message: "Internal server error" });
52+
} else {
53+
res.status(200).json(results);
54+
}
55+
})
56+
4657
app.post("/post/:guild/:user", authMiddleware, async (req, res) => {
4758
const { guild, user } = req.params;
4859
const { name, pfp, xp, nickname } = req.body;
@@ -339,7 +350,7 @@ app.get("/leaderboard/:guild", async (req, res) => {
339350
const [usersErr, usersData] = await getUsers(guild);
340351

341352
if (!guildData) {
342-
return res.status(404).render("error", { error: { status: 404, message: "The guild does not exist" } });
353+
return res.status(404).render("error", { error: { status: 404, message: "The guild does not exist. If Chatr is no longer in this server, the data for this guild has been locked from public access" } });
343354
}
344355

345356
if (guildErr) {

api/views/error.ejs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,9 @@
2222
<div class="user">
2323
<div class="userInfo">
2424
<h1 class="userName">Message</h1>
25-
<h1>
25+
<p>
2626
<%= error.message %>
27-
</h1>
27+
</p>
2828
</div>
2929
</div>
3030
</div>

bot/events/guildRemove.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import { Events } from "discord.js";
2+
import client from "../index";
3+
import { removeGuild } from "../utils/requestAPI";
4+
5+
client.on(Events.GuildDelete, async (guild) => {
6+
try {
7+
await removeGuild(guild.id);
8+
console.log(`Left guild ${guild.name} with ${guild.memberCount} members. The database has been locked`);
9+
} catch (e) {
10+
console.error(e);
11+
}
12+
})

bot/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ const client = new Client({
1212
intents: [
1313
GatewayIntentBits.Guilds,
1414
GatewayIntentBits.GuildMessages,
15-
GatewayIntentBits.MessageContent,
15+
GatewayIntentBits.MessageContent
1616
]
1717
});
1818

bot/utils/requestAPI.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,16 @@ export async function updateGuildInfo(guild: string, name: string, icon: string,
5454
})
5555
}
5656

57+
export async function removeGuild(guild: string) {
58+
await fetch(`http://localhost:18103/post/${guild}/remove`, {
59+
headers: {
60+
'Content-Type': 'application/json',
61+
'Authorization': process.env.AUTH as string,
62+
},
63+
method: 'POST',
64+
})
65+
}
66+
5767
export async function setXP(guild: string, user: string, xp: number) {
5868
const response = await fetch(`http://localhost:18103/admin/set/${guild}/xp`, {
5969
"headers": {

0 commit comments

Comments
 (0)