Giter Site home page Giter Site logo

mcpeblocker / telegraf-pagination Goto Github PK

View Code? Open in Web Editor NEW
11.0 1.0 4.0 83 KB

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

License: MIT License

JavaScript 100.00%
pagination-library telegraf telegraf-plugin telegrafjs telegram-bot

telegraf-pagination's Introduction

telegraf-pagination

A simplified Telegraf plugin to provide users with a great pagination interface. The plugin provides two ways of list pagination interfaces depending on developer's choice:

  1. Text mode

2. Buttons mode

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 { Markup, 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", async (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)
    isButtonsMode: false, // optional. Default value: false. Allows you to display names on buttons (there is support for associative arrays)
    buttonModeOptions: {
      isSimpleArray: true, // optional. Default value: true. Enables/disables support for associative arrays
      titleKey: '' // optional. Default value: null. If the associative mode is enabled (isSimply: false), determines by which key the title for the button will be taken.
    },
    isEnabledDeleteButton: true, // optional. Default value: true
    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: "โŒ"
    },
    inlineCustomButtons: [
      Markup.button.callback('Title custom button', 'your_callback_name')
    ] // optional. Default value: null
  });

  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");
});

โšก๏ธ Recent features:

  • Buttons mode

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

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

bot.start(async ctx => {
    let pagination = new Pagination({
        data,
        isButtonsMode: true,
        buttonModeOptions: {
          title: "name", // the 'name' property of each item is displayed
          
          // you can implement complex combinations of item keys using function ๐Ÿ‘‡
          // title: (item, i) => i + 1 + ". " + item.title,
        },
    });
    let text = await pagination.text();
    let keyboard = await pagination.keyboard();
    ctx.reply(text, keyboard);

    pagination.handleActions(bot);
});

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

telegraf-pagination's People

Contributors

arnurarykbaev avatar destyk avatar mcpeblocker avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

telegraf-pagination's Issues

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)

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"));

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.