Flex Coder
2.06K subscribers
372 photos
64 videos
2 files
336 links
Uɴʟᴇᴀsʜ Tʜᴇ Pᴏᴡᴇʀ Oғ Bᴏᴛ Cᴏᴅɪɴɢ. Gᴇᴛ Fʀᴇᴇ Bᴏᴛ & Cᴏᴅᴇ Oɴ Oᴜʀ Cʜᴀɴɴᴇʟ 🧑‍💻

🔰 Oᴜʀ Yᴏᴜᴛᴜʙᴇ Cʜᴀɴɴᴇʟ: https://www.youtube.com/@Flex_Coder

📞 Cᴏɴᴛᴀᴄᴛ Us Oɴ: @Flex_Help
🌐 Oɴʟɪɴᴇ Fʀᴏᴍ: 3-07-2024
Download Telegram
💀 Surprise Code (Made for educational purposes)


Can simple JavaScript actually make your browser freeze or crash?. Check out the GitHub repo and test it yourself

🔗 GitHub: Visit Repo

⚠️ WARNING
Don't run this on your main browser
Don't run it on someone else's device
It can freeze/crash your browser and make you lose unsaved work
Test only on your own device
🧪 Try experimenting with a small number of tabs and see how your browser handles it.

What other crazy but safe browser experiments should I build 🤔?
Drop your ideas below 👇
👍4
📦 Automated Office Parcel Reception & Shelf Staging

Front desk clipboards and lost courier notes become an absolute nightmare once your team scales past twenty people. Instead of building a bespoke mobile check-in app, you can give your reception team a lightning-fast reply keyboard workflow that records delivery shelf locations into Firebase and updates aggregate totals instantly. The floor staff taps one button to record the delivery bay, the persistent reply keyboard resets cleanly, and the intake queue updates in real time.

📁 Filename: drop.js
👨‍💻 Code:
sendReplyKeyboard("Select the arrival shelf zone for this parcel:", [
["Bay A - General", "Bay B - Secure Lockbox"],
["Bay C - Cold Storage", "Front Desk Holding"]
])
waitForAnswer("confirm_drop")


📁 Filename: confirm_drop.js
👨‍💻 Code:
clearWait()
const zone = message
pushDB("deliveries/inbound", {
zone: zone,
logged_by: user.first_name,
received_at: Date.now()
})
BOT.add("inbound_parcel_count", 1)
removeKeyboard(`Logged parcel to *${zone}*! Inventory tally updated.`)


📁 Filename: parcels.js
👨‍💻 Code:
const count = await BOT.getProp("inbound_parcel_count").value() || 0
sendMessage(`🏢 *Facility Parcel Hub*\nTotal inbound packages processed: *${count}*`, {
buttons: [{ text: "Log New Drop", command: "/drop" }]
})


💡 Calling removeKeyboard directly with a message string removes the custom keypad layout and posts your confirmation text in one clean step.

⚠️ Note: Ensure your FIREBASE_URL and FIREBASE_SECRET are configured so pushDB writes persist directly into your database.


#FlexGram
1👍1
Are ads showing below 🤔?

click on it for some help 😉
👍2🐳1
🚐 Zero-Friction Morning Fleet Inspection & Mileage Intake

Depot drivers will skip vehicle walkaround sheets nine times out of ten if they have to fill out paper clipboards or download heavy native apps. Routing pre-trip logs right into Telegram lets drivers send odometer numbers, select condition tags off a custom reply keyboard, and strip the keyboard away the moment their route is approved. Everything syncs straight to the dispatch database before the van even exits the lot.

📁 Filename: inspect.js
👨‍💻 Code:
sendMessage(`Hey ${user.first_name}, let's log your morning pre-trip inspection. Reply with your current van odometer mileage:`)
waitForAnswer('record_mileage')


📁 Filename: record_mileage.js
👨‍💻 Code:
TEMP.setProperty('van_odometer', message)
sendReplyKeyboard('Select vehicle exterior and tire condition:', [
['🟢 All Clear - Good to Go', '🟡 Minor Scuff / Dirty'],
['🔴 Maintenance Required']
])
waitForAnswer('finish_inspection')


📁 Filename: finish_inspection.js
👨‍💻 Code:
const odo = await TEMP.getProp('van_odometer').value()
pushDB('fleet_inspections', {
driver: user.first_name,
driver_id: user.id,
mileage: odo,
condition: message,
timestamp: new Date().toISOString()
})
clearWait()
removeKeyboard(`Inspection submitted! Mileage: ${odo} km | Status: ${message}. Drive safe today!`)


