A simplified Telegraf plugin to provide users with a great interface.

Overview

telegraf-pagination

A simplified Telegraf plugin to provide users with a great interface.

Getting started

Prerequisites

You need to have telegraf installed on your project to use that plugin.

$ npm install telegraf

or

$ yarn add telegraf

See offical guide for more info. Once you have installed telegraf in your project, you can use telegraf-pagination.

Installing

Run one of these commands depending on what package manager you're using:

$ npm install telegraf-pagination

or

$ yarn add telegraf-pagination

Quick start

Default mode

const { Pagination } =  require('telegraf-pagination');

let data = [...]; // define data as an array

bot.start(async ctx => {
    let pagination = new Pagination({ data });
    let text = await pagination.text();
    let keyboard = await pagination.keyboard();
    ctx.reply(text, keyboard);

    pagination.handleActions(bot);
});

Lazy mode

const { Pagination } =  require('telegraf-pagination');

let data = [...]; // define data as an array

bot.start(async ctx => {
    let pagination = new Pagination({
        lazy: true, // switch lazy mode on
        data: (page, size) => data.slice((page-1)*size, page*size), // callback that returns items of the page. Can be asynchronous
        total: data.length // optional. can be useful when generating a header
    });
    let text = await pagination.text();
    let keyboard = await pagination.keyboard();
    ctx.reply(text, keyboard);

    pagination.handleActions(bot);
});

Full Example

const { Telegraf } = require("telegraf");
const { Pagination } = require("telegraf-pagination");

const TOKEN = "YOUR_BOT_TOKEN";
const bot = new Telegraf(TOKEN);

let fakeData = Array(10)
  .fill(0)
  .map((_, i) => ({
    id: i,
    title: `Item ${i + 1}`,
  }));

bot.command("pagination", (ctx) => {
  const pagination = new Pagination({
    data: fakeData, // array of items
    header: (currentPage, pageSize, total) =>
      `${currentPage}-page of total ${total}`, // optional. Default value: 👇
    // `Items ${(currentPage - 1) * pageSize + 1 }-${currentPage * pageSize <= total ? currentPage * pageSize : total} of ${total}`;
    format: (item, index) => `${index + 1}. ${item.title}`, // optional. Default value: 👇
    // `${index + 1}. ${item}`;
    pageSize: 8, // optional. Default value: 10
    rowSize: 4, // optional. Default value: 5 (maximum 8)
    onSelect: (item, index) => {
      ctx.reply(item.title);
    }, // optional. Default value: empty function
    messages: {
      // optional
      firstPage: "First page", // optional. Default value: "❗️ That's the first page"
      lastPage: "Last page", // optional. Default value: "❗️ That's the last page"
      prev: "◀️", // optional. Default value: "⬅️"
      next: "▶️", // optional. Default value: "➡️"
      delete: "🗑", // optional. Default value: "❌"
    },
  });

  pagination.handleActions(bot); // pass bot or scene instance as a parameter

  let text = await pagination.text(); // get pagination text
  let keyboard = await pagination.keyboard(); // get pagination keyboard
  ctx.replyWithHTML(text, keyboard);
});

bot.launch().then(() => {
  console.log("Bot is running");
});

Contributing

Please read CODE_OF_CONDUCT.md for details on our code of conduct. Feel free to submit any pull request.

Versioning

We use SemVer for versioning. For the versions available, see the tags on this repository.

Authors

See also the list of contributors who participated in this project.

License

This project is licensed under the MIT License - see the LICENSE.md file for details

