Skip to content

Commit 983bd9e

Browse files
authored
feat(bot): sync on user updates (#372)
1 parent 36000e8 commit 983bd9e

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import type { SapphireClient } from '@sapphire/framework';
2+
import { Events } from 'discord.js';
3+
import { copyClass, emitEvent, mockUser } from '@answeroverflow/discordjs-mock';
4+
import { setupAnswerOverflowBot } from '~discord-bot/test/sapphire-mock';
5+
import {
6+
createDiscordAccount,
7+
findDiscordAccountById,
8+
} from '@answeroverflow/db';
9+
import { toAODiscordAccount } from '~discord-bot/utils/conversions';
10+
11+
let client: SapphireClient;
12+
13+
beforeEach(async () => {
14+
client = await setupAnswerOverflowBot();
15+
});
16+
17+
describe('Guild Member Update', () => {
18+
it('should update an existing user', async () => {
19+
const oldUser = mockUser(client, {
20+
username: 'old name',
21+
});
22+
await createDiscordAccount(toAODiscordAccount(oldUser));
23+
const newUser = copyClass(oldUser, client, {
24+
username: 'new name',
25+
});
26+
await emitEvent(client, Events.UserUpdate, oldUser, newUser);
27+
const updated = await findDiscordAccountById(oldUser.id);
28+
expect(updated).toBeDefined();
29+
expect(updated?.name).toBe('new name');
30+
});
31+
it("should not update a user that doesn't exist", async () => {
32+
const oldUser = mockUser(client, {
33+
username: 'old name',
34+
});
35+
const newUser = copyClass(oldUser, client, {
36+
username: 'new name',
37+
});
38+
await emitEvent(client, Events.UserUpdate, oldUser, newUser);
39+
const updated = await findDiscordAccountById(oldUser.id);
40+
expect(updated).toBeNull();
41+
});
42+
});
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import { ApplyOptions } from '@sapphire/decorators';
2+
import { Listener } from '@sapphire/framework';
3+
import { Events, User } from 'discord.js';
4+
import {
5+
findDiscordAccountById,
6+
updateDiscordAccount,
7+
} from '@answeroverflow/db';
8+
9+
@ApplyOptions<Listener.Options>({
10+
event: Events.UserUpdate,
11+
name: 'Sync On User Update',
12+
})
13+
export class SyncOnUserUpdate extends Listener<typeof Events.UserUpdate> {
14+
public async run(_: User, updated: User) {
15+
const existing = await findDiscordAccountById(updated.id);
16+
if (!existing) return;
17+
await updateDiscordAccount({
18+
id: updated.id,
19+
avatar: updated.avatar,
20+
name: updated.username,
21+
});
22+
}
23+
}

0 commit comments

Comments
 (0)