Flex Coder
2.08K subscribers
366 photos
61 videos
2 files
328 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
What topics would you like me to cover in future videos 🤔?

Drop your suggestions in the comments. I'm looking for new video ideas, so let me know what you'd like to learn, see, or explore next 👇
👍3🔥1🕊1
🌟 Automating client feedback loops on autopilot

Clients rarely fill out feedback forms emailed to them, but they'll tap a button in Telegram in two seconds. I built this lightweight flow to capture star ratings and text reviews directly inside our support chat. It stores the rating in memory, shifts the user context to wait for their text comments, and then commits everything to their persistent database profile in one seamless conversational experience.

📁 Filename:command/feedback.js
👨‍💻 Code:
sendMessage("How would you rate our service today?", {
buttons: [
[
{ text: " 1", command: "/rate 1" },
{ text: " 2", command: "/rate 2" },
{ text: " 3", command: "/rate 3" },
{ text: " 4", command: "/rate 4" },
{ text: " 5", command: "/rate 5" }
]
]
})


📁 Filename:command/rate.js
👨‍💻 Code:
TEMP.setProp("rating", params)
sendMessage("Awesome! Now, please type a short comment about your experience:")
waitForAnswer("save")


📁 Filename:command/save.js
👨‍💻 Code:
const rating = await TEMP.getProp("rating").value()
USER.setProp("last_rating", rating)
USER.setProp("last_comment", message)
sendMessage("Thank you! Your feedback has been saved securely.")
clearWait()


💡 Always remember to call clearWait() at the end of your waiting sequence, or your user will remain locked inside that input handler forever.

⚠️ Note: Make sure your FIREBASE_URL and FIREBASE_SECRET environment variables are configured so the persistent feedback data is successfully saved to your database.


#FlexGram
👍2🐳2
🛰️ Quick-and-dirty uptime monitor in 15 lines of code

I got tired of logging into heavy monitoring dashboards just to check if my clients' staging servers were still breathing during weekend deployments. So I built this ultra-lightweight uptime command panel that pings any endpoint on demand right inside Telegram. It uses Firebase to save your target endpoint and edits the interface in-place with inline callbacks so you aren't spamming your own chat history.

📁 Filename: command/monitor.js
👨‍💻 Code:
if (!params) return sendMessage("Provide a URL: `/monitor https://myapi.com`", { parse_mode: "Markdown" });
USER.setProp("url", params);
sendMessage(`Now tracking \`${params}\`. Click below to run a test.`, {
buttons: [{ text: "Check Status ", command: "/status" }],
parse_mode: "Markdown"
});


📁 Filename: command/status.js
👨‍💻 Code:
const url = await USER.getProp("url").value();
if (!url) return sendMessage("Set a URL first: `/monitor <url>`", { parse_mode: "Markdown" });
sendChatAction("typing");
const ok = await HTTP.get({ url }).then(() => true).catch(() => false);
const text = `*Uptime Monitor*\n\nURL: \`${url}\`\nStatus: ${ok ? " *ONLINE*" : "🚨 *OFFLINE*"}`;
const btns = [{ text: "🔄 Refresh Status", command: "/status" }];
if (isCallback) {
answerCallback(ok ? "Systems nominal!" : "Server unreachable!", !ok);
editCallbackMessage(text, btns, message_id);
} else {
sendMessage(text, { buttons: btns, parse_mode: "Markdown" });
}


💡 To prevent Telegram from hitting webhook timeouts, keep your monitored servers' cold starts under 5 seconds or the callback spinner might hang.

⚠️ Note: Ensure your target URLs include the full protocol like https:// to prevent HTTP client errors.


#FlexGram
👌2👍1🔥1
🔑 Shared office space hacks on a budget.

I had a local co-working client asking for a quick way to let members book phone booths without paying for heavy enterprise scheduling software. We solved it in an hour by building a shared dashboard right inside their Telegram group using Firebase-backed global state. When any member claims or vacates a room, the shared board updates in real-time for everyone else using snappy inline callbacks.

