Coder Social home page Coder Social logo

gazmull / discord-paginationembed Goto Github PK

View Code? Open in Web Editor NEW
89.0 89.0 17.0 1.81 MB

A pagination utility for MessageEmbed in Discord.JS

Home Page: https://docs.thegzm.space/discord-paginationembed

License: MIT License

JavaScript 37.37% Shell 1.30% TypeScript 61.33%
discord-js embeds leaderboard messageembed paged pages pagination paginationembed utility

discord-paginationembed's People

Contributors

androz2091 avatar cycloptux avatar d-shaun avatar gazmull avatar kyleboyer avatar sawa-ko avatar steven-peralta 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

Watchers

 avatar  avatar  avatar  avatar  avatar

discord-paginationembed's Issues

Embed is not showing

I try to put a simple test Embed but the result is that in the response of the message there is nothing, the embed does not appear.

    let embeds = [];
    embeds.push(
      new MessageEmbed().setDescription('xd').setFooter('xd').setTitle('uy'),
    );
    
    try {
      new Pagination.Embeds()
        .setArray(embeds)
        .setAuthorizedUsers(command.author.id)
        .setChannel(command.channel as TextChannel | DMChannel)
        .setPageIndicator(true)
        .setPage(1)
        .setTitle('Test')
        .setDescription(
          'Test',
        )
        .setFooter(EmbedMessageEnum.FOOTER_HELP)
        .setColor(this._embedMessageService.getRandomColor())
        .setThumbnail(Environments.photo)
        .build();
    } catch ({ message }) {
      await command.author.send(
        this._embedMessageService.noPermissionMessage(
          command.guild.channels.cache.get(command.channel.id).name,
        ),
      );
    }
  }

Response

image

As you can see, the embed that was entered in the array does not appear.

Method showPageIndicator() Has No Effect

new paginator.Embeds()
    .setArray(embeds)
    .setAuthorizedUser(message.author)
    .setChannel(message.channel)
    .showPageIndicator(false)
    .build();

Even it I put false explicitly or leave it out the page indication still seems to show.

This seems to be because in Embeds you check for this.showPageIndicator.

const shouldIndicate = this.showPageIndicator

But in PaginationEmbed, showPageIndicator() is actually setting this.pageIndicator

this.pageIndicator = boolean;

Having an issue with my embed.

Getting an error with a few of my commands just updated to the newest version 11 i am guessing.

image

I havent been able to figure out how to fix it yet

old versions not published to npm

I'm trying to use 0.8.0 (as it seems discord 12 isn't yet on npm) and I checked npm. It seems 0.8.0 is not published there - can you do that?

this.clientAssets.prompt.replace is not a function

(node:16116) UnhandledPromiseRejectionWarning: TypeError: this.clientAssets.prompt.replace is not a function
    at exports.Embeds._awaitResponseEx (\node_modules\discord-paginationembed\bin\base\index.js:206:89)
    at exports.Embeds._awaitResponse (\node_modules\discord-paginationembed\bin\base\index.js:173:63)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
(node:16116) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 4) 

appears when I use page jumper

addFields() bug!?

image

(node:15268) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'build' of undefined
at Object.character (*hide)
at Client. (*hide)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(node:15268) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:15268) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I used this tutorial

image

however, addField() works well!

.setElementsPerPage is not a function

Hi, I really like this npm package, but when I have .setElementsPerPage(1) it gives me this error:
[Uncaught Exception] TypeError: (intermediate value).setArray(...).setDeleteOnTimeout(...).setAuthorizedUsers(...).setChannel(...).setPageIndicator(...).setThumbnail(...).setFooter(...).setURL(...).setColor(...).setElementsPerPage is not a function

Embed Data stacks

I created a Pagination embed object, and it works perfectly. However, whenever the command is called twice, it would double the total amount of pages, and EmbedMsg.addField would occur twice, and the data would be copied another the additional pages. Is there any way to reset the embed data?

      embedMsg = new Pagination.Embeds()
      embeds.push(
        new Discord.MessageEmbed()
          .setTitle("Test")
          .setAuthor("Test")
          .setDescription("Test")
          .addField("\u200b", "\u200b")
          .addField(
            "Test3",
            "test"
          )
      );

        embedMsg
        .setArray(embeds)
        .setDeleteOnTimeout(true)
        .setChannel(msg.channel)
        .setPageIndicator(true)
        .setPage(1)
        .addField("\u200b", "\u200b")
        .addField("Test", "TestData")
        .setFooter(
          "Footer"
        )
        .setColor(0xff00ae)
        .build()

