I'm writing a telegram bot. There is a piece of working code that responds to messages from the user, searches for key word matching database and sends the result to user. The problem is that the sample result gets into the console, how to send it to the user? Please, help
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);
}
})
})
Based on sendMessage api and data in message Your code should look like this:
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);
}
}
})
Check manuals: