【问题标题】:Output results to the user输出结果给用户
【发布时间】:2021-10-12 22:28:20
【问题描述】:

我正在写一个电报机器人。有一段工作代码响应来自用户的消息,搜索关键字匹配数据库并将结果发送给用户。问题是样本结果进入控制台,如何将其发送给用户?请帮忙

             bot.on('message', (ctx) => {
                const text = ctx.text
                const log = sequelize.query("SELECT book FROM books t WHERE (t.*)::text LIKE '%"+ text +"%'") .then( (result) => {
                    console.log(result,log)
                }) .catch( (err)  => {
                    console.log(err);
                    for (const result of results) {
                        ctx.reply(result.book);
                    }
                })
            })

【问题讨论】:

  • 你把reply命令放在了错误处理函数里?
  • 我删了,结果还是一样。输出到控制台
  • 你不应该删除,你应该将它移动到成功函数(你当前正在记录它但不做任何其他事情)

标签: javascript


【解决方案1】:

基于sendMessage api 和message 中的数据,您的代码应如下所示:

const { QueryTypes } = sequelize;

bot.on('message', async (message) => {
  const {text, chat} = message; // https://core.telegram.org/bots/api#message
  const {id: chatId} = chat; // https://core.telegram.org/bots/api#chat
  
  let response = '';

  try {
    const rows = await sequelize.query(
      'SELECT book FROM books t WHERE (t.*)::text LIKE :searchText', 
      {
        replacements: { searchText: `%${text}%` },
        type: QueryTypes.SELECT,
      }
    );
    
    console.log('ROWS:', rows);

    if (rows.length) {
      response = rows.map(row => row.book).join("\n");
    }
    else {
      response = 'Book not found';
    }
  }
  catch (error) {
    console.error(error.message);
    response = 'Unable to lookup';
  }
  finally {
    if (response) {
      bot.sendMessage(chatId, response);
    }
  }
})

查看手册:

  1. sendMessage
  2. Message object
  3. Chat object
  4. Sequelize replacements

【讨论】:

  • 我执行了你的代码并且有错误Unhandled rejection Error: ETELEGRAM: 400 Bad Request: message must be non-empty
  • 感谢您的回答!
  • @anonym 我已经更新了我的答案,它确保在 db 中找到书以避免空字符串作为响应
  • 谢谢,但它仍然是 400 错误请求。我会尝试根据你的例子重写它。
  • 有效!!非常感谢!!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-12
  • 1970-01-01
  • 2017-08-15
  • 2012-11-07
  • 2018-08-29
  • 2013-12-20
  • 1970-01-01
相关资源
最近更新 更多