FieldsEmbed Mode Not Working at DJSv13

For upcoming release of PaginationEmbed v3

FieldsEmbed mode has an extension method formatField which still overrides the field value/s with function for array mapping, however with discordjs/discord.js#4880, now it causes the module to throw out an error due to field value/s being non-string type.

Proposed Solution

  • formatField will no longer directly pass the arguments to <FieldsEmbed>.embed.fields, instead it will be stored as a property (array of fields) in the current instance of FieldsEmbed and then all formatted fields' functions will be invoked and its output will be passed to <FieldsEmbed>.embed.fields.
    • This also means that invoking addField first is required.
    • This will remove inline option in favour of required addField invocation.
  • Name parameter will be converted to as a field identifier for resolving the desired field and will accept number type for providing the desired field's index. Number type will be added due to the case of different fields with identical field name.
Code Example

New syntax

- formatField(name: string, mapFn: Function, inline: boolean)
+ formatField(nameOrIndex: string | number, mapFn: Function)

Usage
From:

fieldsEmbed.formatField('Occupation', el => el.occupation, true);

To:

fieldsEmbed
  .addField('Occupation', 'Could not be loaded', true)
  // Or pass `0` instead of `'Occupation'`
  .formatField('Occupation', el => el.occupation)

Note: Subject to change

ps. If you got something on your mind regarding this issue, please do not hesitate to post πŸ₯‚
ps2. NICE

Regarding the issue of RichEmbeds and attachments.

Hey

So I've been trying to use an array of embeds, but instead of message embeds, a Rich Embed array, because I needed images to pop up.

And like, the first image went well, but the second one...

Why is this a thing?
Here's the code btw:

