如何将结果划分为几条消息? [英] How to divide the result into several messages?

查看:15
本文介绍了如何将结果划分为几条消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,查询数据库的结果涉及50条记录的输出。这些记录是在一条聊天消息中发布的,这很难分析。如何将结果分成几条消息,每条消息有3条记录?

bot.on('message', async (message) => {
        const {text, chat} = message;
        const {id: chatId} = chat;

        let response = '';

        try {
            const [rows] = await sequelize.query(`SELECT book FROM books t WHERE (t.*)::text LIKE '%${text}%' LIMIT 3`);
            if (rows.length) {
                response = rows.map(row => row.book).join("
");
            } else {
                response = 'text';
            }
        } catch (error) {
            console.error(error.message);
            response = 'book not found';
        } finally {
            if (response) {
                bot.sendMessage(chatId, response);
            }
        }
    })

推荐答案

  1. 使用splice

    将数据库中的行分块到N个项目
  2. 然后使用map将该块转换为图书名称数组

  3. 通过在本例中使用换行符连接某些逻辑将书名块转换为消息

  4. 推送到消息数组

  5. 最后迭代数组并发送

bot.on('message', async (payload) => {
  const {text, chat} = payload;
  const {id: chatId} = chat;

  const BOOKS_PER_MESSAGE = 3;
  let messages = [];

  try {

    const query = `SELECT book FROM books t WHERE (t.*)::text LIKE '%${text}%'`;
    let [rows] = await sequelize.query(query);

    while(rows.length) {
      const chunk = rows.splice(0, BOOKS_PER_MESSAGE); // [1]
      const books = chunk.map(row => row.book);        // [2]
      const message = books.join("
");                // [3]
      messages.push(message);                          // [4]
    }

  } 
  catch (error) {
    console.error(error.message);
  } 
  finally {
    if (!messages.length) {
      bot.sendMessage(chatId, 'Book not found');
      return;
    }
    messages.forEach(message => 
                     bot.sendMessage(chatId, message)); // [5]
  }
});

这篇关于如何将结果划分为几条消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