I am using twit npm package to read direct messages
var stream = T.stream('user', { stringify_friend_ids: true })
stream.on('direct_message', function (directMsg) {
console.log(directMsg)
}
I want to reply the directMsg received , is there any method call of twit which can be used to achieve or any other nodejs package recommended to achieve the same.
Can't provide the exact code solution, but the way is to implement the following steps
Get USER_ID property from directMsg object
Use Twit Rest API method T.post(path, [params], callback) to send direct message to the user with USER_ID
Use Twitter API documentation to understand what you need to send direct messages, you need to properly provide parameters like in documentation
So the code will look like this
T.post("direct_messages/new", {
user_id: USER_ID, // USER_ID is parameter from directMsg object
text: 'YOUR_REPLY'
});
Hope it will help you.
Even i ran into it, here is what you have to do.
Listen to the user stream for direct_message and retrieve the sender.screen_name and recipient.screen_name and verify it's not equal + you need the sender.id as stated by #RashadIbrahimov above.
// Reply to Twitter messages
function replyToDirectMessage(){
//get the user stream
var stream = T.stream('user');
stream.on('direct_message', function (eventMsg) {
var msg = eventMsg.direct_message.text;
var screenName = eventMsg.direct_message.sender.screen_name;
var userId = eventMsg.direct_message.sender.id;
// reply object
var replyTo = { user_id: userId,
text: "Thanks for your message :)",
screen_name: screenName };
console.log(screenName + " says: " + msg );
// avoid replying to yourself when the recipient is you
if(screenName != eventMsg.direct_message.recipient_screen_name){
//post reply
T.post("direct_messages/new",replyTo, function(err,data,response){
console.info(data);
});
}
});
}
and call it
replyToDirectMessage();
Related
I'm trying to find a way to emit from my client an instruction to the server which is inside a JSON object.
Here's my problem, my server receive my first instruction. But my second instruction 'deleteFile' is inside a json object,and the server never received this second instruction.
I would like to know if this is possible, and if i'm doing it in the wrong way.
I want to do something like this:
Client: I emit 'instruction' with my var "message"
service.deleteFile = function (peer, filename, callback) {
if (! LoginService.connected || ! LoginService.socket) {
console.log("deleteFile : not connected to server");
callback("no server");
var message = {
message : 'deleteFile',
dest_list : _.flattenDeep([peer]),
filename : filename,
};
LoginService.socket.emit('instruction',(message));
console.log("service.deleteFile : " , message);
callback(200);
};
And on server app.js for 'instruction':
socket.on('instruction', function(jsonMessage){
var dest_list = jsonMessage.dest_list;
var message = jsonMessage.message;
var filename = jsonMessage.filename;
var user_id = dest_list;
var instruction = {
message : message,
user_id : user_id,
filename : filename,
};
if (dest_list.length){
for (var i = 0; i < dest_list.length; i++) {
var user_id = dest_list[i].toLowerCase();
if (user_id in socket_clients){
var socketId = socket_clients[user_id].socketId;
socket.broadcast.to(socketId).emit('instruction', instruction);
console.log(instruction); //print "{message:'deleteFile', user_id: ['emitter'], filename: 'thegoodfile'}
}
else{
console.log("Error", user_id);
}
}
} else{
console.log("Error");
} });
Then on server app.js for 'deleteFile'(this instruction is inside my JSON object emited from client):
socket.on('deleteFile', function(jsonMessage) {
console.log("Test message"); };
I think my server don't understand my instruction 'deleteFile', but I don't find a way to tell him that it is an instruction.
Tell me if I missed some informations.
Thank you if you can help.
Found a solution with this post: socket, emit event to server from server
I can't send from my server to himself with 'broadcast'. From socket.io doc:
// sending to all clients except sender
socket.broadcast.emit('broadcast', 'hello friends!');
It was written ..
So I used Event handler in Node (doc: https://nodejs.org/api/events.html) and it works.
help me with discord-api. Sending private messages to the user who just logged on to the server. I have the following code:
const robot = new Discord.Client();
robot.on("guildMemberAdd", (gMembAdd) =>
{
gMembAdd.guild.channels.find("name", "test").sendMessage(gMembAdd.toString() + "hello guys");
});
Added the following code:
robot.on("guildMemberAdd", (gMembAdd) =>
{
gMembAdd.guild.channels.find("name", "test").sendMessage(gMembAdd.toString() + "hello guys");
gMembAdd.mentions.users.first().sendMessage("Test");
});
I received an error message. Help me please.
First thing you shouldn't use .sendMessage() as it was deprecated in newer versions. You need to use .send().
When you subscribing to guildMemberAdd you will recieve a GuildMember, from there you can directly send a message:
robot.on("guildMemberAdd", (gMembAdd) => {
gMembAdd.guild.channels.find("name", "test").send(gMembAdd.toString() + "hello guys");
gMembAdd.send("Test");
});
This should send a message directly to the member that joined.
I am using nativescript to build an app that will programmatically send a pre-built text to multiple preset parties in case of emergency.
I have an array of phone numbers and want to iterate over each one, using SMSmanager to send the text and the sentIntent argument seen in android docs to verify that the text was sent before moving on to the next array item.
I have created the pendingIntent variable to pass into "sms.sendTextMessage" as follows:
var sms = android.telephony.SmsManager.getDefault();
var utils = require("utils/utils");
//Gets application's current state
var context = utils.ad.getApplicationContext();
//Create a replica of Android's intent object
var intent = new android.content.Intent(context, com.tns.NativeScriptActivity.class);
//Create a replica of Android's pendingIntent object using context and intent
var pendingIntent = android.app.PendingIntent.getActivity(context, 1, intent, android.app.PendingIntent.FLAG_UPDATE_CURRENT);
I then send the text, passing in the pending intent var:
sms.sendTextMessage("5555555555", null, "hello", pendingIntent, null);
I then attempt to make a basic broadcast receiver using the information I found in the nativescript docs which should just log something to the console when it recieves the expected data.
app.android.registerBroadcastReceiver(pendingIntent, function() {
console.log("##### text sent #####");
});
The problem is: nothing happens. I'd expect to get ""##### text sent #####" logged to the console. I've googled a lot and am thinking maybe I need to add something about this broadcast reciever in the manifest, or perhaps my implimentation is wrong somewhere, but this is my first crack at an android app and I'm at a bit of a loss. Any help would be appreciated.
I'm going to answer my own question here in case anyone else runs into this.
The code that worked is:
var app = require("application");
var utils = require("utils/utils");
var context = utils.ad.getApplicationContext();
var sms = android.telephony.SmsManager.getDefault();
var SendMessages = {
init: function() {
var id = "messageSent";
this.sendText(id, this.pendingIntent(id));
},
sendText: function(id, pendingIntent) {
sms.sendTextMessage("5555555555", null, "Hello :)", pendingIntent, null);
this.broadcastReceiver(id, function() {
console.log("$$$$$ text sent $$$$$");
});
},
pendingIntent: function(id) {
var intent = new android.content.Intent(id);
return android.app.PendingIntent.getBroadcast(context, 0, intent, 0);
},
broadcastReceiver: function(id, callback) {
app.android.registerBroadcastReceiver(id, function() {
callback();
});
}
};
module.exports = SendMessages;
To explain: it seems as #Mike M mentioned each intent object needs some string as an id.
Then to make the "pendingIntent" object, again as #Mike M. mentioned I needed to hook to "getBroadcast" method, then I needed to pass pending intent the app context as the first argument, then 0, then the intent object with the id.
The pending intent then is receivable in a simple broadcast receiver function by simply passing the intent id as the first argument and the callback as the second. I've tested and it's working perfectly.
Following is a simplified version, no bs code approach to what you need to make it run. You need permissions and to make sure the user accepts those permissions. This is also one of the two ways (this one is the context-registered receiver way) to create a broadcast receiver, read more about both types here: https://developer.android.com/guide/components/broadcasts#receiving-broadcasts
Info on registering broadcast receiver: https://docs.nativescript.org/api-reference/classes/application.androidapplication.html#registerbroadcastreceiver
AndroidManifest.xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="__PACKAGE__"
android:versionCode="10000"
android:versionName="1.0">
<!-- ...more code -->
<uses-permission android:name="android.permission.SEND_SMS" />
<!-- ...more code -->
</manifest>
JavaScript:
import * as application from 'tns-core-modules/application';
import * as platform from 'tns-core-modules/platform';
import * as utils from 'tns-core-modules/utils/utils';
import * as permissions from 'nativescript-permissions';
// ...more code
try {
await permissions.requestPermission(
android.Manifest.permission.SEND_SMS,
'Need to send.'
);
console.log('SEND_SMS permission accepted.');
const text = 'Herro.';
const mobileNumber = '55555555';
const intentFilter = 'something_here';
const context = utils.ad.getApplicationContext();
const intent = new android.content.Intent(intentFilter);
const pendingIntent = android.app.PendingIntent.getBroadcast(context, 0, intent, 0);
const sms = android.telephony.SmsManager.getDefault();
application.android.registerBroadcastReceiver(intentFilter, function() {
console.log(`Text has been sent: ${text}`);
});
setTimeout(() => {
console.log('Sending text.');
sms.sendTextMessage(mobileNumber, null, text, pendingIntent, null);
}, 5000);
} catch (error) {
console.log('Permission error:', error);
}
The code above is created inside the activity and uses the main ui thread. This means that if the user exits the activity, the broadcast receiver will linger in limbo and android can destroy it.
I'm making a request but it doesn't seem to work. If I copy code into my browser it works good, but in my console it shows up this :
{
"status" : "success",
"data" : {
"error_message" : "API access enabled, but unable to verify two-factor authentication code. If you need help with this, please contact support#bitskins.com."
}
}
What am I doing wrong? It's based on two-factor authentication that as I said works good while printing the url itself and when i'm copying it into my browser.
var url = 'https://bitskins.com/api/v1/get_item_price/?api_key='+bitskins.apikey+'&code='+bitskins.code+'&names='+encodeURIComponent(items[i].market_hash_name)+'&delimiter=!END!';
console.log(url);
request(url, function (error, response, body) {
if (!error) {
console.log(body)
}
});
In case you want, here is my api key module to generating it (api key deleted for security)
var TOTP = require('onceler').TOTP;
//Create a TOTP object with your secret
var totp = new TOTP('deleted');
// print out a code that's valid right now
// console.log(totp.now());
var code = totp.now();
module.exports = {
code: code,
apikey: 'deleted'
}
Founder of BitSkins, Inc. here. You need to have the following:
1) Your API Key
2) Your Secure Access Secret
You see the Secret when you enable Secure Access. If you do not have this, just disable/re-enable Secure Access and note the Secret down. The TOTP code you generate is with that Secret. Generate the TOTP code right before every API call and you'll be fine.
I think it should work. For me it works fine.
var API_KEY = ''; //It is very important
var SECRET_KEY = ''; //It is very important
var totp = new TOTP(SECRET_KEY);
var code = totp.now();
var options = {
url: 'https://bitskins.com/api/v1/get_item_price',
form: {
'api_key': API_KEY,
'names': 'Tec-9%20%7C%20Sandstorm%20(Minimal%20Wear)',
'delimiter': '!END!',
'code': code
}
};
function callback(error, response, body) {
if (!error) {
var info = JSON.parse(body);
console.log(info);
}
}
request.post(options, callback);
What npm package do you use to create 2FA code? I'm using "onceler" from example but I think it creates wrond codes. Here is my code:
var API_KEY = ''; //correct key from settings page
var SECRET_KEY = ''; // correct key which I copied from form with QR code.
var totp = new TOTP("SECRET_KEY");
var code = totp.now();
This code doesn't equal code which I can see in my mobile device and with this code I get error message like in author's question. But if I put code from my mobile in programm code - it works fine. So what package should I use to get correct codes?
I'm attempting to create a simple web service using node.js, express, monk, and mongodb which returns results from mongodb based on the params in the URL. I want to add jsonp support to the calls. The service will be called as such:
localhost:3000/database/collection/get?param1=Steve¶m2=Frank&callback=foo
app.js
var mongo_address = 'localhost:27017/database';
var db = monk(mongo_address);
app.get('/:coll/get', routes.handle(db);
routes/index.js
exports.handle = function(db) {
return function(req, res) {
// Send request
db.get(req.params.coll).find(req.query, {fields:{_id:0}}, function(e,docs) {
if (e) throw e;
res.jsonp(docs)
});
};
}
When I use the built in JSONP support with res.jsonp, it sends the callback param to mongo and returns an empty list. I've tried stripping out the callback param during the query and then manually adding it back to the results without much luck. I feel like I'm missing something simple. Any help would be appreciated.
After some messing around with JS, I found a workable solution with minimal additional code. AFter stripping the callback from the query and storing the function value, I had to explicitly build the return string for JSONP requests.
exports.handle = function(db) {
return function(req, res) {
//Determine if URL implements JSONP
var foundCallback = req.query.callback;
var callbackVar;
//If asking for JSONP, determine the callback function name and delete it from the map
if (foundCallback){
callbackVar = req.query.callback;
delete req.query.callback
}
// Send request
db.get(req.params.coll).find(req.query, {fields:{_id:0}}, function(e,docs) {
if (e) throw e;
//If callback, send function name and query results back, else use express JSON built in
if (foundCallback)
res.send('typeof ' + callbackVar + ' === \'function\' && ' + callbackVar + '(' + JSON.stringify(docs) + ');');
else
res.json(docs);
});
};
}
Try
app.set("jsonp callback", true);