📁 Filename: command/rooms.js
👨‍💻 Code:
const r1 = await BOT.getProp("room1").value() || "Free";
const r2 = await BOT.getProp("room2").value() || "Free";
sendMessage("Quiet Room Bookings:\n\nRoom 1: " + r1 + "\nRoom 2: " + r2, {
buttons: [
[{ text: r1 === "Free" ? "🟢 Book Room 1" : "🔴 Vacate Room 1", command: "/book 1" }],
[{ text: r2 === "Free" ? "🟢 Book Room 2" : "🔴 Vacate Room 2", command: "/book 2" }]
]
});


📁 Filename: command/book.js
👨‍💻 Code:
const roomKey = "room" + params;
const current = await BOT.getProp(roomKey).value() || "Free";
const nextState = current === "Free" ? user.first_name : "Free";
BOT.setProp(roomKey, nextState);
answerCallback("Room " + params + " updated!");
const r1 = await BOT.getProp("room1").value() || "Free";
const r2 = await BOT.getProp("room2").value() || "Free";
editCallbackMessage("Quiet Room Bookings:\n\nRoom 1: " + r1 + "\nRoom 2: " + r2, [
[{ text: r1 === "Free" ? "🟢 Book Room 1" : "🔴 Vacate Room 1", command: "/book 1" }],
[{ text: r2 === "Free" ? "🟢 Book Room 2" : "🔴 Vacate Room 2", command: "/book 2" }]
], message_id);


Make sure you use BOT instead of USER properties here so the state updates globally for all members instead of being sandboxed to the clicking user. 🕒

⚠️ Note: Make sure your FIREBASE_URL and FIREBASE_SECRET environment variables are configured so the bot can persist the global room state across restarts.


#FlexGram
👍2🔥1
📦 Share npm packages directly in any chat

I got tired of constantly jumping back and forth to my browser just to grab npm package links when talking tech with clients and other devs. Using this sleek setup, you can search and share dependency details directly from your Telegram input box in any chat, or query it directly inside the bot.

📁 Filename: command/__inline__.js
👨‍💻 Code:
if (!inlineQuery) return;
const res = await HTTP.get({ url: `https://registry.npmjs.org/${encodeURIComponent(inlineQuery)}` });
if (res && res.name) {
API.answerInlineQuery({
inline_query_id: inlineQueryId,
results: [{
type: "article", id: res.name, title: res.name, description: res.description,
input_message_content: { message_text: `*${res.name}*\n${res.description || ""}\nhttps://www.npmjs.com/package/${res.name}`, parse_mode: "Markdown" }
}]
});
}


📁 Filename: command/npm.js
👨‍💻 Code:
if (!params) return sendMessage("Send package name");
sendChatAction("typing");
const res = await HTTP.get({ url: `https://registry.npmjs.org/${encodeURIComponent(params)}` });
if (!res || !res.name) return sendMessage("Not found");
sendMessage(`*${res.name}*\n${res.description || ""}\nhttps://www.npmjs.com/package/${res.name}`, { parse_mode: "Markdown" });


💡 Inline queries run on every keystroke, so the lightweight HTTP wrapper makes it incredibly snappy without lagging the user.

⚠️ Note: Remember to message @BotFather and send the /setinline command to enable inline mode for your bot before testing.


#FlexGram
🤩2👍1🔥1
🥐 Local bakery flash-sales on autopilot.

A local artisan bakery client wanted a dead-simple way to clear out their leftover daily inventory before closing time without relying on low-reach Instagram stories. We built them a lightning-fast VIP broadcast bot where neighborhood locals subscribe to get instant push alerts whenever fresh batches drop or flash discounts go live. The entire setup runs off Firebase and handles high-volume messaging without hitting Telegram API rate limits thanks to the framework's built-in throttled broadcast system.

📁 Filename: command/start.js
👨‍💻 Code:
const { setDB } = require('../core/firebase');
setDB(`subscribers/${user.id}`, true);
sendMessage('Welcome to the Bakery Alerts VIP club! 🥐 You will get notified the moment hot pastries are ready.');


📁 Filename: command/alert.js
👨‍💻 Code:
const { getDB } = require('../core/firebase');
if (user.id !== parseInt(process.env.ADMIN_ID)) return sendMessage('Unauthorized access.');
const subs = await getDB('subscribers') || {};
const ids = Object.keys(subs);
const res = await broadcast(ids, '🥐 *Warm pastries ready right now!* Get 30% off for the next 45 minutes.', [{ text: 'Get Code', command: '/claim' }], 100);
sendMessage(`Broadcast complete! Sent: ${res.sent}, Failed: ${res.failed}`);


📁 Filename: command/claim.js
👨‍💻 Code:
sendMessage('Show this code at the register to claim your 30% discount:\n\n*BAKERYVIP30*');


Use a 100ms throttle delay in the broadcast call to safely stay within Telegram's broadcast limits while keeping delivery fast.

⚠️ Note: You must add your Telegram user ID as the ADMIN_ID environment variable so only authorized staff can trigger the alerts.


#FlexGram
1👏1
I have decided to live stream on that what should we do 🤔?

Comment Down 👇
👍2🔥21
🐛 In-chat bug collector with zero web forms needed

I needed a smooth way for beta testers to submit structured bug reports without kicking them out to a external form. By chaining conversational steps with waitForAnswer and holding uncommitted input in TEMP memory, you can collect multiple user inputs sequentially and push a complete record to Firebase only when finished.

📁 Filename: command/report.js
👨‍💻 Code:
const prompt = "<b>Issue Reporter</b>\n\nPlease send a headline for the bug:";
sendMessage(prompt);
waitForAnswer("get_desc");


📁 Filename: command/get_desc.js
👨‍💻 Code:
TEMP.setProp("bug_title", message);
sendMessage("Got it. Now reply with full details or steps to reproduce:");
waitForAnswer("finish_report");


📁 Filename: command/finish_report.js
👨‍💻 Code:
const title = await TEMP.getProp("bug_title").value();
pushDB("bugs", { userId: user.id, title, desc: message });
TEMP.deleteProp("bug_title");
clearWait();
sendMessage("<b>Report logged!</b> Our team will review it shortly.");


💡 Always invoke clearWait() at the end of a multi-step conversation to ensure subsequent user messages revert to default command routing.

#FlexGram
👍1👏1
🎛️ Remote staging deploys right from your group chat

Context switching to cloud dashboards just to kick off a staging build during team discussions kills momentum. This setup gives your development team an inline command center to trigger webhooks, update shared deployment states, and modify the chat UI dynamically using callback queries. Team members see real-time updates instantly without cluttering the chat history with spam messages.

📁 Filename: command/staging.js
👨‍💻 Code:
sendChatAction("typing");
let current = await BOT.getProp("build_status").value() || "Ready";
sendMessage(`*Staging Control Panel*\nCurrent Status: *${current}*`, {
buttons: [
[{ text: "🚀 Deploy Staging", command: "/run_deploy" }],
[{ text: "🔄 Check Status", command: "/staging" }]
]
});


📁 Filename: command/run_deploy.js
👨‍💻 Code:
if (isCallback) {
await answerCallback("Initiating deploy sequence...", true);
await BOT.setProp("build_status", "Deploying...");
let res = await HTTP.post({
url: "https://api.github.com/repos/acme/app/dispatches",
body: { event_type: "deploy" }
});
let result = res ? "Deployed" : "Failed";
await BOT.setProp("build_status", result);
editCallbackMessage(`*Staging Control Panel*\nCurrent Status: *${result}*`, [
[{ text: "🔄 Refresh Status", command: "/staging" }]
], message_id);
}


💡 Always use editCallbackMessage when responding to inline buttons to update the interface in place without flooding chat history with redundant messages.

⚠️ Note: Replace the target URL in HTTP.post with your CI/CD pipeline or GitHub action dispatch webhook.


#FlexGram
👍1😁1
💱 Instant currency conversion for remote teams in Telegram

Managing international contractors means constantly checking conversions before approving invoices or budget requests. Instead of leaving Telegram to look up exchange rates, this lightweight setup lets users store their default base currency in Firebase state and pull live rates instantly using the built-in HTTP client.

📁 Filename: setbase.js
👨‍💻 Code:
if (!params[0]) return sendMessage("Usage: /setbase USD");
let code = params[0].toUpperCase();
USER.setProperty("base", code);
sendMessage(`Base currency updated to *${code}*`);


📁 Filename: base.js
👨‍💻 Code:
let base = await USER.getProp("base").value();
let current = base || "USD";
sendMessage(`Your active currency preference is set to *${current}*`);


📁 Filename: convert.js
👨‍💻 Code:
let amount = parseFloat(params[0]) || 100;
let target = (params[1] || "EUR").toUpperCase();
let base = (await USER.getProp("base").value()) || "USD";
sendChatAction("typing");
let data = await HTTP.get({ url: `https://open.er-api.com/v6/latest/${base}` });
let rate = data?.rates?.[target];
if (!rate) return sendMessage("Conversion failed. Check currency codes.");
let converted = (amount * rate).toFixed(2);
sendMessage(`*${amount} ${base}* = *${converted} ${target}*`);


💡 Persistent user properties saved via USER remain available across server restarts without needing manual DB schemas.

#FlexGram
👍1👌1
🎟️ In-group event RSVP tracker with live atomic seat count

Running community meetups usually means wrestling with third-party event forms that half the members forget to fill out. I set up a quick RSVP system directly inside our Telegram group using Firebase-backed persistent state. Users claim or cancel spots with single commands, while global atomic counters prevent overbooking without needing a custom database layer.

📁 Filename: command/rsvp.js
👨‍💻 Code:
const rsvp = await USER.getProp('rsvp').value();
if (rsvp) return sendMessage('You already reserved a spot for this meetup!');
const count = await BOT.getProp('rsvps').value() || 0;
if (count >= 30) return sendMessage('Sorry, this meetup is completely full!');
await USER.setProp('rsvp', true);
await BOT.getProp('rsvps').add(1);
sendMessage(`*RSVP Confirmed!* You bagged spot #${count + 1} of 30.`);


📁 Filename: command/cancel.js
👨‍💻 Code:
const rsvp = await USER.getProp('rsvp').value();
if (!rsvp) return sendMessage('You do not have an active spot reserved.');
await USER.deleteProp('rsvp');
await BOT.getProp('rsvps').add(-1);
sendMessage('Your reservation was canceled and the spot is back open.');


📁 Filename: command/status.js
👨‍💻 Code:
const count = await BOT.getProp('rsvps').value() || 0;
const left = Math.max(0, 30 - count);
sendMessage(`*Meetup Capacity Status*\n\nBooked spots: ${count}/30\nRemaining spots: ${left}`);


💡 Passing negative numbers to .add() safely decrements persistent global counters without manual arithmetic transactions.
⚠️ Note: Ensure FIREBASE_URL and FIREBASE_SECRET are configured in your environment variables so persistent state works seamlessly.


#FlexGram
🤩2
Share code snippets in any chat without leaving Telegram

Jumping back and forth between text editors and Telegram just to share repeated boilerplate or setup commands in tech groups gets exhausting fast. By leveraging FlexGram's built-in inline query support, you can search and drop formatted code blocks directly into any chat window. Here is a clean multi-file pattern using shared Firebase state to add and inline-search snippets globally.

📁 Filename: addsnippet.js
👨‍💻 Code:
if (!params) return sendMessage("Usage: /addsnippet Title | Code");
const [title, code] = params.split("|").map(s => s.trim());
if (!title || !code) return sendMessage("Provide both title and code split by |");
const list = (await BOT.getProp("snippets").value()) || [];
list.push({ title, code });
await BOT.setProperty("snippets", list);
sendMessage(`*Snippet saved!* Type \`@yourbot ${title}\` in any chat to use it.`);