💡 Calling removeKeyboard() immediately wipes custom reply buttons from the chat view so the driver's standard keyboard returns the second their submission finishes.

⚠️ Note: Ensure your database rules allow authenticated REST writes from the bot backend to the fleet_inspections path.


#FlexGram
3👍1
🏗️ Subcontractor Jobsite Safety Muster & Daily Shift Sign-off

Subcontractors on active commercial build sites refuse to install bloated native apps just to clock in and confirm their morning hazard walkthrough. Wiring Telegram's persistent reply keyboards directly to Firebase lets field crews tap physical, chunky buttons without peeling off their work gloves. Workers punch in, their muster timestamps push directly into your database, and clocking out cleanly dismisses the custom keyboard from their screen.

📁 Filename: shift.js
👨‍💻 Code:
sendReplyKeyboard("👷 *Jobsite Check-in Active*\nSelect your shift status below:", [
["/checkin", "/safety_ok"],
["/signoff"]
], "Markdown");


📁 Filename: checkin.js
👨‍💻 Code:
const stamp = new Date().toISOString();
pushDB("jobsite_logs", {
worker: user.first_name,
telegram_id: user.id,
event: "clock_in",
timestamp: stamp
});
sendMessage(` Clock-in recorded for *${user.first_name}* at \`${stamp.slice(11, 19)} UTC\`.`, { parse_mode: "Markdown" });


📁 Filename: safety_ok.js
👨‍💻 Code:
pushDB("safety_audits", {
worker_id: user.id,
worker_name: user.first_name,
status: "ppe_verified",
timestamp: Date.now()
});
sendMessage("🦺 *Safety briefing acknowledged.* Morning PPE check logged.", { parse_mode: "Markdown" });


📁 Filename: signoff.js
👨‍💻 Code:
pushDB("jobsite_logs", {
worker_id: user.id,
event: "clock_out",
timestamp: Date.now()
});
removeKeyboard("👋 Shift complete. Custom keyboard cleared. Drive safe!");


💡 When sending command strings inside reply keyboard rows, match each button text to an exact file in /command so taps route instantly without touching a fallback parser.

⚠️ Note: Set FIREBASE_URL and FIREBASE_SECRET in your environment so pushDB can persist log entries directly to your Realtime Database.


#FlexGram
👍2🕊1
Chatgpt, claude and grok are down at same time 😂
😁21🤯1💯1
📜 Mobile Escrow Packet & Closing Pin Dispatcher

Mobile signing agents waste tons of time in parking lots wrestling with clunky document portals just to grab a buyer's signing sheet, an escrow officer's direct line, and a map pin. This automation lets an on-the-road notary text a single file reference to get an all-in-one dispatch bundle delivered natively inside Telegram. The bot pings the title API, streams the PDF closing document with sendDocument, pushes the title officer's phone card via sendContact, and drops an exact destination coordinate with sendLocation so the agent can launch navigation with a single tap.

📁 Filename: closing.js
👨‍💻 Code:
sendMessage("Enter the 6-digit escrow file ID to retrieve your closing packet:", {
buttons: [{ text: "Cancel", command: "/cancel" }]
});
waitForAnswer("get_closing");


📁 Filename: get_closing.js
👨‍💻 Code:
clearWait();
sendChatAction("upload_document");
const res = await HTTP.get({ url: `https://api.titleops.internal/files/${encodeURIComponent(message)}` });
if (!res || !res.data || !res.data.pdf_url) {
return sendMessage("Escrow file not found. Please verify the ID and run /closing again.");
}
pushDB("signings", { file: message, notary: user.id, at: Date.now() });
sendDocument(res.data.pdf_url, { caption: `*Escrow File #${message}* Ready for execution.` });
sendContact(res.data.officer_phone, res.data.officer_name);
sendLocation(res.data.lat, res.data.lng);


📁 Filename: cancel.js
👨‍💻 Code:
clearWait();
sendMessage("Request cancelled. Enter /closing whenever you are ready.");


💡 Firing sendChatAction('upload_document') right before your HTTP call gives agents instant UI feedback in the Telegram header while third-party PDFs are being negotiated.

