Git Product home page Git Product logo

telegram-keyboard's Introduction

Telegram Keyboard Builder

Simple and powerful reply and inline keyboard builder for Telegram Bots

Installation

Just use npm

npm i telegram-keyboard --save

or yarn

yarn add telegram-keyboard

Example of use in Telegraf

const Telegraf = require('telegraf')
const { Keyboard } = require('telegram-keyboard')

const bot = new Telegraf(process.env.BOT_TOKEN)

bot.on('text', async (ctx) => {
  const keyboard = Keyboard.make([
    ['Button 1', 'Button 2'], // First row
    ['Button 3', 'Button 4'], // Second row
  ])

  await ctx.reply('Simple built-in keyboard', keyboard.reply())
  await ctx.reply('Simple inline keyboard', keyboard.inline())
})

Reply (build-in) keyboard

Example

const { Keyboard } = require('telegram-keyboard')

const keyboard = Keyboard.make(['Button 1', 'Button 2']).reply()

// or using shortcut
const keyboard = Keyboard.reply(['Button 1', 'Button 2'])

console.log(keyboard)

Result

{
  "reply_markup": {
    "resize_keyboard": true,
    "keyboard": [
      [
        "Button 1",
        "Button 2"
      ]
    ]
  }
}

Inline keyboard

Example

const { Keyboard } = require('telegram-keyboard')

const keyboard = Keyboard.make(['Button 1', 'Button 2']).inline()

// or using shortcut
const keyboard = Keyboard.inline(['Button 1', 'Button 2'])

console.log(keyboard)

Result

{
  "reply_markup": {
    "resize_keyboard": true,
    "inline_keyboard": [
      [
        {
          "text": "Button 1",
          "callback_data": "Button 1"
        },
        {
          "text": "Button 2",
          "callback_data": "Button 2"
        }
      ]
    ]
  }
}

Inline keyboard with custom callback data

Example

const { Keyboard, Key } = require('telegram-keyboard')

const keyboard = Keyboard.make([
  Key.callback('Button 1', 'action1'),
  Key.callback('Button 2', 'action2'),
]).inline()

console.log(keyboard)

Result

{
  "reply_markup": {
    "resize_keyboard": true,
    "inline_keyboard": [
      [
        {
          "text": "Button 1",
          "callback_data": "action1"
        },
        {
          "text": "Button 2",
          "callback_data": "action2"
        }
      ]
    ]
  }
}

Fixed columns keyboard

Example

const { Keyboard } = require('telegram-keyboard')

const keyboard = Keyboard.make(['1', '2', '3', '4', '5'], {
  columns: 2,
}).reply()

console.log(keyboard)

Result

{
  "reply_markup": {
    "resize_keyboard": true,
    "keyboard": [
      ["1", "2"],
      ["3", "4"],
      ["5"]
    ]
  }
}

Calculated columns keyboard

Example

const { Keyboard } = require('telegram-keyboard')

const keyboard = Keyboard.make(['1', '2', '3', '4', '5'], {
  wrap: (row, index, button) => Math.random() > 0.5
}).reply()

console.log(keyboard)

Result

{
  "reply_markup": {
    "resize_keyboard": true,
    "keyboard": [ // different every time
      ["1", "2"],
      ["3"],
      ["4"],
      ["5"]
    ]
  }
}

Pattern

Example

In this example pattern: [3, 1, 1] means that the first row will have 3 buttons, the second - 1, the third - 1 and all the other buttons in the last row

const { Keyboard } = require('telegram-keyboard')

const keyboard = Keyboard.make([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], {
    pattern: [3, 1, 1]
}).reply()

console.log(keyboard)

Result

{
  "reply_markup": {
    "resize_keyboard": true,
    "keyboard": [
      ["1", "2", "3"],
      ["4"],
      ["5"],
      ["6", "7", "8", "9", "10"]
    ]
  }
}

Custom filter function

Default filter function is button => !button.hide but you can pass your filtering function

Example

const { Keyboard } = require('telegram-keyboard')

