diff --git a/src/command.ts b/src/command.ts index 4c4af41..29dd65e 100644 --- a/src/command.ts +++ b/src/command.ts @@ -1,5 +1,6 @@ import { DiscordImage, MJConfig } from "./interfaces"; - +import async from "async"; +import { sleep } from "./utils"; export const Commands = [ "ask", "blend", @@ -49,7 +50,7 @@ export class Command { include_applications: "true", }); const url = `${this.config.DiscordBaseUrl}/api/v9/guilds/${this.config.ServerId}/application-command-index`; - const response = await this.config.fetch(url, { + const response = await this.safeFetch(url, { headers: { authorization: this.config.SalaiToken }, }); @@ -65,15 +66,8 @@ export class Command { } async getCommand(name: CommandName) { - const searchParams = new URLSearchParams({ - type: "1", - query: name, - limit: "1", - include_applications: "true", - // command_ids: `${this.config.BotId}`, - }); - const url = `${this.config.DiscordBaseUrl}/api/v9/channels/${this.config.ChannelId}/application-commands/search?${searchParams}`; - const response = await this.config.fetch(url, { + const url = `${this.config.DiscordBaseUrl}/api/v9/guilds/${this.config.ServerId}/application-command-index`; + const response = await this.safeFetch(url, { headers: { authorization: this.config.SalaiToken }, }); const data = await response.json(); @@ -82,6 +76,39 @@ export class Command { } throw new Error(`Failed to get application_commands for command ${name}`); } + private safeFetch(input: RequestInfo | URL, init?: RequestInit | undefined) { + const request = this.config.fetch.bind(this, input, init); + return new Promise((resolve, reject) => { + this.fetchQueue.push( + { + request, + callback: (res: Response) => { + resolve(res); + }, + }, + (error: any, result: any) => { + if (error) { + reject(error); + } else { + resolve(result); + } + } + ); + }); + } + private async processFetchRequest({ + request, + callback, + }: { + request: () => Promise; + callback: (res: Response) => void; + }) { + const res = await request(); + callback(res); + await sleep(1000 * 4); + } + private fetchQueue = async.queue(this.processFetchRequest, 1); + async imaginePayload(prompt: string, nonce?: string) { const data = await this.commandData("imagine", [ {