⚠️ Note: Replace the title API URL with your actual document service endpoint and ensure it returns direct downloadable file URLs.


#FlexGram
1👍1
🔧 Step-by-Step Hardware Repair Ticket Intake

Clients DMing blurry photos of broken gear with zero context used to wreck my entire morning workbench flow. Instead of playing twenty questions over chat, this three-step waitForAnswer pipeline collects the hardware model, captures the failure symptoms, and commits the ticket without cluttering permanent storage until the customer finishes.

📁 Filename: repair.js
👨‍💻 Code:
sendMessage('🛠️ *Hardware Repair Intake*\n\nWhat is the exact make and model of the device needing service?');
waitForAnswer('repair_issue');


📁 Filename: repair_issue.js
👨‍💻 Code:
TEMP.setProp('device_model', message);
sendMessage('Got it. Please describe the exact symptoms, error codes, or physical damage:');
waitForAnswer('repair_finish');


📁 Filename: repair_finish.js
👨‍💻 Code:
const model = await TEMP.getProp('device_model').value();
clearWait();
TEMP.deleteProp('device_model');
USER.setProp('active_ticket', `${model} - ${message}`);
sendMessage(` *Ticket Logged*\n\nDevice: *${model}*\nReport: ${message}\n\nA bench technician has been queued.`);


💡 Calling clearWait() right at the start of your final step prevents follow-up chatter from getting trapped in the conversation pipeline.

#FlexGram
1👍1🎉1
⏱️ Shared Client Retainer Hour Burn Ledger

Running a dev shop with prepaid client retainers usually means either fighting clunky time-tracking SaaS or losing billable hours because nobody wants to open an external app for a 15-minute bug fix. Wiring a burn ledger directly into our team chat lets engineers log fractional hours instantly without interrupting their flow. The engine uses persistent Firebase global and user properties with atomic additions and subtractions, keeping the team's combined client pool synchronized in real time.

📁 Filename: burn.js
👨‍💻 Code:
const amount = parseFloat(params);
if (!amount || isNaN(amount) || amount <= 0) {
sendMessage('Provide hours to deduct: `/burn 1.5 staging db patch`', { parse_mode: 'Markdown' });
return;
}
BOT.remove('retainer_hours', amount);
USER.add('hours_billed', amount);
const pool = (await BOT.getProp('retainer_hours').value()) || 0;
sendMessage(`Burned <b>${amount} hrs</b> by ${user.first_name}.\nActive retainer pool: <b>${pool} hrs</b> remaining.`);


📁 Filename: pool.js
👨‍💻 Code:
const pool = (await BOT.getProp('retainer_hours').value()) || 0;
const billed = (await USER.getProp('hours_billed').value()) || 0;
sendMessage(`<b>Current Retainer Balance</b>\nClient Pool: <b>${pool} hrs</b> remaining\nYour personal logged time: <b>${billed} hrs</b>`);


📁 Filename: topup.js
👨‍💻 Code:
const added = parseFloat(params);
if (!added || isNaN(added) || added <= 0) {
sendMessage('Pass an allotment to credit: `/topup 40`', { parse_mode: 'Markdown' });
return;
}
BOT.add('retainer_hours', added);
const balance = await BOT.getProp('retainer_hours').value();
sendMessage(`Credited <b>${added} hrs</b>. Active client allotment is now <b>${balance} hrs</b>.`);


💡 Both BOT and USER mutate properties instantly without await, but always remember to await the .value() call whenever reading the updated numbers back to display them.

⚠️ Note: Lock the topup.js command to your Telegram user ID by checking user.id or user.telegramid against your admin ID before running the credit math.


#FlexGram
👍1🤩1
🎛️ Live Production Feature Flag Switchboard

Flipping an emergency killswitch or toggling maintenance mode while away from your desk usually means fumbling through sluggish cloud consoles on mobile Safari. We mapped our team's core runtime flags into an instant inline button switchboard backed by global bot properties. Tapping any toggle updates shared Firebase state across all microservices, updates the button matrix in place, and logs an audit record.

📁 Filename: command/flags.js
👨‍💻 Code:
const [m, b] = await Promise.all([BOT.getProp('maint_mode').value(), BOT.getProp('beta_gate').value()]);
const buttons = [
[{ text: `Maintenance: ${m === 'ON' ? '🔴 ACTIVE' : '🟢 OFF'}`, command: '/toggle maint_mode' }],
[{ text: `Beta Gate: ${b === 'ON' ? '🚀 OPEN' : '🔒 CLOSED'}`, command: '/toggle beta_gate' }]
];
sendMessage('🎛️ <b>Live Feature Flags</b>\nTap to flip runtime configurations across active services:', { buttons });