const keyboard = Keyboard.make([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], {
    columns: 2,
    filter: btn => btn % 2
}).reply()

console.log(keyboard)

Result

{
  "reply_markup": {
    "resize_keyboard": true,
    "keyboard": [
      ["1", "3"],
      ["5", "7"],
      ["9"]
    ]
  }
}

Filter after build

Example

const { Keyboard } = require('telegram-keyboard')

const keyboard = Keyboard.make([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], {
    columns: 2,
    filter: btn => btn % 2,
    filterAfterBuild: true
}).reply()

console.log(keyboard)

Result

{
  "reply_markup": {
    "resize_keyboard": true,
    "keyboard": [
      ["1"],
      ["3"],
      ["5"],
      ["7"],
      ["9"]
    ]
  }
}

Flat buttons

Example

const { Keyboard } = require('telegram-keyboard')

const keyboard = Keyboard.make([[1, 2], [3, 4, 5, 6], [7, 8, 9, 10]], {
    flat: true,
    columns: 3,
}).reply()

console.log(keyboard)

Result

{
  "reply_markup": {
    "resize_keyboard": true,
    "keyboard": [
      ["1", "2", "3"],
      ["4", "5", "6"],
      ["7", "8", "9"],
      [ "10"]
    ]
  }
}

Combine keyboards

Example

const { Keyboard } = require('telegram-keyboard')

const keyboard1 = Keyboard.make(['1', '2', '3', '4'], {
  columns: 2
})
const keyboard2 = Keyboard.make(['5', '6', '7', '8'])

const keyboard = Keyboard.combine(keyboard1, keyboard2).reply()

console.log(keyboard)

Result

{
  "reply_markup": {
    "resize_keyboard": true,
    "keyboard": [
      ["1", "2"],
      ["3", "4"],
      ["5", "6", "7", "8"]
    ]
  }
}

Construct keyboard

Example

Full example in examples/pagination.js

Instead of writing a separate function to create the keyboard like this:

const createKeyboard = page => {
  return Keyboard
    .make(/* ... */)
}

You can pass function to Keyboard.make method. The function must return either an array of buttons or another keyboard. After that with the keyboard.construct(someArgs) method you can recreate it

const { Keyboard } = require('telegram-keyboard')

const items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const itemsPerPage = 4

const keyboard = Keyboard.make((page) => {
    const pageItems = items.slice(page * itemsPerPage, page * itemsPerPage + itemsPerPage)
    
    return Keyboard.combine(
        Keyboard.make(pageItems, { columns: 3 }),
        Keyboard.make([
            Key.callback('<----', 'left', page === 0),
            Key.callback('---->', 'right', page === 2),
        ])
    )
})

// remake keyboard with some other arguments
console.log(keyboard.construct(0).reply())
console.log(keyboard.construct(1).reply())

More examples you may find in examples

telegram-keyboard's People

Contributors

d1dee avatar dependabot[bot] avatar destroyou avatar ditherx avatar mkikets99 avatar realpeha avatar s0ftik3 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

telegram-keyboard's Issues

double click on inline buttons

Hello,
I made inline menu with telegram-keyboard library.
I have a button in every step that will back to pervious step.
Its action is when user clicked on it will remove current menu( deleteMessage() method ) and will print pervious menu.
But if user double click on button i will receive this error: 'Bad Request: message to delete not found'.
I also have this problem with the other buttons.
Is there any solution to fix this problem?

Buttons that open app on mobile

Hi, I am not sure if this is the place to ask this, but if is not it would be great if you can help me clarifying this issue.

I have a telegram bot and I need to create a button that when the user tap on it it should open a mobile app, when I do this on a HTML site I add on an anchor tag this href

