Output results to the user - javascript

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:
sendMessage
Message object
Chat object
Sequelize replacements

Related

PERN stack: Iterating through array of data, my call to my database is not going through for every data record

I have been trying like crazy to find a solution to my problem, but nothing seems to work and I don't know where I am going wrong. I am creating an app using the PERN stack, and I have an array of data with a length of 24.
I iterate through my data array with following snippet of code (this is after trying to find solutions but the result is always the same):
const createEntry = async function (data) {
let whatever = await Promise.all(
data.map(async (item) => {
try {
console.log(`${item.name}`);
await Entry.post("/", item); //call to database
} catch (err) {
console.log(err);
}
})
);
whatever.then(console.log("I hate my life."));
};
I know the entire data array is being iterated through because of the console.logs, but the call to Entry.post() is only happening like maybe six times, and I am not getting all of my data entered into my database.
My express app.post code looks like this:
app.post("/url", async (req, res) => {
try {
const results = await db.query(
"INSERT INTO database (id, name) values ($1, $2)",
[
req.body.id,
req.body.name,
]
);
res.send({
status: "success",
results: results.rows.length,
data: {
entry: results.rows[0],
},
});
} catch (err) {
console.log(`${err.detail} for ${req.body.name}`);
}
});
So, I resolved this on my own and found a working solution.
My createEntry code from my question:
const createEntry = async function (data) {
let whatever = await Promise.all(
data.map(async (item) => {
try {
console.log(`${item.name}`);
await Entry.post("/", item); //call to database
} catch (err) {
console.log(err);
}
})
);
whatever.then(console.log("I hate my life."));
};
now looks like this:
const createEntry = async function (data) {
try {
let result = await CreateDB.post("/", data);
return result;
} catch (err) {
console.log(err);
}
};
And my app.post code
app.post("/url", async (req, res) => {
try {
const results = await db.query(
"INSERT INTO database (id, name) values ($1, $2)",
[
req.body.id,
req.body.name,
]
);
res.send({
status: "success",
results: results.rows.length,
data: {
entry: results.rows[0],
},
});
} catch (err) {
console.log(`${err.detail} for ${req.body.name}`);
}
});
Now looks like this:
app.post("/url", async (req, res) => {
try {
const results = await db.query(
"INSERT INTO database (id, name) values ($1, $2)",
[
req.body.id,
req.body.name,
]
);
res.send(res.rows[0]);
} catch (err) {
console.log(`${err.detail} for ${req.body.name}`);
}
});
And my call to my createEntry is:
let temp = {obj: some object};
createEntry(temp).then((newEntry) => {
dbArray.push(newEntry.data);
manipulateData(newEntry.data);
});
And with this I am now able to create a database entry, retrieve the database object and do work with it and it works for any size array which makes me really happy. So hopefully, if anyone has a similar problem, this can help.

MongoDB query doesn't find the requested entries

i'm trying to show a user specific data using req.session.user and pass the ID to the criteria i'm building. (every entry also has a user field so i can match) yet it does not work.
The Service :
async function query(filterBy) {
try {
const criteria = _buildCriteria(filterBy);
const collection = await dbService.getCollection('tab');
const tabs = await collection.find(criteria).toArray();
// const userTabs = await collection.find({ user: '62be030cb4de461a8462b863' }).toArray();
return tabs;
} catch (err) {
logger.error('Can not find tabs', err);
throw err;
}
}
The console.log('userId', userId) returns the Id I get from my controller
function _buildCriteria(filterBy) {
const criteria = {};
const { text, genre, userId } = filterBy;
console.log('userId', userId);
if (text) {
const txtCriteria = { $regex: text, $options: 'i' };
criteria.name = txtCriteria;
}
if (genre) {
criteria.genre = { $eq: genre };
}
if (userId) {
criteria.user = { $eq: userId };
}
return criteria;
}
The controller :
async function getTabs(req, res) {
try {
const userId = req?.session?.user?._id;
const filterBy = req.query;
const fitlerUpdated = { ...filterBy, id: userId };
const tabs = await tabService.query(fitlerUpdated);
res.json(tabs);
} catch (err) {
logger.error('Failed to get tabs', err);
res.status(500).send({ err: 'Failer ti get tabs' });
}
}
I tried using
const userTabs = await collection.find({ user: '62be030cb4de461a8462b863' }).toArray()
and it works yet it doens't work along with the criteria.
thanks for any help!
I have realize I accidentally passed the wrong key.
should have been id and not userId

Problems with page loading data on JS

