diff --git a/bun.lockb b/bun.lockb index b2e680d..7fd744c 100755 Binary files a/bun.lockb and b/bun.lockb differ diff --git a/package.json b/package.json index b181d40..e7a1a27 100644 --- a/package.json +++ b/package.json @@ -1,15 +1,23 @@ { - "name": "discord.ts-rewrite", + "name": "discord.ts", "module": "src/index.ts", "type": "module", + "main": "out/index.js", "scripts": { "test": "bun run testing/demo.test.ts", - "test:inspect": "bun --inspect testing/demo.test.ts" + "test:inspect": "bun --inspect testing/demo.test.ts", + "build": "bun run build:types && bun build src/index.ts --outdir out", + "build:types": "tsc --emitDeclarationOnly --project tsconfig.json --noCheck", + "build:watch": "concurrently \"tsc --emitDeclarationOnly --project tsconfig.json --noCheck --watch\" \"bun build src/index.ts --outdir out --watch\"" }, "devDependencies": { - "@types/bun": "latest" + "@types/bun": "latest", + "concurrently": "^9.1.0" }, "peerDependencies": { "typescript": "^5.0.0" + }, + "dependencies": { + "ws": "^8.18.0" } } \ No newline at end of file diff --git a/src/services/api.ts b/src/services/api.ts index 58f5a70..e1ce067 100644 --- a/src/services/api.ts +++ b/src/services/api.ts @@ -1,3 +1,4 @@ +import { exists, log } from "../utils"; import type { Client } from "./client"; export class API { @@ -32,6 +33,30 @@ export class API { // console.log(`API Body: ${JSON.stringify(data, null, 4)}`); // console.log('API Response:', JSON.stringify(body, null, 4)); + // Extract rate limit headers + const remaining = response.headers.get('X-RateLimit-Remaining'); + const limit = response.headers.get('X-RateLimit-Limit'); + const reset = response.headers.get('X-RateLimit-Reset'); + const resetSeconds = response.headers.get('X-RateLimit-Reset-After'); + const limitBucket = response.headers.get('X-RateLimit-Bucket'); + + // Log rate limit info for debugging + log(`Rate Limit: ${remaining}/${limit} - Reset: ${reset} (${resetSeconds}s) - Bucket: ${limitBucket}`); + + // If status is 429, we are being rate limited + if (response.status === 429) { + // Look for the retry-after header + const retryAfter = response.headers.get('Retry-After'); + if (exists(retryAfter)) { + // Wait for the retry-after time + await new Promise(resolve => setTimeout(resolve, parseInt(retryAfter) * 1000)); + } else { + // TODO: Handle this case better + // Maybe wait some arbitrary time?? + throw new Error('Rate limited without Retry-After header'); + } + } + return body; } diff --git a/src/services/hydrator.ts b/src/services/hydrator.ts index 5971a22..479ef81 100644 --- a/src/services/hydrator.ts +++ b/src/services/hydrator.ts @@ -38,11 +38,14 @@ export async function hydrate, K exte if (data instanceof Context) { for (const expectation of expectations) { - if (expectation === Expectation.Guild && exists(data.guild_id)) { + if (expectation === Expectation.Message && exists(data.message_id)) { + let context = data as unknown as HydratedContext<[Expectation.Message, ...Expectation[]]>; + context.message = await client.messages.get(data.channel_id, data.message_id); + } else if (expectation === Expectation.Guild && exists(data.guild_id)) { let context = data as unknown as HydratedContext<[Expectation.Guild, ...Expectation[]]>; context.guild = await client.guilds.get(data.guild_id); } else { - throw new Error(`Could not resolve expectation: ${expectation}`); + throw new Error(`Invalid expectation requested for Context: ${expectation}`); } } } else if (data instanceof Message) { @@ -54,7 +57,7 @@ export async function hydrate, K exte let message = data as unknown as HydratedMessage<[Expectation.Guild, ...Expectation[]]>; message.guild = await client.guilds.get(data.guild_id); } else { - throw new Error(`Could not resolve expectation: ${expectation}`); + throw new Error(`Invalid expectation requested for Message: ${expectation}`); } } } diff --git a/src/types/context.ts b/src/types/context.ts index 4b30ded..651a68f 100644 --- a/src/types/context.ts +++ b/src/types/context.ts @@ -102,8 +102,6 @@ export class Context { * @returns The message that was sent */ public reply = async (message: Message | string, reference: boolean = true): Promise => { - console.log('this.interaction', this.interaction) - if (isNil(this.message)) { throw new Error('Cannot reply without a message'); } diff --git a/src/types/message.ts b/src/types/message.ts index acc1a96..5958890 100644 --- a/src/types/message.ts +++ b/src/types/message.ts @@ -1,4 +1,4 @@ -import { isNil } from '../utils'; +import { exists, isNil } from '../utils'; import { GatewayObject } from './base'; import { fromDiscord, Trait, type Expectation, type Expects } from './common'; import { Embed } from './embed'; @@ -125,9 +125,17 @@ export class Message extends GatewayObject { this.channel_id = data?.channel_id; this.guild_id = data?.guild_id; this.content = data?.content ?? ''; + this.message_reference = data?.message_reference; this.timestamp = data?.timestamp; }; + // NOTE: Overriden here because the `fromDiscord` method returns a `MessagePayload` object + // and the GatewayObject getter overrides the return type to `Message` + // TODO: Fix type in GatewayObject so this override is not needed + public static get fromDiscord() { + return this[Trait.fromDiscord]; + } + public static [Trait.fromDiscord](data: DiscordMessage): T { return new Message({ id: data.id, @@ -135,6 +143,15 @@ export class Message extends GatewayObject { channel_id: data.channel_id, guild_id: data.guild_id, content: data.content, + // TODO: Add embeds + // embeds: data.embeds.map(embed => Embed.fromDiscord(embed)), + // TODO: Add components + // components: data.components, + message_reference: exists(data.message_reference) ? { + id: data.message_reference.message_id, + channel_id: data.message_reference.channel_id, + guild_id: data.message_reference.guild_id + } : undefined, timestamp: new Date(data.timestamp) }) as T; }; diff --git a/testing/demo.test.ts b/testing/demo.test.ts index 7d485ab..6dc6af5 100644 --- a/testing/demo.test.ts +++ b/testing/demo.test.ts @@ -10,7 +10,7 @@ const client = new Client({ Intent.GUILD_MESSAGE_REACTIONS, Intent.MESSAGE_CONTENT ], - prefix: '??' + prefix: '!' }); // Register arbitrary event handler to the client bus @@ -105,25 +105,4 @@ client.chatCommands.register('here', async (context: Context, _args: any[]) => { } }); -// Quote command -client.chatCommands.register('quote', async (context: Context, _args: any[]) => { - const { message } = await context.hydrate(context, [Expectation.Message]); - const reference = (await context.hydrator(message, [Expectation.Message]))(message); - - let reply: MessagePayload; - - if (reference) { - reply = await context.reply(`> "${message.reference.content}"\n> — ${message.reference.author.display_name ?? message.reference.author.username}`, true); - // Save to quote database - // TODO - } else { - reply = await context.reply('No message to quote', true); - } - - // Wait 3 seconds then delete the quote - setTimeout(() => { - context.deleteMessage(reply.id); - }, 3000); -}); - client.connect(); \ No newline at end of file diff --git a/tsconfig.json b/tsconfig.json index 238655f..54f8459 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,4 +1,6 @@ { + "files": ["src/index.ts"], + "include": ["src/**/*.ts", "src/**/*.tsx"], "compilerOptions": { // Enable latest features "lib": ["ESNext", "DOM"], @@ -8,11 +10,14 @@ "jsx": "react-jsx", "allowJs": true, + "declaration": true, + "outDir": "out", + // Bundler mode "moduleResolution": "bundler", "allowImportingTsExtensions": true, "verbatimModuleSyntax": true, - "noEmit": true, + "emitDeclarationOnly": true, // Best practices "strict": true,