How to reply to someone's tweet using node.js twit? - javascript

I'm trying to make a bot that responds to my friend's tweets with an image every time they tweet. Everything works fine, but I can't get it to respond to the original tweet, only replies. Is there any way to do this?
function tweetEvent(tweetMsg) {
var replyto = tweetMsg.in_reply_to_screen_name;
var from = tweetMsg.user.screen_name;
var id = tweetMsg.id_str;
if(from === "---"){
var b64content = fs.readFileSync('media/img.png', {
encoding: 'base64'
})
T.post('media/upload', {
media_data: b64content
}, uploaded);
function uploaded(err, data, response) {
var mediaIdStr = data.media_id_string;
var params = {
status,
in_reply_to_status_id: id,
media_ids: [mediaIdStr]
}
//! Post tweet
T.post('statuses/update', params, tweeted);
};
function tweeted(err, reply) {
if(err) {
console.log(err);
console.log();
console.log("Error.");
} else {
console.log("tweeted");
}
}
}
}
I want it to reply to the original tweet, the only way it's worked is by using:
if(replyto === "---"){
}
But that doesn't do what I want it to do.

I was able to do it with if (tweet.in_reply_to_screen_name === null) tweetEvent(tweet);
const tweets = [
{
created_at: "Wed Feb 10 03:50:17 +0000 2021",
id: 1359348938248183800,
id_str: "1359348938248183809",
text: "reply test 1290hHhbjikl",
truncated: false,
entities: [Object],
metadata: [Object],
source:
'Twitter Web App',
in_reply_to_status_id: 1359339654080790500,
in_reply_to_status_id_str: "1359339654080790530",
in_reply_to_user_id: 1167232572067369000,
in_reply_to_user_id_str: "1167232572067368960",
in_reply_to_screen_name: "OpenDreamPhone",
user: [Object],
geo: null,
coordinates: null,
place: null,
contributors: null,
is_quote_status: false,
retweet_count: 0,
favorite_count: 0,
favorited: false,
retweeted: false,
lang: "in",
},
{
created_at: "Wed Feb 10 03:13:23 +0000 2021",
id: 1359339654080790500,
id_str: "1359339654080790530",
text: "this is a test. 1290hHhbjikl",
truncated: false,
entities: [Object],
metadata: [Object],
source:
'Twitter Web App',
in_reply_to_status_id: null,
in_reply_to_status_id_str: null,
in_reply_to_user_id: null,
in_reply_to_user_id_str: null,
in_reply_to_screen_name: null,
user: [Object],
geo: null,
coordinates: null,
place: null,
contributors: null,
is_quote_status: false,
retweet_count: 0,
favorite_count: 0,
favorited: false,
retweeted: false,
lang: "en",
},
];
const tweetEvent = (tweet) => {
var b64content = fs.readFileSync("twitt/img.png", {
encoding: "base64",
});
T.post(
"media/upload",
{
media_data: b64content,
},
uploaded
);
function uploaded(err, data, response) {
var mediaIdStr = data.media_id_string;
var params = {
status: "hi",
in_reply_to_status_id: tweet.id_str,
media_ids: [mediaIdStr],
};
//! Post tweet
T.post("statuses/update", params, tweeted);
}
function tweeted(err, reply) {
if (err) {
console.log(err);
console.log();
console.log("Error.");
} else {
console.log(reply);
console.log("tweeted");
}
}
};
tweets.forEach((tweet) => {
if (tweet.in_reply_to_screen_name === null) tweetEvent(tweet);
});

Related

Promise pending even after its resolved