I have a problem with my code, when the page is loading and the code is starting running The code works very fast, and even before it is enough to reach all the lines it already continues to run.
What happens is that the page does not get the data disability and I'm not getting the users right way.
Here is my code:
var users = [{}]
getUsers();
function getUsers() {
const res = http.get('users/')
.then(res => {
users = res.data
})
.catch(function (error) {
console.log(error);
})
}
mock.onPost('/api/auth/access-token').reply(config => {
const data = JSON.parse(config.data);
const { access_token } = data;
try {
const { id } = jwt.verify(access_token, jwtConfig.secret);
const usersID = window.localStorage.getItem('usersId')
const user = _.cloneDeep(users.find(_user => _user.uuid === usersID));
delete user.password;
const updatedAccessToken = jwt.sign({ id: user.uuid }, jwtConfig.secret, { expiresIn: jwtConfig.expiresIn });
const response = {
user,
access_token: updatedAccessToken
};
return [200, response];
} catch (e) {
const error = 'Invalid access token detected';
return [401, { error }];
}
});
if you have an idea how to fix the code I will be very happy.
Thanks

How to use nextPageToken to retrieve contacts list from google api. Working example

I´m using this code to retrieve my contacts list inside a firebase function following the
(https://github.com/googleapis/google-api-nodejs-client/blob/master/samples/people/contacts.js) example
const { google } = require('googleapis');
const clientAuth = require('./clientAuth');
exports.getGoogleContacts = functions.https.onCall(async (data, context) => {
console.log('getGoogleContacts- init function')
const contacts = google.people({
version: 'v1',
auth: clientAuth.oAuth2Client,
});
return new Promise((resolve, reject) => {
clientAuth
.authenticate(['https://www.googleapis.com/auth/contacts'])
.then(async () => {
console.log('after client auth')
contacts.people.connections.list({
resourceName: "people/me",
pageSize:200,
personFields: ['addresses',
'ageRanges',
'biographies',
'birthdays',
'braggingRights',
'coverPhotos'], // ... and many other fields
}, function (err, response) {
if (err) {
console.log('contacts.people.connections error')
console.log(err)
reject(new Error(err))
} else if (response) {
console.log('contacts.people.connections response')
console.log(response)
if (response.pageToken) {
// how could I continue to retrieve next page of contacts?
}
resolve(response)
}
})
})
})
})
If there is a nextPageToken, there is no working example I´ve was able to found.
edited - this code was able to solve the pagination with array concatenation
I was able to come up with this solution, even though now I´m facing a problem of pushing to the connections array... It´s not working
const listOptions = {
resourceName: "people/me",
pageSize: 200,
personFields: ['addre...']
}
async function getConnectionsList(contacts, nextPageToken) {
if (!nextPageToken) {
return contacts.people.connections.list(listOptions)
} else {
listOptions.pageToken = nextPageToken
return contacts.people.connections.list(listOptions)
}
}
let response = await getConnectionsList(contacts)
let nextPage = response.data.nextPageToken
let connections = response.data.connections
while (nextPage) {
nextPage = await getConnectionsList(contacts, nextPage)
connections.push(nextPage.data.connections) // not working
connections.concat(nextPage.data.connections) // also not working...
nextPage = nextPage.data.nextPageToken
console.log('hasNextPage?', nextPage)
}
console.log('connections',connections)
resolve(connections)

Adding a row to a google spreadsheet using google-spreadsheet node module and returning the status

I am able to successfully add a row to a google spreadsheet using the google-spreadsheet node module as follows:
const logToGoogleSpreadsheet = (userName, description, link) => {
const spreadsheetId = 'my-spreadsheet-id'
const doc = new GoogleSpreadsheet(`${spreadsheetId}`)
const clientEmail = 'my-client-email'
const privateKey = 'my-private-key'
const payload = {
client_email: clientEmail,
private_key: privateKey
}
let status = ''
doc.useServiceAccountAuth(payload, function (err) {
doc.addRow(1, { 'Reported By': userName, 'Description': description, 'Screenshot Link': link, 'Status': 'Open' }, function(err) {
if(err) {
console.log(err);
status = 'some error'
} else {
console.log('It worked')
status = 'success'
}
});
})
return status
}
const result = logToGoogleSpreadsheet('username', 'description', 'link')
console.log(`The value of result is ${result}`) //This always shows undefined as the value
The value of result always is 'undefined'. I know this is due to the asynchronous nature of javascript and being unable to modify anything in a callback function, but im not able to fix this issue. Can someone please show me an example of how i can return the status from the logToGoogleSpreadsheet function ?
Thank You
you could do this:
const logToGoogleSpreadsheet = *async* (userName, description, link) => {//add async keyword
const spreadsheetId = 'my-spreadsheet-id'
const doc = new GoogleSpreadsheet(`${spreadsheetId}`)
const clientEmail = 'my-client-email'
const privateKey = 'my-private-key'
const payload = {
client_email: clientEmail,
private_key: privateKey
}
let status = ''
doc.useServiceAccountAuth(payload, function (err) {
doc.addRow(1, { 'Reported By': userName, 'Description': description, 'Screenshot Link': link, 'Status': 'Open' }, function(err) {
if(err) {
console.log(err);
status = 'some error'
} else {
console.log('It worked')
status = 'success'
}
});
})
return status
}
logToGoogleSpreadsheet('username', 'description', 'link').then(res => console.log(res));
adding the async keyword to logToGoogleSpreadsheet will make it return a Promise. Now it is a 'thenable' meaning the then method can be called with the resolved result, which here is your status. So in the then call we log it.

Categories