all repos — stealth-developers @ 9c88eb5426cd3c1798852ca45544c4486883809c

apps/bot/src/feats/guild-actor.ts (view raw)

 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
import type { Guild, OAuth2Guild } from "discord.js";

import { type Actor, upsertActor, upsertGuild } from "@stealth-developers/db";

import { client } from "@/client";
import { logger } from "@/lib";

const GUILD_ACTORS = new Map<string, Actor>();

export async function upsertGuildActor(guild: OAuth2Guild | Guild) {
	const member = await client.guilds.cache.get(guild.id)?.members.fetchMe();
	if (!member) return;

	const dbGuild = await upsertGuild({
		discordId: guild.id,
		icon: guild.iconURL(),
		name: guild.name,
	});
	if (!dbGuild) return;

	const actor = await upsertActor({
		moderator: true,
		guild: {
			discordId: guild.id,
			icon: guild.iconURL(),
			name: guild.name,
		},
		user: {
			discordId: member.user.id,
			username: member.user.username,
			displayName: member.displayName,
			avatar: member.user.avatarURL(),
		},
	});

	if (actor) GUILD_ACTORS.set(guild.id, actor);

	logger.info({ actor }, `upserted guild actor for ${guild.id} (${guild.name})`);
	return actor;
}

export function getGuildActor(guildId: string) {
	return GUILD_ACTORS.get(guildId);
}