This repository has been archived by the owner on Mar 26, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.ts
210 lines (165 loc) · 4.91 KB
/
main.ts
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
const VERSION = "0.1.0";
const loadEnvs = () => {
const env: Record<string, unknown> = {};
const keys = [
{ key: "BOT_TOKEN", optional: false, fn: String },
{ key: "CATEGORY_ID", optional: false, fn: BigInt },
{ key: "DB_PATH", optional: false, fn: String },
{ key: "GUILD_ID", optional: false, fn: BigInt },
];
const none = [];
for (const { key, optional, fn } of keys) {
const value = Deno.env.get(key);
if (!value && !optional) {
none.push(key);
}
if (!value) {
continue;
}
env[key] = fn(value);
}
if (none.length !== 0) throw Error(`required environment values, ${none}`);
return env as {
BOT_TOKEN: string;
CATEGORY_ID: bigint;
DB_PATH: string;
GUILD_ID: bigint;
};
};
const { BOT_TOKEN, CATEGORY_ID, DB_PATH, GUILD_ID } = loadEnvs();
type Data = {
[userId: string]: { subscribed: string[] };
};
const db = {
path: DB_PATH,
save: async function (o: Data) {
const data = JSON.stringify(o);
await Deno.writeTextFile(this.path, data, { create: true });
},
load: async function (): Promise<Data> {
try {
const data = await Deno.readTextFile(this.path);
return JSON.parse(data);
} catch (e) {
if (e instanceof Deno.errors.NotFound) {
Deno.writeTextFile(this.path, "{}", { create: true });
return {};
}
throw e;
}
},
};
import * as discordeno from "https://deno.land/x/discordeno/mod.ts";
const bot = discordeno.createBot({
token: BOT_TOKEN,
intents: discordeno.Intents.DirectMessages |
discordeno.Intents.GuildMessages |
discordeno.Intents.MessageContent,
});
const channelIds = (await discordeno.getChannels(bot, GUILD_ID))
.filter((c) => c.parentId === CATEGORY_ID)
.map((c) => c.id);
type Handler = (
bot: discordeno.Bot,
message: discordeno.Message,
signal: unknown,
) => void | Promise<void>;
const ignoreBot: Handler = (_, m, s) => {
if (m.isFromBot) throw s;
};
const allowCategory: Handler = (_, m, s) => {
if (!channelIds.includes(m.channelId)) throw s;
};
const handleSubscribeCommand: Handler = async (b, m) => {
if (!m.content.startsWith("!sub")) return;
const n = m.content.replace("!sub", "").trim();
try {
const id = BigInt(n);
await discordeno.getChannel(b, id);
} catch {
await discordeno.sendMessage(b, m.channelId, {
content: `\`${n}\` という購読先は正しくないらしい.`,
messageReference: { failIfNotExists: false, channelId: m.channelId },
});
return;
}
const authorId = String(m.authorId);
const data = await db.load();
if (!data[authorId]) data[authorId] = { subscribed: [] };
data[authorId].subscribed.push(n);
await db.save(data);
await discordeno.sendMessage(b, m.channelId, {
content: "多分, 購読してる.",
messageReference: { failIfNotExists: false, channelId: m.channelId },
});
};
const handleUnsubscribeCommand: Handler = async (b, m) => {
if (!m.content.startsWith("!unsub")) return;
const n = m.content.replace("!unsub", "").trim();
try {
const id = BigInt(n);
await discordeno.getChannel(b, id);
} catch {
await discordeno.sendMessage(b, m.channelId, {
content: `\`${n}\` という購読先は正しくないらしい.`,
messageReference: { failIfNotExists: false, messageId: m.id },
});
return;
}
const authorId = String(m.authorId);
const data = await db.load();
if (!data[authorId]) data[authorId] = { subscribed: [] };
data[authorId].subscribed = data[authorId].subscribed.filter((s) => s !== n);
await db.save(data);
await discordeno.sendMessage(b, m.channelId, {
content: "多分, 購読してない.",
messageReference: { failIfNotExists: false, messageId: m.id },
});
};
const handleDefault: Handler = async (b, m) => {
const data = await db.load();
const userIds = [];
for (const [k, v] of Object.entries(data)) {
if (v.subscribed.includes(String(m.channelId))) userIds.push(k);
}
const author = await discordeno.getUser(b, m.authorId);
const url = b.helpers.getAvatarURL(author.id, author.discriminator, {
avatar: author.avatar,
format: "webp",
});
const embed: discordeno.Embed = {
author: {
name: author.username,
iconUrl: url,
},
color: 0x888888,
description: m.content,
timestamp: m.timestamp,
title: `<#${m.channelId}>`,
};
await Promise.all(
userIds.map(async (userId) => {
const channel = await b.helpers.getDmChannel(userId);
await discordeno.sendMessage(b, channel.id, { embeds: [embed] });
}),
);
};
const handlers: Handler[] = [
ignoreBot,
allowCategory,
handleSubscribeCommand,
handleUnsubscribeCommand,
handleDefault,
];
bot.events.messageCreate = async (bot, msg) => {
const obj = new Object();
for (const handle of handlers) {
try {
await handle(bot, msg, obj);
} catch (e) {
if (e === obj) break;
throw e;
}
}
};
await discordeno.startBot(bot);