javascript pubnub messaging system - pubnub

I am currently using PubNub SDK for chatting in website and iPhone. Now i want to implement functionality like i want to send message from iPhone to web-end once user sends a message from iPhone to web-end ( user will be notified ).
Now the issue is when initially user1 sends message from iPhone to webend i am not getting notification.
on first message i am not getting notification.
code is somewhat like this
var socket = new WebSocket("Pubnub + channel1id";
var chat_socket = new WebSocket("Pubnub + channel2id";
socket.onmessage = function (evt)
{
//Here i implemeted our notification functionality.
}
chat_socket.onmessage = function (evt)
{
//Here i implemeted our notification functionality.
}
on second message i am getting object on .onmessage but not for first.

Related

iOS not receiving pending push after turn on device or Internet from Azure Notification Hub

I have a Notification Hub in Azure to send PUSH to Android and iOS devices. Everything is working well in Android. In iOS I have this problem:
I turn off the WiFi or I turn off the device
I send chat messages to my app (push notifications) and also messages to that device from WhatsApp.
I turn on the WiFi or turn on the device after a few minutes
I receive all the WhatsApp messages notifications but no one of the notification to my App. If the device and Internet is on, I receive the notifications without problem.
My question is: Anyone has experienced something like that or know how to fix it?
At least I should have to receive the last push, right?
I'm sending the push to a tag. I can see the Device registered in the hub either when WiFi or iPhone are off.
When sending notification ensure that you set the expiration. Default value is zero. Hence, APNs treats the notification as if it expires immediately and does not store the notification or attempt to redeliver it.
https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingwithAPNs.html
apns-expiration
If this value is nonzero, APNs stores the notification
and tries to deliver it at least once, repeating the attempt as needed
if it is unable to deliver the notification the first time. If the
value is 0, APNs treats the notification as if it expires immediately
and does not store the notification or attempt to redeliver it.
If you are using template notifications, here is how you do it.
AppleTemplateRegistrationDescription registration = new AppleTemplateRegistrationDescription(parameters.registrationID)
{ BodyTemplate = new CDataMember("{\"aps\":{\"alert\":\"$(body)\",\"payload\":\"$(payload)\",\"deeplinking\":\"$(deeplinking)\",\"category\":\"$(category)\",\"image\":\"$(image)\"}}"),
Tags = itags,
Expiry = "$(APNS_Expiry)"
};
As part of send, you can pass the expiry value.
var notification = new TemplateNotification(new Dictionary<string, string>()
{
{"APNS_Expiry", DateTime.UtcNow.AddMinutes(10).ToString("o") }, //Timestamp
{"body", NotificationText},
{"payload", NotificationText},
{"deeplinking", payload},
});
var Responsehub = hub.SendNotificationAsync(notification);
If you are using native notifications,
// Native notification
var notification = new AppleNotification(#"
{
""aps"": {
""alert"":""New notification!""
}
}");
notification.Expiry = DateTime.UtcNow.AddMinutes(2);
await notificationHubClient.SendNotificationAsync(notification);
If you are using template notifications, here is how you do it.
AppleTemplateRegistrationDescription registration = new AppleTemplateRegistrationDescription(parameters.registrationID)
{ BodyTemplate = new CDataMember("{\"aps\":{\"alert\":\"$(body)\",\"payload\":\"$(payload)\",\"deeplinking\":\"$(deeplinking)\",\"category\":\"$(category)\",\"image\":\"$(image)\"}}"),
Tags = itags,
Expiry = "$(APNS_Expiry)"
};
As part of send, you can pass the expiry value.
var notification = new TemplateNotification(new Dictionary<string, string>()
{
{"APNS_Expiry", DateTime.UtcNow.AddMinutes(10).ToString("o") }, //Timestamp
{"body", NotificationText},
{"payload", NotificationText},
{"deeplinking", payload},
});
var Responsehub = hub.SendNotificationAsync(notification);
If you are using native notifications,
// Native notification
var notification = new AppleNotification(#"
{
""aps"": {
""alert"":""New notification!""
}
}");
notification.Expiry = DateTime.UtcNow.AddMinutes(2);
await notificationHubClient.SendNotificationAsync(notification);

How can I post a welcome message to a newly joined user via a Slack bot?

I am trying to leverage Slack's Real-time messaging (RTM) API to post a welcome message to newly joined users of my team from a "Greeter Bot".
The event I'm listening for is team_join.
I have confirmed that the event is firing, and that messages can be sent to previously joined users out upon receiving that event. However, when trying to notify the newly joined user, nothing comes through.
I've played around with adding a delay (up to 45secs) after receiving the event before notifying the user, but still no dice.
Here my index.js file:
var SlackBot = require('slackbots');
var bot = new SlackBot({
token: process.env.SLACK_TOKEN || '',
name: process.env.BOT_NAME || 'greeterbot'
});
bot.on('message', function(data) {
var self = this;
if ('team_join' === data.type) {
setTimeout(function() {
var message = 'hello.';
// this works. 'some crusty old user' gets a DM message from my greeterbot.
self.postMessageToUser('some crusty old user', message, { as_user: true });
// FAIL. what am i doing wrong?!
self.postMessageToUser(data.user.name, message, { as_user: true });
}, 45000);
console.log("'" + data.user.name + "' has joined the team."); // works. the user name is present in the log.
}
});
I figured it out. There is a caching issue with the underlying bot library that I'm using.
For reference, here is a link to a PR that aims to address this issue.
https://github.com/mishk0/slack-bot-api/pull/25
Switching libs now.
Our Slack team, SKGTech.io uses Janitr that we wrote. Janitr is a Slack bot that welcomes new users based on your preferences.

Messaging a user a bot does not know

I am using the Slack RTM node client and having a bit of an issue with DM's. Say a user joins the channel who has never DM'ed the bot before, the user types a command in the channel that the bot usually will respond to and by default the bot responds in a private message to the user. However, the bot cannot do this because the dataStore does not contain any DM data for this user. Code sample below...
rtm.on(RTM_EVENTS.MESSAGE, function (message) {
user = rtm.getUserById(message.user);
console.log(user); // It gets the user object fine
dm = rtm.getDMByName(user.name);
console.log(dm); // This is always undefined unless the user has DM'ed the bot previously
});
Is there a way around this? I can't seem to find anything in the docs or code to suggest there might be.
You can use the im.open method of the web API. Here's roughly how you'd do it with #slack/client (untested, apologies in advance!):
var webClient = new WebClient(token);
...
rtm.on(RTM_EVENTS.MESSAGE, function (message) {
var dm = rtm.getDMById(message.user);
if (dm) {
console.log(`Already open IM: ${dm}`);
// send a message or whatever you want to do here
} else {
webClient.im.open(message.user, function (err, result) {
var dm = result.channel.id;
console.log(`Newly opened IM: ${dm}`);
// send a message or whatever you want to do here
});
}
});

how can I make private chat rooms with sockjs?

I am trying to make a chat system where only two users are able to talk to each other at a time ( much like facebook's chat )
I've tried multiplexing, using mongoDB's _id as the name so every channel is unique.
The problem I'm facing is that I cannot direct a message to a single client connection.
this is the client side code that first sends the message
$scope.sendMessage = function() {
specificChannel.send(message)
$scope.messageText = '';
};
this is the server side receiving the message
specificChannel.on('connection', function (conn) {
conn.on('data', function(message){
conn.write('message')
}
}
When I send a message, to any channel, every channel still receives the message.
How can I make it so that each client only listens to the messages sent to a specific channel?
It appeared that SockJS doesn't support "private" channels. I used the following solution for a similar issue:
var channel_id = 'my-very-private-channel'
var connection = new SockJS('/pubsub', '')
connection.onopen = function(){
connection.send({'method': 'set-channel', 'data': {'channel': channel_id}})
}
Backend solution is specific for every technology stack so I can't give a universal solution here. General idea is the following:
1) Parse the message in "on_message" function to find the requested "method name"
2) If the method is "set-channel" -> set the "self.channel" to this value
3) Broadcast further messages to subscribers with the same channel (I'm using Redis for that, but it also depends on your platform)
Hope it helps!

Pusher binding to events regardless of channel

I am attempting to listen to a particular event type regardless of the channel it was triggered in. My understanding of the docs (http://pusher.com/docs/client_api_guide/client_events#bind-events/lang=js) was that I can do so by calling the bind method on the pusher instance rather than on a channel instance. Here is my code:
var pusher = new Pusher('MYSECRETAPPKEY', {'encrypted':true}); // Replace with your app key
var eventName = 'new-comment';
var callback = function(data) {
// add comment into page
console.log(data);
};
pusher.bind(eventName, callback);
I then used the Event Creator tool in my account portal to generate an event. I used a random channel name, set the Event to "new-comment" and just put in some random piece of text into the Event Data. But, I am getting nothing appearing in my Console.
I am using https://d3dy5gmtp8yhk7.cloudfront.net/2.1/pusher.min.js, and performing this test in the latest Chrome.
What am I missing?
Thanks!
Shaheeb R.
Pusher will only send events to the client if that client has subscribed to the channel. So, the first thing you need to do is subscribe the channel. Binding to the event on the client:
pusher.bind('event_name', function( data ) {
// handle update
} );
This is also known as "global event binding".
I've tested this using this code and it does work:
http://jsbin.com/AROvEDO/1/edit
For completeness, here's the code:
var pusher = new Pusher('APP_KEY');
var channel = pusher.subscribe('test_channel');
pusher.bind('my_event', function(data) {
alert(data.message);
});

Resources