📁 Filename: command/toggle.js
👨‍💻 Code:
if (!params) return;
const val = (await BOT.getProp(params).value()) === 'ON' ? 'OFF' : 'ON';
BOT.setProp(params, val);
pushDB('flag_audit', { flag: params, val, by: user.username || user.id, at: Date.now() });
answerCallback(`${params}: ${val}`);
const [m, b] = await Promise.all([BOT.getProp('maint_mode').value(), BOT.getProp('beta_gate').value()]);
const buttons = [
[{ text: `Maintenance: ${m === 'ON' ? '🔴 ACTIVE' : '🟢 OFF'}`, command: '/toggle maint_mode' }],
[{ text: `Beta Gate: ${b === 'ON' ? '🚀 OPEN' : '🔒 CLOSED'}`, command: '/toggle beta_gate' }]
];
editCallbackMessage('🎛️ <b>Live Feature Flags</b>\nTap to flip runtime configurations across active services:', buttons, message_id);


📁 Filename: command/flagaudit.js
👨‍💻 Code:
const logs = (await getDB('flag_audit')) || {};
const entries = Object.values(logs).slice(-5).reverse();
if (!entries.length) return sendMessage('No flag modifications found in audit trail.');
const text = entries.map(e => `${e.flag} turned ${e.val} by @${e.by}`).join('\n');
sendMessage(`📋 <b>Recent Runtime Adjustments:</b>\n\n${text}`);


💡 Calling editCallbackMessage with message_id repaints the keyboard state cleanly in the same message frame without spamming notification alerts.

⚠️ Note: Gate these files by checking user.id against a list of authorized team IDs to ensure unauthorized members cannot toggle production settings.


#FlexGram
🎉1
Dead-Letter Webhook Triage & In-Place Remediation

Silent webhook delivery failures and dead-letter queues usually end with engineers digging through cloud consoles while customers complain about missing syncs. Instead of routing noisy JSON dumps into an unmonitored channel where alerts get ignored, this flow pushes compact incident cards with instant remediation controls right into your team chat. On-call engineers can trigger an immediate replay or inspect and purge the stalled payload via native alert modals, while the message card edits itself in place so nobody duplicates work.

📁 Filename: command/dlq.js
👨‍💻 Code:
sendChatAction("typing");
const eventId = params || "ev_9402";
sendMessage(`⚠️ <b>Dead-Letter Exception</b> [<code>${eventId}</code>]\nRoute: <code>POST /api/webhooks/billing</code>\nFailure: <code>Upstream 504 Gateway Timeout</code>\nAttempts: 3 exhausted`, {
buttons: [[
{ text: "🔄 Replay Event", command: `/dlq_retry ${eventId}` },
{ text: "🗑️ Purge & Drop", command: `/dlq_drop ${eventId}` }
]]
});


📁 Filename: command/dlq_retry.js
👨‍💻 Code:
if (!isCallback) return;
answerCallback("Dispatched payload back to active worker queue");
sendChatAction("typing");
const operator = user.username ? `@${user.username}` : user.first_name;
editCallbackMessage(`🔄 <b>Replay In Progress</b> [<code>${params}</code>]\nRoute: <code>POST /api/webhooks/billing</code>\nTriggered by: ${operator}\nStatus: Processing in worker tier`, [
[{ text: "🗑️ Purge Record", command: `/dlq_drop ${params}` }]
], message_id);


📁 Filename: command/dlq_drop.js
👨‍💻 Code:
if (!isCallback) return;
answerCallback(`Payload ${params} was permanently purged from storage.`, true);
deleteMessage(message_id);


💡 Passing true as the second argument in answerCallback() triggers an interactive Telegram popup modal that requires user dismissal instead of a passive bottom toast.

⚠️ Note: Wrap these actions with a check against your engineering team chat.id to ensure only authorized infrastructure operators can replay or purge failed event queues.


#FlexGram
👍1🤩1
🔍 Zero-Switch Inline Runbook Injector for Incident Chats