I want to get the array of rooms and assign it to each property wrt their property_id, but the value returned is a pending promise. Not sure what's wrong. Although when I log the rooms inside the then it does log the value correctly. The result of console.log(property) is given below.
const vendorProfile = catchAsync(async (req, res, next) => {
await passport.authenticate("vendor-jwt", { session: false }, (err, user, info) => {
if (err) {
res.error = err || info.message;
return next(401);
}
if (!user) {
res.error = info.message;
return next(401);
}
return Promise.resolve(
getVendorProfileInfo(user._id)
.then((result) => {
if (result == "error") {
res.error = "Failed to fetch Vendor Profile";
next(500);
}
return getPropertyByVendorId(result._id).then((prop) => {
for (const property of prop) {
property._doc.property_rooms = getAllRooms(property._id).then((rooms) => rooms);
console.log(property);
}
res.message = "Vendor Profile fetched successfully";
res.data = {
vendor_info: result,
vendor_properties: prop,
};
return next(200);
});
})
.catch((err) => {
Logger.error(err);
res.error = "Failed to get vendor profile";
return next(500);
})
).catch((err) => {
Logger.error(err);
res.error = "Failed to get vendor profile";
return next(500);
});
})(req, res, next);
});
This is the function to get all the rooms for that property_id:
const getAllRooms = (propertyId) => {
return Promise.resolve(Room.find({ property_id: propertyId }).then((result) => result)).catch((err) => {
Logger.error(err);
return "error";
});
};
Here is my console.log(property):
{
property_basic_info: {
property_name: 'Welcome',
property_star_rating: 1,
property_booking_since: 2021,
property_channel_manager: ''
},
property_location: {
property_geo_loc: { coordinates: [Array], type: 'Point' },
property_locality: 'bhandup',
property_address: 'MAHAVIR UNIVERSE',
property_country: 'India',
property_state: 'Maharashtra',
property_city: 'Mumbai',
property_zip_code: '400078'
},
property_contact_details: { phone_no: '7059462868', email: 'roy.srijan#outlook.com' },
property_amenities: {
basic_facilities: [ 'Electricity', 'Air Conditioning', 'Elevator/ Lift', 'Bathroom' ],
general_services: [ 'Food', 'Bellboy service' ],
outdoor_activities_sports: [],
common_area: [],
food_drink: [],
health_wellness: [],
business_center_conference: [],
beauty_spa: [],
security: []
},
property_policies: {
checkin_time: '10:06',
checkout_time: '22:06',
cancellation_policy: 'Free cancellation upto 48 hrs'
},
property_rules: {
id_proof: {
acceptable_identity_proofs: 'Adhaar',
unacceptable_identity_proofs: 'Adhaar',
allow_same_id: true
},
guest_profile: [
[Object], [Object],
[Object], [Object],
[Object], [Object],
[Object]
],
general_safety_hygiene_guidelines: [],
room_safety_hygiene: [],
social_distancing: [],
food_drinks_hygiene: [],
property_restrictions: [],
pet_policy: [],
guest_suitabilty: [],
checkin_checkout_policy: [],
extra_bed_policy: [ [Object] ],
custom_policy: []
},
property_finance_legal: { gst_details: '29AAACR4849R2ZG' },
property_status: 1,
property_photo_id: [],
_id: 61607791b1af193c7b8b9f08,
vendor_id: 61607775b1af193c7b8b9f07,
createdAt: 2021-10-08T16:53:37.734Z,
updatedAt: 2021-10-08T16:53:37.734Z,
__v: 0,
property_rooms: Promise { <pending> }
}
Thanks in advance.
That's because you are logging the promise outside the then method.
The promise is resolved async so outside then it is not resolved yet.
you have to change this line:
property._doc.property_rooms = getAllRooms(property._id).then((rooms) => rooms);
console.log(property);
to
property._doc.property_rooms = getAllRooms(property._id).then((rooms) => console.log(rooms));
or use async/await to work with it like sync values

Unable to update record in MongoDB using findOneAndUpdate

I am using Mongoose to update an Announcement record, with the following definition:
const { DateTime } = require('luxon');
const Schema = new mongoose.Schema({
title: String,
description: String,
date: {
type: Date,
set: (dt) => dt.toJSDate(),
get: (d) => DateTime.fromJSDate(d),
},
club: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Club',
},
});
I am performing the update operation in this function
exports.update = async (id, params) => {
console.log(params)
await Announcement.findOneAndUpdate({ _id: id }, params, {
upsert: true,
useFindAndModify: false,
});
return "exports.get(id)";
};
However, I get an error when running Announcement.findOneAndUpdate:
$set' is empty. You must specify a field like so: {$set: {<field>: ...}}
This is what the params look like:
{
title: 'Name!',
description: 'Description!',
date: DateTime {
ts: 1601524800000,
_zone: LocalZone {},
loc: Locale {
locale: 'en-US',
numberingSystem: null,
outputCalendar: null,
intl: 'en-US',
weekdaysCache: [Object],
monthsCache: [Object],
meridiemCache: null,
eraCache: {},
specifiedLocale: null,
fastNumbersCached: null
},
invalid: null,
weekData: null,
c: {
year: 2020,
month: 10,
day: 1,
hour: 0,
minute: 0,
second: 0,
millisecond: 0
},
o: -240,
isLuxonDateTime: true
},
club: '99cb91bdc3464f14678934ca'
}
I know that all the ObjectId's are valid because I have tested them from Mongo shell. However, I can't figure out why I am not able to run findOneAndUpdate on an Announcement record.