href = "lightning:lnbc60n1p3yyvn6pp5yx2eycreyxuxy048v4cf9305vmhtdhk23kxk0tp6xtd39r64mkcsdpl2pshjmt9de6zqen0wgsrvgrsd9ux2mrnypshggrnv96x7umgd9ejuurvv93k2tsxqzjccqpjsp5p9lyqyu3fskh9zzjldyq2zgdrmh9thzcjpr8zeun6hjk9sy99y5qrzjqfyyyppkypkukp3nrql8kektwzp6vcf4j9n7w8f8c5axh3me6ktsvzj0w5qqztcqqqqqqqryqqqqqqgq9q9qyyssqs0gspkcm8dqw2gh358yygjg8kav5rlg5u7d0rgejmqkc9k9t2xvq7p7pwu08ff3m275t39rdc9888vw8ht7hy8u883wcvcymvwe0tnsputm7w6"

I tried to do it on a inline button with url but it doesn't work.

customizing the buttons

Is it posible to create buttons with custom styles, like background color or font color, etc?

Keyboard as command

How to make keyboard as command and then i can pass it seems like slash ex. /help

Cannot deploy to heroku

I have this running fine locally but when i try to deploy to heroku the modules won't work.
Is there a different package.json configuration needed to work with heroku?

2021-11-18T17:18:54.547748+00:00 app[web.1]: Require stack:
2021-11-18T17:18:54.547749+00:00 app[web.1]: - /app/index.js```

Newline after .remove and .add

How can I keep my new .added option in the keyboard to a newline?:

const options = {
inline: false, // default
duplicates: false, // default
newline: true
};

const keyboard2 = new Keyboard(options);

keyboard2
.add("Athletic", "Alavés", "Atlético", "Barcelona")
.add("Betis", "Espanyol", "Getafe", "Granada");

ctx.reply(
"I know stuff. Choose any two teams and I'll tell you its past games",
keyboard2.draw()
);

keyboard2.remove(${msg});

keyboard2.add(${teamSelected[0]});

I display 8 teams to the User and ask the user to choose a Team, and then I remove it, so the user can only choose a rival between the remaining 7 teams. But on a new iteration after he chooses this second team, I want to reenter the first team removed. How can I enter it as a newline?

Limit access to admins only

How to limit access so the buttons don't show up for all users.

Either only the user currently pressing the buttons or all admins?

SyntaxError: Unexpected token =

Hello, I'm trying to use the library and nodejs is returning the following error:

/my-project/node_modules/telegram-keyboard/lib/keyboard.js:12
    static defaultOptions = {
                          ^

SyntaxError: Unexpected token =

I already searched a lot but I didn't find anything like that, do you know what it can be?

Unhandled error while processing update

I am following simple keyboard given here: https://github.com/RealPeha/telegram-keyboard/blob/master/examples/telegraf/simple.js

I am deploying my bot on AWS lamda using serverless framework that's why I am using telegraf-aws module.

The webhook gets triggered when I send message to the bot but it ends up in an error.

The code looks very simple but still not working. Here is my code:

"use strict";

const token = process.env.BOT_TOKEN;

if (!token) {
  throw new Error("BOT_TOKEN must be provided!");
}

const { Telegraf } = require("telegraf");

const telegrafAWS = require("telegraf-aws");

const bot = new Telegraf(token, {
  telegram: {
    webhookReply: true,
  },
});

const handler = telegrafAWS(bot, {
  timeout: 3000,
});

const { Keyboard } = require("telegram-keyboard");

const mainMenuKeyboard = Keyboard.make([
  ["Main menu", "Inline Menu"],
  ["Help"],
]).reply();

bot.start(({ reply }) => {
  return reply("Simple Keyboard", mainMenuKeyboard);
});

module.exports = { handler };

And here is the error

2021-01-26 17:56:17.857 (+05:00)	ba407db1-3a49-4553-b3ff-1afb6dd8fcd1	ERROR	Unhandled error while processing {
  update_id: 158445257,
  message: {
    message_id: 150,
    from: {
      id: 935285759,
      is_bot: false,
      first_name: 'Abdul',
      last_name: 'Fatah',
      username: 'abdulfatah66',
      language_code: 'en'
    },
    chat: {
      id: 935285759,
      first_name: 'Abdul',
      last_name: 'Fatah',
      username: 'abdulfatah66',
      type: 'private'
    },
    date: 1611665763,
    text: '/start',
    entities: [ [Object] ]
  }
}

Please help. Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.