onlinecompiler.io

Build a Discord or Telegram bot that runs code

Members paste code in the chat and your bot answers with what it printed. The code runs in a sandbox on OnlineCompiler.io, never on your bot's server, in any of 46 languages, and the Free plan covers 100,000 runs a month.

How it works

A member writes !run and a code block. Your bot sends the code to the API, waits for the result (about a second for a short program) and replies with the output and any errors. The bot never runs the code itself, so a member's infinite loop or rm -rf can't touch your server.

  1. Sign in at OnlineCompiler.io and copy your API key from the API Keys page.
  2. Set it on your bot's server as ONLINECOMPILER_API_KEY, next to your bot token.
  3. Copy one of the bots below and run it.

A Discord bot in Python (discord.py)

The language after the three backticks picks the compiler. Text after the code block becomes the program's input. Turn on Message Content Intent for your bot in the Discord Developer Portal, or it can't read the code.

bot.py
# pip install discord.py aiohttp
import os
import re

import aiohttp
import discord

API = "https://api.onlinecompiler.io/api/run-code-sync/"
API_KEY = os.environ["ONLINECOMPILER_API_KEY"]

# The language written after ``` in a Discord code block, and the compiler that runs it.
COMPILERS = {
    "py": "python-3.14", "python": "python-3.14",
    "js": "nodejs-24", "javascript": "nodejs-24",
    "ts": "typescript-deno", "typescript": "typescript-deno",
    "c": "gcc-15", "cpp": "g++-15", "c++": "g++-15",
    "java": "openjdk-25", "cs": "dotnet-csharp-10", "csharp": "dotnet-csharp-10",
    "go": "go-1.26", "rs": "rust-1.93", "rust": "rust-1.93",
    "rb": "ruby-4.0", "ruby": "ruby-4.0", "php": "php-8.5",
    "kt": "kotlin-2.4", "kotlin": "kotlin-2.4", "lua": "lua-5.5",
    "sh": "bash-5.2", "bash": "bash-5.2",
}
BLOCK = re.compile(r"```([\w+#]*)\n(.*?)```", re.S)


async def run(compiler, code, stdin=""):
    """Run code on OnlineCompiler.io; return what it printed and its errors."""
    async with aiohttp.ClientSession() as session:
        async with session.post(API, headers={"Authorization": API_KEY},
                                json={"compiler": compiler, "code": code, "input": stdin},
                                timeout=aiohttp.ClientTimeout(total=60)) as response:
            answer = await response.json()
            if response.status != 200:
                return answer.get("error") or f"HTTP {response.status}"
    return (answer["output"] + answer["error"]).strip() or "(no output)"


intents = discord.Intents.default()
intents.message_content = True  # also turn on Message Content Intent in the Developer Portal
client = discord.Client(intents=intents)


@client.event
async def on_message(message):
    if message.author.bot or not message.content.startswith("!run"):
        return
    block = BLOCK.search(message.content)
    if block is None:
        await message.reply("Send !run with a code block, such as ```py\nprint('hi')\n```")
        return
    language, code = (block.group(1) or "py").lower(), block.group(2)
    compiler = COMPILERS.get(language)
    if compiler is None:
        await message.reply(f"I don't run {language} yet. Try py, js, java, c, cpp, go or rust.")
        return
    stdin = message.content[block.end():].strip()  # text after the block is the program's input
    result = await run(compiler, code, stdin)
    await message.reply(f"```\n{result[:1900]}\n```")  # a Discord message holds 2,000 characters


client.run(os.environ["DISCORD_TOKEN"])

A Discord bot in JavaScript (discord.js)

The same command for discord.js 14 on Node.js 18 or later, which has fetch built in.

bot.js
// npm install discord.js   (Node.js 18 or later)
const { Client, GatewayIntentBits } = require('discord.js');

const API = 'https://api.onlinecompiler.io/api/run-code-sync/';

// The language written after ``` in a Discord code block, and the compiler that runs it.
const COMPILERS = {
  py: 'python-3.14', python: 'python-3.14',
  js: 'nodejs-24', javascript: 'nodejs-24',
  ts: 'typescript-deno', typescript: 'typescript-deno',
  c: 'gcc-15', cpp: 'g++-15', 'c++': 'g++-15',
  java: 'openjdk-25', cs: 'dotnet-csharp-10', csharp: 'dotnet-csharp-10',
  go: 'go-1.26', rs: 'rust-1.93', rust: 'rust-1.93',
  rb: 'ruby-4.0', ruby: 'ruby-4.0', php: 'php-8.5',
  kt: 'kotlin-2.4', kotlin: 'kotlin-2.4', lua: 'lua-5.5',
  sh: 'bash-5.2', bash: 'bash-5.2',
};
const BLOCK = /```([\w+#]*)\n([\s\S]*?)```/;

// Run code on OnlineCompiler.io; return what it printed and its errors.
async function run(compiler, code, input = '') {
  const response = await fetch(API, {
    method: 'POST',
    headers: { Authorization: process.env.ONLINECOMPILER_API_KEY, 'Content-Type': 'application/json' },
    body: JSON.stringify({ compiler, code, input }),
    signal: AbortSignal.timeout(60_000),
  });
  const answer = await response.json();
  if (!response.ok) return answer.error ?? `HTTP ${response.status}`;
  return (answer.output + answer.error).trim() || '(no output)';
}

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

client.on('messageCreate', async (message) => {
  if (message.author.bot || !message.content.startsWith('!run')) return;
  const block = BLOCK.exec(message.content);
  if (!block) return message.reply("Send !run with a code block, such as ```py\nprint('hi')\n```");
  const language = (block[1] || 'py').toLowerCase();
  const compiler = COMPILERS[language];
  if (!compiler) return message.reply(`I don't run ${language} yet. Try py, js, java, c, cpp, go or rust.`);
  const input = message.content.slice(block.index + block[0].length).trim(); // text after the block is the input
  const result = await run(compiler, block[2], input);
  await message.reply('```\n' + result.slice(0, 1900) + '\n```'); // a Discord message holds 2,000 characters
});

client.login(process.env.DISCORD_TOKEN);

A Telegram bot (python-telegram-bot)

Telegram has no code blocks in commands, so the language goes on the first line and the code below it.

telegram_bot.py
# pip install python-telegram-bot aiohttp
import os

import aiohttp
from telegram import Update
from telegram.ext import Application, CommandHandler, ContextTypes

API = "https://api.onlinecompiler.io/api/run-code-sync/"
API_KEY = os.environ["ONLINECOMPILER_API_KEY"]
COMPILERS = {"py": "python-3.14", "js": "nodejs-24", "c": "gcc-15", "cpp": "g++-15",
             "java": "openjdk-25", "go": "go-1.26", "rust": "rust-1.93"}


async def run(compiler, code, stdin=""):
    """Run code on OnlineCompiler.io; return what it printed and its errors."""
    async with aiohttp.ClientSession() as session:
        async with session.post(API, headers={"Authorization": API_KEY},
                                json={"compiler": compiler, "code": code, "input": stdin},
                                timeout=aiohttp.ClientTimeout(total=60)) as response:
            answer = await response.json()
            if response.status != 200:
                return answer.get("error") or f"HTTP {response.status}"
    return (answer["output"] + answer["error"]).strip() or "(no output)"


async def run_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """/run py on the first line, the code on the lines below it."""
    first_line, _, code = update.message.text.partition("\n")
    words = first_line.split()
    language = words[1].lower() if len(words) > 1 else "py"
    if language not in COMPILERS or not code.strip():
        await update.message.reply_text("Send /run py, then your code on the next lines.")
        return
    result = await run(COMPILERS[language], code)
    await update.message.reply_text(result[:4000])  # a Telegram message holds 4,096 characters


app = Application.builder().token(os.environ["TELEGRAM_TOKEN"]).build()
app.add_handler(CommandHandler("run", run_command))
app.run_polling()

Limits worth knowing for a bot

  • The Free plan allows 60 runs a minute and 4 at once. Past that the API answers 429 with a Retry-After header, and the bots above reply with its message. On a busy server, give each member a short cooldown.
  • Each run has 30 seconds and no network access. Output is cut at 64 KB, and the bots cut it again to fit one chat message.
  • Keep the API key in an environment variable on the server. Never paste it into a chat or commit it.

Moving a bot from the public Piston API

The public Piston API at emkc.org has answered 401 to everyone but approved projects since 15 February 2026. If your bot was built on it, our Piston v2-compatible API takes the same requests, so the change is the base URL and a key:

Piston bots
# Before: the public Piston API (401 since 15 February 2026)
PISTON = "https://emkc.org/api/v2/piston"

# After: the same execute and runtimes requests and responses
PISTON = "https://api.onlinecompiler.io/api/v2/piston"
HEADERS = {"Authorization": "YOUR_API_KEY"}

More: why Piston answers 401 and the Piston-compatible API docs. Bots built on Judge0 can switch the same way: migrate from Judge0.

More you can build

The same API powers autograders, practice problems, runnable examples in docs and AI assistants that run code: 10 things you can build with OnlineCompiler.io.

Frequently asked questions

Is it free to run code from my bot?

Yes. The Free plan runs 100,000 programs a month, 60 a minute and 4 at once, with no credit card, and commercial use is included. A busy server can move to a paid plan later without changing the bot.

Can someone's code harm the server my bot runs on?

No. The code never runs on your server. Each run gets a new sandbox on ours with no network access, 512 MB of memory and a 30-second timeout, and the sandbox is destroyed afterwards. Your bot only sends text and gets text back.

Which languages can the bot run?

46 languages, including Python, JavaScript, TypeScript, Java, C, C++, C#, Go, Rust, Ruby, PHP, Kotlin, Lua and Bash. Add any compiler id from the docs to the COMPILERS table.

How do users give their program input?

In the Discord bots, anything written after the code block is sent as the program's standard input, so input() and scanf read it.

My bot used the public Piston API and now gets 401. What do I change?

Point its base URL at https://api.onlinecompiler.io/api/v2/piston and send your API key in the Authorization header. Piston's requests and responses stay the same.