Post an array of objects ExpressJs Mongoose NodeJs

UPDATE
I have a mongoose schema and express controller, now I have to post an Array of Objects based on that schema, I have to post like 30 Objets, here is an example of two I posted and I received that response, and I wanto to see the Array of all Objects.
CoursesModel.ts
const CoursesSchema = new Schema({
courses: [{
course_status: String,
course_code: String,
course_name: req.body.course_name,
institute_name: String,
hour_duration: Number,
modality: String,
schedule: String,
start_date: Date,
finish_date: Date,
enroll_date_limit: Date,
course_value: Number,
}],
created_at: {
type: Date,
default: Date.now
}
});
coursesController.ts // createCourse
const Courses = CoursesModel;
public createCourses(req: Request, res: Response) {
try {
if (!req.body) {
throw new Error(`Is missing parameter : Table data`);
}
const createCourse = {
courses: [{
course_status: req.body.course_status,
course_code: req.body.course_code,
course_name: req.body.course_name,
institute_name: req.body.institute_name,
hour_duration: req.body.hour_duration,
modality: req.body.modality,
schedule: req.body.schedule,
start_date: req.body.start_date,
finish_date: req.body.finish_date,
enroll_date_limit: req.body.enroll_date_limit,
course_value: req.body.course_value,
}],
created_at: new Date()
};
let newCourses = new Courses(createCourse);
newCourses.save().then(data => {
res.json(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while creating the course"
});
})
);
} catch (error) {
this.logger.error({
data: req.body,
error: error,
source: 'Error in function createCourses'
});
res.status(500);
return res.send({ error: (error.message) ? error.message : "Internal server error" });
}
}
Json body I post on Insomnia
{"courses":[{
"course_status": "Active",
"course_code": "0004",
"institute_name": "Berkley",
"course_name": "Programming",
"month_duration": 2,
"hour_duration": 120,
"modality": "Virtual",
"schedule": "2 a 5",
"start_date": "2021-07-02T05:00:16.000Z",
"finish_date": "2021-07-02T05:00:16.000Z",
"enroll_date_limit": "2021-07-02T05:00:16.000Z",
"course_value": 300000,
},
{
"course_status": "Active",
"course_code": "0005",
"institute_name": "MIT",
"course_name": "Digital Marketing",
"hour_duration": 120,
"modality": "Virtual",
"schedule": "2 a 5",
"start_date": "2021-07-02T05:00:16.000Z",
"finish_date": "2021-07-02T05:00:16.000Z",
"enroll_date_limit": "2021-07-02T05:00:16.000Z",
"course_value": 300000,
}]}
This is what I get from Insomnia
Insomnia response
{
"successfully": true,
"data": {
"_id": "5f1ae0e3cf5d702706b5bb09",
"courses": [
{
"_id": "5f1ae0e3cf5d702706b5bb0a"
}
],
"created_at": "2020-07-24T13:23:47.173Z",
"__v": 0
}
}
I solve in this way
const Courses = CoursesModel;
public async createCourses(req: Request, res: Response) {
try {
if (!req.body) {
throw new Error(`Is missing parameter : Table data`);
}
const courses = []
for(const course of req.body.courses){
const tableCourse ={
course_status: course.course_status,
course_code: course.course_code,
course_name: course.course_name,
institute_name: course.institute_name,
hour_duration: course.hour_duration,
modality: course.modality,
schedule: course.schedule,
start_date: course.start_date,
finish_date: course.finish_date,
enroll_date_limit: course.enroll_date_limit,
course_value: course.course_value,
created_at: new Date()
};
let newCourses = new Courses(tableCourse);
const newCourses = await newTableCourses.save()
courses.push(newCourses)
}
res.json({ successfully: true, data: { courses } });
} catch (error) {
this.logger.error({
data: req.body,
error: error,
source: 'Some error occurred while creating the course.'
});
res.status(500);
return res.send({ error: (error.message) ? error.message : "Internal server error" });
}
}
CourseModel.ts
const CoursesSchema = new Schema({
course_status: String,
course_code: String,
course_name: req.body.course_name,
institute_name: String,
hour_duration: Number,
modality: String,
schedule: String,
start_date: Date,
finish_date: Date,
enroll_date_limit: Date,
course_value: Number,
created_at: {
type: Date,
default: Date.now
}
});
Use res.json(data) instead of res.send(data) and instead of return from directly use save
const Courses = CoursesModel;
public createCourses(req: Request, res: Response) {
try {
if (!req.body) {
throw new Error(`Is missing parameter : Table data`);
}
const createCourse =Courses ({
courses: [{
course_status: req.body.course_status,
course_code: req.body.course_code,
course_name: req.body.course_name,
institute_name: req.body.institute_name,
hour_duration: req.body.hour_duration,
modality: req.body.modality,
schedule: req.body.schedule,
start_date: req.body.start_date,
finish_date: req.body.finish_date,
enroll_date_limit: req.body.enroll_date_limit,
course_value: req.body.course_value,
}],
created_at: new Date()
});
newCourses.save().then(data => {
res.json(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while creating the course"
});
})
);
} catch (error) {
this.logger.error({
data: req.body,
error: error,
source: 'Error in function createCourses'
});
res.status(500);
return res.send({ error: (error.message) ? error.message : "Internal server error" });
}
}

