Build an X sniper bot
A post on X moves a coin: a developer posts the mint of the coin they just launched, an account with a following names one, and every bot reading it buys at once. The bot that buys first gets the price before the crowd. This guide builds that bot in a little over a hundred lines of Node.js: Shrine's X stream sends each new post from the accounts you pick, the bot finds the mint in it, and Lightspeed buys it in one request, raced over every lane. The X stream comes with Professional.
How it works
- The posts come to you. You name up to 50 X accounts, and the X stream sends each new post from them as a
tweetevent, seconds after it is posted. No X account, no X API key, no scraping on your side. Their reposts come too, for the accounts you switch them on for. - The mint in the post. A Solana address is 32 to 44 base58 characters, and a pump.fun mint ends in
pump. The bot reads each post's text and takes the first mint it has not seen before. When the text holds none, it looks at where the post'st.coshort links point. - One request to buy. Lightspeed builds, signs and sends the buy from your Lightspeed wallet, over all the SWQoS lanes and the block 0 lane at once; nothing is read from the chain on the way.
- A report to you. Each buy is printed with its signature and the post behind it, and, if you give the script a Telegram bot, sent to you on Telegram.
What you need
- Node.js 22 or newer,
npm install socket.io-client. - A Professional plan and its key (
sk_…, on the dashboard): it opens the X stream. The stream servers' addresses are on the dashboard too, with whether each is up. - A funded Lightspeed account made for this bot: its
ls_…key signs the buys. - The X handles to follow, up to 50.
- A server next to the API: Frankfurt, Amsterdam or New York (Regions). The stream servers are in the US, Europe and Asia: connect to the one nearest your server.
- Optional, for reports on Telegram: a bot made with @BotFather. Send it
/startfrom your own account, then openhttps://api.telegram.org/bot<token>/getUpdatesand take your chat id from the answer.
The script
Save it as x-sniper.mjs.
import { io } from "socket.io-client";
// ─── change these ─────────────────────────────────────
const STREAM_KEY = "sk_…"; // your Professional plan's key: it opens the X stream
const SERVERS = ["https://YOUR_STREAM_SERVER"]; // from your dashboard; with several, the first copy of a post wins
const ACCOUNTS = [ // X handles to follow, up to 50
"dev_handle",
{ user: "caller_handle", reposts: true }, // their reposts too
];
const TRIGGERS = []; // handles whose posts may buy; empty: every account above
const LS_KEY = "ls_…"; // your Lightspeed account key
const BUY_SOL = 0.05; // per post
const AMOUNTS = {}; // per account, lower case: { dev_handle: 0.2 }
const SLIPPAGE = 25; // percent; a posted coin moves fast
const PRIORITY_FEE = 0.0002; // SOL; every copy that reverts pays it too
const TIP = 0.001; // SOL per provider copy, paid once by the copy that lands
const PROVIDERS = ["all"]; // race every lane and the block 0 lane
const PUMP_ONLY = true; // only mints ending in "pump"
const RESOLVE_LINKS = true; // no mint in the text: look where its t.co links point
const MAX_AGE_S = 15; // skip a post that reaches you later than this
const REPORT_BOT = ""; // optional: a Telegram bot's token from @BotFather ...
const REPORT_CHAT = ""; // ... and your chat id with it; empty: the console only
const DRY_RUN = true;
// ──────────────────────────────────────────────────────
const API = "https://sol.shrine.trade";
const MINT_RE = /\b[1-9A-HJ-NP-Za-km-z]{32,44}\b/g; // base58, the length of a Solana address
const LINK_RE = /https?:\/\/t\.co\/\w+/g; // X's short links
const FATAL = new Set(["api_key_required", "unknown_key", "key_disabled", "plan_required"]);
const triggers = new Set(TRIGGERS.map((h) => h.replace(/^@/, "").toLowerCase()));
const seen = new Set(); // every mint already bought or tried
const posts = new Set(); // post ids already read, from any server
async function lightspeed(body) {
if (DRY_RUN) { console.log(" dry-run", body); return { success: true }; }
const r = await (await fetch(`${API}/api/lightspeed`, {
method: "POST", headers: { "content-type": "application/json", "x-api-key": LS_KEY }, body: JSON.stringify(body),
})).json();
if (!r.success) throw new Error(`${r.error}: ${r.message}`);
return r;
}
// To the console, and to your Telegram when REPORT_BOT is set. Not awaited: the buy is already out.
function report(text) {
console.log(text);
if (!REPORT_BOT) return;
fetch(`https://api.telegram.org/bot${REPORT_BOT}/sendMessage`, {
method: "POST", headers: { "content-type": "application/json" },
body: JSON.stringify({ chat_id: REPORT_CHAT, text, link_preview_options: { is_disabled: true } }),
}).catch(() => {});
}
const fresh = (m) => !seen.has(m) && (!PUMP_ONLY || m.endsWith("pump"));
const mintIn = (text) => [...text.matchAll(MINT_RE)].map((m) => m[0]).find(fresh);
// Where a short link points: t.co's redirect names it, nothing past it is fetched.
async function target(link) {
try {
const r = await fetch(link, { redirect: "manual", signal: AbortSignal.timeout(2000) });
return r.headers.get("location") ?? (await r.text()); // some answers carry it in a small page instead
} catch { return ""; }
}
async function buy(mint, why, amount = BUY_SOL) {
seen.add(mint); // before the request: a second post cannot buy it again
const t0 = performance.now();
try {
const r = await lightspeed({
action: "buy", mint, amount, slippage: SLIPPAGE,
priorityFee: PRIORITY_FEE, tip: TIP, providers: PROVIDERS,
});
const ms = (performance.now() - t0).toFixed(0);
const lanes = r.submissions ? `, ${r.submissions.filter((s) => s.accepted).length} lanes took it` : "";
report(`bought ${amount} SOL of ${mint}\n${why}\nsent in ${ms} ms${lanes}\n` +
(r.signature ? `https://solscan.io/tx/${r.signature}` : "dry run"));
} catch (e) {
report(`buy of ${mint} failed: ${e.message}\n${why}`);
}
}
// Every new post: find a mint, buy it once.
async function onTweet(t) {
if (posts.has(t.id)) return; // the same post from a second server
posts.add(t.id);
const who = t.user.toLowerCase();
const age = (Date.now() - t.postedAt) / 1000;
console.log(`@${t.user} ${t.kind}, X→stream ${t.receivedAt - t.postedAt} ms, →you ${age.toFixed(2)} s: ${t.text.slice(0, 80)}`);
if (triggers.size && !triggers.has(who)) return; // followed to read, not to buy
if (age > MAX_AGE_S) return; // late: the crowd has bought it already
let mint = mintIn(t.text);
if (!mint && RESOLVE_LINKS) {
for (const link of t.text.match(LINK_RE) ?? []) if ((mint = mintIn(await target(link)))) break;
}
if (!mint) return;
await buy(mint, `${t.kind} by @${t.user}: ${t.url}`, AMOUNTS[who] ?? BUY_SOL);
}
// One socket per server. Follows belong to the socket: subscribe again on every (re)connect.
for (const server of SERVERS) {
const socket = io(server, { auth: { api_key: STREAM_KEY }, transports: ["websocket"] });
let stopped = false;
socket.on("connect", () => {
socket.emit("subscribe_tweets", { users: ACCOUNTS }, (ack) => {
if (!ack.ok) return console.error(`${server}: ${ack.error} ${ack.message ?? ""}`);
for (const u of ack.users) console.log(`${server}: @${u.user} ${u.status} ${u.message ?? ""}`);
if (ack.rejected) console.log(`${server}: not on X:`, ack.rejected);
console.log(`${server}: following ${ack.users.length} of ${ack.max}, feed ${ack.feed}`);
});
});
socket.on("tweet", onTweet);
socket.on("tweet_user", (u) => console.log(`${server}: @${u.user} ${u.status} ${u.message ?? ""}`));
socket.on("subscription_error", (e) => { // the plan ended or the key was switched off
if (FATAL.has(e.error)) { stopped = true; console.error(`${server}: ${e.error}`); }
});
socket.on("connect_error", (e) => { // refused at the handshake: Socket.IO won't retry on its own
console.error(`${server}: ${e.message}`);
if (!socket.active && !FATAL.has(e.message)) setTimeout(() => socket.connect(), 5000);
});
socket.on("disconnect", (reason) => { // a server update closes the socket once
console.error(`${server}: disconnected (${reason})`);
if (reason === "io server disconnect" && !stopped) setTimeout(() => socket.connect(), 1000);
});
}
console.log(`watching ${ACCOUNTS.length} X accounts on ${SERVERS.length} server(s)`);
Run it
- Fill in the top. Your plan's key, a stream server's address from the dashboard, the accounts to follow and your Lightspeed key.
- Dry run. With
DRY_RUN = trueit connects, prints each account as it goes live (or why it can't), and then every post: who posted it, how long it took to reach the stream and you, and the buy it would send. Let it run through a few posts and check what it would have bought. - Go live.
DRY_RUN = false, a smallBUY_SOL, and watch the first fills.
What each part does
- The follows.
subscribe_tweetsruns on every connect, because follows belong to the socket: one that reconnects follows nothing until it subscribes again. The ack lists each account:live,pendingwhile it is set up (atweet_userevent follows when it is), orerrorwith the reason, a protected account for instance. A handle X has no account for comes back underrejected. The@, a link to the profile and any case all work inACCOUNTS. - Reading the post. The pattern matches anything shaped like a Solana address;
PUMP_ONLYkeeps the ones ending inpump, which also drops the wallet and pool addresses a post quotes. A very long post can come shortened, and a mint past the cut is not intext; the post'surlhas the whole of it. - The links. When the text holds no mint,
RESOLVE_LINKSreads where eacht.colink points, from the shortener's redirect, without fetching the page behind it, and looks for a mint there: apump.fun/coin/<mint>link, a chart link. That costs one round trip to X's shortener, on the posts whose text has no mint and only on those. Switch it off if your accounts always write the mint out. - Several servers. Each server sends every post of the accounts you follow there, and keeps its own count of your follows and sockets. With more than one in
SERVERS,postskeeps the first copy of each post (byid) and drops the rest. - One buy per mint. The same mint is posted again, reposted and quoted within seconds. It goes into
seenbefore the request leaves, so a second sighting, even one that arrives while the first buy is in flight, buys nothing. - The buy. One Lightspeed request,
amountin SOL. Lightspeed routes from its own cache: a coin on its curve is bought on pump.fun, a graduated one on PumpSwap. An address that is not a tradable token answers with an error, and nothing is sent. - The report. Lightspeed answers once a provider has the trade:
successmeans it is on its way,submissionslists every copy, and any accepted one may be the copy that lands. The Solscan link is the first; to confirm a fill, watch them all or the wallet's balance (Trade). - The delay line.
postedAtis when the post was made, in milliseconds, andreceivedAtwhen our server had it, soX→streamis the stream's side of the delay;→youadds the hop to your bot, measured on your clock. Keep the server's clock synced, or the second number is off by as much as the clock.
Settings worth tuning
BUY_SOLandAMOUNTS. One size per post, and a size per account on top: more on a developer whose launches you trust, less on a caller.SLIPPAGE. A posted coin moves before most buys land. Too little and the buy fails while the crowd buys ahead of you; too much and you pay whatever the first seconds charge. 25% is room for the rush; lower it for accounts whose posts move a coin less.TRIGGERS. Follow more accounts than you buy from: those not inTRIGGERSare printed and never bought. A repost counts as the reposting account's (itsuser), so switch reposts on only for accounts whose reposts you would buy.- Dedupe.
seenkeeps one buy per mint while the script runs and forgets on a restart: to keep it across restarts, write it to a file and read it back at start.postsis only for the copies of a post from several servers. MAX_AGE_S. A post that reaches you late, after a reconnect for instance, has been bought by everyone who saw it in time; past this age it is skipped.PUMP_ONLY. With it off, any address in a post is tried, coins on other launchpads among them: Lightspeed routes those too. Keep it on unless your accounts post coins that are not pump.fun's.TIP,PRIORITY_FEEandPROVIDERS. Every copy races; one that reverts pays its priority fee, and only the one that lands pays the tip, so the budget goes intoTIP. A provider whose minimum tip is aboveTIPsits the race out: 0.001 reaches every one but Node1, 0.002 reaches all (Trade). With a durable nonce (nonce: truein the request) the copies that lose cost nothing at all.
Exits
The script buys and stops there. For a target, a stop and a timer, follow the coin's trades and sell through Lightspeed, as the sniper guide does. subscribe_trades takes the mint itself, so a post needs nothing more:
import { io } from "socket.io-client";
const socket = io("https://sol.shrine.trade", { transports: ["websocket"] });
// after a buy:
socket.emit("subscribe_trades", { mint });
// then the sniper guide's "trade" handler: entry, target, stop, timer, one "100%" sell
X and Telegram on one socket
The same servers and the same key carry the Telegram stream: one socket can follow X accounts and Telegram chats, and the Telegram posts come with their mints already picked out. Add it to the script above and both feeds share seen, so a coin posted on X and called on Telegram is bought once:
// in the "connect" handler, next to subscribe_tweets:
socket.emit("subscribe_telegram", { chats: ["solana_calls"] }, (ack) => console.log(ack.chats ?? ack));
// next to socket.on("tweet", ...):
socket.on("telegram", (p) => {
const mint = p.addresses.solana.find(fresh);
if (mint) buy(mint, `call in ${p.title}: ${p.url ?? ""}`);
});
The Telegram sniper guide has the stream version on its own, with the filters for groups and edits.
Where the time goes
| Step | Time |
|---|---|
| account posts, post reaches our stream server | on X's side; every post carries it as receivedAt - postedAt |
| stream server to your bot | one network hop: connect to the server nearest you |
| mint found, filters | well under a millisecond; a t.co link adds a round trip to X |
| request reaches Lightspeed from the same city | about 1 ms |
| sent to landed | about 50 ms, raced over every lane |
- X is the slow part. How long a post takes to reach the stream is decided on X's side, and it varies by account and by moment. The script prints it for every post, so you see it for the accounts you follow. Everything after the post arrives should take milliseconds.
- Close to the stream and to the API. Run the bot in a Lightspeed region, Frankfurt, Amsterdam or New York, and connect to the stream server on the same side of the ocean. To shave the stream's side too, connect to several servers: the first copy of a post wins.
- Nothing on the way. Keep the Lightspeed wallet funded and look nothing up between the post and the request: no balance check, no metadata, no chain read. The one exception is a
t.colink, and only on a post whose text has no mint. - Sockets. 5 per key on each server, shared with the Telegram stream: a second bot on the same key takes from the same 5.
- Racing. Professional races all 8 SWQoS lanes and the block 0 lane at once, about 50 ms to landing (provider racing), which decides the slot when every bot following the account fires together.
Safety
- Dry run first. Watch a few posts with
DRY_RUN = truebefore any SOL moves. A wrong filter buys every address in every post. - A spare wallet, small amounts. Use a Lightspeed wallet made for this bot, and fund it with what you snipe with, not more.
- A post is not a reason. Accounts get hacked and post a mint to sell into the buyers it brings; developers post their own coin to do the same; copies with the same name and ticker under a different mint are posted to catch fast bots. Follow accounts you trust, and keep
TRIGGERSandPUMP_ONLYon. - Handles, not names. The stream follows the handle you give it, so a display name copied by an impersonator changes nothing. Check the handle itself: one letter off is another account.
- Your keys stay yours. Never paste your plan's key, your Lightspeed key or your bot's token into a chat or a bot. Anyone asking for them, "support" included, is a scam.
Professional also brings everything Developer has: provider racing, all three regions and the Ultra Fast Shred Stream. See Plans and limits.