📁 Filename: __inline__.js
👨‍💻 Code:
const query = inlineQuery.toLowerCase();
const list = (await BOT.getProp("snippets").value()) || [];
const matches = list.filter(item => item.title.toLowerCase().includes(query));
const results = matches.map((item, id) => ({
type: "article",
id: String(id),
title: item.title,
input_message_content: { message_text: `\`\`\`\n${item.code}\n\`\`\``, parse_mode: "Markdown" }
}));
answerInlineQuery(results);


💡 Turn on Inline Mode via BotFather with /setinline so Telegram triggers inline suggestions in your message bar.

#FlexGram
👍1🔥1
New Video Uploaded 👇
https://youtu.be/sf-v0scqi9U

📹 Video Description:
Are members leaving your Telegram channel without you knowing? In this video, I show you how to create a Telegram Bot that instantly detects when someone leaves your channel and make him join channel again. If he won't use bot than also he need to join.

⚠️ Note: Subscribe Backup Channel: https://youtube.com/@flecdev
🔥1
🔔 Leave Notify Telegram Bot Code

🧑‍💻 Code:
import { getDB, deleteDB } from "./firebase.js";

export const commandName = "__message__";

export default async function (flex) {
  const body = flex.request.body;
  const leftMember = body.message && body.message.left_chat_member;
  const chatMemberUpdate = body.chat_member;

  const farewellText = `👋 <b>Sorry to see you leave!</b>

<b>You’ve stepped away from our community, but you’re always welcome back.</b>

Whether it was by accident, you needed some time away, or simply wanted a change, our doors remain open for you.

📢 Don’t miss future updates, exclusive offers, and valuable content shared with our members.

👇 Whenever you're ready, tap the button below and rejoin the community. We'd be happy to have you back!`;

  const button = [{ text: "🔗 Join Again", url: "https://t.me/Flex_Coder" }];

  if (leftMember) {
    await API.sendMessage({
      chat_id: leftMember.id,
      text: farewellText,
      parse_mode: "HTML",
      reply_markup: {
        inline_keyboard: [button],
      },
    });
    return;
  }

  if (chatMemberUpdate) {
    const newStatus =
      chatMemberUpdate.new_chat_member &&
      chatMemberUpdate.new_chat_member.status;
    const oldStatus =
      chatMemberUpdate.old_chat_member &&
      chatMemberUpdate.old_chat_member.status;
    const leftNow =
      (newStatus === "left" || newStatus === "kicked") &&
      oldStatus !== "left" &&
      oldStatus !== "kicked";
    if (leftNow) {
      const u = chatMemberUpdate.old_chat_member.user;
      await API.sendMessage({
        chat_id: u.id,
        text: farewellText,
        parse_mode: "HTML",
        reply_markup: {
          inline_keyboard: button,
        },
      });
      return;
    }
  }

  const userId = flex.user.id;

  let pending = null;
  try {
    pending = await getDB(`wait_for_answer/${userId}`);
  } catch {}

  if (pending?.command) {
    if (Date.now() > pending.expires_at) {
      await deleteDB(`wait_for_answer/${userId}`).catch(() => {});
      await sendMessage(" Session timed out. Please start again.");
      return;
    }
    await deleteDB(`wait_for_answer/${userId}`).catch(() => {});
    await runCommand(pending.command, flex.message);
    return;
  }
}

🎥 Tutorial Video: https://youtu.be/sf-v0scqi9U
1
📱 Streamline freelance project intake directly inside Telegram

Onboarding agency clients through raw Telegram DMs gets messy fast when everyone wants custom scopes and optional add-ons. This flow uses native reply keyboards to grab the core service selection, strips the custom keyboard away immediately, and lets the client toggle extra SLAs on the fly with live button edits.

📁 Filename: command/start.js
👨‍💻 Code:
sendReplyKeyboard("Select a dev service package to kick off your quote:", [
[{ text: "🛠️ Web App" }, { text: "📱 Mobile App" }],
[{ text: "🤖 Telegram Bot" }]
])


