Compare commits

..

2 Commits

Author SHA1 Message Date
a
542070a4cb
noot
Some checks failed
commit-tag / commit-tag-image (map[context:./migrations file:./migrations/Dockerfile name:migrations]) (push) Successful in 19s
commit-tag / commit-tag-image (map[context:./ts file:./ts/Dockerfile name:ts]) (push) Failing after 58s
2025-06-15 03:14:42 -05:00
a
a43c1959c0
noot 2025-06-15 02:20:47 -05:00
27 changed files with 554 additions and 148 deletions

View File

@ -0,0 +1,16 @@
-- Create Discord guild settings table for storing Discord guild configuration
CREATE TABLE IF NOT EXISTS discord.guild_settings (
guild_id Numeric NOT NULL, -- Discord guild ID
key TEXT NOT NULL,
value JSONB NOT NULL DEFAULT '{}',
PRIMARY KEY (guild_id, key)
);
-- Create index for faster lookups by guild_id
CREATE INDEX idx_discord_guild_settings_guild_id ON discord.guild_settings(guild_id);
-- Add comments for documentation
COMMENT ON TABLE discord.guild_settings IS 'Stores Discord guild-specific configuration settings as key-value pairs with JSONB values';
COMMENT ON COLUMN discord.guild_settings.guild_id IS 'Discord guild ID';
COMMENT ON COLUMN discord.guild_settings.key IS 'Setting key/name';
COMMENT ON COLUMN discord.guild_settings.value IS 'Setting value stored as JSONB for flexibility';

Binary file not shown.

View File

@ -49,7 +49,7 @@
"pino": "^9.6.0",
"pino-logfmt": "^0.1.1",
"pino-pretty": "^13.0.0",
"postgres": "^3.4.5",
"postgres": "^3.4.7",
"superjson": "^2.2.2",
"ts-markdown-builder": "^0.4.0",
"why-is-node-running": "^3.2.2",

View File