Switching between active incident war rooms and our internal documentation just to grab standard diagnostic cURL commands was killing our response velocity during live outages. We dropped our team's critical recovery commands into Firebase so on-call engineers can invoke them directly inside any channel or customer DM without opening another tab. By routing query lookups through __inline__.js, the bot filters matching commands in real time and inserts cleanly formatted shell snippets straight into the current chat with a single tap.

📁 Filename: command/snippet.js
👨‍💻 Code:
const [key, ...content] = (params || '').split(' ');
if (!key || content.length === 0) {
sendMessage('Usage: <code>/snippet &lt;name&gt; &lt;command/url/text&gt;</code>');
return;
}
await setDB('snippets/' + key.toLowerCase(), { name: key, text: content.join(' ') });
sendMessage(`Snippet <b>${key}</b> stored in global inline registry.`);


📁 Filename: command/__inline__.js
👨‍💻 Code:
const q = (inlineQuery || '').toLowerCase().trim();
const data = (await getDB('snippets')) || {};
const matches = Object.values(data).filter(s => s.name.toLowerCase().includes(q)).slice(0, 8);
const results = matches.map((s, i) => ({
type: 'article',
id: String(i),
title: s.name,
description: s.text.slice(0, 50),
input_message_content: { message_text: `<b>Runbook: ${s.name}</b>\n<code>${s.text}</code>`, parse_mode: 'HTML' }
}));
answerInlineQuery(results);


📁 Filename: command/delsnippet.js
👨‍💻 Code:
if (!params) {
sendMessage('Usage: <code>/delsnippet &lt;name&gt;</code>');
return;
}
await deleteDB('snippets/' + params.trim().toLowerCase());
sendMessage(`Snippet <b>${params.trim()}</b> removed from inline registry.`);


💡 Telegram aggressively caches inline query payloads on mobile clients, so pass { cache_time: 1 } as the second argument to answerInlineQuery if your team updates snippets frequently.

⚠️ Note: You must enable Inline Mode for your bot in BotFather via /setinline before Telegram starts dispatching inline_query events to your webhook.


#FlexGram
1😁1
New Video Uploaded 👇
https://youtu.be/vAMUm4hNSN4

📹 Video Description:
In this video, you would able to learn how to build a complete Telegram Subscription Bot using Node.js. In this tutorial, you'll create a system that automatically add users to channel, tracks subscription expiry dates, sends reminders, and removes expired members without manual work.

⚠️ Note: Subscribe Backup Channel: https://youtube.com/@flecdev
1👍1😍1
🎙️ Live Broadcast Listener Audio Voicemail Box

Chasing down listener audio questions across emails, WhatsApp voice notes, and messy cloud folders right before recording a weekly show is complete chaos. This setup turns Telegram into a direct studio dropbox where audience members send native voice recordings that get cataloged straight into Firebase. The show host can toggle the line on or off with a shared bot property, capture voice file IDs seamlessly with conversational routing, and preview queued listener clips right in Telegram without downloading third-party media files.

📁 Filename: record.js
👨‍💻 Code:
const isOpen = await BOT.getProp("voicemail_open").value();
if (!isOpen) {
sendMessage("🎙️ Voicemail line is currently closed for this segment.");
return;
}
sendMessage("🎙️ Record and send your voice note now. Speak clearly into the mic!");
waitForAnswer("/save_audio", { timeout_ms: 120000 });


📁 Filename: save_audio.js
👨‍💻 Code:
const voiceId = flex.request?.message?.voice?.file_id;
if (!voiceId) {
sendMessage("⚠️ Please send a voice memo recording, or tap /record to try again.");
return;
}
clearWait();
sendChatAction("record_voice");
await pushDB("voicemails", { sender: user.username || user.id, file_id: voiceId, timestamp: Date.now() });
sendMessage(" Voice memo captured! It has been forwarded to the production queue.");


📁 Filename: producer_gate.js
👨‍💻 Code:
const active = await BOT.getProp("voicemail_open").value();
await BOT.setProp("voicemail_open", !active);
const label = !active ? "🟢 OPEN" : "🔴 CLOSED";
sendMessage(`Studio voicemail line is now ${label}.`);


📁 Filename: queue_pull.js
👨‍💻 Code:
sendChatAction("upload_voice");
const inbox = await getDB("voicemails");
const keys = inbox ? Object.keys(inbox) : [];
if (!keys.length) {
sendMessage("No unreviewed listener audio clips in the queue.");
return;
}
const clip = inbox[keys[keys.length - 1]];
sendVoice(clip.file_id, { caption: `🎙️ Caller: @${clip.sender}` });


