Microsoft Azure Bot Framework SDK 4: Send proactive message to specific users from bot using Node js - node.js

I am able to send message to specific users with older botbuilder SDK 3.13.1 by saving message.address field in database.
var connector = new builder.ChatConnector({
appId: process.env.MicrosoftAppId,
appPassword: process.env.MicrosoftAppPassword,
openIdMetadata: process.env.BotOpenIdMetadata
});
var bot = new builder.UniversalBot(connector);
var builder = require('botbuilder');
var msg = new builder.Message().address(msgAddress);
msg.text('Hello, this is a notification');
bot.send(msg);
How can this be done with botbuilder SDK 4? I am aware of the Rest API but want to achieve this with the SDK itself because the SDK is the more preferred way of communication between the bot and user.
Thanks in advance.

Proactive Messages in the BotFramework v4 SDK enable you to continue conversations with individual users or send them notifications.
First, you need to import TurnContext from the botbuilder library so you can get the conversation reference.
const { TurnContext } = require('botbuilder');
Then, in the onTurn method, you can call the getConversationReference method from TurnContext and save the resulting reference in a database.
/**
* #param {TurnContext} turnContext A TurnContext object representing an incoming message to be handled by the bot.
*/
async onTurn(turnContext) {
...
const reference = TurnContext.getConversationReference(turnContext.activity);
//TODO: Save reference to your database
...
}
Finally, you can retrieve the reference from the database and call the continueConversation method from the adapter to send specific users a message or notification.
await this.adapter.continueConversation(reference, async (proactiveTurnContext) => {
await proactiveTurnContext.sendActivity('Hello, this is a notification')
});
For more information about proactive messages, take a look at the documentation or this example on GitHub. Hope this is helpful.

Related

Direct Messaging custom slack bot built on node.js