📁 Filename: command/__message__.js
👨‍💻 Code:
removeKeyboard(`Got it! Package selected: *${message}*`)
sendMessage("Would you like to attach high-priority SLA support to this project?", {
buttons: [
{ text: " Add Express SLA", command: "/priority_on" }
]
})


📁 Filename: command/priority_on.js
👨‍💻 Code:
if (isCallback) {
answerCallback("Express SLA appended!", true)
editButton(message_id, [
{ text: " Express SLA Active", command: "/priority_off" }
])
}


📁 Filename: command/priority_off.js
👨‍💻 Code:
if (isCallback) {
answerCallback("Express SLA removed")
editButton(message_id, [
{ text: " Add Express SLA", command: "/priority_on" }
])
}


💡 Swapping inline buttons with editButton updates option state instantly without re-sending or cluttering the message thread.

#FlexGram
👍1😍1
🚨 Instant API health checks and incident broadcasts from Telegram

When an API endpoint starts misbehaving during off-hours, logging into a heavy monitoring dashboard just to confirm service status is a pain. We set up an on-demand health checker that pings microservices directly via HTTP, updates shared state, and lets admins push instant incident notifications to every subscriber using built-in broadcast throttling.

📁 Filename: command/check.js
👨‍💻 Code:
sendChatAction('typing')
const response = await HTTP.get({ url: 'https://api.github.com/zen' })
if (response) {
BOT.setProp('last_check', Date.now())
sendMessage('*System Status:* All systems operational 🟢')
} else {
BOT.setProp('last_status', 'DOWN')
sendMessage('*System Status:* Service disruption detected 🔴')
}


📁 Filename: command/alert.js
👨‍💻 Code:
if (String(user.telegramid) !== process.env.ADMIN_ID) {
return sendMessage('Unauthorized command.')
}
const allUsers = await getDB('users')
const userIds = allUsers ? Object.keys(allUsers) : []
const report = await broadcast(userIds, `🚨 *Incident Update:* ${params || 'Maintenance in progress.'}`, [], 50)
sendMessage(`Alert dispatched: ${report.sent} delivered, ${report.failed} failed.`)


📁 Filename: command/__message__.js
👨‍💻 Code:
sendMessage('Unrecognized command. Use /check to test system health.')


💡 The built-in broadcast() helper automatically handles rate-limiting delays between sends, preventing Telegram API 429 throttling errors when messaging large user lists.

⚠️ Note: Requires the ADMIN_ID environment variable set in your deployment environment to restrict alert privileges.


#FlexGram
1👍1🏆1
🎫 Instant digital pass activation for private Telegram communities

Selling digital licenses or paid community access usually involves clunky email flows and manual link distribution. I automated real-time license key redemption directly inside Telegram using external API verification and persistent user properties. When an buyer pastes their license key, the bot validates it against the payment provider API and grants instant channel access.

📁 Filename: activate.js
👨‍💻 Code:
const active = await USER.getProp('vip_status').value();
if (active) {
sendMessage(' You already have an active VIP membership!');
return;
}
waitForAnswer('verify_key');
sendMessage('🔑 Please enter your VIP license key to activate access:');


📁 Filename: verify_key.js
👨‍💻 Code:
const res = await HTTP.post({ url: 'https://api.example.com/verify', body: { key: message, uid: user.telegramid } });
if (res && res.valid) {
USER.setProperty('vip_status', true);
clearWait();
sendMessage('🎉 *Key activated!* Access your VIP portal below:', { buttons: [{ text: 'Join VIP Lounge', url: 'https://t.me/+example' }] });
} else {
sendMessage(' Invalid or expired license key. Please check your key and try again.');
}


📁 Filename: pass.js
👨‍💻 Code:
const active = await USER.getProp('vip_status').value();
if (!active) {
sendMessage('🔒 No active VIP pass found. Type /activate to redeem a key.');
return;
}
sendMessage('🎫 *VIP Member Card*\nUser: *' + user.first_name + '*\nStatus: *Active*');


