Autobahn identify subscription - node.js

When creating a websockets connection how can I determine the name of the subscription in the event function.
For example if I have three subscriptions I wish to be able to identify which once triggered the event.
var autobahn = require('autobahn');
var connection = new autobahn.Connection({url: 'ws://127.0.0.1:9000/', realm: 'realm1'});
connection.onopen = function (session) {
function onevent(args) {
console.log("Colour is: ", ?????);
}
["Red", "Green", "Brown"].forEach(function(colour) {
session.subscribe(colour, onevent);
}
};
connection.open();

Your onevent function actually receives three arguments: args, kwargs and details, where the first two are message payload (an array and an object). The details object contains what you are looking for: the subscription topic.

Related

Cannot find documentation for botframework-connector functions examples

I'm using the botframework-connector npm package. And I want to use the sendOperationRequest & sendRequest methods from the ConnectorClient instance.
I have searched for the method examples here but can not find them.
Can anyone help me, please?
Edit:
I know how to use the create/update conversations via Conversations methods. I'm trying to scope whether I can use the package for other operations such as createChannel, add members to a group etc.
You should explore code samples in
https://github.com/microsoft/BotBuilder-Samples/tree/main/samples
rather than trying to understand how to use the SDK through the class references.
sendOperationRequest & sendRequest aren't really meant to be used explicitly, ConnectorClient uses it to send the request.
In order to send your message you first need a conversation reference (otherwise, how would the bot know which conversation to send the message to?) For example, look at the sample code on the documentation page of the NPM package you linked :
var { ConnectorClient, MicrosoftAppCredentials } = require('botframework-connector');
async function connectToSlack() {
var credentials = new MicrosoftAppCredentials('<your-app-id>', '<your-app-password>');
var botId = '<bot-id>';
var recipientId = '<user-id>';
var client = new ConnectorClient(credentials, { baseUri: 'https://slack.botframework.com' });
var conversationResponse = await client.conversations.createConversation({
bot: { id: botId },
members: [
{ id: recipientId }
],
isGroup: false
});
var activityResponse = await client.conversations.sendToConversation(conversationResponse.id, {
type: 'message',
from: { id: botId },
recipient: { id: recipientId },
text: 'This a message from Bot Connector Client (NodeJS)'
});
console.log('Sent reply with ActivityId:', activityResponse.id);
}
The botID and recipientID is dependent on the channel you use.
Edit : As I misunderstood the intent of the question.
If you want to create a channel, check out
https://github.com/howdyai/botkit/blob/main/packages/docs/core.md
There are officially supported channels with adapters that you can utilize. But if you are looking to connect to a custom app, look at https://github.com/howdyai/botkit/blob/main/packages/docs/reference/web.md#webadapter
for the generic web adapter that you can use to send and receive messages.

Mqtt unsubscribe not ending topic subcription

I am able to publish and subscribe to a topic but when the unsubscribe function is not working it?
var mqtt = require('mqtt');
var client = mqtt.connect('mqtt://localhost:1883');
var topic = 'home/machine1/lightSensor';
client .on('connect', ()=>{
client.unsubscribe(topic,console.log);
});
it returning null
From the mqttjs docs:
mqtt.Client#unsubscribe(topic/topic array, [options], [callback])
Unsubscribe from a topic or topics
topic is a String topic or an array of topics to unsubscribe from
options: options of unsubscribe.
properties: object
userProperties: The User Property is allowed to appear multiple times to represent multiple name, value pairs object
callback - function (err), fired on unsuback. An error occurs if client is disconnecting.
Returning null is the correct response if the unsubscribe succeeds.

Sending message to a specific group of subscriber in azure service bus topic with masstransit

I'm new to azure service bus and masstransit. I'm looking for a solution to a specific situation.
I have a azure service bus topic with multiple subscribers. Subscriber will receive message based on filters. I've created the topic and subscriber with code below
class Program
{
static void Main(string[] args)
{
string connectionString = "Endpoint connection string";
// the names of topics and subscriptions we'll be working with
const string topicName = "MyTestTopic";
const string allMessagesSubName = "AllMessages";
const string filteredSubName1 = "Filtered1";
const string filteredSubName2 = "Filtered2";
// let's create the topic if it doesn't already exist...
var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);
if (!namespaceManager.TopicExists(topicName))
{
var td = new TopicDescription(topicName);
namespaceManager.CreateTopic(td.Path);
}
if (!namespaceManager.SubscriptionExists(topicName, allMessagesSubName))
{
namespaceManager.CreateSubscription(topicName, allMessagesSubName);
}
if (!namespaceManager.SubscriptionExists(topicName, filteredSubName1))
{
namespaceManager.CreateSubscription(
new SubscriptionDescription(topicName, filteredSubName1),
new Microsoft.ServiceBus.Messaging.SqlFilter("From LIKE '%Smith'"));
}
if (!namespaceManager.SubscriptionExists(topicName, filteredSubName2))
{
namespaceManager.CreateSubscription(
new SubscriptionDescription(topicName, filteredSubName2),
new Microsoft.ServiceBus.Messaging.SqlFilter("sys.Label='important'"));
}
var message1 = new BrokeredMessage("Hello World");
var message2 = new BrokeredMessage("Second message");
message2.Label = "important";
var message3 = new BrokeredMessage("Third message");
message3.Properties["From"] = "Kelly Smith";
message3.Label = "information";
var client = TopicClient.CreateFromConnectionString(connectionString, topicName);
client.Send(message1);
client.Send(message2);
client.Send(message3);
client.Close();
}
}
Here in the code we're adding Message custom properties like From.
Now I want to send such message using masstransit. In masstransit I cannot find any option of adding Message custom properties using the Publish() method. Is there any way that I can send these messages using masstransit where these filters can be used?
NB: I've read the answer of this question But the anwer here tells us to filter the messages in subscriber side. What I want is that this filtering will occur before reaching the subscriber.
When using Azure Service Bus with MassTransit, you can add subscription endpoints in additional to regular endpoints. When configuring a subscription endpoint, you should be able to specify rules and/or filters as part of the subscription. Which is exactly what you're doing above, so that is handled.
The other part, adding properties to the message, can be done by adding text headers to the SendContext. Those headers are copied to the message Properties collection, which I believe can be used to filter messages using a "SQL" filter (which is configured on the subscription endpoint, or the topic subscription on a receive endpoint).

