-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.ts
More file actions
194 lines (163 loc) · 5.13 KB
/
bot.ts
File metadata and controls
194 lines (163 loc) · 5.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
import {
Client,
GatewayIntentBits,
REST,
Routes,
SlashCommandBuilder,
ActivityType,
Interaction,
ChatInputCommandInteraction,
} from "discord.js";
import axios from "axios";
import "dotenv/config";
const isDev = process.env.NODE_ENV === "development";
const EPHEMERAL_FLAG = 64;
type ProductAccess = {
product_id: number;
[key: string]: any;
};
type ProductResponse = {
data?: { name?: string };
name?: string;
[key: string]: any;
};
function getEnv(name: string): string {
const v = process.env[name];
if (!v) throw new Error(`Missing env var ${name}`);
return v;
}
const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers],
});
const commands = [
new SlashCommandBuilder()
.setName("products")
.setDescription("Show products bought by the user")
.toJSON(),
new SlashCommandBuilder()
.setName("sync")
.setDescription("Sync user roles based on purchased products")
.toJSON(),
];
const rest = new REST({ version: "10" }).setToken(getEnv("DISCORD_TOKEN"));
async function apiGet<T = any>(path: string): Promise<T> {
try {
const res = await axios.get(getEnv("API_BASE_URL") + path, {
headers: {
Authorization: `Bearer ${getEnv("API_TOKEN")}`,
},
});
if (isDev) {
console.log("API GET", path, "status", res.status, "response:", res.data);
}
return res.data as T;
} catch (err: any) {
if (axios.isAxiosError(err)) {
const status = err.response?.status;
const data = err.response?.data;
if (isDev) {
console.log("API GET ERROR", path, "status", status, "response:", data);
}
throw new Error(
`${status ?? "ERROR"} ${
typeof data === "string" ? data : JSON.stringify(data)
}`,
);
}
throw err;
}
}
async function getUserProductAccesses(
discordId: string,
): Promise<ProductAccess[]> {
const userId = await apiGet<string>(`/users/discord?id=${discordId}`);
const productAccessesRaw = await apiGet<any>(`/users/${userId}/accesses`);
return Array.isArray(productAccessesRaw)
? productAccessesRaw
: productAccessesRaw.data || [];
}
async function deployCommands(): Promise<void> {
await rest.put(Routes.applicationCommands(getEnv("CLIENT_ID")), {
body: commands,
});
console.log("Slash commands deployed");
}
client.once("clientReady", () => {
deployCommands().catch(console.error);
if (!client.user) return;
console.log(`Logged in as ${client.user.tag}`);
client.user.setPresence({
status: "online",
activities: [
{
name: "Checking purchases",
type: ActivityType.Watching,
},
],
});
});
client.on("interactionCreate", async (interaction: Interaction) => {
if (!interaction.isChatInputCommand()) return;
const cmd = interaction as ChatInputCommandInteraction;
if (cmd.commandName === "products") {
await cmd.deferReply({ flags: EPHEMERAL_FLAG });
try {
const productAccesses = await getUserProductAccesses(cmd.user.id);
if (productAccesses.length === 0) {
await cmd.editReply("You haven't purchased any products yet.");
return;
}
const productDetails = await Promise.all(
productAccesses.map((access) =>
apiGet<ProductResponse>(`/products/${access.product_id}`),
),
);
const productNames = productDetails
.map((product) => product.data?.name || product.name || "Unknown")
.join(", ");
await cmd.editReply(`**Purchased products:** ${productNames}`);
} catch (error) {
console.error(error);
await cmd.editReply(
"Failed to fetch products. Make sure your Discord is linked.",
);
}
} else if (cmd.commandName === "sync") {
await cmd.deferReply({ flags: EPHEMERAL_FLAG });
try {
const productAccesses = await getUserProductAccesses(cmd.user.id);
const targetProductId = parseInt(getEnv("PRODUCT_ID"), 10);
const hasProduct = productAccesses.some(
(access) => access.product_id === targetProductId,
);
if (!cmd.guild) {
await cmd.editReply("This command must be used in a server.");
return;
}
const member = await cmd.guild.members.fetch(cmd.user.id);
const role = await cmd.guild.roles.fetch(getEnv("DISCORD_ROLE_ID"));
if (!role) {
await cmd.editReply("Role not found in this server.");
return;
}
const hasRole = member.roles.cache.has(role.id);
if (hasProduct && !hasRole) {
await member.roles.add(role);
await cmd.editReply(`Role **${role.name}** has been added!`);
} else if (!hasProduct && hasRole) {
await member.roles.remove(role);
await cmd.editReply(`Role **${role.name}** has been removed.`);
} else if (hasProduct && hasRole) {
await cmd.editReply(`You already have the **${role.name}** role.`);
} else {
await cmd.editReply("You don't have access to this product.");
}
} catch (error) {
console.error(error);
await cmd.editReply(
"Failed to sync roles. Make sure your Discord is linked.",
);
}
}
});
client.login(getEnv("DISCORD_TOKEN"));