简体   繁体   English

node.js select 查询结果作为电报机器人应答发送

[英]node.js select query results to send as telegram bot answer

Need a little help to understand MySQL query result.需要一点帮助来了解 MySQL 查询结果。 There is table authors with columns AuthorID , FirstName , ..., SearchName .有列AuthorIDFirstName 、 ...、 SearchName的表authors I'd like to select from it and send values of SearchName as an answer of bot我想从中获取SearchName并发送 SearchName 的值作为机器人的答案

This way:这边走:

bot.on('text', (ctx) => {
const q = ctx.message.text //here I recieve a message to bot as a string to use in select
const sql = "SELECT SearchName FROM authors WHERE LastName LIKE '%"+ q +"%'";
connection.query(sql, function(err, results) {

    if(err) console.log(err);
    console.log(results);
    ctx.reply(results);
    console.log(q);
});
})

So it results this way in console:所以它在控制台中以这种方式产生:

  TextRow { SearchName: 'ПЕТРОВА ЮЛИЯ ИГОРЕВНА' },
  TextRow { SearchName: 'ПЕТРОВА ЕЛЕНА ВЛАДИМИРОВНА' },
  TextRow { SearchName: 'ПЕТРОВА ИРИНА ВЛАДИМИРОВНА' },
  TextRow { SearchName: 'ПЕТРОВА В К' },
  TextRow { SearchName: 'ПЕТРОВА ВЛАДИНАТА' },
  TextRow { SearchName: 'ПЕТРОВА ИРИНА' },

and sure same data, but unrowed view in bot answer:并确定相同的数据,但机器人答案中的未分类视图:

 [{"SearchName":"ПЕТРОВА ЮЛИЯ ИГОРЕВНА"},{"SearchName":"ПЕТРОВА ЕЛЕНА ВЛАДИМИРОВНА"},{"SearchName":"ПЕТРОВА ИРИНА ВЛАДИМИРОВНА"},{"SearchName":"ПЕТРОВА В К"},{"SearchName":"ПЕТРОВА ВЛАДИНАТА"},{"SearchName":"ПЕТРОВА ИРИНА"},

So, I ask for help how to get values only and further I'd like to manage it as separated replies from bot to user.因此,我请求帮助如何仅获取值,并且进一步我想将其作为从机器人到用户的单独回复进行管理。 ie user sending string and getting as many replies as many rows query returns.即用户发送字符串并获得与查询返回的行数一样多的回复。

All that's left to do now is just to loop through the results inside db query callback, craft and send the bot messages there.现在剩下要做的就是循环遍历 db 查询回调中的结果,制作并在那里发送机器人消息。 Here is an example,这是一个例子,

bot.on('text', (ctx) => {
    const q = ctx.message.text //here I recieve a message to bot as a string to use in select
    const sql = "SELECT SearchName FROM authors WHERE LastName LIKE '%"+ q +"%'";

    connection.query(sql, function(err, results) {
        if(err) console.log(err);
        console.log(results);

        for (const result of results) { // each row
            ctx.reply(result.SearchName); // send the SearchName field from the object
        }
    });
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM