Injected API
Build your own app, bot or client on top of an Injected account. Injected keeps the IRC connections open; your code reads, sends and listens over plain HTTPS.
The API has two parts:
- REST endpoints that return JSON: list networks and channels, read message history, send messages, join channels, manage networks.
- A live event stream (Server-Sent Events) that delivers messages, joins, parts and connection changes as they happen.
Base URL for everything on this page:
https://injected-irc.com/api/v1
Requests are authenticated with an API token that the account owner creates. The API works from servers, command-line tools, desktop and mobile apps, and from browser pages on any origin.
Get a token
In Injected, open the user menu, choose Account settings, and find API tokens. Name the token, tick the permissions the app needs, pick an expiry, and confirm with your password. The token is shown once. It looks like this:
inj_pat_Jq3vX0m2c9K1fT7sYwB4uLhZ8eR5dN6aPgQoVtCiMxE
Each token carries one or more permissions (scopes):
| Scope | Allows |
|---|---|
read | Networks, channels, members, message history, and the live event stream. |
send | Sending messages, joining and leaving channels, changing nick, topic and away status, and sending raw IRC lines. |
manage | Adding, editing, removing, connecting and disconnecting networks. |
A request that needs a scope the token lacks gets 403 with code insufficient_scope. Ask for the smallest set that works: a dashboard that only displays chat needs read and nothing else.
- An account can hold up to 10 tokens. Use one per app, so one can be revoked without breaking the others.
- Revoking a token in Account settings takes effect immediately and closes its open event streams.
- Tokens keep working after a password change. Revoke them yourself if you think one has leaked.
- A token cannot change the account's password, email, two-factor settings or billing, and cannot create other tokens.
send token can talk on IRC as that user. Keep tokens out of source control and out of URLs.Quick start
Put your token in a variable, then try the three calls most integrations are built from.
export INJECTED_TOKEN="inj_pat_..."
1. List your networks and note the id of the one you want:
curl https://injected-irc.com/api/v1/networks \
-H "Authorization: Bearer $INJECTED_TOKEN"
2. Send a message to a channel on that network:
curl https://injected-irc.com/api/v1/networks/NETWORK_ID/messages \
-H "Authorization: Bearer $INJECTED_TOKEN" \
-H "Content-Type: application/json" \
-d '{"target": "#mychannel", "text": "hello from the API"}'
3. Watch what happens, live (-N stops curl from buffering):
curl -N https://injected-irc.com/api/v1/events \
-H "Authorization: Bearer $INJECTED_TOKEN"
Requests & errors
Send the token in the Authorization header on every request. Request bodies are JSON with Content-Type: application/json; responses are JSON.
Authorization: Bearer inj_pat_...
Errors always have the same shape. code is stable and meant for your program; error is a sentence for a person.
{ "error": "This token does not have the \"send\" scope", "code": "insufficient_scope" }
| Status | Code | Meaning |
|---|---|---|
| 400 | invalid_request | A parameter is missing or malformed. The message says which. |
| 401 | invalid_token | No token, or it is wrong, expired or revoked. |
| 403 | insufficient_scope | The token lacks the scope this endpoint needs. |
| 403 | plan_limit | The account's plan does not allow another network. |
| 404 | not_found | No such network, channel or endpoint. |
| 409 | not_connected | The network is not connected to IRC right now. |
| 409 | already_connected | Connect was called on a network that is connected or connecting. |
| 409 | bouncer_enabled | The network uses the ZNC backend and has to be deleted from Injected itself. |
| 429 | rate_limited | Too many requests. Wait Retry-After seconds. |
| 429 | too_many_streams | The token already has 5 event streams open. |
| 502 | worker_error | Injected could not carry out a connect, disconnect or reconnect. |
Rate limits
Each token may make 120 requests per minute. Within that, requests that put a line on IRC (everything under Sending, plus creating, editing, connecting and reconnecting a network) are limited to 30 per minute. Every response carries X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset (seconds until the window resets).
Accepted lines are also paced on their way to the IRC server, the same way messages typed in Injected are, so a burst of sends is delivered over a few seconds and not all at once.
Account
GET/me any scope
Who the token belongs to and what it may do. A good first call to check a token a user has pasted into your app.
{
"id": 42,
"username": "sam",
"plan": "free",
"token": {
"id": "0b6f6c1e-7a4e-4c69-9d0c-2f1f7c3f4f0a",
"name": "My IRC app",
"scopes": ["read", "send"],
"expiresAt": 1771200000000
}
}
All timestamps in the API are milliseconds since the Unix epoch. expiresAt is null for a token that does not expire.
Networks
A network is one IRC server the user has set up in Injected, together with its live connection. Its id is a string and appears in the path of most other endpoints.
GET/networks read
{
"networks": [
{
"id": "server-1731600000000-k3j9x1",
"name": "Libera.Chat",
"host": "irc.libera.chat",
"port": 6697,
"ssl": true,
"acceptInvalidCert": false,
"nickname": "sam",
"username": "",
"realname": "",
"saslUsername": "sam",
"hasPassword": false,
"hasSaslPassword": true,
"autoConnect": true,
"autoJoinChannels": ["#injected", "#linux"],
"performCommandCount": 0,
"keepNick": false,
"bouncer": false,
"floodProtection": { "enabled": true, "burstCount": 4, "burstInterval": 1500 },
"state": {
"status": "connected",
"nickname": "sam",
"modes": "+i",
"isOper": false,
"channelCount": 2,
"lastError": null
}
}
]
}
state.status is one of connected, connecting, reconnecting or disconnected. state.nickname is the nick the network actually gave the user, which can differ from the configured nickname.
Passwords are never returned. hasPassword and hasSaslPassword say whether one is stored, and perform commands are reported only as a count because they often contain one.
GET/networks/{id} read
One network, in the same shape as an entry of the list above.
Channels & members
GET/networks/{id}/channels read
The channels the user is in right now.
{
"channels": [
{ "name": "#injected", "topic": "Welcome", "topicSetBy": "dome", "modes": "+nt", "memberCount": 37 }
]
}
GET/networks/{id}/members?channel=%23injected read
Who is in a channel. Remember to URL-encode the # as %23. prefix is the highest status symbol (@, + and so on) and modes lists all of the member's channel modes.
{
"channel": "#injected",
"members": [
{ "nick": "dome", "prefix": "@", "modes": ["o"], "ident": "~dome", "hostname": "user/dome" },
{ "nick": "sam", "prefix": "", "modes": [], "ident": "~sam", "hostname": "203.0.113.7" }
]
}
GET/networks/{id}/buffers read
Everything that has message history: joined channels, and the nicks the user has exchanged private messages with.
{ "channels": ["#injected", "#linux"], "queries": ["alice", "nickserv"] }
Message history
GET/networks/{id}/messages read
| Parameter | Description |
|---|---|
target | Required. A channel (%23injected), a nick for private messages, or @status for server messages. |
limit | How many messages to return, 1 to 500. Default 100. |
before | A nextBefore value from an earlier response, to fetch the page before it. |
Without before you get the newest messages. Messages come back oldest first, ready to append to a chat view.
curl "https://injected-irc.com/api/v1/networks/NETWORK_ID/messages?target=%23injected&limit=50" \
-H "Authorization: Bearer $INJECTED_TOKEN"
{
"messages": [
{ "id": 918273, "target": "#injected", "type": "privmsg", "nick": "alice", "text": "morning", "timestamp": 1763200000123 },
{ "id": 918274, "target": "#injected", "type": "join", "nick": "bob", "text": "", "timestamp": 1763200004456 }
],
"nextBefore": "1763200000123_918273"
}
To page further back, repeat the request with before set to nextBefore. When nextBefore is null there is nothing older. Treat the cursor as opaque.
type is one of privmsg, action, notice, join, part, quit, kick, mode, nick, topic, motd, wallops or snotice. Some types carry extra fields, such as ident and hostname.
How far back history goes depends on the account's plan, and is empty for users who have turned logging off in their privacy settings.
Read state
Injected keeps one read marker per buffer and shares it between all of the user's clients. A marker is a time: lastReadTimestamp, in milliseconds since the Unix epoch. Everything in the buffer with a timestamp after it is unread. Using these endpoints, your client shows the same unread state as Injected's own apps, and reading a buffer in one clears it in the others.
GET/networks/{id}/read-state read
Every marker stored for the network. A buffer that is not listed has never been read.
{
"readState": [
{ "target": "#injected", "lastReadTimestamp": 1763200000123 },
{ "target": "alice", "lastReadTimestamp": 1763199990000 }
]
}
PUT/networks/{id}/read-state send
Marks one buffer as read up to a point in time. It needs the send scope because it changes what the user's other clients show, but it puts nothing on IRC: the network does not have to be connected, and it does not count toward the 30 per minute send limit.
| Field | Description |
|---|---|
target | Required. A channel, the other person's nick for a private conversation, or @status. Case does not matter. |
lastReadTimestamp | Usually the timestamp of the newest message the user has seen. Leave it out to mark the buffer read as of now. |
curl -X PUT https://injected-irc.com/api/v1/networks/NETWORK_ID/read-state \
-H "Authorization: Bearer $INJECTED_TOKEN" \
-H "Content-Type: application/json" \
-d '{"target":"#injected","lastReadTimestamp":1763200000123}'
{ "ok": true, "target": "#injected", "lastReadTimestamp": 1763200000123 }
- Markers only move forward. If another client has already read further, yours is ignored and the response carries the marker that stands, so always use the value you get back.
- A timestamp in the future is brought back to the server's current time.
- When a marker moves, whichever client moved it, every event stream gets a
read-stateevent. - Read state does not depend on stored history, so it works the same for users who have turned logging off.
Sending
All of these need the send scope, take a JSON body, need the network to be connected (otherwise 409 not_connected), and answer { "ok": true } once the command is queued for IRC. IRC itself answers asynchronously: watch the event stream for the result, for example a join event, or an error event if the channel is invite-only.
No value may contain a line break. One request is one IRC line.
POST/networks/{id}/messages send
| Field | Description |
|---|---|
target | Required. A channel or a nick. |
text | Required. One line, up to 400 bytes of UTF-8. |
type | message (default), action (a /me), or notice. |
curl https://injected-irc.com/api/v1/networks/NETWORK_ID/messages \
-H "Authorization: Bearer $INJECTED_TOKEN" \
-H "Content-Type: application/json" \
-d '{"target": "alice", "text": "waves", "type": "action"}'
Messages and actions are saved to the user's history and appear in their Injected clients, exactly as if they had typed them. The response includes the timestamp the message was recorded with.
POST/networks/{id}/join send
Body: { "channel": "#name", "key": "optional" }. The channel is also added to the network's auto-join list, so the user is back in it after a reconnect.
POST/networks/{id}/part send
Body: { "channel": "#name", "reason": "optional" }. Removes the channel from the auto-join list.
POST/networks/{id}/topic send
Body: { "channel": "#name", "topic": "New topic" }.
POST/networks/{id}/nick send
Body: { "nick": "newnick" }.
POST/networks/{id}/away send
Body: { "message": "back in an hour" }. Send an empty message, or no body, to come back.
POST/networks/{id}/raw send
Body: { "line": "WHOIS alice" }. Sends one raw IRC line, up to 510 bytes, for anything without its own endpoint. Replies arrive on the event stream; subscribe to the raw event to see numerics that have no event of their own.
Managing networks
These need the manage scope.
POST/networks manage
Adds a network and connects to it. Answers 201 with the new network.
| Field | Description |
|---|---|
host | Required. Hostname or IP address of the IRC server. It must be a public address: private, loopback and Injected's own addresses are refused. |
nickname | Required. |
name | Display name. Defaults to the host. |
port | Defaults to 6697 with TLS, 6667 without. Mail, SSH, HTTP and ident ports (22, 25, 80, 113, 465, 587) are refused. |
ssl | Use TLS. Default true. |
acceptInvalidCert | Accept a self-signed or expired certificate. |
password | Server password. |
username, realname | Optional identity fields. |
saslUsername, saslPassword | SASL login. |
autoConnect | Connect automatically. Default true. |
autoJoinChannels | Array of channel names to join on connect. |
performCommands | Array of raw IRC lines to send on connect. |
keepNick | Take the configured nick back whenever it frees up. |
floodProtection | { "enabled": true, "burstCount": 4, "burstInterval": 1500 } |
curl https://injected-irc.com/api/v1/networks \
-H "Authorization: Bearer $INJECTED_TOKEN" \
-H "Content-Type: application/json" \
-d '{"host": "irc.libera.chat", "nickname": "sam", "autoJoinChannels": ["#injected"]}'
{ "ok": true, "network": { "id": "server-1763200000000-9f2c1a7b", "name": "irc.libera.chat", "...": "..." } }
If the network was saved but connecting failed, ok is false and connectError says why. How many networks an account may have depends on its plan; one too many answers 403 plan_limit.
PATCH/networks/{id} manage
Changes a network. Send only the fields you want to change; everything else, stored passwords included, is kept. Saving reconnects the network so the changes take effect, as it does in Injected. PUT is accepted as an alias.
One exception protects stored secrets. If the request changes host or port, turns ssl off, or turns acceptInvalidCert on, the stored server password, SASL login and perform commands are dropped unless the same request sends them again. A network that moves keeps its secrets only when the caller already knows them.
DELETE/networks/{id} manage
Disconnects and removes the network. Its message history is kept.
POST/networks/{id}/connect manage
POST/networks/{id}/disconnect manage
POST/networks/{id}/reconnect manage
No body. Follow the progress through connection-state events or by polling GET /networks/{id}.
Live events
GET/events read
A long-lived Server-Sent Events stream. Each event has a name and a JSON payload:
event: ready
data: {"time":1763200000000}
event: message
data: {"serverId":"server-1731600000000-k3j9x1","nick":"alice","ident":"~alice","hostname":"user/alice","channel":"#injected","message":"morning","timestamp":1763200000123}
: ping
The stream opens with ready. Lines starting with a colon are keep-alive comments sent every 25 seconds; SSE libraries ignore them for you. Every payload has serverId (the network's id) and most have timestamp.
| Parameter | Description |
|---|---|
network | Only events from this network id. |
events | Comma-separated event names to receive, such as message,join,part. Without it you get everything except raw. |
Events
| Event | Payload fields |
|---|---|
message | nick, ident, hostname, channel, message, isAction, tags. channel is the target: a channel name, or the user's own nick for a private message. Messages the user sends, from Injected or through the API, arrive too, marked "self": true. |
notice | nick, target, message |
join | nick, ident, hostname, channel, account |
part | nick, ident, hostname, channel, reason |
quit | nick, ident, hostname, reason |
kick | nick (who kicked), kicked, channel, reason |
nick | oldNick, newNick |
topic | nick, channel, topic |
mode | nick, target, modes, params, modeList |
invite | nick, channel |
typing | target, nick, state (active, paused or done) |
read-state | target, lastReadTimestamp: a read marker moved forward, in Injected or through the API. This is one of the few events without a timestamp field. |
connection-state | status, nickname, modes, isOper, error, host, port, ssl |
channels-sync | Sent when a network becomes connected: channels, topics, modes, users for every joined channel. |
user-list | channel, users: the full member list of one channel. |
channel-info | channel, modes, topic, topicSetBy, topicSetAt |
whois | nick, ident, hostname, realname, server, channels, idle, account, away and more |
error | error, reason, and channel or nick when it applies |
ctcp, wallops, snotice, motd, list, ban-list, invite-list, except-list | Less common IRC traffic, passed through as Injected parses it. |
raw | line, command, params: every line received from the IRC server. High volume, so it is only sent when you name it in events. |
Reading the stream
Any HTTP client that can read a response as it arrives will do. In Node 18 or newer:
const res = await fetch('https://injected-irc.com/api/v1/events?events=message', {
headers: { Authorization: `Bearer ${process.env.INJECTED_TOKEN}` },
});
let buffer = '';
for await (const chunk of res.body.pipeThrough(new TextDecoderStream())) {
buffer += chunk;
let end;
while ((end = buffer.indexOf('\n\n')) !== -1) {
const block = buffer.slice(0, end);
buffer = buffer.slice(end + 2);
const event = /^event: (.*)$/m.exec(block)?.[1];
const data = /^data: (.*)$/m.exec(block)?.[1];
if (event && data) console.log(event, JSON.parse(data));
}
}
In Python, with requests:
import json, os, requests
r = requests.get(
"https://injected-irc.com/api/v1/events",
headers={"Authorization": f"Bearer {os.environ['INJECTED_TOKEN']}"},
stream=True,
)
event = None
# chunk_size=1 hands each event over as it arrives instead of waiting for a full buffer
for line in r.iter_lines(chunk_size=1, decode_unicode=True):
if line.startswith("event: "):
event = line[7:]
elif line.startswith("data: "):
print(event, json.loads(line[6:]))
EventSource cannot send an Authorization header. Use fetch and read response.body as in the Node example, which works unchanged in browsers.Staying connected
- Streams end when the server restarts, when a network path drops, or when the token is revoked. Reconnect with a short, growing delay. A
401on reconnect means the token is gone, so stop. - Events are not replayed. After reconnecting, fetch message history for the buffers you show to fill the gap, and networks, channels and read state for current state.
- A token may hold 5 streams open at once.
- Listening does not mark the user as online in Injected and does not stop their phone notifications.
Example bot
A complete bot that answers !ping in any channel. It needs Node 18 or newer and a token with the read and send scopes.
// ping-bot.mjs - run with: INJECTED_TOKEN=inj_pat_... node ping-bot.mjs
const API = 'https://injected-irc.com/api/v1';
const headers = {
Authorization: `Bearer ${process.env.INJECTED_TOKEN}`,
'Content-Type': 'application/json',
};
async function say(networkId, target, text) {
await fetch(`${API}/networks/${encodeURIComponent(networkId)}/messages`, {
method: 'POST',
headers,
body: JSON.stringify({ target, text }),
});
}
async function listen() {
const res = await fetch(`${API}/events?events=message`, { headers });
if (res.status === 401) throw new Error('Token rejected');
let buffer = '';
for await (const chunk of res.body.pipeThrough(new TextDecoderStream())) {
buffer += chunk;
let end;
while ((end = buffer.indexOf('\n\n')) !== -1) {
const data = /^data: (.*)$/m.exec(buffer.slice(0, end))?.[1];
buffer = buffer.slice(end + 2);
if (!data) continue;
const msg = JSON.parse(data);
// Skip our own lines, and only answer in channels.
if (msg.self || !msg.channel?.startsWith('#')) continue;
if (msg.message?.trim() === '!ping') await say(msg.serverId, msg.channel, `${msg.nick}: pong`);
}
}
}
// Reconnect forever, backing off up to 30 seconds.
for (let delay = 1000; ; delay = Math.min(delay * 2, 30000)) {
try { await listen(); delay = 1000; }
catch (err) { console.error(err.message); if (err.message === 'Token rejected') break; }
await new Promise((r) => setTimeout(r, delay));
}
Ground rules
- You are acting as a real person on real IRC networks. Everything a token sends is sent under the user's nick, and each network's own rules apply to it. Networks ban for spam and flooding, and the ban lands on the user.
- Ask for the least access you need, and tell your users which scopes to tick and why.
- Store tokens safely. Never embed a user's token in a public web page or a repository. If one leaks, revoke it in Account settings.
- Back off on
429. HonourRetry-Afterinstead of retrying in a loop. - Versioning. Endpoints under
/api/v1stay backwards compatible. New fields and new event types can appear at any time, so ignore what you don't recognise. Breaking changes would ship under a new version prefix.
Found a bug or need an endpoint that isn't here? Use Report a bug in Injected's user menu.