`async function techInformation(message, CorpMember) {
const messagesplit = message.content.split(" ")

let embeds = []

for(let tech in TechData) {
    let Embed = new RichEmbed().setColor("RANDOM")
    Embed.setTitle(`${tech}`)
    Embed.attachFile(`techIcons/${tech}.png`)
    Embed.setThumbnail(`attachment://${tech}.png`)
    embeds.push(Embed)
}
let iptech = new Pagination.Embeds()
    .setArray(embeds)
    .setAuthorizedUsers([message.author.id])
    .setChannel(message.channel)
    .setPageIndicator(true)
    .setTitle(`Interactive Tech System for ${message.author.username}`)
    .setColor("RANDOM")
    .setDisabledNavigationEmojis(['DELETE'])
    .build()

}
`

This is on 11.5.1

how do I use rich embeds?

Maybe I'm not understanding this API completely, but it seems as though rich embeds are the outgoing embed, and message embed is the representation of that from a read perspective. So if I have an array of rich embeds, why doesn't that work exactly?

v1.0.0 Roadmap

Pull Requests are welcome!

This will change without prior notice.

Changes

Converting to TypeScript

  • Reduces development time when trying to sync up typings from src
  • Fixes Defined In from the Documentation site
  • Reduces dependency bloat (eslint)
  • Possible API rewrite
    • PaginationEmbed and Embeds Mode should not extend MessageEmbed as there is no significant identical members and it's only bothered as a massive bloat, instead only FieldsEmbed should extend MessageEmbed as they have significant identical members (accessibility).

Requirements

  • Change to Node 10 as minimum Node version (please re-check package.json for this)

Additions

Event Emitter

  • Either do a mixin with MessagedEmbed or have a listener property under PaginationEmbed
  • Starters: build, finish, cancel, expire, error

More Behaviour Options

  • Such as customising prompt message

Publish to NPM

  • Proper installation with NPM (also revert yarn scripts+lock)

Change the jump message

I want to change the Jump message to other languages, (spanish in this case)
How could I?

Reaction navigation buttons in DM's doesn't go to initial state

Hi, great plugin it helped me a lot building my small Discord Bot. But I have small problem with reaction buttons. In guilds they works very well, after clicking reaction it goes back to initial state. But in DM's after clicking emoji reaction it stays in the same state and user needs to "unclick" it before continuing. Is there any possible fix for it?

setAuthorizedUsers([]) results in Error

I would like to have a message embed where anyone that is not a bot can interact with the menu, however when setting authorized users to the default value/blank array, I still get the Error: Cannot invoke PaginationEmbed class without initialising the authorized users properly.

Disabling jump navigation emoji isn't enough to send paginated embed without MANAGE_MESSAGES

Steps to reproduce:

  1. Create Discord channel in server with bot (no MANAGE_MESSAGES or ADMIN perm) with discord-paginatedembed .
  2. Run command that creates a PaginationEmbed and builds it. This command should also disable the jump navigation emoji, the only emoji I believe that requires MANAGE_MESSAGE to work properly (since it deletes another user's message). Here's a short sample of some code that would fit this requirement:
const msg = <some Message instance>;

new Pagination.Embeds()
    .setArray([
        new Discord.MessageEmbed().addField('Test 1', 'test 1'),
        new Discord.MessageEmbed().addField('Test 2', 'test 2')
    ])
    .setAuthorizedUsers([msg.author.id])
    .setChannel(msg.channel)
    .setDisabledNavigationEmojis(['jump'])
    .build()
    .catch(err => {
        if (err) msg.channel.send('I do not have the required permissions to create a paginated embed here.');
    });

Expected result:
Paginated embed successfully builds and sends.

Actual result:
Catch code block runs with an error, saying that the client needs MANAGE_MESSAGES permission. However, since the jump navigation emoji is disabled, my understanding is that this permission is no longer required.

Emoji Reactions not responding

This is the code I have right now:
image

The embed sends without any problem, but the reactions don't do anything when clicked
The bot has full permissions

Catch delete errors

When people delete a embed before the bot can do it, it returns a Discord API error 'Unknown message', could you return on those errors so they won't appear in the console?

Option for error message in jumping pages by input

Hey there! Was just trying this library out and wondering how would I handle a case where user inputs a page number that doesn't exist.

Example: I have pagination of 5 embeds and a reaction emoji which prompts the user for a page number ( using .setClientAssets for a custom prompt message). I want to handle the case where the user enters a number like 6...

Here is my code

      const embeds = [];
      for (let i = 1; i <= 5; ++i) {
        embeds.push(new Discord.MessageEmbed().addField('Page', i));
      }
      const Embeds = new PaginationEmbed.Embeds()
        .setArray(embeds)
        .setAuthorizedUsers([message.author.id])
        .setChannel(message.channel)
        .setPageIndicator(true)
        .setTitle('Test Title')
        .setDescription('Test Description')
        .setFooter('Test Footer Text')
        .setURL('https://gazmull.github.io/discord-paginationembed')
        .setColor(0xFF00AE)
        .setTimeout(60000)
        .setClientAssets({ prompt: 'Page plz {{user}}' })
        .setDeleteOnTimeout(true)
        .setFunctionEmojis({
          '⬆': (_, instance) => {
            for (const embed of instance.array)
              embed.fields[0].value++;
          },
          '⬇': (_, instance) => {
            for (const embed of instance.array)
              embed.fields[0].value--;
          }
        })
        .on('start', () => console.log('Started!'))
        .on('finish', (user) => console.log(`Finished! User: ${user.username}`))
        .on('react', (user, emoji) => console.log(`Reacted! User: ${user.username} | Emoji: ${emoji.name} (${emoji.id})`))
        .on('expire', () => console.warn('Expired!'))
        .on('error', (error) => {
          console.log(error);
        });
      
      await Embeds.build();

The error doesn't actually come at .on('error', ...) listener

Reopen of #35

I am still running into this issue, reference to #35

TypeError: Cannot read property 'last' of undefined
    at exports.Embeds._awaitResponse (/rbd/pnpm-volume/62876d80-160e-479c-88ac-d013b13a516d/node_modules/.registry.npmjs.org/discord-paginationembed/2.0.0-beta.4/node_modules/discord-paginationembed/bin/base/index.js:163:38)
    at process._tickCallback (internal/process/next_tick.js:68:7)

Get message object?

Is it possible to get the message object used by an Embeds pagination or attach a pagination to a pre-existing message?

'Prepearing...' still visible after embed is shown

const embeds = hero.forms.map((form, idx, arr) => new MessageEmbed()
        .setTitle(`${translate(form.name)} (${form.star}β˜…)`)
        .setDescription(translate(form.lore))
        .setThumbnail(imageUrl(form.image))
        .setFooter(`Page ${idx + 1}/${arr.length}`)
    );

const msg = new EmbedsMode()
    .setArray(embeds)
    .setAuthorizedUsers([message.author.id])
    .setChannel(message.channel)
    .setPage(page)
    .showPageIndicator(false)
    .setDisabledNavigationEmojis(['JUMP'])
    .setColor(classColors[hero.class])
    .addField('Class', capitalizeFirstLetter(hero.class), true)
    .addField('Type', capitalizeFirstLetter(hero.type), true)
    .addField('Domain', hero.domain ? '-' : '-', true)
    .addField('Gender', capitalizeFirstLetter(hero.gender), true)
    .build();

message.channel
    .send(msg)
    .catch(error => console.log(error));

image

However, if I change in your library code ('src/struct/Embeds.js')

await this.clientMessage.message.edit(shouldIndicate, { embed: this.currentEmbed });

to

await this.clientMessage.message.edit(null, { embed: this.currentEmbed });

'Prepearing...' caption is removed.

The problem is that clientMessage.content which is used to build shouldIndicate is shared with initial message, so if I set it to empty string, space, non breaking space, etc - Discord discards message, because it is treated as empty.

discord v13

can we run discord paginationembed at discord v13. is it possible for create a guide for v13 or are you release a new version of discord paginationembed.

weird display bug ??

Hey there! I was trying out the library and it is very useful and easy! But I stampeded into a problem and am stuck. Below is my code-

`const embed = new Discord.MessageEmbed ()