💡 Native Telegram voice notes preserve original Opus compression, so playing them back via sendVoice using the stored file_id avoids any re-upload delay or extra bandwidth on your server.
⚠️ Note: Guard producer_gate.js and queue_pull.js by matching user.id against your team's admin ID list so listeners cannot toggle the booth or leak peer submissions.


#FlexGram
👍2🎉1
🖨️ Makerspace 3D Print Queue & Laser Run Logger

Members at our community workshop kept starting eight-hour PETG prints without tagging the plate, leaving everyone guessing when a bed would actually free up. Instead of mounting a dusty tablet kiosk by the machines, we dropped this three-file flow in so anyone can log their job specs directly from the chat bench. It grabs their parameters through an interactive conversational wait, commits the slot into Firebase, and lets anyone query what's currently cooking.

📁 Filename: slice.js
👨‍💻 Code:
sendChatAction("typing");
sendMessage(
`Hey *${user.first_name}*, enter your print run details.\nFormat: \`PrinterName | Minutes | Filament\``
);
waitForAnswer("commit_slice");


📁 Filename: commit_slice.js
👨‍💻 Code:
clearWait();
const [printer, mins, filament] = message.split("|").map(s => s.trim());
if (!printer || !mins) {
return sendMessage("Format was off. Tap /slice to try again using: `Printer | Minutes | Material`");
}
await pushDB("workshop_jobs", {
maker: user.first_name,
printer,
minutes: parseInt(mins, 10) || 60,
filament: filament || "PLA",
loggedAt: Date.now()
});
sendMessage(`🛏 Reserved *${printer}* for ~${mins}m (${filament}). See all runs with /machinelog.`);


📁 Filename: machinelog.js
👨‍💻 Code:
sendChatAction("typing");
const runs = await getDB("workshop_jobs");
if (!runs || Object.keys(runs).length === 0) {
return sendMessage("No print jobs currently registered on the floor.");
}
const list = Object.values(runs)
.slice(-6)
.map(j => `• *${j.printer}*: ${j.minutes}m (${j.filament}) logged by ${j.maker}`)
.join("\n");
sendMessage(` *Recent Active Shop Runs*:\n\n${list}`);


💡 Always call clearWait() right away inside your target step handler so a failed validation check doesn't leave the user accidentally stuck in your waiting loop.

⚠️ Note: Make sure FIREBASE_URL and FIREBASE_SECRET are present in your environment so pushDB and getDB can access your database instance.


#FlexGram
1👍1
🛰️ On-Call Edge Probe & Instant Service Purge

Getting paged about sluggish checkout latency while standing in line for coffee used to mean tethering my laptop just to run three basic curl requests. With this setup, our on-call rotation fires synthetic health checks against production microservices and purges stale edge caches directly from our phones. The bot calculates network roundtrip latency in milliseconds, inspects HTTP response payloads, and issues authenticated REST mutations without opening an SSH tunnel.

📁 Filename: command/probe.js
👨‍💻 Code:
sendChatAction("typing");
const target = params ? params.trim() : "gateway";
const endpoints = { gateway: "https://api.internal.run/health", auth: "https://auth.internal.run/ping" };
const url = endpoints[target] || endpoints.gateway;
const t0 = Date.now();
const res = await HTTP.get({ url, headers: { "X-Monitor-Origin": "FlexGram-Edge" } });
const latency = Date.now() - t0;
const healthy = res && (!res.status || res.status < 400);
const badge = healthy && latency < 750 ? "🟢 *HEALTHY*" : "🔴 *DEGRADED*";
sendMessage(`${badge}\nEndpoint: \`${target}\`\nLatency: \`${latency}ms\`\nStatus: \`${res.status || 200}\``);


📁 Filename: command/purge.js
👨‍💻 Code:
sendChatAction("typing");
const zone = params ? params.trim() : "global";
const res = await HTTP.post({
url: "https://api.internal.run/v1/cache/purge",
headers: { "Authorization": "Bearer ops-secret-token", "Content-Type": "application/json" },
body: { zone, triggered_by: user.username || user.telegramid }
});
const status = res && res.success ? " *Purge Complete*" : "⚠️ *Purge Queued*";
sendMessage(`${status}\nZone: \`${zone}\`\nCluster: \`${res.cluster || "core-us-east"}\``);