Comments
  • usage with wizard scenes

    usage with wizard scenes

    image Please tell me how to use the stage. If I use return await ctx.wizard.next() , then the next scene starts with the ${callback-data}-next callback. If you remove ctx.wizard.next() at all, then the next scene simply does not start

    const { Telegraf, Composer, Scenes, session, Markup } = require("telegraf");
    const bot = new Telegraf(process.env.BOT_TOKEN);
    const { Pagination } =  require('telegraf-pagination');
    
    
    
    const startWizard = new Composer();
    startWizard.on("text", async (ctx) => {
      const trackerMessage = `some text`;
      await ctx.reply(trackerMessage);
      return ctx.wizard.next();
    });
    
    const searchTorrent = new Composer();
    searchTorrent.on("text", async (ctx) => {
       arrayRes = [
    {title: 'fist', id: 1},
    {title: 'second', id: 2}, 
    {title: 'third', id: 3}, 
    {title: 'fourth', id: 4}, 
    {title: 'fifth', id: 5}, 
    {title: 'sixth', id: 6}, 
    {title: 'seventh', id: 7}, 
    {title: 'eighth', id: 8},
    {title: 'ninth', id: 9}, 
    {title: 'tenth', id: 10}, 
    {title: 'eleventh', id: 11}, 
    {title: 'twelfth', id: 12}, 
    {title: 'thirteenth', id: 13}
    ]
        const pagination = new Pagination({
          data: arrayRes, 
          //some options
        });
    
        pagination.handleActions(searchTorrent);
      
        let text = await pagination.text(); 
        let keyboard = await pagination.keyboard(); 
        await ctx.replyWithHTML(text, keyboard);
        
        return await ctx.wizard.next()
      }
    
    });
    
    const searchTorrentAction = new Composer();
    searchTorrentAction.action(/.+/, async (ctx) => {
      await ctx.deleteMessage();
      console.log(ctx, 'CONTEXT');
      return ctx.scene.leave();
    });
    
    
    /* Scenes declare */
    const menuScene = new Scenes.WizardScene(
      "sceneWizard",
      searchTorrent,
      searchTorrentAction,
    );
    const stage = new Scenes.Stage([menuScene]);
    
    /* middleware to scenes */
    bot.use(session());
    bot.use(stage.middleware());
    
    bot.on("text", (ctx) => ctx.scene.enter("sceneWizard"));
    
    opened by ArnurArykbaev 2
  • Added support `isButtonMode`, `inlineCustomButtons`, `isEnabledDeleteButton`

    Added support `isButtonMode`, `inlineCustomButtons`, `isEnabledDeleteButton`

    Now it is possible to switch between button mode and text mode (as it was before). And also disable the display of the "Delete" button if it is not needed.

    I think this innovation will be useful to many. Thanks!

    opened by destyk 1
  • Provide example for scene instance

    Provide example for scene instance

    When used like that:

    myScene.action("...", ctx => {
       ...
       pagination.handleActions(ctx.scene); // pass bot or scene instance as a parameter
    });
    

    Produces error:

    UnhandledPromiseRejectionWarning: TypeError: composer.action is not a function
        at Pagination.handleActions (D:\work\TgBot\node_modules\telegraf-pagination\index.js:108:18)
    
    opened by iamcsharper 1
  • Hide pagination buttons & fixes

    Hide pagination buttons & fixes

    1. Added hiding pagination buttons when there is only one page with data.
    2. And also fixed the situation when telegraf could throw an exception due to an empty button name (relevant when isButtonMode = true)
    opened by destyk 0
  • `rowSize` doesn't work with `isButtonsMode`

    `rowSize` doesn't work with `isButtonsMode`

    I think can be resolved by replacing https://github.com/mcpeblocker/telegraf-pagination/blob/b296dd5859556f6f423932e83875212cbb421bb2/index.js#L154

    to

    if (0 === i % this.rowSize && row.length) {
    
    opened by Viiprogrammer 0
Releases(1.4.1)
  • 1.4.0(Oct 1, 2022)

    Support for layout adjustment of custom inline buttons

    Custom inline buttons option now expect the same array as given for Markup.keyboard() function of Telegraf

    Code below will be displayed as row

        inlineCustomButtons: [
          [
            Markup.button.callback("Custom 1", "custom1"),
            Markup.button.callback("Custom 2", "custom2"),
          ],
        ],
    

    Code below will be displayed as column of these two

        inlineCustomButtons: [
          [Markup.button.callback("Custom 1", "custom1")],
          [Markup.button.callback("Custom 2", "custom2")],
        ],
    
    Source code(tar.gz)
    Source code(zip)
  • v1.3.4(Sep 27, 2022)

    Using function became available in Buttons Mode:

    • Either string as key and function to form string from item can be used.
    • Function takes item and its index as arguments and can use to form complex combinations.
    Source code(tar.gz)
    Source code(zip)
  • 1.3.3(Sep 23, 2022)

  • v1.3.2(Sep 23, 2022)

  • 1.3.2(Sep 23, 2022)

  • 1.3.1(Sep 23, 2022)

  • 1.3.0(Sep 23, 2022)

  • 1.2.2(Sep 17, 2022)

    1. Added hiding pagination buttons when there is only one page with data.
    2. And also fixed the situation when telegraf could throw an exception due to an empty button name (relevant when isButtonMode = true)

    Special thanks to @destyk!

    Source code(tar.gz)
    Source code(zip)
  • 1.2.1(Sep 16, 2022)

Owner
Alisher Ortiqov
Backend Developer. 15 y.o.
Alisher Ortiqov
USA Covid-19 Tracker is a mobile-first application built with React and Redux to give precise information about the virus behavior in the United States. Great transitions and user feedback made with plain CSS.

React.js USA Covid-19 Tracker This application allows the public to keep track of the stadistics of the Covid-19 Pandemic in the United Stated. You wi

Rafael Echart 14 Oct 25, 2022
Web application that consumes an API to provide an complete experience of an recipes app

Project: Recipes App Project developed studying in Trybe. Technologies and tools used React React Hooks Context API SCRUM / Kanban Project objective T

Ádran Farias Carnavale 0 Jun 14, 2022
Gnome Shell extension to provide a flexible applications dock (WIP).

Flexi Dock (WIP) Gnome Shell extension to provide a flexible applications dock. Installation The easiest way to install this extension is via the offi

Hardpixel 3 Aug 29, 2022
Provide solutions to make your app flexible for different screen sizes, different devices.

react-native-size-scaling Provide solutions to make your app flexible for different screen sizes, different devices, based on your device's pixel rati

Hoà Phan 33 Dec 23, 2022
TryShape is an open-source platform to create shapes of your choice using a simple, easy-to-use interface. You can create banners, circles, polygonal shapes, export them as SVG, PNG, and even as CSS.

Create, Export, Share, and Use any Shapes of your choice. View Demo · Report Bug · Request Feature ?? Introducing TryShape TryShape is an opensource p

TryShape 148 Dec 26, 2022
Joke feedback interface that prevents unconstructive criticism

Feedback Sentiment Try it out! I always love and welcome constructive criticism, but when "feedback" becomes unconstructive and borderline insulting..

null 34 Nov 30, 2021
An application that has a frontend (user interface) that allows you to create, read, update or delete (CRUD) products using an API in which you can also create, read, update or delete products.

CRUD app with React and Firebase 9 An application that has a frontend (user interface) that allows you to create, read, update or delete (CRUD) produc

Júlio Bem 3 Sep 28, 2021
The UI for staking NFTs on Solana. Cardinal staking UI can be treated as an admin interface for stake pools hosted by cardinal-staking as well as a barebones end-user staking UI

Cardinal Staking UI This repository hosts the UI inteface that powers https://stake.cardinal.so for staking NFTs on Solana. Use this repo to create an

Cardinal 55 Dec 24, 2022
The user interface of the Restreamer for the connection to the Core application.

Restreamer-UI The user interface of the Restreamer for the connection to the Core application. React Material-UI (MUI) Development For the Restreamer

datarhei 12 Dec 21, 2022
CEP is a software platform designed for users that want to learn or rapidly prototype using standard A.I. components.

Cortic Edge-computing Platform (CEP) CEP is a software platform designed for users that want to learn or rapidly prototype using standard A.I. compone

Cortic Technology Corp. 137 Jan 1, 2023
A web application that allows users to book rockets and join selected space missions, Using the SpaceX API.

Space-Travelers-Hub A web application that allow users to book rockets and join selected space missions, Using the SpaceX API. This project was bootst

Rachid Boudaoudi 6 Dec 9, 2021
Github Leaderboard API - Most popular users, repositories, etc.

Github Leaderboard API Data pengguna, repositori, organisasi populer yang ada di Github dan diurutkan berdasarkan jumlah dari informasi tertentu, misa

Feri Irawan 15 Dec 22, 2022
💸 1st place at Hack The Job 2022 - A chrome extension that automatically tracks purchases and budgets, alerting users if they go over their spending limits and allowing them to download PDF reports.

?? Won 1st place overall @ Hack the Job! ?? A browser extension for keeping on top of your finances. This project will keep track of the purchases you

Harsh Topiwala 11 Oct 4, 2022
React app that allows users to compare and analyze the cost of living between cities around the world.

✨ LivingApp is a react app that allows users to compare and analyze the cost of living between cities around the world. ✨ Features ?? Simple: Bootstra

Ivan Kuznietsov 3 Feb 5, 2022
This compress library was made with Brotli and Gzip help, for React users who want to make website more performance and reduce JS bundle code

React-compress This compress library was made with Brotli and Gzip help, for React users who want to make website more performance and reduce JS bundl

Koma Human 30 Jan 6, 2023
Math Magicians! This is a website for all fans of mathematics. It is a Single Page App (SPA) that allows users to make basic calculations and read a random math-related quote.

Math Magicians Math Magicians is the first React Project I'm building. The main objective of this is to understand React features with a project-based

Andrés Felipe Arroyave Naranjo 7 Feb 26, 2022
A Single Page App (SPA) that allows users to: make simple calculations and read a random math-related quote

Math magicians is a website for all fans of mathematics. It is a Single Page App (SPA) that allows users to: make simple calculations and read a random math-related quote.

Sahar Abdel Samad 13 May 31, 2022
"BookStore" is a web app for adding books. It is a Single Page App (SPA) that allows users to add and remove a book from the library

BookStore | M3Wx "BookStore" is a web app for adding and removing books from a library storage. It is a Single Page App (SPA) that allows users to add

Alexander Oguzie-Ibeh 4 Apr 11, 2022
Choosy is a mobile application that allows users to create photo polls that others can vote on and help declare which photo is the best.

Choosy - Create photo polls The freshest mobile application for your photo polls! Explore the docs » Table of Contents Introduction App concept Target

Choosy 13 Sep 7, 2022