const FieldsEmbed =new Pagination.FieldsEmbed()
.setArray(inv)
.setAuthorizedUsers([message.author.id])
.setElementsPerPage(2)
.setChannel(message.channel)
.setPageIndicator(true)
.setPage(1)
.formatField ("Inv", i => i.inv)
.setDeleteOnTimeout(false)
.setDisabledNavigationEmojis(['delete'])

FieldsEmbed.embed
.setColor(color)
.setDescription('Test Description');

await FieldsEmbed.build();

message.channel.send (FieldsEmbed)`

what happens is everytime the timeout happens or if i use the delete emoji to cancel the embed , the bot will send me another embed, containing what I put in the format field! Is that some kind of bugs or a mistake in my behalf? I really cannot continue my code with this thing happening-
IMG_20210430_164556

error TS2611: 'pages' is defined as a property

Command
tsc -p tsconfig.json

{
  "discord-paginationembed": "gazmull/discord-paginationembed#master",
   "typescript": "^4.2.3",
   "yarn": "^1.22.10"
}
node_modules/discord-paginationembed/typings/Embeds.d.ts:38:9 - error TS2611: 'pages' is defined as a property in class 'PaginationEmbed<MessageEmbed>', but is overridden here in 'Embeds' as an accessor.

38     get pages(): number;
           ~~~~~

node_modules/discord-paginationembed/typings/FieldsEmbed.d.ts:24:9 - error TS2611: 'pages' is defined as a property in class 'PaginationEmbed<Element>', but is overridden here in 'FieldsEmbed<Element>' as an accessor.

24     get pages(): number;
           ~~~~~


Found 2 errors.

Cannot use Homogeneous Arrays

Hi,

I Have Homogeneous Array like
const test = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

Can you tell me how to use this on pagination? I Have tried to use example like .formatField(LINK, el => el.(???)

This just works for arrays that have object inside.

I want, for example, show just 2 numbers per page passing this on .setElementsPerPage(2)

t.users.last is not a function

Here is my code:

const { lastPosts } = await this.client.insta.getProfile(this.client.config.insta);
const lastPostShortCode = lastPosts[0].shortcode;
const lastPost = await this.client.insta.getPost(lastPostShortCode);
const embeds = [];

lastPost.contents.forEach((item) => {
    const embed = new Discord.MessageEmbed()
    .setImage(item.url);
    embeds.push(embed);
});

let pagination = new Pagination.Embeds()
.setArray(embeds)
.setAuthorizedUsers([message.author.id])
.setChannel(message.channel)
.setPageIndicator(true)
.setColor("#FF0000")
.setTitle("Ouvrir sur Instagram")
.setURL(lastPosts[0].link)
.addField("❀️ Likes", lastPost.likes)
.addField("πŸ’¬ Commentaires", lastPosts[0].comments);

pagination.build();

The embeds var contains an Array of MessageEmbeds. When I react, all the reactions are removed without error.

I added a console.log(t); at the top of the _cleanUp function, and now I'm getting this error:

TypeError: t.users.last is not a function
    at exports.Embeds._awaitResponse (/Users/simon/Documents/GitHub/cyanide-happiness-bot/node_modules/discord-paginationembed/bin/base/index.js:163:32)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)

Capture d’écran 2020-02-14 aΜ€ 10 36 38

Jump message edit Error

IF image

Error:
(node:7684) UnhandledPromiseRejectionWarning: DiscordAPIError: Unknown Message at RequestHandler.execute (C:\Users\Drelaky\Desktop\bot2\node_modules\discord.js\src\rest\RequestHandler.js:170:25) at processTicksAndRejections (internal/process/task_queues.js:97:5) (Use node --trace-warnings ...to show where the warning was created) (node:7684) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag--unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1) (node:7684) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

IF
image
What is the problem???
please help meee

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.