Discord Bot Integration

Build a Discord bot that generates anime images with AnimeAPI

Prerequisites

  • Node.js 18+ installed
  • A Discord account and a server to test in
  • An AnimeAPI key from your dashboard

Step 1: Create a Discord Bot

  1. Go to the Discord Developer Portal
  2. Click "New Application" and give it a name
  3. Go to the "Bot" section and click "Add Bot"
  4. Copy your bot token (keep it secret!)
  5. Enable "Message Content Intent" under Privileged Gateway Intents
  6. Go to OAuth2 → URL Generator, select "bot" scope with "Send Messages" and "Attach Files" permissions
  7. Use the generated URL to invite the bot to your server

Step 2: Set Up Your Project

mkdir anime-discord-bot
cd anime-discord-bot
npm init -y
npm install discord.js

Create a .env file:

DISCORD_TOKEN=your_discord_bot_token
ANIMEAPI_KEY=ank_your_api_key

Step 3: Write the Bot Code

Create index.js:

require('dotenv').config();
const { Client, GatewayIntentBits, AttachmentBuilder } = require('discord.js');

const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent,
  ],
});

const ANIMEAPI_KEY = process.env.ANIMEAPI_KEY;

client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}`);
});

client.on('messageCreate', async (message) => {
  // Ignore bot messages
  if (message.author.bot) return;

  // Check for command
  if (!message.content.startsWith('!anime ')) return;

  const prompt = message.content.slice(7).trim();
  if (!prompt) {
    return message.reply('Please provide a prompt! Example: `!anime cute anime girl`');
  }

  // Send "generating" message
  const statusMsg = await message.reply('Generating your anime image...');

  try {
    // Call AnimeAPI
    const response = await fetch('https://api.animeapi.com/api/generate', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${ANIMEAPI_KEY}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        prompt,
        orientation: 'portrait', // portrait, square, or landscape
        allowNSFW: true,
      }),
    });

    const data = await response.json();

    if (!response.ok) {
      throw new Error(data.error || 'Generation failed');
    }

    // Download the image and send it
    const imageResponse = await fetch(data.image_url);
    const imageBuffer = Buffer.from(await imageResponse.arrayBuffer());
    const attachment = new AttachmentBuilder(imageBuffer, { name: 'anime.webp' });

    await statusMsg.edit({
      content: `Here's your anime image! (Balance: $${data.balance_usd.toFixed(2)})`,
      files: [attachment],
    });
  } catch (error) {
    console.error('Generation error:', error);
    await statusMsg.edit(`Failed to generate image: ${error.message}`);
  }
});

client.login(process.env.DISCORD_TOKEN);

Step 4: Run Your Bot

npm install dotenv
node index.js

Your bot should now be online! Try typing !anime cute anime girl with cat ears in your Discord server.

API Options

The API supports these optional parameters:

ParameterValuesDefault
orientationportrait (832x1280), square (1024x1024), landscape (1280x832)portrait
allowNSFWtrue, falsetrue

You could add command flags like !anime -landscape cute anime scene to let users choose orientation.

Tips

  • Add a cooldown to prevent spam (e.g., 1 request per 10 seconds per user)
  • Use slash commands for a better user experience
  • Store images locally or on a CDN for faster repeat access
  • Add error handling for rate limits (429 responses)
  • Consider adding a queue system for busy servers
  • Let users choose orientation with flags like -square or -landscape

Ready to build your bot?

Get your API key and credits to start generating images.