I have built a slack bot using the slack/bots apis in node.js: https://slack.dev/bolt-js/tutorial/getting-started
Currently, it is working fine when I type <bot> help in a channel I have set up for using webhooks. I am trying to run those same commands in a DM with the bot using the app.event('app_mention',...) method but it is not working. its like the message doesn't register in a DM with the bot for some reason but it works in a public channel. code snippet below:
app.event('app_mention', async ({ event, client}) => {
console.log(event);
const text = event.text;
const parentMessageId = event.ts;
const eventChannel = event.channel;
if (text.includes("help")) {
console.log(event);
try {
await client.chat.postMessage({
channel: eventChannel,
text: helpMessage,
thread_ts: parentMessageId
});
} catch (err) {
console.error(err);
}
I should have permissions set up correctly as well. I basically have all the permissions that I can add for the bot
The documentation of the app_mention api specifically mentions that this event does not work with DMs.
Messages sent to your app in direct message conversations are not
dispatched via app_mention, whether the app is explicitly mentioned or
otherwise. Subscribe to message.im events to receive messages directed
to your bot user in direct message conversations.
Check here : https://api.slack.com/events/app_mention

how can i request message by using fcm api?

i'm using react native with firebase to use fcm push notification..
this is documnet example
// Node.js
var admin = require('firebase-admin');
// ownerId - who owns the picture someone liked
// userId - id of the user who liked the picture
// picture - metadata about the picture
async function onUserPictureLiked(ownerId, userId, picture) {
// Get the owners details
const owner = admin
.firestore()
.collection('users')
.doc(ownerId)
.get();
// Get the users details
const user = admin
.firestore()
.collection('users')
.doc(userId)
.get();
await admin.messaging().sendToDevice(
owner.tokens, // ['token_1', 'token_2', ...]
{
data: {
owner: JSON.stringify(owner),
user: JSON.stringify(user),
picture: JSON.stringify(picture),
},
},
{
// Required for background/quit data-only messages on iOS
contentAvailable: true,
// Required for background/quit data-only messages on Android
priority: 'high',
},
);
}
document says if i want to request message by using rest api instead of firebase admin
i have to use this url
which is
https://fcm.googleapis.com/fcm/send
but i confused how can i use this url??
and i wonder should i use this url in backend or frontend?
Sending messages to devices through FCM requires that you specify the so-called FCM server key to the API. As its name implies this key should only be used in trusted environments, such as a server you control, your development machine, or Cloud Functions.
There is no secure way to send messages directly from client-side code directly through the FCM API. For more on this, see:
the architectural overview in the Firebase documentation
How to send one to one message using Firebase Messaging

Sending Notification With Firebase Cloud Functions to Specific users

I am using firebase cloud function in my firebase group chat app, Setup is already done but problem is when some one send message in any group then all user get notification for that message including non members of group.
I want to send notification to group specific users only, below is my code for firebase cloud function -
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const _ = require('lodash');
admin.initializeApp(functions.config().firebase);
exports.sendNewMessageNotification = functions.database.ref('/{pushId}').onWrite(event => {
const getValuePromise = admin.database()
.ref('messages')
.orderByKey()
.limitToLast(1)
.once('value');
return getValuePromise.then(snapshot => {
const { text, author } = _.values(snapshot.val())[0];
const payload = {
notification: {
title: text,
body: author,
icon: ''
}
};
return admin.messaging()
.sendToTopic('my-groupchat', payload);
});
});
This will be really help full, if anyway some one can suggest on this.
As per our conversation on the comments I believe that the issue is that you are using a topic that contains all the users, which is the my-groupchat topic. The solution would be to create a new topic with the users that are part of this subtopic.
As for how to create such topics, there are a couple of examples in this documentation, in there you can see that you could do it server side, or client side. In your case, you could follow the examples for the server side, since you would need to add them in bulk, but as new users are added it could be interesting to implement the client side approach.

How to catch conversation ending event?

Using Microsoft BotBuilder, I want to catch event when user close or terminate a conversation with my bot. Here is the code of my bot:
const builder = require('botbuilder');
const connector = new builder.ChatConnector({
appId: process.env.MICROSOFT_APP_ID,
appPassword: process.env.MICROSOFT_APP_PASSWORD
});
const inMemoryStorage = new builder.MemoryBotStorage();
const bot = new builder.UniversalBot(connector).set('storage', inMemoryStorage);
initialize(bot);
function initialize(bot) {
bot.on('conversationUpdate', function(data) {
});
}
From the block of code above, I want to add an event that will handle ending conversation. Here is my example code:
function initialize(bot) {
bot.on('conversationEnd', function(data) {
var user = data.user,
address = data.address,
conversationId = data.address.conversation.id;
});
}
So, is there an event of conversationEnd like above code? I want to know if botBuilder can handle an ending conversation?
There is no event like converstaionEnd. Think of it in this way. If you are chatting with someone, you can just opt to not reply anymore. To a human user, it will seem that conversation has ended, but bot will not have any clue. It will keep on waiting. Unless you provide the intelligence to bot, to wait for a certain amount of time before considering that conversation has ended.
That said there are some other things you can handle:
You can handle conversationUpdate event. This event is triggered when any member joins/leaves a converstaion. Example
You can use a certain keyword (like goodbye, exit, etc.) as conversation ending keyword, which can trigger endConversationActionExample

How to receive my own telegram messages in node.js without bot

I would like to have a very simple client in nodejs (an example) that can receive messages from my contacts in telegram. I just searched in internet but I only get bot samples. I want to receive group messages in what I don't have access to give privileges to my bot so I would like to know if I can receive my own messages with no bot as intermediary.
Well... Other answers give examples from unmaintained libraries. Hence, you should not rely on these libraries.
See: telegram.link is dead
You should use the newest Telegram client library which is telegram-mtproto
1. Obtain your api_id and api_hash from:
Telegram Apps
2. Install the required client library:
npm install telegram-mtproto#beta --save
3. Initialize your node.js application with api_id and api_hash you got from Telegram Apps and with your phone number:
import MTProto from 'telegram-mtproto'
const phone = {
num : '+90555555555', // basically it is your phone number
code: '22222' // your 2FA code
}
const api = {
layer : 57,
initConnection : 0x69796de9,
api_id : 111111
}
const server = {
dev: true //We will connect to the test server.
} //Any empty configurations fields can just not be specified
const client = MTProto({ server, api })
async function connect(){
const { phone_code_hash } = await client('auth.sendCode', {
phone_number : phone.num,
current_number: false,
api_id : 111111, // obtain your api_id from telegram
api_hash : 'fb050b8fjernf323FDFWS2332' // obtain api_hash from telegram
})
const { user } = await client('auth.signIn', {
phone_number : phone.num,
phone_code_hash: phone_code_hash,
phone_code : phone.code
})
console.log('signed as ', user);
}
connect();
4. Receive messages (The fun part! 👨🏻‍💻)
const telegram = require('./init') // take a look at the init.js from the examples repo
const getChat = async () => {
const dialogs = await telegram('messages.getDialogs', {
limit: 50,
})
const { chats } = dialogs;
const selectedChat = await selectChat(chats);
return selectedChat;
}
Furthermore, Take a look at the examples from the original repo:
Usage Examples
Reading Chat History
Updating Profile Info
If you want to interact with Telegram data outside one of the official applications (website, mobile or desktop app etc...) you will have to create an App, so you will be required to generate API key and/or use any already existing App which fit your requirement (bots in your case).
Let me underline that with API system it appear difficult to get access to something which is restricted, if you don't have previously grant or add privileges to access it ... Nobody want that anyone could access any data...
Regards
You can use the following libraries.
https://github.com/zerobias/telegram-mtproto
https://github.com/dot-build/telegram-js
They provide abstractions to build applications to interact with telegram. for an example on how to use telegram-js, you can use https://github.com/dot-build/telegram-js/blob/master/sample.js.
(Thank you #gokcand for the feedback)

Resources