Algolia generate Invalid Secured API-Keys

So I'm trying to generate some secured API-Keys but it seems that they aren't generated right, I've followed the API docs without any luck.
This is what I'm doing
var algoliasearch = require('algoliasearch');
var admin_client = algoliasearch('APP', 'ADMIN_KEY');
var search_client = algoliasearch('APP', 'ONLY_SEARCH_KEY');
var admin_index = admin_client.initIndex('INDEX');
var search_index = search_client.initIndex('INDEX');
admin_index.search('dav', (err, content) => { console.log(err, content) });
//------------------CONSOLE-------------------------------
null { hits:
[ { firstname: 'David',
lastname: 'De Anda',
_tags: [Object],
objectID: '2',
_highlightResult: [Object] } ],
nbHits: 1,
page: 0,
nbPages: 1,
hitsPerPage: 20,
processingTimeMS: 1,
query: 'dav',
params: 'query=dav' }
//-------------------------------------------------
search_index.search('dav', (err, content) => { console.log(err, content) });
//------------------CONSOLE-------------------------------
null { hits:
[ { firstname: 'David',
lastname: 'De Anda',
_tags: [Object],
objectID: '2',
_highlightResult: [Object] } ],
nbHits: 1,
page: 0,
nbPages: 1,
hitsPerPage: 20,
processingTimeMS: 1,
query: 'dav',
params: 'query=dav' }
//-------------------------------------------------
Everything seems to work until now
But now I want to generate some Secured API-Keys
var valid_until = Math.floor(Date.now() / 1000) + 3600
var from_admin_api_key = admin_client.generateSecuredApiKey('from_admin', {validUntil: valid_until});
var from_search_api_key = search_client.generateSecuredApiKey('from_search', {validUntil: valid_until});
var sub_admin_client = algoliasearch('APP', from_admin_api_key);
var sub_search_client = algoliasearch('APP', from_search_api_key);
var sub_admin_index = sub_admin_client.initIndex('INDEX');
var sub_search_index = sub_search_client.initIndex('INDEX');
sub_admin_index.search('dav', (err, content) => { console.log(err, content) });
//------------------CONSOLE-------------------------------
{ Error
at success (/app/node_modules/algoliasearch/src/AlgoliaSearchCore.js:334:32)
at process._tickDomainCallback (internal/process/next_tick.js:129:7)
name: 'AlgoliaSearchError',
message: 'Invalid Application-ID or API key',
debugData:
[ { currentHost: 'https://ge24e6css9-dsn.algolia.net',
headers: [Object],
content: '{"params":"query=dav"}',
contentLength: 22,
method: 'POST',
timeouts: [Object],
url: '/1/indexes/INDEX/query',
startTime: 2017-01-13T17:46:42.519Z,
endTime: 2017-01-13T17:46:44.038Z,
duration: 1519,
statusCode: 403 } ],
statusCode: 403 } undefined
//-------------------------------------------------
sub_search_index.search('dav', (err, content) => { console.log(err, content) });
//------------------CONSOLE-------------------------------
{ Error
at success (/app/node_modules/algoliasearch/src/AlgoliaSearchCore.js:334:32)
at process._tickDomainCallback (internal/process/next_tick.js:129:7)
name: 'AlgoliaSearchError',
message: 'Invalid Application-ID or API key',
debugData:
[ { currentHost: 'https://ge24e6css9-dsn.algolia.net',
headers: [Object],
content: '{"params":"query=dav"}',
contentLength: 22,
method: 'POST',
timeouts: [Object],
url: '/1/indexes/INDEX/query',
startTime: 2017-01-13T17:46:42.519Z,
endTime: 2017-01-13T17:46:44.038Z,
duration: 1519,
statusCode: 403 } ],
statusCode: 403 } undefined
//-------------------------------------------------
I misunderstood the generateSecuredApiKey first parameter that actually was the origin API Key.
So the right code will be
var from_admin_api_key = admin_client.generateSecuredApiKey('ADMIN_KEY', {validUntil: valid_until});
var from_search_api_key = search_client.generateSecuredApiKey('ONLY_SEARCH_KEY', {validUntil: valid_until});
And of course the generated key form the ADMIN_KEY won't work.

Node.js - Counting the number of objects in MongoDB collection

I am new to Node.js and MongoDB and I am really struggling to wrap my head around callbacks. I have read a few articles but it is still quite confusing to me. In the code below, I am trying to return the count of orders that have some properties which I have expressed in the query in orderModel.count(query, next):
controllers/order.js:
var mongoose = require ('../config/db');
var orderModel = require('../models/order').model;
var User = require('./user');
var Error = require('../config/error');
createOrder: function (user, order, next) {
if (newOrder.totalPrice > user.credit && orderModel.
count({$and: [{user: order.user}, {active: true}, {$or: [{status: 0}, {status: 1}]}]},
function(err, count){
if(err)
console.log(err);
else
count; }) > 0)
return next({error: Error.InsufficientCredits});
}
I don't think I am correctly obtaining the variable count because when I tried printing out the result of the second condition in the if statement, I got this data printed out:
Query {
_mongooseOptions: {},
mongooseCollection:
NativeCollection {
collection: Collection { s: [Object] },
opts: { bufferCommands: true, capped: false },
name: 'orders',
collectionName: 'orders',
conn:
NativeConnection {
base: [Object],
collections: [Object],
models: [Object],
config: [Object],
replica: false,
hosts: null,
host: 'dsXXXXXX.mlab.com',
port: XXXXXX,
user: 'XXXX',
pass: 'XXXX',
name: 'X',
options: [Object],
otherDbs: [],
_readyState: 1,
_closeCalled: false,
_hasOpened: true,
_listening: false,
db: [Object],
_events: {},
_eventsCount: 0 },
queue: [],
buffer: false,
emitter:
EventEmitter {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined } },
....
You need to put your logic inside the Model.count() method callback function as:
var mongoose = require ('../config/db'),
orderModel = require('../models/order').model,
User = require('./user'),
Error = require('../config/error');
var createOrder = function (user, order, next) {
orderModel.count({
"user": order.user,
"active": true,
"status": { "$in": [0, 1] }
}, function(err, count) { //<-- put logic in this callback
if (err) {
console.log(err);
throw err;
} else if (newOrder.totalPrice > user.credit && count > 0) {
// logic for creating order here
} else {
return next({ "error": Error.InsufficientCredits });
}
})
}

Categories