📁 Filename: command/evict.js
👨‍💻 Code:
sendChatAction("typing");
const lockId = params ? params.trim() : "global-lock";
const res = await HTTP.custom({
url: `https://api.internal.run/v1/locks/${lockId}`,
method: "DELETE",
header: { "Authorization": "Bearer ops-secret-token" }
});
sendMessage(`🗑️ Lock Eviction: \`${lockId}\`\nHTTP Result: \`${res.status || 204} OK\``);


💡 Calling sendChatAction("typing") right before async external HTTP requests keeps the client updated and prevents Telegram from timing out during cold API starts.

⚠️ Note: Replace internal endpoints and ops-secret-token with your authenticated gateway URLs or ingest them from environment variables.


#FlexGram
👍2🤩1
Pickup Match Pitch Pin & Attendance Poll Hub

Organizing our weekly local pickup league meant answering forty repetitive group chat pings about the pitch coordinates and who was actually turning up. Instead of juggling external signup spreadsheets or pinning stale messages, we wired native Telegram poll dispatches and geo coordinates into quick organizer commands. Team captains trigger a persistent custom reply board right above their chat tray to drop pins and roster polls in seconds.

📁 Filename: match.js
👨‍💻 Code:
sendReplyKeyboard(
" *Match Day Hub*\nSelect an action below to dispatch to the squad:",
[["/pitch", "/poll"], ["/dismiss"]],
"Markdown"
);


📁 Filename: pitch.js
👨‍💻 Code:
sendChatAction("find_location");
sendLocation(51.5560, -0.1075, {
reply_to_message_id: message_id
});
sendMessage("📍 *Highbury Turf Pitch 2*\nKick-off at 19:30. Bring both dark and light shirts.", {
parse_mode: "Markdown"
});


📁 Filename: poll.js
👨‍💻 Code:
sendPoll(
" Who is in for tonight's 8-a-side run?",
["In (Outfield)", "In (Goalie)", "Bench Sub Only", "Out"],
{
is_anonymous: false
}
);


📁 Filename: dismiss.js
👨‍💻 Code:
removeKeyboard("Match controls dismissed. Send /match to bring them back.");


💡 Native reply keyboards stay pinned to the user's input tray across app restarts until explicitly wiped with removeKeyboard.

⚠️ Note: Ensure your bot has the permission to post polls enabled in group chat settings if you run these commands in a community room.


#FlexGram
1👍1
Day 1/30: License Key Claim & Identity Binding 🔑

I was manually pasting software activation keys into Postgres every time someone bought a seat for my desktop app, which got old remarkably fast. We are kicking off a 30-day build turning FlexGram into an automated licensing backend for digital tools and micro-SaaS products. Today's foundation allows buyers to run a single command with their invoice token to lock the seat to their Telegram ID and store their active subscription tier across persistent state.

📁 Filename: claim.js
👨‍💻 Code:
const key = (params || '').trim().toUpperCase();
if (!key) return sendMessage('Usage: `/claim ABCD-1234`', { parse_mode: 'Markdown' });
const record = await BOT.getProp(`key_${key}`).value();
if (!record) return sendMessage(' License key not recognized. Check your purchase receipt.');
if (record.owner && record.owner !== user.id) return sendMessage(' Key already claimed by another user.');
await BOT.setProp(`key_${key}`, { ...record, owner: user.id, claimed_at: Date.now() });
await USER.setProp('license_key', key);
await FLEX.setProperty('tier', record.tier || 'pro');
sendMessage(` *${(record.tier || 'pro').toUpperCase()}* seat bound to account \`${user.id}\`! Check status via /license.`, { parse_mode: 'Markdown' });


📁 Filename: license.js
👨‍💻 Code:
const key = await USER.getProp('license_key').value();
if (!key) return sendMessage('No license linked yet. Run `/claim <KEY>` to register your copy.', { parse_mode: 'Markdown' });
const tier = await FLEX.getProperty('tier').value() || 'Standard';
const record = await BOT.getProp(`key_${key}`).value();
const claimedDate = record?.claimed_at ? new Date(record.claimed_at).toLocaleDateString('en-US') : 'Unknown';
sendMessage(`🪪 *Active License Record*\n\nKey: \`${key}\`\nTier: *${tier.toUpperCase()}*\nActivated: ${claimedDate}\nTelegram ID: \`${user.id}\``, { parse_mode: 'Markdown' });


