Какой тип объекта ожидает discord-js-пагинация?

#javascript #pagination #discord.js #bots

Вопрос:

Здесь я столкнулся с небольшой проблемой.

Работа с discord.js v12. Пытаюсь найти способ создания разбиения на страницы с > 25 полями для отправки сообщений. В настоящее время я использую discord-js-разбиение на страницы.

Из того, что я могу сказать, я отправляю правильный тип для разбиения на страницы, однако кажется, что страницы попадают так же, как undefined и до прохождения pagination пакета. Я не уверен, как это возможно (читайте ниже).

Свою ошибку я получаю:

 (node:7328) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'send' of undefined
    at paginationEmbed (E:myProjectsromanBotnode_modulesdiscord.js-paginationindex.js:6:36)
    at run (E:myProjectsromanBotbotmain.js:88:33)
    at E:myProjectsromanBotbotmain.js:101:29
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:7328) 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:7328) [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.
 

Из БД я получаю [{}] (data used in function below) сообщение в этом формате:

 [ { id: 1, quote: 'hello', createdAt: '2021-07-04T15:31:32.571Z', updatedAt: '2021-07-04T15:31:32.571Z' } ]
 

Функция для создания страниц:

 if (msg.content.toLowerCase().startsWith(prefix   'romanreport')) {
                axios.get(`${host}/quote`)
                    .then(({ data }) => {
                        if (data.length > 0) {
                            const run = async (message) => {
                                console.log(data)
                                const MAX_FIELDS = 25;
                                // iterate over the commands and create field objects
                                const fields = data.map(i => ({ name: i.id, value: i.quote }))

                                // if there is less than 25 fields, you can safely send the embed
                                // in a single message
                                if (fields.length <= MAX_FIELDS)
                                    return message.reply(
                                        new Discord.MessageEmbed()
                                            .setTitle('Help')
                                            .setDescription(`Prefix: ${prefix}`)
                                            .addFields(fields),
                                    );

                                // if there are more, you need to create chunks w/ max 25 fields
                                const chunks = chunkify(fields, MAX_FIELDS);
                                // an array of embeds used by `discord.js-pagination`
                                const pages = [];

                                chunks.forEach((chunk) => {
                                    // create a new embed for each 25 fields
                                    pages.push(
                                        new Discord.MessageEmbed()
                                            .setTitle('Help')
                                            .setDescription(`Prefix: ${prefix}`)
                                            .addFields(chunk),
                                    );
                                });
                                console.log('pages', pages)
                                pagination('some message', pages);
                            }
                            function chunkify(arr, len) {
                                let chunks = [];
                                let i = 0;
                                let n = arr.length;

                                while (i < n) {
                                    chunks.push(arr.slice(i, (i  = len)));
                                }

                                return chunks;
                            }
                            run(data);
 

Когда я console.log(pages) перед инициализацией pagination('some message', pages) получаю:

 pages [
  MessageEmbed {
    type: 'rich',
    title: 'Help',
    description: 'Prefix: !',
    url: null,
    color: null,
    timestamp: null,
    fields: [
      [Object], [Object], [Object],
      [Object], [Object], [Object],
      [Object], [Object], [Object],
      [Object], [Object], [Object],
      [Object], [Object], [Object],
      [Object], [Object], [Object],
      [Object], [Object], [Object],
      [Object], [Object], [Object],
      [Object]
    ],
    thumbnail: null,
    image: null,
    video: null,
    author: null,
    provider: null,
    footer: null,
    files: []
  },
  MessageEmbed {
    type: 'rich',
    title: 'Help',
    description: 'Prefix: !',
    url: null,
    color: null,
    timestamp: null,
    fields: [ [Object], [Object] ],
    thumbnail: null,
    image: null,
    video: null,
    author: null,
    provider: null,
    footer: null,
    files: []
  }
]
 

Страницы[0].поля возвращает:

 pages [
  { name: '1', value: 'hello', inline: false },
  { name: '2', value: 'hello', inline: false },
  { name: '3', value: 'hello', inline: false },
  { name: '4', value: 'hello', inline: false },
  { name: '5', value: 'hello', inline: false },
  { name: '6', value: 'hello', inline: false },
  { name: '7', value: 'hello', inline: false },
  { name: '8', value: 'hello,hello', inline: false },
  { name: '9', value: 'hello', inline: false },
  { name: '10', value: 'hello', inline: false },
  { name: '11', value: 'hello', inline: false },
  { name: '12', value: 'hello', inline: false },
  { name: '13', value: 'hello', inline: false },
  { name: '14', value: 'hello', inline: false },
  { name: '15', value: 'hello', inline: false },
  { name: '16', value: 'hello', inline: false },
  { name: '17', value: 'hello', inline: false },
  { name: '18', value: 'hello', inline: false },
  { name: '19', value: 'hello', inline: false },
  { name: '20', value: 'hello', inline: false },
  { name: '21', value: 'hello', inline: false },
  { name: '22', value: 'hello', inline: false },
  { name: '23', value: 'hello', inline: false },
  { name: '24', value: 'hello', inline: false },
  { name: '25', value: 'hello', inline: false }
]
 

Мое непонимание проявляется при попытке оценить, что должен принимать пакет разбиения на страницы. Похоже, ему нужен массив объектов/массивов. Именно это я и посылаю.

Любая помощь будет признательна.

Комментарии:

1. РЕШЕНО! Было решено путем изменения pagination('some message', pages); на pagination(msg, pages); . Без фактического сообщения разбиение на страницы discord-js не может решить проблему отправки на канал сообщения.

Ответ №1:

Ошибка исходит от discord.js-pagination модуля, и это происходит потому message , что методу не pagination() передается.

pagination(msg, pages); должно сработать.

Я также внес некоторые изменения в ваш код. Ниже вы можете найти полный рабочий код:

 const bot = () => {
  const pagination = require('discord.js-pagination');
  const Discord = require('discord.js');
  const axios = require('axios');
  require('dotenv').config();

  const client = new Discord.Client();
  const host = 'http://localhost:3000';
  const prefix = '!';
  const botInfo = new Discord.MessageEmbed()
    .setTitle('OFFICIAL BUDDY COMMANDS')
    .setColor('#00ffe5')
    .setDescription(
      `Official commands for buddyBot. Created by Larry.n Repo: https://github.com/lschwall/buddyBotn `,
    )
    .addField(
      `**GENERAL COMMANDS**`,
      `1. __*!buddy*__ : list of commands n2. __*!romansaid <quote>*__ : add quote from romann3. __*!randomroman*__ : gives random roman quoten4. __*!romanreport*__ : lists all of the previous roman quotes`,
    );

  client.on('message', async (msg) => {
    const args = msg.content.slice(prefix.length).split(/  /);
    const command = args.shift().toLowerCase();

    if (msg.author.bot) return;

    if (command === 'buddy') {
      msg.channel.send(botInfo);
    }

    if (msg.channel.id !== process.env.BOT_SHIT) {
      if (command === 'romansaid') {
        msg.reply(
          `Please place in ${msg.guild.channels.cache.find(
            (channel) => channel.name === 'roman_justroman',
          )}`,
        );
      }
      return;
    }

    if (command === 'romansaid') {
      let quote = args.join(' ');
      axios
        .post(`${host}/quote/create?quote=${encodeURI(quote)}`)
        .then(() => msg.reply(`thanks for adding`))
        .catch((err) => console.error(err));
    }

    if (command === 'randomroman') {
      axios
        .get(`${host}/quote/find`)
        .then(({ data }) => msg.reply(`Your random Roman quote: ${data}`))
        .catch((err) => console.error(err));
    }

    if (command === 'romanreport') {
      const MAX_FIELDS = 25;
      axios
        .get(`${host}/quote`)
        .then(({ data }) => {
          if (!data.length) return msg.reply('Sorry, no quotes found.');

          // iterate over the commands and create field objects
          // "name" and "value" props are required, "inline" is optional
          const fields = data.map((d) => ({
            name: d.id,
            value: d.quote,
          }));

          // if there is less than 25 fields, you can safely send the embed
          // in a single message
          if (fields.length <= MAX_FIELDS)
            return msg.reply(
              new Discord.MessageEmbed()
                .setTitle(`Roman's Quotes`)
                .setColor('#00ffe5')
                .setDescription(
                  '|<><><><><><><><><><><><><><><><><><><><><><><><><>|',
                )
                .setFooter(
                  '|<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>|',
                )
                .addFields(fields),
            );

          // if there are more, you need to create chunks w/ max 25 fields
          const chunks = chunkify(fields, MAX_FIELDS);
          // an array of embeds used by `discord.js-pagination`
          const pages = [];

          chunks.forEach((chunk) => {
            // create a new embed for each 25 fields
            pages.push(
              new Discord.MessageEmbed()
                .setTitle(`Roman's Quotes`)
                .setColor('#00ffe5')
                .setDescription(
                  '|<><><><><><><><><><><><><><><><><><><><><><><><><>|',
                )
                .setFooter(
                  '|<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>|',
                )
                .addFields(chunk),
            );
          });
          pagination(msg, pages);
        })
        .catch((err) => console.error(err));
    }
  });

  client.on('ready', () => {
    console.log('bot online');
  });

  client.login(process.env.TOKEN);

  function chunkify(arr, len) {
    let chunks = [];
    let i = 0;
    let n = arr.length;

    while (i < n) {
      chunks.push(arr.slice(i, (i  = len)));
    }

    return chunks;
  }
};

module.exports = { bot };
 

введите описание изображения здесь