Search code examples
node.jstelegramtelegram-bottelegraf.js

Display an admin-only inline button in Telegraf.js


I have a telegram shop bot written in Telegraf.js.

  • When a normal user starts the bot I want the people to see only 4 buttons (products, cart, account and info)
  • When instead someone starts the bot and its id is in a config json file I want the bot to display another button "Admin Panel" or similar.

    I have this code:
const Config = require("./config");
client.start(async (Context) => {
    if (Config.bans.includes(Context.chat.id)) return;

    var user = Config.users.find((usr => {
        return usr.id === Context.from.id
    }));
    if (!user) Config.users.push({
        id: Context.from.id,
        balance: 0,
        cart: []
    });
    writeFileSync("config/index.json", JSON.stringify(Config));

    // Actual problem down here
    Context.reply("Welcome user", {
        parse_mode: 'HTML',
        ...Markup.inlineKeyboard([
            Markup.button.callback("📚 Products", "products"),
            Markup.button.callback("🛒 Cart", "products"),
        ]),
        ...Markup.inlineKeyboard([
            Markup.button.callback("🪪 Account", "account"),
            Markup.button.callback("ℹ️ Info", "info"),
        ]),
        // BUTTON
    })
})

Where I wrote "BUTTON" I'd like to add a button that only shows if the user id is in the admin list, so I tried this way:

if (Config.administrators.includes(Context.from.id)) {
    ...Markup.inlineKeyboard([
        Markup.button.callback("Admin Panel", "admin")
    ]),
}

but I get that a comma is expected and can't accomplish my goal.


Solution

  • Resolved the problem in this way:

    let keyboard = {
        inline_keyboard: [
            [Markup.button.callback("📚 Prodotti", "products")],
            [Markup.button.callback("🪪 Account", "account"), Markup.button.callback("ℹ️ Info", "info")],
        ],
    }
    
    if (user.admin)
        keyboard.inline_keyboard.push([Markup.button.callback("🛠️ Pannello Amministratori", "panel")])
    
    
    await Context.editMessageReplyMarkup(keyboard);
    

    edit: easier way