@ -1,27 +1,35 @@
import { type InteractionCallbackData, type InteractionCallbackOptions, InteractionResponseTypes, InteractionTypes, MessageFlags } from 'discordeno'
import { type InteractionCallbackData, type InteractionCallbackOptions, MessageFlags } from 'discordeno'
import { c } from '#/di'
import type { InteractionRef } from '#/discord'
import { InteractionResponseTypes } from '@discordeno/types'
import { Bot } from '#/discord/bot'
// from https://github.com/discordeno/discordeno/blob/21.0.0/packages/bot/src/transformers/interaction.ts#L33
export const reply_to_interaction = async (props: {
ref: InteractionRef
type: number
options: InteractionCallbackOptions & { isPrivate?: boolean; content?: string }
type: InteractionResponseTypes
options?: InteractionCallbackOptions & { isPrivate?: boolean; content?: string }
}) => {
const bot = await c.getAsync(Bot)
const { ref, type, options } = props
const data: InteractionCallbackData = options
const data: InteractionCallbackData = options || {}
if (options?.isPrivate) {
data.flags = MessageFlags.Ephemeral
}
if (ref.acknowledged) {
return await bot.helpers.sendFollowupMessage(ref.token, data)
switch (type) {
case InteractionResponseTypes.UpdateMessage:
if(ref.acknowledged) {
return await bot.helpers.editOriginalInteractionResponse(ref.token, data)
}
default:
if (ref.acknowledged) {
const followUp = await bot.helpers.sendFollowupMessage(ref.token, data)
return followUp
}
return await bot.helpers.sendInteractionResponse(ref.id, ref.token, { type, data }, { withResponse: options?.withResponse })
}
return await bot.helpers.sendInteractionResponse(ref.id, ref.token, { type, data }, { withResponse: options?.withResponse })
}

View File

@ -0,0 +1,61 @@
import { c } from '#/di'
import { PG } from '#/services/pg'
import { DiscordGuildSettingsService, DiscordGuildSettingKey, DiscordGuildSettingValue } from '#/services/guild_settings'
import { logger } from '#/logger'
export interface SetDiscordGuildSettingParams<K extends DiscordGuildSettingKey> {
guildId: bigint
key: K
value: DiscordGuildSettingValue<K>
}
export async function set_discord_guild_setting<K extends DiscordGuildSettingKey>(
params: SetDiscordGuildSettingParams<K>
): Promise<void> {
const settingsService = await c.getAsync(DiscordGuildSettingsService)
await settingsService.setSetting(params.guildId, params.key, params.value)
logger.info({
guildId: params.guildId,
key: params.key,
}, 'discord guild setting updated')
}
export async function get_discord_guild_setting<K extends DiscordGuildSettingKey>(
guildId: bigint,
key: K
): Promise<DiscordGuildSettingValue<K> | null> {
const settingsService = await c.getAsync(DiscordGuildSettingsService)
return await settingsService.getSetting(guildId, key)
}
export async function delete_discord_guild_setting(
guildId: bigint,
key: DiscordGuildSettingKey
): Promise<boolean> {
const settingsService = await c.getAsync(DiscordGuildSettingsService)
return await settingsService.deleteSetting(guildId, key)
}
export async function get_wynn_guild_info(guildNameOrTag: string): Promise<{ uid: string; name: string; prefix: string } | null> {
const { sql } = await c.getAsync(PG)
// Try to find by name or prefix (case-insensitive)
const result = await sql<{ uid: string; name: string; prefix: string }[]>`
SELECT uid, name, prefix
FROM wynn.guild_info
WHERE LOWER(name) = LOWER(${guildNameOrTag})
OR LOWER(prefix) = LOWER(${guildNameOrTag})
LIMIT 1
`
if (result.length === 0) {
return null
}
return result[0]
}

View File

@ -4,6 +4,7 @@
export * from './database'
export * from './discord'
export * from './discord_guild_settings'
export * from './guild'
export * from './guild_messages'
export * from './leaderboards'

View File

@ -6,58 +6,36 @@ import { WApi } from '#/lib/wynn/wapi'
import { PG } from '#/services/pg'
const playerSchemaFail = type({
code: 'string',
message: 'string',
data: type({
player: {
meta: {
cached_at: 'number',
},
username: 'string',
id: 'string',
raw_id: 'string',
avatar: 'string',
skin_texture: 'string',
properties: [
{
name: 'string',
value: 'string',
signature: 'string',
},
],
name_history: 'unknown[]',
},
}),
success: 'false',
path: 'string',
errorMessage: 'string',
})
const playerSchemaSuccess = type({
code: 'string',
message: 'string',
data: type({
player: {
meta: {
cached_at: 'number',
},
username: 'string',
id: 'string',
raw_id: 'string',
avatar: 'string',
skin_texture: 'string',
properties: [
{
name: 'string',
value: 'string',
signature: 'string',
},
],
name_history: 'unknown[]',
},
}),
success: 'true',
id: 'string',
name: 'string',
})
const playerSchema = playerSchemaFail.or(playerSchemaSuccess)
const getUUIDForUsername = async (username: string) => {
const resp = await axios.get(`https://api.mojang.com/users/profiles/minecraft/${username}`, {
validateStatus: function (status) {
return status < 500;
},
})
if (resp.headers['content-type'] !== 'application/json') {
throw new Error('invalid content type')
}
log.info('response data', {data: resp.data})
const parsed = playerSchema.assert(resp.data)
if('errorMessage' in parsed) {
throw new Error(`error message: ${parsed.errorMessage}`)
}
const pid = parsed.id
// TODO: the pid is a uuid with no hyphens. add the hyphens back in.
return pid
}
export const scrape_online_players = async () => {
const api = await c.getAsync(WApi)
const raw = await api.get('/v3/player')
@ -77,19 +55,7 @@ export const scrape_online_players = async () => {
if (ans.length === 0) {
// the user doesn't exist, so we need to grab their uuid
try {
const resp = await axios.get(`https://playerdb.co/api/player/minecraft/${playerName}`, {
headers: {
'User-Agent': 'lil-robot-guy (a@tuxpa.in)',
},
})
const parsedPlayer = playerSchema.assert(resp.data)
if (!parsedPlayer.success) {
log.warn(`failed to get uuid for ${playerName}`, {
payload: parsedPlayer,
})
continue
}
const uuid = parsedPlayer.data.player.id
const uuid = await getUUIDForUsername(playerName)
// insert the user.
await sql`insert into minecraft.user (name, uid, server) values (${playerName}, ${uuid},${server})
on conflict (uid) do update set

View File

@ -6,8 +6,9 @@ import { config } from '#/config'
import { DISCORD_GUILD_ID } from '#/constants'
import { c } from '#/di'
import { Bot } from '#/discord/bot'
import { events } from '#/discord/botevent/handler'
import { SLASH_COMMANDS } from '#/discord/botevent/slash_commands'
import { events } from '#/discord/handler'
import { SLASH_COMMANDS } from '#/discord/slash_commands'
import { logger } from '#/logger'
export class BotCommand extends Command {
static paths = [['bot']]
@ -17,12 +18,12 @@ export class BotCommand extends Command {
}
const bot = await c.getAsync(Bot)
bot.events = events()
console.log('registring slash commands')
await bot.rest.upsertGuildApplicationCommands(DISCORD_GUILD_ID, SLASH_COMMANDS).catch(console.error)
await bot.rest.upsertGuildApplicationCommands('547828454972850196', SLASH_COMMANDS).catch(console.error)
logger.info('registering slash commands')
await bot.rest.upsertGuildApplicationCommands(DISCORD_GUILD_ID, SLASH_COMMANDS).catch((err) => logger.error(err, 'failed to register slash commands for main guild'))
await bot.rest.upsertGuildApplicationCommands('547828454972850196', SLASH_COMMANDS).catch((err) => logger.error(err, 'failed to register slash commands for secondary guild'))
console.log('connecting bot to gateway')
logger.info('connecting bot to gateway')
await bot.start()
console.log('bot connected')
logger.info('bot connected')
}
}

View File

@ -6,12 +6,13 @@ import { c } from '#/di'
import '#/services/temporal'
import path from 'node:path'
import { Client, ScheduleNotFoundError, type ScheduleOptions, ScheduleOverlapPolicy } from '@temporalio/client'
import { NativeConnection, Worker } from '@temporalio/worker'
import { NativeConnection, Worker, Runtime } from '@temporalio/worker'
import { PG } from '#/services/pg'
import { workflowSyncAllGuilds, workflowSyncGuildLeaderboardInfo, workflowSyncGuilds, workflowSyncOnline } from '#/workflows'
import * as activities from '../activities'
import { config } from '#/config'
import { logger } from '#/logger'
const schedules: ScheduleOptions[] = [
{
@ -93,10 +94,11 @@ const addSchedules = async (c: Client) => {
const handle = c.schedule.getHandle(o.scheduleId)
try {
const desc = await handle.describe()
console.log(desc)
logger.info({ scheduleId: o.scheduleId, description: desc }, 'schedule already exists')
} catch (e: any) {
if (e instanceof ScheduleNotFoundError) {
await c.schedule.create(o)
logger.info({ scheduleId: o.scheduleId }, 'created schedule')
} else {
throw e
}
@ -107,15 +109,38 @@ const addSchedules = async (c: Client) => {
export class WorkerCommand extends Command {
static paths = [['worker']]
async execute() {
logger.info('starting worker')
// Install pino logger for Temporal
Runtime.install({
logger: {
log: (level, message, attrs) => {
const pinoLevel = level.toLowerCase()
if (pinoLevel in logger) {
(logger as any)[pinoLevel](attrs, message)
} else {
logger.info(attrs, message)
}
},
info: (message, attrs) => logger.info(attrs, message),
warn: (message, attrs) => logger.warn(attrs, message),
error: (message, attrs) => logger.error(attrs, message),
debug: (message, attrs) => logger.debug(attrs, message),
trace: (message, attrs) => logger.trace(attrs, message),
},
})
const { db } = await c.getAsync(PG)
const client = await c.getAsync(Client)
// schedules
logger.info('configuring schedules')
await addSchedules(client)
const connection = await NativeConnection.connect({
address: config.TEMPORAL_HOSTPORT,
})
logger.info({ address: config.TEMPORAL_HOSTPORT }, 'connected to temporal')
const worker = await Worker.create({
connection,
namespace: config.TEMPORAL_NAMESPACE,
@ -138,9 +163,10 @@ export class WorkerCommand extends Command {
stickyQueueScheduleToStartTimeout: 5 * 1000,
activities,
})
logger.info({ taskQueue: 'wynn-worker-ts', namespace: config.TEMPORAL_NAMESPACE }, 'starting temporal worker')
await worker.run()
console.log('worked.run exited')
logger.info('worker.run exited')
await db.end()
await connection.close()
}

View File

@ -2,12 +2,27 @@ import { InjectionToken } from '@needle-di/core'
import { createBot } from 'discordeno'
import { config } from '#/config'
import { c } from '#/di'
import { type BotType, createBotParameters } from './index'
import { logger } from '#/logger'
import { type BotType, desiredProperties, intents } from './index'
const createBotWithToken = (token: string) => {
return createBot({
...createBotParameters,
intents: intents.reduce((acc, curr) => acc | curr, 1 as any),
desiredProperties,
token,
loggerFactory: (name: 'REST' | 'GATEWAY' | 'BOT') => {
// Create a child logger with the component name
const childLogger = logger.child({ component: `discordeno-${name.toLowerCase()}` })
// Return logger object with required methods
return {
debug: (message: string, ...args: any[]) => childLogger.debug({ args }, message),
info: (message: string, ...args: any[]) => childLogger.info({ args }, message),
warn: (message: string, ...args: any[]) => childLogger.warn({ args }, message),
error: (message: string, ...args: any[]) => childLogger.error({ args }, message),
fatal: (message: string, ...args: any[]) => childLogger.fatal({ args }, message),
}
},
})
}
export const Bot = new InjectionToken<BotType>('DISCORD_BOT')

View File

@ -1,11 +0,0 @@
import type { BotType } from '#/discord'
export type BotEventsType = BotType['events']
export type InteractionHandler = NonNullable<BotType['events']['interactionCreate']>
export type InteractionType = Parameters<InteractionHandler>[0]
export type MuxHandler<T> = (interaction: InteractionType, params?: T) => Promise<any>
export interface SlashHandler {
[key: string]: MuxHandler<any> | SlashHandler
}

View File

@ -31,6 +31,8 @@ export const events = () => {
token: interaction.token,
type: interaction.type,
acknowledged: interaction.acknowledged,
guildId: interaction.guildId,
channelId: interaction.channel.id || interaction.channelId,
},
data,
},
@ -59,5 +61,5 @@ export const events = () => {
],
})
},
} as BotType['events']
} as const satisfies BotType['events']
}

View File

@ -1,5 +1,5 @@
import { Intents, type InteractionTypes } from '@discordeno/types'
import type { Bot, CompleteDesiredProperties, DesiredPropertiesBehavior, InteractionData } from 'discordeno'
import type { Bot, CompleteDesiredProperties, DesiredPropertiesBehavior, DiscordInteractionContextType, InteractionData, RecursivePartial, TransformersDesiredProperties } from 'discordeno'
export const intents = [
Intents.GuildModeration,
Intents.GuildWebhooks,
@ -18,42 +18,63 @@ export const intents = [
Intents.GuildMessages,
] as const
export const desiredProperties = {
interaction: {
id: true,
data: true,
type: true,
token: true,
message: true,
channelId: true,
channel: true,
guildId: true,
guild: true,
user: true,
member: true,
context: true,
},
message: {
id: true,
member: true,
guildId: true,
},
} as const satisfies RecursivePartial<TransformersDesiredProperties>
export type DesiredProperties = typeof desiredProperties
export const createBotParameters = {
intents: intents.reduce((acc, curr) => acc | curr, Intents.Guilds),
desiredProperties: {
interaction: {
id: true,
data: true,
type: true,
token: true,
message: true,
channelId: true,
channel: true,
guildId: true,
guild: true,
user: true,
member: true,
},
message: {
id: true,
member: true,
guildId: true,
},
},
desiredProperties,
} as const
// Extract the type of desired properties from our parameters
type ExtractedDesiredProperties = typeof createBotParameters.desiredProperties
// The BotType uses the CompleteDesiredProperties helper to fill in the missing properties
export type BotType = Bot<CompleteDesiredProperties<ExtractedDesiredProperties>, DesiredPropertiesBehavior.RemoveKey>
export type BotType = Bot<CompleteDesiredProperties<DesiredProperties>, DesiredPropertiesBehavior.RemoveKey>
// Type for the interaction reference passed to workflows/activities
export interface InteractionRef {
// id of the interaction
id: bigint
/** A continuation token for responding to the interaction */
token: string
type: InteractionTypes
acknowledged?: boolean
/** The guild it was sent from */
guildId?: bigint;
channelId?: bigint;
/** Guild member data for the invoking user, including permissions */
memberId?: bigint ;
/** User object for the invoking user, if invoked in a DM */
userId?: bigint;
/** For the message the button was attached to */
messageId?: bigint;
// locale of the interaction
locale?: string;
/** The guild's preferred locale, if invoked in a guild */
guildLocale?: string;
/** Context where the interaction was triggered from */
context?: DiscordInteractionContextType;
}
// Type for the complete interaction handling payload

View File

@ -1,4 +0,0 @@
import { c } from '#/di'
export class EventMux {
}

View File

@ -33,6 +33,14 @@ export const SLASH_COMMANDS = [
name: 'set_wynn_guild',
description: 'set the default wynncraft guild for the server',
type: ApplicationCommandOptionTypes.SubCommand,
options: [
{
name: 'guild',
description: 'the wynncraft guild',
type: ApplicationCommandOptionTypes.String,
required: true,
},
],
},
],
},

View File

@ -1,10 +1,12 @@
import { pino } from 'pino'
export const logger = pino({
transport: {
target: 'pino-logfmt',
},
level: process.env.PINO_LOG_LEVEL || 'info',
formatters: {
level: (label) => {
return { level: label }
},
},
timestamp: pino.stdTimeFunctions.isoTime,
redact: [], // prevent logging of sensitive data
})

View File

@ -0,0 +1,163 @@
import { type } from 'arktype'
import { c } from '#/di'
import { PG } from '#/services/pg'
import { logger } from '#/logger'
import { JSONValue } from 'postgres'
import { snowflake } from '#/utils/types'
import { inject } from '@needle-di/core'
// Define the guild settings types
export const DiscordGuildSettingSchema = type({
guild_id: 'string', // Discord guild ID
key: 'string',
value: 'unknown', // JSONB can be any valid JSON
})
export type DiscordGuildSetting = typeof DiscordGuildSettingSchema.infer
// Define setting schemas with arktype
export const DISCORD_GUILD_SETTING_SCHEMAS = {
wynn_guild: type('string.uuid'),
rank_roles: type({
member: snowflake.optional(),
recruiter: snowflake.optional(),
captain: snowflake.optional(),
strategist: snowflake.optional(),
chief: snowflake.optional(),
owner: snowflake.optional(),
}),
features: type({
autoRole: 'boolean',
warTracking: 'boolean',
activityTracking: 'boolean',
leaderboard: 'boolean',
}),
} as const
export type DiscordGuildSettingKey = keyof typeof DISCORD_GUILD_SETTING_SCHEMAS
export type DiscordGuildSettingValue<K extends DiscordGuildSettingKey> =
typeof DISCORD_GUILD_SETTING_SCHEMAS[K]['infer']
export class DiscordGuildSettingsService {
constructor(private readonly pg = inject(PG)) {}
/**
* Get a specific setting for a guild
*/
async getSetting<K extends DiscordGuildSettingKey>(
guildId: bigint,
key: K
): Promise<DiscordGuildSettingValue<K> | null> {
const { sql } = this.pg
const result = await sql<{ value: unknown }[]>`
SELECT value
FROM discord.guild_settings
WHERE guild_id = ${guildId.toString()} AND key = ${key}
`
if (result.length === 0) return null
// Validate the value with arktype
const schema = DISCORD_GUILD_SETTING_SCHEMAS[key]
const parsed = schema(result[0].value)
if (parsed instanceof type.errors) {
logger.error({ guildId, key, errors: parsed.summary }, 'Invalid guild setting value in database')
return null
}
return parsed as DiscordGuildSettingValue<K>
}
/**
* Get all settings for a guild
*/
async getAllSettings(guildId: bigint): Promise<DiscordGuildSetting[]> {
const { sql } = this.pg
const result = await sql<DiscordGuildSetting[]>`
SELECT guild_id, key, value
FROM discord.guild_settings
WHERE guild_id = ${guildId.toString()}
ORDER BY key
`
return result.map(row => DiscordGuildSettingSchema.assert(row))
}
/**
* Set a setting for a guild (upsert)
*/
async setSetting<K extends DiscordGuildSettingKey>(
guildId: bigint,
key: K,
value: DiscordGuildSettingValue<K>
): Promise<void> {
const { sql } = this.pg
// Validate the value with arktype
const schema = DISCORD_GUILD_SETTING_SCHEMAS[key]
const parsed = schema(value)
if (parsed instanceof type.errors) {
throw new Error(`Invalid value for guild setting ${key}: ${parsed.summary}`)
}
await sql`
INSERT INTO discord.guild_settings (guild_id, key, value)
VALUES (${guildId.toString()}, ${key}, ${sql.json(parsed as JSONValue)})
ON CONFLICT (guild_id, key)
DO UPDATE SET
value = EXCLUDED.value
`
logger.info({ guildId, key }, 'guild setting updated')
}
/**
* Delete a specific setting for a guild
*/
async deleteSetting(guildId: bigint, key: DiscordGuildSettingKey): Promise<boolean> {
const { sql } = this.pg
const result = await sql`
DELETE FROM discord.guild_settings
WHERE guild_id = ${guildId.toString()} AND key = ${key}
RETURNING 1
`
const deleted = result.length > 0
if (deleted) {
logger.info({ guildId, key }, 'guild setting deleted')
}
return deleted
}
/**
* Delete all settings for a guild
*/
async deleteAllSettings(guildId: bigint): Promise<number> {
const { sql } = this.pg
const result = await sql`
DELETE FROM discord.guild_settings
WHERE guild_id = ${guildId.toString()}
RETURNING 1
`
const count = result.length
if (count > 0) {
logger.info({ guildId, count }, 'guild settings deleted')
}
return count
}
}
// Register the service with dependency injection
c.bind(DiscordGuildSettingsService)

View File

@ -1,6 +1,7 @@
import { Client, Connection } from '@temporalio/client'
import { config } from '#/config'
import { c } from '#/di'
import { logger } from '#/logger'
c.bind({
provide: Client,
@ -17,7 +18,7 @@ c.bind({
},
})
process.on('exit', () => {
console.log('closing temporal client')
logger.info('closing temporal client')
client.connection.close()
})
return client

View File

@ -0,0 +1 @@
export * from './snowflake'

View File

@ -0,0 +1,15 @@
import { type } from 'arktype'
// Custom arktype for Discord snowflake IDs (bigint)
export const snowflake = type('string|bigint').pipe((value, ctx) => {
if (typeof value === 'bigint') return value
// Parse string as base 10 bigint
try {
return BigInt(value)
} catch {
return ctx.error(`Invalid snowflake ID: ${value}`)
}
})
export type Snowflake = bigint

View File

@ -2,10 +2,11 @@ import { InteractionTypes } from '@discordeno/types'
import { proxyActivities, startChild, workflowInfo } from '@temporalio/workflow'
import type * as activities from '#/activities'
import type { InteractionCreatePayload } from '#/discord'
import { CommandHandlers, createCommandHandler } from '#/discord/botevent/command_parser'
import { SLASH_COMMANDS } from '#/discord/botevent/slash_commands'
import { CommandHandlers, createCommandHandler } from '#/discord/command_parser'
import { SLASH_COMMANDS } from '#/discord/slash_commands'
import { handleCommandGuildInfo, handleCommandGuildLeaderboard, handleCommandGuildOnline } from './guild_messages'
import { handleCommandPlayerLookup } from './player_messages'
import { handleCommandSetWynnGuild } from './set_wynn_guild'
const { reply_to_interaction } = proxyActivities<typeof activities>({
startToCloseTimeout: '1 minute',
@ -73,14 +74,14 @@ const workflowHandleApplicationCommand = async (payload: InteractionCreatePayloa
},
admin: {
set_wynn_guild: async (args) => {
await reply_to_interaction({
ref,
type: 4,
options: {
content: 'Not implemented yet',
isPrivate: true,
},
const handle = await startChild(handleCommandSetWynnGuild, {
workflowId: `${workflowInfo().workflowId}-set-wynn-guild`,
args: [{
ref,
args,
}],
})
await handle.result()
},
},
},

View File

@ -3,17 +3,28 @@ import type * as activities from '#/activities'
import { WYNN_GUILD_ID } from '#/constants'
import type { InteractionRef } from '#/discord'
const { formGuildInfoMessage, formGuildOnlineMessage, formGuildLeaderboardMessage, reply_to_interaction } = proxyActivities<typeof activities>({
const { formGuildInfoMessage, formGuildOnlineMessage, formGuildLeaderboardMessage, reply_to_interaction, get_discord_guild_setting } = proxyActivities<typeof activities>({
startToCloseTimeout: '30 seconds',
})
interface CommandPayload {
ref: InteractionRef
discordGuildId?: bigint
}
export async function handleCommandGuildInfo(payload: CommandPayload): Promise<void> {
const { ref } = payload
const msg = await formGuildInfoMessage(WYNN_GUILD_ID)
const { ref, discordGuildId } = payload
// Try to get the associated Wynncraft guild for this Discord guild
let guildId = WYNN_GUILD_ID // Default fallback
if (discordGuildId) {
const wynnGuild = await get_discord_guild_setting(discordGuildId, 'wynn_guild')
if (wynnGuild?.uid) {
guildId = wynnGuild.uid
}
}
const msg = await formGuildInfoMessage(guildId)
await reply_to_interaction({
ref,
type: 4,
@ -22,8 +33,18 @@ export async function handleCommandGuildInfo(payload: CommandPayload): Promise<v
}
export async function handleCommandGuildOnline(payload: CommandPayload): Promise<void> {
const { ref } = payload
const msg = await formGuildOnlineMessage(WYNN_GUILD_ID)
const { ref, discordGuildId } = payload
// Try to get the associated Wynncraft guild for this Discord guild
let guildId = WYNN_GUILD_ID // Default fallback
if (discordGuildId) {
const wynnGuild = await get_discord_guild_setting(discordGuildId, 'wynn_guild')
if (wynnGuild?.uid) {
guildId = wynnGuild.uid
}
}
const msg = await formGuildOnlineMessage(guildId)
await reply_to_interaction({
ref,
type: 4,
@ -32,8 +53,18 @@ export async function handleCommandGuildOnline(payload: CommandPayload): Promise
}
export async function handleCommandGuildLeaderboard(payload: CommandPayload): Promise<void> {
const { ref } = payload
const msg = await formGuildLeaderboardMessage(WYNN_GUILD_ID)
const { ref, discordGuildId } = payload
// Try to get the associated Wynncraft guild for this Discord guild
let guildId = WYNN_GUILD_ID // Default fallback
if (discordGuildId) {
const wynnGuild = await get_discord_guild_setting(discordGuildId, 'wynn_guild')
if (wynnGuild?.uid) {
guildId = wynnGuild.uid
}
}
const msg = await formGuildLeaderboardMessage(guildId)
await reply_to_interaction({
ref,
type: 4,

View File

@ -8,3 +8,4 @@ export * from './guilds'
export * from './items'
export * from './player_messages'
export * from './players'
export * from './set_wynn_guild'

View File

@ -0,0 +1,81 @@
import { proxyActivities } from '@temporalio/workflow'
import type * as activities from '#/activities'
import type { InteractionRef } from '#/discord'
import { InteractionResponseTypes } from '@discordeno/types'
const { reply_to_interaction, set_discord_guild_setting, get_wynn_guild_info } = proxyActivities<typeof activities>({
startToCloseTimeout: '10 seconds',
})
export interface SetWynnGuildPayload {
ref: InteractionRef
args: {
guild: string
}
}
export async function handleCommandSetWynnGuild(payload: SetWynnGuildPayload): Promise<void> {
const { ref, args } = payload
// Defer the response since this might take a moment
await reply_to_interaction({
ref,
type: InteractionResponseTypes.DeferredChannelMessageWithSource,
})
ref.acknowledged = true
if (!ref.guildId) {
await reply_to_interaction({
ref,
type: InteractionResponseTypes.UpdateMessage,
options: {
content: `❌ Could not find discord guild. Please try again.`,
isPrivate: true,
},
})
return
}
try {
// Validate the Wynncraft guild exists
const guildInfo = await get_wynn_guild_info(args.guild)
if (!guildInfo) {
await reply_to_interaction({
ref,
type: InteractionResponseTypes.UpdateMessage, // Update the deferred response
options: {
content: `❌ Could not find Wynncraft guild "${args.guild}". Please check the guild name and try again.`,
isPrivate: true,
},
})
return
}
// Set the association in the database using the generic activity
await set_discord_guild_setting({
guildId: ref.guildId,
key: 'wynn_guild',
value: guildInfo.uid,
})
await reply_to_interaction({
ref,
type: InteractionResponseTypes.UpdateMessage, // Update the deferred response
options: {
content: `✅ Successfully linked this Discord server to Wynncraft guild **[${guildInfo.prefix}] ${guildInfo.name}**`,
isPrivate: true,
},
})
} catch (error) {
await reply_to_interaction({
ref,
type: InteractionResponseTypes.UpdateMessage, // Update the deferred response
options: {
content: `❌ An error occurred while setting the guild: ${error}`,
isPrivate: true,
},
})
}
}

View File

@ -1922,7 +1922,7 @@ __metadata:
pino: "npm:^9.6.0"
pino-logfmt: "npm:^0.1.1"
pino-pretty: "npm:^13.0.0"
postgres: "npm:^3.4.5"
postgres: "npm:^3.4.7"
rollup: "npm:^4.34.8"
superjson: "npm:^2.2.2"
ts-markdown-builder: "npm:^0.4.0"
@ -4178,10 +4178,10 @@ __metadata:
languageName: node
linkType: hard
"postgres@npm:^3.4.5":
version: 3.4.5
resolution: "postgres@npm:3.4.5"
checksum: 10c0/53415acea77e97bdc1eeb861048f34964e2236e4d4d42f408fc9b901e62bfcf7443a487ebfdad18b57b468c6e297bf8d22097106a200f62eb1262eb5a71355df
"postgres@npm:^3.4.7":
version: 3.4.7
resolution: "postgres@npm:3.4.7"
checksum: 10c0/b2e61b1064d38e7e1df8291f6d5a7e11f892a3240e00cf2b5e5542bf9abbfe97f3963164aeb56b42c1ab6b8aae3454c57f5bbc1791df0769375542740a7cde72
languageName: node
linkType: hard