How to log the response message in a Registered Handler - ServiceStack RabbitMQ

Given this snippet of code:
//DirectApi
mqServer.RegisterHandler<LeadInformationInfo>(m =>
{
repository.SaveMessage(m as Message);
LeadInformationInfoResponse response = new LeadInformationInfoResponse();
try
{
var client = new JsonServiceClient(settingsFactory.GetMasterSetting("ProcessorApi:baseUri"));
response = client.Post(m.GetBody());
}
catch (WebServiceException webServiceException)
{
_log.Error("RegisterHandler<LeadInformationInfo>", webServiceException);
response = ((LeadInformationInfoResponse) webServiceException.ResponseDto);
response.CorrelationId = m.Id;
}
// Log response message here
return response;
}, 1);
I've gone to great lengths to make sure that a correlationId based off the original message Id property is propagated through the life of this message and any child messages spawned from this action. How do I get a handle on the response message so that I may log it in the handler? I only have access to the ResponseDto and not the message.
One of the reasons for this request is that the message queue client does not have access to the database, only the process that has the handler registered does. Hope that explains the situation better.
Just to clarify, this question is about persisting a MQ Response Message in the handler, the correlation Id is something that all messages in 1 request/response workflow will share. I'm also using ServiceStack ORMlite to persist the Message object, so querying this table by ID for troubleshooting is paramount.
Thank you,
Stephen
You're calling a WebService from within your MQ Handler:
var client = new JsonServiceClient(...);
response = client.Post(m.GetBody());
So there is no MQ Response which is only available in MQ Services. Although the WebService will return the response for the request that's sent so you can either use the CorrelationId on the MQ Request, otherwise you can have your Response DTO implement an interface like IHasCorrelationId and get it that way, e.g:
var correlationResponse = response as IHasCorrelationId;
if (correlationResponse != null)
{
var correlationId = correlationResponse.CorrelationId;
}
Create your own Instance of Message
As the Message<T> class is just a POCO if you wanted to create your own you can intialize your own instance:
var mqResponse = new Message<Response>(response);
If you only had the runtime late-bound type info, you can create one with:
var mqResponse = MessageFactory.Create(response);
Use RabbitMQ Message Filters
If you just wanted to log incoming and outgoing messages you can use the RabbitMQ Message Filters, e.g:
var mqServer = new RabbitMqServer("localhost")
{
PublishMessageFilter = (queueName, properties, msg) => {
properties.AppId = "app:{0}".Fmt(queueName);
},
GetMessageFilter = (queueName, basicMsg) => {
var props = basicMsg.BasicProperties;
receivedMsgType = props.Type; //automatically added by RabbitMqProducer
receivedMsgApp = props.AppId;
}
};

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