MechGen exposes a global MechGen object with a clean JavaScript API designed for programmatic use. Whether you are building a Discord bot, a web dashboard with user avatars, or an AI agent framework with visual identity, this guide covers every method you need and the patterns that work best in production.

The MechGen Global Object

When you load mechgen.app in a browser (or a headless browser like Puppeteer), the MechGen object is available on window. It provides eight methods that cover the full lifecycle: generation, state management, and export.

Let us walk through each one.

Core Methods

MechGen.fromSeed(string)

The workhorse for deterministic generation. Pass any string and get the same mech every time:

MechGen.fromSeed("my-discord-bot");
// Canvas now shows a specific mech that will never change for this seed

This is the method you want when identity consistency matters. Agent names, user IDs, email addresses, UUIDs — any string works as a seed. The internal hashing ensures even similar strings like "bot-1" and "bot-2" produce visually distinct results.

MechGen.randomize()

Generates a completely random mech with a random color palette:

MechGen.randomize();
// Every call produces a different mech

Use this when you want variety without caring about reproducibility. Good for “show me something new” buttons, random avatar assignment on first visit, or just exploring what the generator can produce.

MechGen.getState()

Returns a plain JavaScript object describing the current mech. This is your serialization method:

const state = MechGen.getState();
console.log(state);
// {
//   head: 2,
//   eyes: 5,
//   antenna: 1,
//   body: 0,
//   arms: 3,
//   legs: 4,
//   accessory: 7,
//   primaryColor: "#00e5ff",
//   secondaryColor: "#1a237e",
//   accentColor: "#ff4081",
//   bgColor: "#0a0a2e"
// }

Each part is an index (0-9) selecting from ten possible variants. Colors are hex strings. This state object is everything you need to recreate a mech exactly.

Practical use: Store this object in a database alongside a user or agent record. It is small (under 200 bytes as JSON) and fully describes the avatar.

MechGen.setState(object)

The inverse of getState(). Pass a partial or complete state object to update the mech:

// Change just the head and eyes, keep everything else
MechGen.setState({ head: 7, eyes: 3 });

// Set a full state from a database record
MechGen.setState({
  head: 2, eyes: 5, antenna: 1, body: 0,
  arms: 3, legs: 4, accessory: 7,
  primaryColor: "#00e5ff",
  secondaryColor: "#1a237e",
  accentColor: "#ff4081",
  bgColor: "#0a0a2e"
});

The method merges your input with the current state, so partial updates work. This is how you restore saved mechs or build custom editors on top of MechGen.

MechGen.getImageDataURL(size?)

Returns the current mech as a base64-encoded PNG data URL. The optional size parameter controls the output resolution in pixels (default is 512):

const dataURL = MechGen.getImageDataURL();      // 512x512
const small = MechGen.getImageDataURL(128);      // 128x128
const large = MechGen.getImageDataURL(1024);     // 1024x1024

// Use it directly in an <img> tag
document.querySelector("img").src = dataURL;

This is the primary method for extracting the avatar image programmatically. The data URL is a self-contained PNG that you can embed in HTML, send over an API, or write to a file.

MechGen.exportPNG()

Triggers a browser download of the current mech as a 512x512 PNG:

MechGen.exportPNG();
// Browser downloads "mech-avatar.png"

This is a convenience method for user-facing “Download” buttons. For programmatic use, getImageDataURL() gives you more flexibility.

MechGen.exportForPlatform(platform)

Downloads a PNG at the optimal resolution for a specific platform:

MechGen.exportForPlatform("discord");  // 512x512
MechGen.exportForPlatform("x");        // 400x400
MechGen.exportForPlatform("github");   // 460x460
MechGen.exportForPlatform("steam");    // 184x184
MechGen.exportForPlatform("youtube");  // 800x800
MechGen.exportForPlatform("twitch");   // 256x256

Each platform has different avatar size requirements. This method handles the sizing so you do not have to look up specs yourself.

Integration Patterns

Pattern 1: Discord Bot Avatar

A Discord bot that generates unique avatars for users based on their user ID:

// In your Discord bot command handler
const { Client, AttachmentBuilder } = require("discord.js");

// Using Puppeteer to access MechGen's API
async function getAvatarForUser(userId) {
  const page = await browser.newPage();
  await page.goto("https://mechgen.app");

  const dataURL = await page.evaluate((id) => {
    MechGen.fromSeed(id);
    return MechGen.getImageDataURL(512);
  }, userId);

  await page.close();

  // Convert data URL to Buffer for Discord
  const base64Data = dataURL.replace(/^data:image\/png;base64,/, "");
  return Buffer.from(base64Data, "base64");
}

