Skip to content

Built for people who want to own their automations. Join the waitlist for an invite.

Package listing

@kody/discord

src/list-guilds.ts

42 lines · 1.4 KB · TypeScript
import { discordOauthRequest } from './oauth.ts'
import { inputRecord, optionalBoolean } from './validation.ts'

type DiscordGuild = {
	id?: string
	name?: string
	owner?: boolean
	permissions?: string
	approximate_member_count?: number
}

/**
 * List guilds the authorizing Discord user belongs to (OAuth `guilds` scope).
 *
 * User OAuth cannot read channel messages — use the bot-token lane for that.
 *
 * @param params.integration - OAuth integration name; default `discord`.
 */
export default async function listGuilds(params: Record<string, unknown> = {}) {
	const input = inputRecord(params)
	const withCounts = optionalBoolean(input, 'withCounts') === true
	const guilds = (await discordOauthRequest('/users/@me/guilds', input, {
		query: withCounts ? { with_counts: 1 } : undefined,
	})) as DiscordGuild[]

	if (!Array.isArray(guilds)) {
		throw new Error('Unexpected Discord guilds response; expected an array.')
	}

	return {
		lane: 'oauth' as const,
		count: guilds.length,
		guilds: guilds.map((guild) => ({
			id: typeof guild.id === 'string' ? guild.id : null,
			name: typeof guild.name === 'string' ? guild.name : null,
			owner: guild.owner === true,
			permissions: typeof guild.permissions === 'string' ? guild.permissions : null,
			approximateMemberCount:
				typeof guild.approximate_member_count === 'number' ? guild.approximate_member_count : null,
		})),
	}
}