### Execute Setup Commands Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/configuration.md Commands to install dependencies, configure secrets, provision infrastructure, and deploy the worker. ```bash # Install dependencies npm install # Set up secrets wrangler secret put DISCORD_BOT_TOKEN wrangler secret put REPLICATE_API_TOKEN # Create KV namespace wrangler kv:namespace create AVATAR_REMIX_FOLLOWUPS # Copy output to wrangler.toml # Create queue wrangler queues create avatar-remix-jobs # Enable in Cloudflare Dashboard if needed # Deploy npm run build wrangler publish # Register slash command curl -X POST https://avatar-remix-bot.yourname.workers.dev/register # Set Interactions Endpoint URL in Discord Developer Portal # https://avatar-remix-bot.yourname.workers.dev ``` -------------------------------- ### Invoke startInstructPix2Pix Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/instructPix2Pix.md Example usage of the function to start a job. ```typescript // Called by queue handler or esrganHandler await startInstructPix2Pix(job, env); ``` -------------------------------- ### Local Development Workflow Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/INDEX.md Commands for installing dependencies, configuring environment variables, and starting the local development server. ```bash # Install dependencies npm install # Copy and configure environment cp example.dev.vars .dev.vars # Edit .dev.vars with your credentials # Start local server on port 3000 npm start # In another terminal, test endpoint curl http://localhost:3000/ # Response: greetings ``` -------------------------------- ### Install dependencies Source: https://github.com/discord/avatar-remix-bot/blob/main/README.md Run this command to install the necessary Node.js dependencies for the project. ```bash npm install ``` -------------------------------- ### Deployment Output Example Source: https://github.com/discord/avatar-remix-bot/blob/main/README.md Expected output after a successful worker deployment. ```text Uploaded avatar-remix-bot (1.16 sec) Published avatar-remix-bot (0.67 sec) https://avatar-remix-bot..workers.dev Consumer for avatar-remix-jobs Current Deployment ID: f5d24e08-a211-4bae-a573-e513b5355910 ``` -------------------------------- ### Usage Example for startEsrgan Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/esrgan.md Demonstrates how to calculate the scale factor and trigger the upscaling process. ```typescript // Called by queue handler when image < 504px const scaleFactor = Math.ceil((504 - 1) / imageWidth); await startEsrgan(job, env, scaleFactor); ``` -------------------------------- ### Enqueue Job Example Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/types.md Example of creating a job object and sending it to the AVATAR_REMIX_JOBS queue. ```typescript // Enqueued to AVATAR_REMIX_JOBS queue const job: Job = { type: 'REMIX', url: 'https://cdn.discordapp.com/avatars/123/abc.png?size=512', prompt: 'make it spooky', strength: 7, seed: 987654321, interactionToken: 'webhook-token', targetUserId: '456', requesterUserId: '789' }; await env.AVATAR_REMIX_JOBS.send(job); ``` -------------------------------- ### Local Development Environment Variables Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/configuration.md Example content for the .dev.vars file used for local development configuration. ```text DISCORD_PUBLIC_KEY=... DISCORD_BOT_TOKEN=... DISCORD_APPLICATION_ID=... REPLICATE_API_TOKEN=... REPLICATE_INSTRUCT_PIX2PIX_MODEL_VERSION=... REPLICATE_ESRGAN_MODEL_VERSION=... WORKER_BASE_URL=http://localhost:3000 ``` -------------------------------- ### Register instructPix2PixHandler route Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/instructPix2Pix.md Example of registering the handler to a router endpoint. ```typescript router.post('/replicate/callback/pix2pix', instructPix2PixHandler); ``` -------------------------------- ### Register ESRGAN Callback Route Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/esrgan.md Example of registering the handler in the router. ```typescript router.post('/replicate/callback/esrgan', esrganHandler); ``` -------------------------------- ### JsonResponse Usage Example Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/util.md Demonstrates returning a JSON response for a Discord interaction. ```typescript return new JsonResponse({ type: InteractionResponseType.PONG, }); // Returns: { status: 200, headers: { 'content-type': 'application/json;charset=UTF-8' }, body: '{"type":1}' } ``` -------------------------------- ### Register Commands Route Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/interactions.md Example of mapping the register command handler to a POST route. ```typescript router.post('/register', registerCommandsHandler); ``` -------------------------------- ### Registering the Queue Consumer Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/queue.md Example of registering the queue handler within the index.ts file for the Cloudflare worker. ```typescript // In index.ts export default { fetch: router.fetch, queue: queueHandler, // registered as queue consumer }; // Consumer automatically calls queue() for each batch // Batch contains Job objects with type, url, prompt, etc. ``` -------------------------------- ### GET / Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/INDEX.md Performs a health check on the service. ```APIDOC ## GET / ### Description Performs a health check on the service. ### Method GET ### Endpoint / ``` -------------------------------- ### Interactions Route Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/interactions.md Example of mapping the main interactions handler to a POST route. ```typescript router.post('/', interactionsHandler); // Triggered when user runs /remix @user make it spooky // Enqueues job and returns deferred response ``` -------------------------------- ### interactionFollowup Usage Example Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/util.md Sends an ephemeral follow-up message to a user. ```typescript await interactionFollowup( 'Failed to remix the avatar. Please try again later.', job.interactionToken, env ); ``` -------------------------------- ### Example usage of getImageGuidanceFromPromptGuidance Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/instructPix2PixHelpers.md Shows that the function currently returns a fixed value regardless of input. ```typescript getImageGuidanceFromPromptGuidance(7) // → 1.5 getImageGuidanceFromPromptGuidance(20) // → 1.5 ``` -------------------------------- ### Initiate ESRGAN Upscaling Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/esrgan.md Defines the function signature for starting an ESRGAN prediction job. ```typescript async function startEsrgan(job: Job, env: Env, scaleFactor: number): Promise ``` -------------------------------- ### Define startInstructPix2Pix request payload Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/instructPix2Pix.md The structure of the payload sent to the Replicate API to start a prediction. ```typescript { version: string; // env.REPLICATE_INSTRUCT_PIX2PIX_MODEL_VERSION webhook_completed: string; // ${WORKER_BASE_URL}/replicate/callback/pix2pix?groupId=test input: { image: string; // URL to image to remix prompt: string; // User instruction (0-500 chars) negative_prompt?: string; // If USE_NEGATIVE_PROMPT=true num_inference_steps: number; // Always 50 guidance_scale: number; // From job.strength (1-20, default 7) image_guidance_scale: number; // 1.5 (fixed) schedule: string; // "K_EULER_ANCESTRAL" seed: number; // For reproducibility num_outputs: number; // Always 1 } } ``` -------------------------------- ### interactionStatus Usage Example Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/util.md Returns an ephemeral status message to the user. ```typescript return interactionStatus('one moment please...'); // Shows ephemeral status message to user ``` -------------------------------- ### Standard Function Documentation Template Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/README.md The required structure for documenting exported functions, including signature, parameters, return values, and usage examples. ```markdown ## Function Name Description ### Signature ```typescript function name(param: Type): ReturnType ``` ### Parameters | Name | Type | Default | Description | |------|------|---------|-------------| | param | Type | — | What it does | ### Returns Description of return value ### Example ```typescript // Real usage example ``` ``` -------------------------------- ### FetchError Usage Example Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/util.md Catches and handles a FetchError to inspect the response status. ```typescript try { await someApiCall(); } catch (error) { if (error instanceof FetchError) { console.error(error.response.status); } } ``` -------------------------------- ### throwFetchError Usage Example Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/util.md Throws a FetchError when a response is not successful. ```typescript if (!response.ok) { throwFetchError(response); } ``` -------------------------------- ### GET / Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/endpoints.md A simple health check endpoint that returns a greeting message to verify the service is running. ```APIDOC ## GET / ### Description Health check / greeting endpoint. ### Method GET ### Endpoint / ### Response #### Success Response (200) - **Body** (text/plain) - "greetings" ### Request Example curl https://avatar-remix-bot.yourname.workers.dev/ ``` -------------------------------- ### Access Env in Handlers Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/types.md Example of accessing environment variables and interacting with bindings within a route handler. ```typescript // In route handlers export async function handler(request: IRequest, env: Env) { const token = env.DISCORD_BOT_TOKEN; const applicationId = env.DISCORD_APPLICATION_ID; const replicateToken = env.REPLICATE_API_TOKEN; // Enqueue job await env.AVATAR_REMIX_JOBS.send(job); // Store in KV await env.AVATAR_REMIX_FOLLOWUPS.put(`replicateId:${id}`, JSON.stringify(job), { expirationTtl: 60 * 60 * 24 * 14 // 2 weeks }); } ``` -------------------------------- ### Example usage of getValidStrengthValue Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/instructPix2PixHelpers.md Demonstrates how various inputs are clamped or defaulted by the validation logic. ```typescript getValidStrengthValue(null) // → 7 getValidStrengthValue(undefined) // → 7 getValidStrengthValue('15') // → 15 getValidStrengthValue(25) // → 20 (clamped) getValidStrengthValue(0) // → 1 (clamped) getValidStrengthValue('abc') // → 7 (NaN) getValidStrengthValue('7.5') // → 7 (parseInt → 7) ``` -------------------------------- ### Deployment and Configuration Commands Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/INDEX.md Commands for setting up Cloudflare infrastructure, deploying the worker, and registering slash commands. ```bash wrangler kv:namespace create AVATAR_REMIX_FOLLOWUPS ``` ```bash wrangler queues create avatar-remix-jobs ``` ```bash npm run build && wrangler publish ``` ```bash curl -X POST https://avatar-remix-bot.yourname.workers.dev/register ``` -------------------------------- ### Build and Deployment Commands Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/INDEX.md Standard commands for type checking, linting, deploying the worker, and registering Discord commands. ```bash # Type check npm run build # Lint npm run lint # Deploy wrangler publish # Register commands curl -X POST https://avatar-remix-bot.yourname.workers.dev/register ``` -------------------------------- ### Configure wrangler.toml Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/types.md Configuration for environment variables and queue bindings in wrangler.toml. ```toml # wrangler.toml [vars] DISCORD_PUBLIC_KEY = '...' DISCORD_APPLICATION_ID = '...' WORKER_BASE_URL = 'https://avatar-remix-bot.yourname.workers.dev' REPLICATE_INSTRUCT_PIX2PIX_MODEL_VERSION = '...' REPLICATE_ESRGAN_MODEL_VERSION = '...' [[queues.producers]] binding = "AVATAR_REMIX_JOBS" [[queues.consumers]] queue = "avatar-remix-jobs" max_batch_size = 6 max_batch_timeout = 1 ``` -------------------------------- ### ANY * Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/endpoints.md Handles all unmatched routes by returning a 404 Not Found response. ```APIDOC ## ANY * ### Description Unmatched routes return a 404 status code. ### Method ANY ### Endpoint * ### Response #### Error Response (404) - **Body** (string) - "Not Found." ``` -------------------------------- ### Define basic Wrangler settings Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/configuration.md Basic configuration for the project name, entry point, and compatibility date in wrangler.toml. ```toml name = "avatar-remix-bot" main = "src/index.ts" compatibility_date = "2023-01-24" ``` -------------------------------- ### POST / Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/interactions.md Main handler for all Discord interactions including PING, slash commands, message components, and modal submissions. ```APIDOC ## POST / ### Description Main handler for all Discord interactions: ping verification, slash commands, message components, and modal submissions. ### Method POST ### Endpoint / ### Parameters #### Request Body - **request** (IRequest) - Required - HTTP request with Discord interaction payload - **env** (Env) - Required - Environment configuration - **context** (ExecutionContext) - Required - Cloudflare Workers execution context ### Response #### Success Response (200) - **response** (JSON) - Discord interaction response format (e.g., {type: 1} for PING) ``` -------------------------------- ### Create Cloudflare Queue Source: https://github.com/discord/avatar-remix-bot/blob/main/README.md Provisions a queue to manage Replicate rate limits during high traffic. ```bash wrangler queues create avatar-remix-jobs ``` -------------------------------- ### startEsrgan Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/esrgan.md Initiates an ESRGAN upscaling prediction with the Replicate API. This function constructs the request payload, authenticates via Bearer token, and stores the job metadata in KV storage. ```APIDOC ## startEsrgan ### Description Initiates an ESRGAN upscaling prediction with Replicate API. ### Signature `async function startEsrgan(job: Job, env: Env, scaleFactor: number): Promise` ### Parameters - **job** (Job) - Required - Job object with url, prompt, interactionToken, etc. - **env** (Env) - Required - Environment with Replicate token and callback URL - **scaleFactor** (number) - Required - Upscaling factor (2, 3, or 4) ### Request Payload Structure ```json { "version": "string", "webhook_completed": "string", "input": { "image": "string", "scale": "number", "face_enhance": "boolean" } } ``` ``` -------------------------------- ### POST /replicate/callback/pix2pix Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/INDEX.md Callback endpoint for InstructPix2Pix model completion. ```APIDOC ## POST /replicate/callback/pix2pix ### Description Callback endpoint for InstructPix2Pix model completion. ### Method POST ### Endpoint /replicate/callback/pix2pix ``` -------------------------------- ### Verify credentials and retry command registration Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/errors.md Use these commands to check secret configuration and manually trigger a slash command registration attempt. ```bash # Verify credentials wrangler secret list # Retry registration curl -X POST https://avatar-remix-bot.yourname.workers.dev/register ``` -------------------------------- ### InstructPix2Pix Replicate Request Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/INDEX.md Configuration object for requesting image remixes via the InstructPix2Pix model. ```javascript { version: REPLICATE_INSTRUCT_PIX2PIX_MODEL_VERSION, webhook_completed: `${WORKER_BASE_URL}/replicate/callback/pix2pix?groupId=test`, input: { image: job.url, prompt: job.prompt, guidance_scale: strength (1-20), image_guidance_scale: 1.5, num_inference_steps: 50, schedule: "K_EULER_ANCESTRAL", seed: job.seed } } ``` -------------------------------- ### POST /replicate/callback/esrgan Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/INDEX.md Callback endpoint for ESRGAN model completion. ```APIDOC ## POST /replicate/callback/esrgan ### Description Callback endpoint for ESRGAN model completion. ### Method POST ### Endpoint /replicate/callback/esrgan ``` -------------------------------- ### POST /replicate/callback/esrgan Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/endpoints.md Webhook endpoint for ESRGAN upscaling job completion callbacks from Replicate API. ```APIDOC ## POST /replicate/callback/esrgan ### Description Webhook endpoint for ESRGAN upscaling job completion callbacks from Replicate API. ### Method POST ### Endpoint /replicate/callback/esrgan ### Parameters #### Request Body - **id** (string) - Required - Prediction ID - **status** (string) - Required - Job status (succeeded, failed, or processing) - **output** (string) - Required - URL to the upscaled image ### Response #### Success Response (200) - **Body** (string) - "FAIL" or "OK" #### Error Response (404) - **Body** (string) - "No job found" ``` -------------------------------- ### InstructPix2Pix Callback Request Body Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/endpoints.md Expected JSON structure for the InstructPix2Pix job completion webhook. ```json { "id": "prediction-id", "status": "succeeded" | "failed" | "processing", "output": ["https://url-to-image.png"] } ``` -------------------------------- ### KV Storage Patterns Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/types.md Shows how jobs and ping tracking are stored in the KV store. ```typescript // In AVATAR_REMIX_FOLLOWUPS KV store replicateId:pred_abc123... → JSON.stringify(job) // TTL: 2 weeks // For tracking pings (prevent spam) pinged:targetUserId → '1' // TTL: 15 minutes ``` -------------------------------- ### Configure Cloudflare Queue Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/configuration.md Define producer and consumer settings for the queue in the wrangler configuration file. ```toml [[queues.producers]] queue = "avatar-remix-jobs" binding = "AVATAR_REMIX_JOBS" [[queues.consumers]] queue = "avatar-remix-jobs" max_batch_size = 6 max_batch_timeout = 1 ``` -------------------------------- ### Invoke sendResult after job completion Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/result.md Example usage of the sendResult function within a handler after a Replicate job finishes. ```typescript // Called by instructPix2PixHandler after Replicate job completes await sendResult(replicateId, imageUrl, job, env); // Results in Discord message: // @user remixed @targetuser's profile picture! // > **make it spooky** // _(remix strength: 7, seed: 123456789)_ // [Image attachment] // [♻️ remix the remix] [🎲 try it again] [✏️ edit instructions] ``` -------------------------------- ### getImageGuidanceFromPromptGuidance(promptGuidance) Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/instructPix2PixHelpers.md Calculates the image guidance scale based on the provided prompt guidance strength. ```APIDOC ## getImageGuidanceFromPromptGuidance(promptGuidance) ### Description Calculates image guidance scale from prompt guidance strength. Currently returns a fixed value of 1.5 regardless of input. ### Signature `getImageGuidanceFromPromptGuidance(promptGuidance: number): number` ### Parameters - **promptGuidance** (number) - Required - Prompt guidance scale (1-20) ### Returns - **number** - Fixed at 1.5 ``` -------------------------------- ### Configure wrangler.toml environment variables Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/INDEX.md Define these variables in your wrangler.toml file to configure the bot's connection to Discord and Replicate services. ```toml [vars] DISCORD_PUBLIC_KEY = "..." # From Discord portal DISCORD_APPLICATION_ID = "..." # From Discord portal WORKER_BASE_URL = "https://avatar-remix-bot.*.workers.dev" REPLICATE_INSTRUCT_PIX2PIX_MODEL_VERSION = "..." # From Replicate REPLICATE_ESRGAN_MODEL_VERSION = "..." # From Replicate ``` -------------------------------- ### POST /register Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/INDEX.md Registers slash commands with Discord. ```APIDOC ## POST /register ### Description Registers slash commands with Discord. ### Method POST ### Endpoint /register ``` -------------------------------- ### Real-ESRGAN Replicate Request Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/INDEX.md Configuration object for upscaling avatar images using the Real-ESRGAN model. ```javascript { version: REPLICATE_ESRGAN_MODEL_VERSION, webhook_completed: `${WORKER_BASE_URL}/replicate/callback/esrgan`, input: { image: job.url, scale: scaleFactor (2-4), face_enhance: true } } ``` -------------------------------- ### Queue Consumer Configuration Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/queue.md Configuration settings for the queue consumer in the wrangler.toml file. ```toml [[queues.consumers]] queue = "avatar-remix-jobs" max_batch_size = 6 # up to 6 messages per batch max_batch_timeout = 1 # dispatch after 1 second ``` -------------------------------- ### POST / Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/INDEX.md Webhook endpoint for receiving Discord interactions. ```APIDOC ## POST / ### Description Webhook endpoint for receiving Discord interactions. ### Method POST ### Endpoint / ``` -------------------------------- ### Create KV Namespace Source: https://github.com/discord/avatar-remix-bot/blob/main/README.md Creates a Workers KV namespace for tracking Replicate jobs. ```sh wrangler kv:namespace create AVATAR_REMIX_FOLLOWUPS ``` -------------------------------- ### Configure wrangler.toml Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/configuration.md Defines the Cloudflare Worker project settings, including KV namespaces, queue bindings, and environment variables. ```toml name = "avatar-remix-bot" main = "src/index.ts" compatibility_date = "2023-01-24" kv_namespaces = [ { binding = "AVATAR_REMIX_FOLLOWUPS", id = "abc123", preview_id = "xyz789" } ] [[queues.producers]] queue = "avatar-remix-jobs" binding = "AVATAR_REMIX_JOBS" [[queues.consumers]] queue = "avatar-remix-jobs" max_batch_size = 6 max_batch_timeout = 1 [vars] DISCORD_PUBLIC_KEY = "6ebc1a23ce676ede92f44f0bf943af50b87a75a693cbe3c1d2ccbf353eaa220c" DISCORD_APPLICATION_ID = "1083422468263387227" WORKER_BASE_URL = "https://avatar-remix-bot.yourname.workers.dev" REPLICATE_INSTRUCT_PIX2PIX_MODEL_VERSION = "30c1d0b916a6f8efce20493f5d61ee27491ab2a60437c13c588468b9810ec23f" REPLICATE_ESRGAN_MODEL_VERSION = "42fed1c4974146d4d2414e2be2c5277c7fcf05fcc3a73abf41610695738c1d7b" ``` -------------------------------- ### APPLICATION_COMMAND Interaction Request and Response Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/endpoints.md Processes slash commands and enqueues remix jobs. ```json { "type": 2, "token": "webhook-token", "member": {"user": {"id": "user-id"}}, "guild_id": "guild-id", "data": { "name": "remix", "options": [ {"name": "user", "value": "target-user-id"}, {"name": "instruction", "value": "make it spooky"}, {"name": "strength", "value": "7"}, {"name": "seed", "value": "123456789"}, {"name": "debug-url", "value": null} ], "resolved": { "users": {"target-user-id": {"avatar": "avatar-hash"}}, "members": {"target-user-id": {"avatar": "member-avatar-hash"}} } } } ``` ```json Status: 200 Content-Type: application/json { "type": 5 } ``` -------------------------------- ### Define startInstructPix2Pix signature Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/instructPix2Pix.md The function signature for initiating an InstructPix2Pix prediction job. ```typescript async function startInstructPix2Pix(job: Job, env: Env): Promise ``` -------------------------------- ### POST /register Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/INDEX.md Registers the Discord slash commands for the bot. ```APIDOC ## POST /register ### Description Registers the Discord slash commands for the bot to enable interaction within the Discord server. ### Method POST ### Endpoint https://avatar-remix-bot.yourname.workers.dev/register ``` -------------------------------- ### POST / Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/endpoints.md The main webhook endpoint for receiving Discord interactions. It requires signature verification using x-signature-ed25519 and x-signature-timestamp headers. ```APIDOC ## POST / ### Description Main Discord interactions webhook endpoint. Handles various interaction types including PING, APPLICATION_COMMAND, MESSAGE_COMPONENT, and MODAL_SUBMIT. ### Method POST ### Endpoint / ### Parameters #### Headers - **x-signature-ed25519** (string) - Required - Request signature for verification - **x-signature-timestamp** (string) - Required - Timestamp for signature validation ### Request Body - **payload** (object) - Required - Discord interaction payload (JSON) ### Response #### Success Response (200) - **type** (integer) - Response type based on interaction (e.g., 1 for PING, 5 for deferred, 9 for modal, 4 for channel message) ### Response Example { "type": 1 } ``` -------------------------------- ### PUT /applications/{id}/commands Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/INDEX.md Registers slash commands for the Discord application. ```APIDOC ## PUT /applications/{id}/commands ### Description Registers slash commands for the Discord application. ### Method PUT ### Endpoint /applications/{id}/commands ``` -------------------------------- ### Configure Cloudflare KV Namespace Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/configuration.md Define the KV namespace binding in the wrangler configuration file. ```toml kv_namespaces = [ { binding = "AVATAR_REMIX_FOLLOWUPS", id = "", preview_id = "" } ] ``` -------------------------------- ### Register Slash Commands Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/endpoints.md Triggers the registration of the /remix command with Discord. Call this after updating command definitions. ```bash curl -X POST https://avatar-remix-bot.yourname.workers.dev/register # Response: Registered commands ``` -------------------------------- ### POST /register Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/interactions.md Registers the /remix slash command with the Discord API. ```APIDOC ## POST /register ### Description Registers the /remix slash command with the Discord API. ### Method POST ### Endpoint /register ### Parameters #### Request Body - **request** (IRequest) - Required - HTTP request object - **env** (Env) - Required - Environment configuration with Discord credentials ### Response #### Success Response (200) - **message** (string) - "Registered commands" #### Error Response (500) - **error** (string) - Failure message ``` -------------------------------- ### Primary Job Flow: REMIX Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/architecture.md Visual representation of the REMIX job lifecycle from slash command input to final Discord webhook delivery. ```text User Input (slash command) ↓ Discord → POST / (interactionsHandler) ↓ Create Job {type: 'REMIX', url, prompt, strength, seed, ...} ↓ env.AVATAR_REMIX_JOBS.send(job) ↓ Queue Consumer (queueHandler) ↓ [Fetch & validate image] ↓ [Check size] ├─ Small (< 504px) → startEsrgan() │ ↓ │ Replicate ESRGAN │ ↓ │ POST /replicate/callback/esrgan │ ↓ │ [Update job.url with upscaled] │ ↓ │ startInstructPix2Pix() │ └─ Normal (≥ 504px) → startInstructPix2Pix() ↓ Replicate InstructPix2Pix ↓ POST /replicate/callback/pix2pix ↓ sendResult() ↓ POST to Discord webhook ↓ User sees result with buttons ``` -------------------------------- ### Discord Invite URL Template Source: https://github.com/discord/avatar-remix-bot/blob/main/README.md Template for constructing the OAuth2 invite URL for the Discord bot. ```text https://discord.com/oauth2/authorize?client_id=&scope=applications.commands+bot ``` -------------------------------- ### ESRGAN Callback Request Body Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/endpoints.md Expected JSON structure for the ESRGAN upscaling job completion webhook. ```json { "id": "prediction-id", "status": "succeeded" | "failed" | "processing", "output": "https://url-to-upscaled-image.png" } ``` -------------------------------- ### Set Secrets via Wrangler Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/types.md Commands to set sensitive API tokens as Cloudflare secrets. ```bash # Secrets (via wrangler secret put) wrangler secret put DISCORD_BOT_TOKEN wrangler secret put REPLICATE_API_TOKEN ``` -------------------------------- ### Define instructPix2PixHandler request body structure Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/instructPix2Pix.md The expected JSON structure for the incoming webhook request body from Replicate. ```typescript { id: string; // Replicate prediction ID status: string; // "succeeded", "failed", "processing", etc. output?: string[]; // Array of image URLs (typically 1 element) } ``` -------------------------------- ### Define public environment variables Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/configuration.md Public variables stored in the [vars] section of wrangler.toml or .dev.vars. ```toml [vars] DISCORD_PUBLIC_KEY = "..." DISCORD_APPLICATION_ID = "..." WORKER_BASE_URL = "..." REPLICATE_INSTRUCT_PIX2PIX_MODEL_VERSION = "..." REPLICATE_ESRGAN_MODEL_VERSION = "..." ``` -------------------------------- ### POST /replicate/callback/pix2pix Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/instructPix2Pix.md Webhook endpoint that receives completion callbacks from the Replicate API. It processes the prediction result, updates the job status, and triggers Discord notifications. ```APIDOC ## POST /replicate/callback/pix2pix ### Description Handles incoming completion callbacks from the Replicate API for InstructPix2Pix jobs. It verifies the job status and updates the system accordingly. ### Method POST ### Endpoint /replicate/callback/pix2pix ### Parameters #### Query Parameters - **groupId** (string) - Optional - Identifier for the job group. #### Request Body - **id** (string) - Required - Replicate prediction ID. - **status** (string) - Required - Status of the prediction (e.g., "succeeded", "failed"). - **output** (string[]) - Optional - Array of image URLs generated by the model. ### Response #### Success Response (200) - **OK** (string) - Returned if the callback was processed successfully. - **FAIL** (string) - Returned if the prediction failed or status is not "succeeded". ``` -------------------------------- ### Define NEGATIVE_PROMPT constant Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/instructPix2PixHelpers.md The default string used to instruct the model to avoid specific artifacts. ```typescript const NEGATIVE_PROMPT = 'duplication, duplicates, mutilation, deformed, mutilated, mutation, twisted body, disfigured, bad anatomy, out of frame, extra fingers, mutated hands, poorly drawn hands, extra limbs, malformed limbs, missing arms, extra arms, missing legs, extra legs, mutated hands, extra hands, fused fingers, missing fingers, extra fingers, rolling eyes, crossed eyes, weird eyes, smudged face, blurred face, poorly drawn face, mutation, mutilation, cloned face, grainy, blurred, blurry, writing, calligraphy, signature, text, watermark, bad art' ``` -------------------------------- ### Register Slash Commands Source: https://github.com/discord/avatar-remix-bot/blob/main/README.md Sends a POST request to the worker to register the /remix slash command. ```sh curl -X POST https://avatar-remix-bot..workers.dev/register ``` -------------------------------- ### sendResult Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/result.md Posts a completed remix image to Discord with action buttons and context, including saving job metadata and handling user mentions. ```APIDOC ## sendResult ### Description Posts a completed remix image to Discord with action buttons and context. This function handles saving job metadata to KV, determining user mentions, and sending the final message with image attachments and interactive buttons. ### Signature `async function sendResult(replicateId: string, imageUrl: string, job: Job, env: Env): Promise` ### Parameters - **replicateId** (string) - Required - Replicate prediction ID for component IDs. - **imageUrl** (string) - Required - URL to the generated image. - **job** (Job) - Required - Job object with metadata (prompt, requester, target user, etc.). - **env** (Env) - Required - Environment with Discord credentials and KV store. ### Returns - **Promise** - Resolves after Discord webhook call completes. ### Example ```typescript await sendResult(replicateId, imageUrl, job, env); ``` ``` -------------------------------- ### getValidStrengthValue(val) Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/instructPix2PixHelpers.md Validates and clamps the prompt guidance strength value to an acceptable range of 1 to 20. ```APIDOC ## getValidStrengthValue(val) ### Description Validates and clamps prompt guidance strength to an acceptable range. If the input is null, undefined, or invalid, it defaults to 7. ### Signature `getValidStrengthValue(val: string | number | null | undefined): number` ### Parameters - **val** (string | number | null | undefined) - Required - Raw strength value from user input ### Returns - **number** - Clamped value in the range [1, 20], defaulting to 7. ### Example ```typescript getValidStrengthValue(null) // → 7 getValidStrengthValue('15') // → 15 getValidStrengthValue(25) // → 20 (clamped) ``` ``` -------------------------------- ### REMIX_COMMAND Definition Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/interactions.md The configuration object defining the /remix slash command structure and options. ```typescript const REMIX_COMMAND = { name: 'remix', description: "Remix someone's profile picture", integration_types: [ApplicationIntegrationType.GuildInstall, ApplicationIntegrationType.UserInstall], contexts: [InteractionContextType.Guild, InteractionContextType.BotDM, InteractionContextType.PrivateChannel], options: [ { name: 'user', description: 'The user whose profile picture you want to remix', type: ApplicationCommandOptionType.User, required: true, }, { name: 'instruction', description: 'What change do you want to make to the profile picture?', type: ApplicationCommandOptionType.String, required: true, }, { name: 'strength', description: 'The strength of the prompt. Defaults to 7', type: ApplicationCommandOptionType.Number, required: false, min_value: 1.0, max_value: 20.0, }, { name: 'seed', description: 'Defaults to a random number', type: ApplicationCommandOptionType.Integer, required: false, min_value: 0, max_value: 1e9, }, { name: 'debug-url', description: 'Debug tool. Not for you!', type: ApplicationCommandOptionType.String, required: false, }, ], } ``` -------------------------------- ### Modal Response for Remix/Edit Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/endpoints.md Displays a modal to the user for remix or edit actions. ```json Status: 200 Content-Type: application/json { "type": 9, "data": { "title": "Remix your remix" | "Remix", "custom_id": "remix:replicate-id", "components": [ { "type": 1, "components": [ { "type": 4, "style": 1, "custom_id": "instructions", "label": "Instructions", "required": true, "min_length": 1, "max_length": 500 } ] } ] } } ``` -------------------------------- ### Define instructPix2PixHandler signature Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/instructPix2Pix.md The function signature for the HTTP webhook handler that processes Replicate API callbacks. ```typescript async function instructPix2PixHandler(request: IRequest, env: Env): Promise ``` -------------------------------- ### Publish Cloudflare Worker Source: https://github.com/discord/avatar-remix-bot/blob/main/README.md Deploys the worker application to Cloudflare. ```sh wrangler publish ``` -------------------------------- ### Perform Health Check Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/endpoints.md Use this endpoint to verify the worker is active and responding. ```bash curl https://avatar-remix-bot.yourname.workers.dev/ # Response: greetings ``` -------------------------------- ### Secondary Flow: Button Interactions Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/architecture.md Workflow for handling user button clicks and modal submissions for retry, remix, and edit operations. ```text User clicks button ↓ POST / (interactionsHandler) - MESSAGE_COMPONENT ↓ [Retrieve job from KV using replicateId] ├─ retry: → Show status, enqueue RETRY job ├─ remix: → Show modal, await modal submission └─ edit: → Show modal with strength field ↓ User submits modal ↓ POST / (interactionsHandler) - MODAL_SUBMIT ↓ [Parse instructions & strength] ↓ [Enqueue new job: REMIX_REMIX or REMIX_EDIT] ↓ [Queue consumer processes new job] ↓ [Send new result to Discord] ``` -------------------------------- ### Define Env Interface Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/types.md TypeScript interface defining the environment variables and Cloudflare bindings for the worker. ```typescript interface Env { AVATAR_REMIX_JOBS: Queue; AVATAR_REMIX_FOLLOWUPS: KVNamespace; DISCORD_PUBLIC_KEY: string; DISCORD_BOT_TOKEN: string; DISCORD_APPLICATION_ID: string; REPLICATE_API_TOKEN: string; REPLICATE_INSTRUCT_PIX2PIX_MODEL_VERSION: string; REPLICATE_ESRGAN_MODEL_VERSION: string; WORKER_BASE_URL: string; } ``` -------------------------------- ### Validate strength value with TypeScript Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/instructPix2PixHelpers.md Defines the function signature for clamping prompt guidance strength. ```typescript function getValidStrengthValue( val: string | number | null | undefined ): number ``` -------------------------------- ### esrganHandler Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/esrgan.md HTTP webhook handler that receives completion callbacks from the Replicate API for ESRGAN jobs. It retrieves job data from KV, processes the result, and triggers the next step in the pipeline. ```APIDOC ## POST /replicate/callback/esrgan ### Description HTTP webhook handler that receives completion callbacks from Replicate API for ESRGAN jobs. ### Method POST ### Parameters - **request** (IRequest) - Required - HTTP request with Replicate callback payload - **env** (Env) - Required - Environment configuration - **context** (ExecutionContext) - Required - Cloudflare Workers execution context ### Expected Request Body ```json { "id": "string", "status": "string", "output": "string" } ``` ### Response - **200 OK** - Callback processed successfully - **200 FAIL** - Prediction failed - **404** - No matching job found ``` -------------------------------- ### PING Interaction Request and Response Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/endpoints.md Handles the initial webhook handshake verification. ```json { "type": 1, "id": "...", "token": "..." } ``` ```json Status: 200 Content-Type: application/json { "type": 1 } ``` -------------------------------- ### EsrganOutput Interface Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/esrgan.md Internal interface representing the expected output format for ESRGAN jobs. ```typescript interface EsrganOutput { id: string; // Replicate prediction ID status: string; // Prediction status output?: string; // Upscaled image URL } ``` -------------------------------- ### POST /webhooks/{id}/{token} Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/INDEX.md Sends webhook messages to a Discord channel. ```APIDOC ## POST /webhooks/{id}/{token} ### Description Sends webhook messages to a Discord channel. ### Method POST ### Endpoint /webhooks/{id}/{token} ``` -------------------------------- ### Set required wrangler secrets Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/INDEX.md Use the wrangler CLI to securely store these sensitive tokens. ```text DISCORD_BOT_TOKEN # From Discord portal REPLICATE_API_TOKEN # From Replicate account ``` -------------------------------- ### Define USE_NEGATIVE_PROMPT constant Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/instructPix2PixHelpers.md Feature flag to enable or disable the negative prompt functionality. ```typescript const USE_NEGATIVE_PROMPT = true ``` -------------------------------- ### Calculate image guidance function signature Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/instructPix2PixHelpers.md Defines the function signature for calculating image guidance scale. ```typescript function getImageGuidanceFromPromptGuidance(promptGuidance: number): number ``` -------------------------------- ### Conditional negative prompt application Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/instructPix2PixHelpers.md Logic for conditionally including the negative prompt in API requests. ```typescript negative_prompt: USE_NEGATIVE_PROMPT ? job.negativePrompt || NEGATIVE_PROMPT : undefined ``` -------------------------------- ### Discord Request Verification Headers Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/INDEX.md Required headers for verifying incoming Discord interaction requests using the public key. ```typescript // All interaction requests include: // x-signature-ed25519: {signature} // x-signature-timestamp: {timestamp} // Verified using DISCORD_PUBLIC_KEY ``` -------------------------------- ### interactionFollowup Request Body Structure Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/util.md Shows the expected JSON structure for the webhook POST request. ```javascript { content: string, // message parameter flags: 64 // ephemeral flag (1 << 6) } ``` -------------------------------- ### Discord API Command Registration Request Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/endpoints.md The structure required for the Discord API call to register slash commands. ```http PUT https://discord.com/api/v10/applications/{DISCORD_APPLICATION_ID}/commands Authorization: Bot {DISCORD_BOT_TOKEN} Content-Type: application/json Body: [REMIX_COMMAND] // Single command in array ``` -------------------------------- ### Store secret tokens Source: https://github.com/discord/avatar-remix-bot/blob/main/README.md Use wrangler to securely store the Discord bot token and Replicate API token as secrets. ```bash wrangler secret put DISCORD_BOT_TOKEN ``` ```bash wrangler secret put REPLICATE_API_TOKEN ``` -------------------------------- ### Register Commands Handler Signature Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/interactions.md The function signature for registering slash commands with the Discord API. ```typescript async function registerCommandsHandler(request: IRequest, env: Env): Promise ``` -------------------------------- ### MODAL_SUBMIT Interaction Request and Response Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/endpoints.md Handles form submissions from modals. ```json { "type": 5, "token": "webhook-token", "member": {"user": {"id": "user-id"}}, "data": { "custom_id": "remix:replicate-id", "components": [ { "type": 1, "components": [ {"type": 4, "custom_id": "instructions", "value": "new instructions"} ] }, { "type": 1, "components": [ {"type": 4, "custom_id": "strength", "value": "10"} ] } ] } } ``` ```json Status: 200 Content-Type: application/json { "type": 4, "data": { "content": "one moment please...", "flags": 64 } } ``` -------------------------------- ### Expected Webhook Request Body Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/esrgan.md The structure of the callback payload received from the Replicate API. ```typescript { id: string; // Replicate prediction ID status: string; // "succeeded", "failed", "processing", etc. output?: string; // Upscaled image URL (single image, not array) } ``` -------------------------------- ### interactionFollowup Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/util.md Sends a follow-up message to a Discord interaction via webhook. The message is ephemeral and only visible to the user who triggered the interaction. ```APIDOC ## POST https://discord.com/api/v10/webhooks/${DISCORD_APPLICATION_ID}/${interactionToken} ### Description Sends a follow-up message to a Discord interaction via webhook. The message is ephemeral (only visible to the user who triggered the interaction). ### Method POST ### Endpoint https://discord.com/api/v10/webhooks/${DISCORD_APPLICATION_ID}/${interactionToken} ### Parameters #### Path Parameters - **interactionToken** (string) - Required - Discord interaction token for webhook #### Request Body - **content** (string) - Required - The message content to send - **flags** (number) - Required - Set to 64 for ephemeral visibility ### Response #### Success Response (200) - **void** - Resolves after POST completes ``` -------------------------------- ### Interactions Handler Signature Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/interactions.md The function signature for the main Discord interaction handler. ```typescript async function interactionsHandler( request: IRequest, env: Env, context: ExecutionContext ): Promise ``` -------------------------------- ### Define Name Interface Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/README.md Interface definition for the Name type used within the project. ```typescript interface Name { ... } ``` -------------------------------- ### Define Environment Interface Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/configuration.md TypeScript interface for type-safe access to environment bindings within the worker. ```typescript interface Env { // KV Store AVATAR_REMIX_FOLLOWUPS: KVNamespace; // Queue AVATAR_REMIX_JOBS: Queue; // Discord DISCORD_PUBLIC_KEY: string; DISCORD_BOT_TOKEN: string; DISCORD_APPLICATION_ID: string; // Replicate REPLICATE_API_TOKEN: string; REPLICATE_INSTRUCT_PIX2PIX_MODEL_VERSION: string; REPLICATE_ESRGAN_MODEL_VERSION: string; // URLs WORKER_BASE_URL: string; } ``` -------------------------------- ### ESRGAN Webhook Handler Signature Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/esrgan.md Defines the function signature for the HTTP callback handler. ```typescript async function esrganHandler( request: IRequest, env: Env, context: ExecutionContext ): Promise ``` -------------------------------- ### ESRGAN Request Payload Structure Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/esrgan.md The expected JSON structure for the Replicate API request. ```typescript { version: string; // env.REPLICATE_ESRGAN_MODEL_VERSION webhook_completed: string; // ${WORKER_BASE_URL}/replicate/callback/esrgan input: { image: string; // URL to image to upscale scale: number; // scaleFactor (2, 3, or 4) face_enhance: boolean; // Always true } } ``` -------------------------------- ### interactionStatus Response Structure Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/util.md Shows the JSON structure returned by interactionStatus. ```javascript { type: 4, // InteractionResponseType.CHANNEL_MESSAGE_WITH_SOURCE data: { content: string, // message parameter flags: 64 // ephemeral flag } } ``` -------------------------------- ### MESSAGE_COMPONENT Interaction Request Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/endpoints.md Handles button click interactions based on custom_id. ```json { "type": 3, "token": "webhook-token", "member": {"user": {"id": "user-id"}}, "data": { "custom_id": "retry:replicate-id" } } ``` -------------------------------- ### interactionStatus Function Definition Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/api-reference/util.md Defines the signature for creating an immediate status response. ```typescript function interactionStatus(message: string): JsonResponse ``` -------------------------------- ### REMIX Job Enqueue Structure Source: https://github.com/discord/avatar-remix-bot/blob/main/_autodocs/endpoints.md The data structure used when enqueuing a remix job to the queue. ```typescript { type: 'REMIX', url: 'https://cdn.discordapp.com/avatars/{userId}/{avatar}.png?size=512', prompt: instruction.trim().slice(0, 500), strength: strength || 7, seed: seed || Math.floor(Math.random() * 1e9), interactionToken: token, targetUserId: userId, requesterUserId: message.member?.user?.id || message.user?.id } ```