Telegram Bot Integration

Build a Telegram bot that generates anime images with AnimeAPI

Prerequisites

  • Python 3.8+ installed
  • A Telegram account
  • An AnimeAPI key from your dashboard

Step 1: Create a Telegram Bot

  1. Open Telegram and search for @BotFather
  2. Send /newbot command
  3. Follow the prompts to name your bot
  4. Copy the bot token BotFather gives you (keep it secret!)

Step 2: Set Up Your Project

mkdir anime-telegram-bot
cd anime-telegram-bot
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
pip install python-telegram-bot requests python-dotenv

Create a .env file:

TELEGRAM_TOKEN=your_telegram_bot_token
ANIMEAPI_KEY=ank_your_api_key

Step 3: Write the Bot Code

Create bot.py:

import os
import requests
from dotenv import load_dotenv
from telegram import Update
from telegram.ext import Application, CommandHandler, ContextTypes

load_dotenv()

TELEGRAM_TOKEN = os.getenv("TELEGRAM_TOKEN")
ANIMEAPI_KEY = os.getenv("ANIMEAPI_KEY")

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Send welcome message when /start is issued."""
    await update.message.reply_text(
        "Welcome to AnimeAPI Bot! \n\n"
        "Use /anime <prompt> to generate anime images.\n"
        "Example: /anime cute anime girl with blue hair"
    )

async def anime(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Generate an anime image from the prompt."""
    if not context.args:
        await update.message.reply_text(
            "Please provide a prompt!\n"
            "Example: /anime cute anime girl"
        )
        return

    prompt = " ".join(context.args)

    # Send "generating" message
    status_msg = await update.message.reply_text("Generating your anime image...")

    try:
        # Call AnimeAPI
        response = requests.post(
            "https://api.animeapi.com/api/generate",
            headers={
                "Authorization": f"Bearer {ANIMEAPI_KEY}",
                "Content-Type": "application/json",
            },
            json={
                "prompt": prompt,
                "orientation": "portrait",  # portrait, square, or landscape
                "allowNSFW": True,
            },
        )

        data = response.json()

        if not response.ok:
            raise Exception(data.get("error", "Generation failed"))

        # Send the image
        await update.message.reply_photo(
            photo=data["image_url"],
            caption=f"Balance: ${data['balance_usd']:.2f}"
        )

        # Delete status message
        await status_msg.delete()

    except Exception as e:
        await status_msg.edit_text(f"Failed to generate image: {str(e)}")

async def credits(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Check remaining credits (by making a test request)."""
    await update.message.reply_text(
        "To check your credits, visit your AnimeAPI dashboard:\n"
        "https://animeapi.ai/dashboard"
    )

def main():
    """Start the bot."""
    application = Application.builder().token(TELEGRAM_TOKEN).build()

    # Add handlers
    application.add_handler(CommandHandler("start", start))
    application.add_handler(CommandHandler("anime", anime))
    application.add_handler(CommandHandler("credits", credits))

    # Run the bot
    print("Bot is running...")
    application.run_polling(allowed_updates=Update.ALL_TYPES)

if __name__ == "__main__":
    main()

Step 4: Run Your Bot

python bot.py

Your bot should now be online! Find your bot on Telegram and try /anime cute anime girl with cat ears.

Alternative: Node.js Version

If you prefer JavaScript, here's a Node.js version using telegraf:

npm install telegraf dotenv
require('dotenv').config();
const { Telegraf } = require('telegraf');

const bot = new Telegraf(process.env.TELEGRAM_TOKEN);
const ANIMEAPI_KEY = process.env.ANIMEAPI_KEY;

bot.start((ctx) => ctx.reply('Use /anime <prompt> to generate anime images!'));

bot.command('anime', async (ctx) => {
  const prompt = ctx.message.text.split(' ').slice(1).join(' ');

  if (!prompt) {
    return ctx.reply('Please provide a prompt! Example: /anime cute anime girl');
  }

  const statusMsg = await ctx.reply('Generating...');

  try {
    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);

    await ctx.replyWithPhoto(data.image_url, {
      caption: `Balance: $${data.balance_usd.toFixed(2)}`
    });
    await ctx.deleteMessage(statusMsg.message_id);
  } catch (error) {
    await ctx.telegram.editMessageText(
      ctx.chat.id,
      statusMsg.message_id,
      null,
      `Error: ${error.message}`
    );
  }
});

bot.launch();
console.log('Bot is running...');

API Options

The API supports these optional parameters:

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

You could add separate commands like /anime_landscape or use inline keyboards to let users choose orientation.

Tips

  • Add rate limiting to prevent abuse
  • Use inline mode for image generation in any chat
  • Add a /help command with usage instructions
  • Consider adding group chat support with cooldowns
  • Use webhooks instead of polling for production
  • Add inline keyboards to let users select orientation before generating

Ready to build your bot?

Get your API key and credits to start generating images.