📁 Filename: genkey.js
👨‍💻 Code:
const adminId = 123456789;
if (user.id !== adminId) return sendMessage(' Unauthorized access.');
const [tier, customKey] = (params || '').trim().split(' ');
if (!tier) return sendMessage('Usage: `/genkey pro` or `/genkey studio MY-CUSTOM-KEY`', { parse_mode: 'Markdown' });
const key = (customKey || `LIC-${Math.random().toString(36).substring(2, 8).toUpperCase()}`).toUpperCase();
await BOT.setProp(`key_${key}`, { tier: tier.toLowerCase(), created_at: Date.now() });
sendMessage(`🔑 New license created!\nKey: \`${key}\`\nTier: *${tier.toUpperCase()}*`, { parse_mode: 'Markdown' });


💡 Reading stored objects via BOT.getProp().value() handles JSON parsing automatically, keeping state validation down to a single clean lookup.

⚠️ Note: Change adminId inside genkey.js to your personal numeric Telegram user ID before issuing license tokens.


#FlexGram
2
Day 2/30: Multi-Seat Node Manager & In-Place Revocation 💻

Buyers kept hitting our support inbox after wiping their machines or buying new laptops because their license seat allocation was still locked to dead hardware. Instead of building an entire web portal with auth sessions just to let users detach an old MacBook, we let them inspect their seat slots and detach machines straight through inline callback actions in Telegram. When an engineer pairs a new host, it claims an available slot, and when they decommission a box, tapping an inline button frees the slot immediately without refreshing the chat history.

📁 Filename: pair.js
👨‍💻 Code:
const node = params ? params.trim() : 'workstation';
const s1 = await USER.getProp('seat_1').value();
const s2 = await USER.getProp('seat_2').value();
if (!s1) {
await USER.setProp('seat_1', node);
sendMessage(`Attached <b>${node}</b> to Slot 1.`, { buttons: [{ text: 'Manage Seats', command: '/seats' }] });
} else if (!s2) {
await USER.setProp('seat_2', node);
sendMessage(`Attached <b>${node}</b> to Slot 2.`, { buttons: [{ text: 'Manage Seats', command: '/seats' }] });
} else {
sendMessage('All device slots full. Revoke an existing machine to continue.', { buttons: [{ text: 'Manage Seats', command: '/seats' }] });
}


📁 Filename: seats.js
👨‍💻 Code:
const s1 = await USER.getProp('seat_1').value();
const s2 = await USER.getProp('seat_2').value();
const buttons = [];
if (s1) buttons.push([{ text: `Revoke ${s1}`, command: '/revoke seat_1' }]);
if (s2) buttons.push([{ text: `Revoke ${s2}`, command: '/revoke seat_2' }]);
buttons.push([{ text: 'Refresh', command: '/seats' }]);
const text = `<b>Hardware Seat Matrix</b>\nSlot 1: ${s1 || '<i>Empty</i>'}\nSlot 2: ${s2 || '<i>Empty</i>'}`;
if (isCallback) {
editCallbackMessage(text, buttons);
} else {
sendMessage(text, { buttons });
}


📁 Filename: revoke.js
👨‍💻 Code:
const slot = params ? params.trim() : 'seat_1';
await USER.deleteProp(slot);
if (isCallback) answerCallback('Machine seat revoked.');
const s1 = await USER.getProp('seat_1').value();
const s2 = await USER.getProp('seat_2').value();
const buttons = [];
if (s1) buttons.push([{ text: `Revoke ${s1}`, command: '/revoke seat_1' }]);
if (s2) buttons.push([{ text: `Revoke ${s2}`, command: '/revoke seat_2' }]);
buttons.push([{ text: 'Refresh', command: '/seats' }]);
const text = `<b>Hardware Seat Matrix</b>\nSlot 1: ${s1 || '<i>Empty</i>'}\nSlot 2: ${s2 || '<i>Empty</i>'}`;
editCallbackMessage(text, buttons);


💡 Calling editCallbackMessage alongside answerCallback gives users instant tactile feedback while keeping the seat matrix updated in a single tidy message bubble.

⚠️ Note: Set FIREBASE_URL and FIREBASE_SECRET in your environment so USER.setProp and USER.deleteProp sync device slots permanently across cold starts.


#FlexGram
👍1🕊1