💡 Always call clearWait() inside your handler command right after successful input processing to release the user from the state machine.

⚠️ Note: Replace the API endpoint in verify_key.js with your actual authentication server URL.


#FlexGram
🏆3
📦 Live inventory counter for floor staff

Updating inventory counts during active warehouse packing sessions usually requires constantly moving back and forth between physical shelves and a desktop dashboard. We built an instant Telegram stock adjuster where floor staff query any product SKU and tap inline buttons to increase or decrease counts in real time. The global bot state updates immediately in Firebase and re-renders the counter interface in place without cluttering the chat.

📁 Filename: stock.js
👨‍💻 Code:
const item = (Array.isArray(params) ? params[0] : params) || "sku_101";
const prop = await BOT.getProp(`stock_${item}`);
const qty = prop ? prop.value() || 0 : 0;
sendMessage(`📦 *Stock Level:* \`${item}\`\nQuantity: *${qty}*`, {
buttons: [[
{ text: "-5", command: `/adj ${item} -5` },
{ text: "-1", command: `/adj ${item} -1` },
{ text: "+1", command: `/adj ${item} 1` },
{ text: "+5", command: `/adj ${item} 5` }
]]
});


📁 Filename: adj.js
👨‍💻 Code:
if (!isCallback) return;
const args = Array.isArray(params) ? params : (params ? params.split(" ") : []);
const item = args[0] || "sku_101";
const delta = parseInt(args[1] || "0", 10);
const prop = await BOT.getProp(`stock_${item}`);
const current = prop ? prop.value() || 0 : 0;
const next = Math.max(0, current + delta);
await BOT.setProp(`stock_${item}`, next);
await answerCallback(`Stock updated to ${next}`);
editCallbackMessage(`📦 *Stock Level:* \`${item}\`\nQuantity: *${next}*`, [[
{ text: "-5", command: `/adj ${item} -5` },
{ text: "-1", command: `/adj ${item} -1` },
{ text: "+1", command: `/adj ${item} 1` },
{ text: "+5", command: `/adj ${item} 5` }
]], message_id);


💡 Using editCallbackMessage mutates the existing message UI instantly so floor staff get clean visual feedback without flooding group history.

⚠️ Note: Ensure your bot has database access configured via FIREBASE_URL and FIREBASE_SECRET so inventory levels persist across server restarts.


#FlexGram
👍1🐳1
🧾 Multi-step receipt intake on the go

Snapping paper receipts while traveling for work usually leaves me with a messy camera roll and zero context when expense reporting comes around. By chaining wait states with session memory in FlexGram, we can collect text notes and photo attachments in a seamless back-and-forth prompt flow. Temporary state holds the expense description in memory while waiting for the image, then increments the persistent receipt count once finished.

📁 Filename: command/expense.js
👨‍💻 Code:
sendChatAction("typing");
sendMessage("Send the expense summary and total cost (e.g., Client Lunch $45):");
waitForAnswer("expense_photo");


📁 Filename: command/expense_photo.js
👨‍💻 Code:
TEMP.setProp("expense_details", message);
sendChatAction("typing");
sendMessage("Got it! Now upload a photo of the receipt image:");
waitForAnswer("expense_save");


📁 Filename: command/expense_save.js
👨‍💻 Code:
const details = await TEMP.getProp("expense_details").value();
clearWait();
USER.add("total_expenses", 1);
TEMP.deleteProp("expense_details");
sendMessage("Logged expense receipt for: " + details);


💡 Always call clearWait() inside the final step handler so subsequent user messages resume normal command routing.

⚠️ Note: Persistent counter methods like USER.add() require setting FIREBASE_URL and FIREBASE_SECRET in your environment variables.


#FlexGram
👍1🔥1
🎉 We have just completed 2 yrs on YouTube


Thanks to each member who has supported me to reach here 🙏

https://www.youtube.com/@Flex_Coder
3🔥1