client.on("messageCreate", async (message) => {
  if (message.content === "!mech") {
    const imageBuffer = await getAvatarForUser(message.author.id);
    const attachment = new AttachmentBuilder(imageBuffer, {
      name: "mech-avatar.png"
    });
    message.reply({ files: [attachment] });
  }
});

Every user gets a unique mech based on their Discord ID, and it is the same mech every time they run the command.

Pattern 2: Web Dashboard with Agent Avatars

For a web app that displays multiple AI agents, you can generate avatars client-side without any server round trips:

<script>
async function loadAgentAvatars(agents) {
  // Load MechGen in a hidden iframe
  const iframe = document.createElement("iframe");
  iframe.src = "https://mechgen.app";
  iframe.style.display = "none";
  document.body.appendChild(iframe);

  await new Promise(resolve => iframe.onload = resolve);

  const MG = iframe.contentWindow.MechGen;

  agents.forEach(agent => {
    MG.fromSeed(agent.id);
    const img = document.getElementById(`avatar-${agent.id}`);
    img.src = MG.getImageDataURL(128);
  });
}

loadAgentAvatars([
  { id: "analyst", name: "Data Analyst" },
  { id: "writer", name: "Content Writer" },
  { id: "reviewer", name: "Code Reviewer" }
]);
</script>

Pattern 3: Server-Side Generation with Playwright

For backends that need to generate avatars without a client browser, Playwright offers a clean approach:

const { chromium } = require("playwright");

class MechAvatarService {
  async init() {
    this.browser = await chromium.launch();
    this.context = await this.browser.newContext();
    this.page = await this.context.newPage();
    await this.page.goto("https://mechgen.app");
  }

  async generateAvatar(seed, size = 512) {
    return await this.page.evaluate(({ s, sz }) => {
      MechGen.fromSeed(s);
      return MechGen.getImageDataURL(sz);
    }, { s: seed, sz: size });
  }

  async generateCustomAvatar(state) {
    return await this.page.evaluate((st) => {
      MechGen.setState(st);
      return MechGen.getImageDataURL(512);
    }, state);
  }

  async close() {
    await this.browser.close();
  }
}

// Usage
const service = new MechAvatarService();
await service.init();

const avatar = await service.generateAvatar("my-bot");
const custom = await service.generateCustomAvatar({
  head: 4, eyes: 2, primaryColor: "#ff6600"
});

By keeping a single browser instance alive, you avoid the overhead of launching a new browser for each avatar. This pattern works well for API servers that generate avatars on demand.

Pattern 4: Slack Bot with Dynamic Avatars

Slack’s chat.postMessage API accepts an icon_url parameter. Combine this with a simple avatar endpoint:

// Express endpoint that serves mech avatars
app.get("/avatar/:seed.png", async (req, res) => {
  const dataURL = await mechService.generateAvatar(req.params.seed);
  const buffer = Buffer.from(
    dataURL.replace(/^data:image\/png;base64,/, ""),
    "base64"
  );
  res.type("png").send(buffer);
});

// When posting to Slack
await slack.chat.postMessage({
  channel: "#general",
  text: "Analysis complete. Here are the results...",
  username: "Data Analyst Bot",
  icon_url: "https://your-server.com/avatar/data-analyst.png"
});

State Persistence

If you want users to customize their mech and save it, the state object is your friend:

// Save to localStorage
MechGen.randomize(); // or let user customize
const state = MechGen.getState();
localStorage.setItem("myMech", JSON.stringify(state));

// Restore later
const saved = JSON.parse(localStorage.getItem("myMech"));
MechGen.setState(saved);

The state object is small enough to store in a database column, a cookie, a URL parameter, or even a QR code. It is a complete, portable description of any mech.

Transparent Backgrounds

For overlaying mechs on custom backgrounds, set the background color to transparent:

MechGen.fromSeed("overlay-bot");
MechGen.setColor("bgColor", "transparent");
const transparentPNG = MechGen.getImageDataURL(512);

The exported PNG will have a transparent background, ready for compositing in any design tool or UI.

What to Build Next

With these methods, you can add unique visual identity to any bot or agent system in minutes. The deterministic seed generation means you never have to store images — just store the seed string and regenerate on demand.

Explore the full MechGen generator to see what 10 million combinations look like, or start coding with the API right away.