Rocket.Chat Live Chat room subscription problem - chat

I'm trying to build my own chat frontend for the Rocket.Chat Live Chat.
But currently I have the problem, that I can't subscribe to a live chat room for listening.
1) RealtimeAPI: I connect to the the rocket.chat webservice
2) RealtimeAPI: I register the guest user with "livechat:registerGuest"
3) Rest API: I create a room with "/api/v1/livechat/room?token="
I get this as answer:
{ room:
{ _id: '43TJpc3q9eRjqhFXW',
msgs: 1,
usersCount: 2,
lm: '2020-05-26T13:29:21.965Z',
fname: 'jxkyZ72fFneYCMNnM',
t: 'l',
ts: '2020-05-26T13:29:21.965Z',
departmentId: '2DKbAHmjxHtEL8g3n',
v:
{ _id: 'D6B7wJ7kcFb2QmR2u',
username: 'guest-83',
token: 'jxkyZ72fFneYCMNnM',
status: 'online' },
cl: false,
open: true,
waitingResponse: true,
_updatedAt: '2020-05-26T13:29:22.047Z',
servedBy:
{ _id: 'irByyRx98ii4wjGmj',
username: 'Admin',
ts: '2020-05-26T13:29:22.019Z' } },
newRoom: true,
success: true }
I use this _id: '43TJpc3q9eRjqhFXW' value for the subscription room name, all others cause "invalid event"
4) I try to subscribe to "stream-room-messages" and to "stream-livechat-room", but for both I receive only {"msg":"nosub","id":"3"} and not something like this
{
"msg":"ready",
"subs":[
"43TJpc3q9eRjqhFXW"
]
}
And I receive no messages from the live chat room.
Can someone tell me what I'm doing wrong or what is missing?
Thanks in advance
Frank

Ok, I found my own answer, after a lot of testings.
To subscribe for live chat message events the object has to look like this:
(Correct Object)
{
"msg":"sub",
"id":"3",
"name":"stream-room-messages",
"params":[
roomname,
{
"useCollection":false,
"args":[{"visitorToken":token}]
}
]
}
It must be "visitorToken" instead of "token".
the official documentation is wrong here, it says:
(Wrong Object)
{
"msg":"sub",
"id":"6NctZomXL3ZdtKNsn",
"name":"stream-livechat-room",
"params":[
"KTZqPAR9DQGxKcxzf",
{
"useCollection":false,
"args":[
{
"token":"jkGaw6duhiuh45"
}
]
}
]
};
Now it works to subscribe the live channel and to receive messages from the Live Agent.

Related

How to decrypt mongodb objectId on Nodejs CosomosDB Trigger

I am retrieving my azure cosmosdb/mongodb document from a custom trigger to azure functions.. But my objectId seems to be encrypted.. How to get the correct objectid..
for example ObjectId("5df88e60d588f00c32a3c9ce") is coming as ]øŽ`Õˆð2£ÉÎ
or ObjectId("5df88f92d588f00c32a3c9d1") is coming as ]ø’Õˆð2£ÉÑ
Is there a way to retrieve objectid in nodejs/python or any script if i give ]ø’Õˆð2£ÉÑ as input.
This is my function.json used in the azure function
{
"scriptFile": "__init__.py",
"bindings": [
{
"type": "cosmosDBTrigger",
"name": "documents",
"direction": "in",
"leaseCollectionName": "leases1",
"connectionStringSetting": "devcosmosdb_DOCUMENTDB",
"databaseName": "devcosmosdb",
"collectionName": "newCollection",
"createLeaseCollectionIfNotExists": "true"
}
]
}
This is my nodejs code..
module.exports = async function (context, documents) {
if (!!documents && documents.length > 0) {
context.log('Document Id: ', documents[0].id);
context.log(documents[0]);
}
}
This is my output and this is where i am not getting the objectid properly..
2020-06-16T17:16:38Z [Information] Executing 'Functions.changeTrigger' (Reason='New changes on collection newCollection at 2020-06-16T17:16:38.2618864Z', Id=adc9556a-133f-4e85-b533-5574283a5a7d)
2020-06-16T17:16:38Z [Information] Document Id: NWRmODhkZGRkNTg4ZjAwYzMyYTNjOWNj
2020-06-16T17:16:38Z [Information] {
id: 'NWRmODhkZGRkNTg4ZjAwYzMyYTNjOWNj',
_rid: 'KEcnAO163B4EAAAAAAAAAA==',
_self: 'dbs/KEcnAA==/colls/KEcnAO163B4=/docs/KEcnAO163B4EAAAAAAAAAA==/',
_ts: 1592327797,
_etag: '"0000c1d2-0000-0300-0000-5ee8fe750000"',
'$t': 3,
'$v': {
_id: { '$t': 7, '$v': ']øÝÕð\f2£ÉÌ' },
name: { '$t': 2, '$v': 'myname' },
email: { '$t': 2, '$v': 'my email' },
},
_lsn: 537
}
Please go to Azure portal to check the content of your document. I have done a test on my side, it just works fine.
Here is the document I used to test.
{
"id": "testid1",
"test1":"testvalue1",
"test2":{
"test21":"test21value",
"objectId":"5df88f92d588f00c32a3c9d1"
}
}
After clicking save button, the function will be triggered.
Here is my testing code.
def main(documents: func.DocumentList) -> str:
if documents:
logging.info('Document id: %s', documents[0]['id'])
logging.info('%s',documents[0].to_json())
The output is as below.
Update:
Currently only SQL API base is supported in Azure function cosmosdb trigger. You can also find the feature under Settings part.
The URI should be something like https://testbowman.documents.azure.com:443/
If you create a mongodb api cosmosdb account, you won't find the 'add to function' feature. And the URI should be something like https://tonycosmosdb.mongo.cosmos.azure.com:443/

Create Payment Request API

I am trying to integrate the Payment Request API for the Google Pay for Payments using javascript but my code returns a PaymentRequest is not defined error.
Here is my code.
CODE:
const supportedInstruments = [
{
supportedMethods: ['https://tez.google.com/pay'],
data: {
pa: 'abc#gmail.com',
pn: 'abc',
tr: '1234ABCD', // your custom transaction reference ID
url: 'http://url/of/the/order/in/your/website',
mc: '1234', // your merchant category code
tn: 'Purchase in Merchant',
},
}
];
const details = {
total: {
label: 'Total',
amount: {
currency: 'INR',
value: '10.01', // sample amount
},
},
displayItems: [{
label: 'Original Amount',
amount: {
currency: 'INR',
value: '10.01',
},
}],
};
let request = null;
try {
request = new PaymentRequest(supportedInstruments, details);
}
catch (e) {
console.log('Payment Request Error: ' + e.message);
return;
}
if (!request) {
console.log('Web payments are not supported in this browser.');
return;
}
Error Message:
Payment Request Error: PaymentRequest is not defined
Sounds to me like you are testing it in an older browser that simply doesn't support it. Browser support is pretty good these days, but not universal. You just need to do a simple bit of feature detection and wrap your code in an if statement to check the browser supports it:
if (window.PaymentRequest) {
// your payment request code here
}

How to use botkit with facebook and wit.ai

I am a novice in chatbot development and I would like some help.
While it seems quite simple to connect botkit with facebook messenger and wit.ai in orger to use NLP. I haven't managed to do so. My initial goal is to have a simple conversation like hello-hello but using wit.ai as middleware.
Below I attach the code. What it should do is receive a "hello" message, pass it to wit.ai and then respond "I heard hello!" as a reply (without using wit at this stage). Instead I just receive
debug: RECEIVED MESSAGE
debug: CUSTOM FIND CONVO XXXXXXXXXXXXXX XXXXXXXXXXXXXX
debug: No handler for message_received
after every message I send to facebook messenger bot. In wit it seems like I am getting the messages since I receive messages in my inbox to update the intents.
If there is any code much simpler than the one below I would be very happy to have it so that I can start with something much simpler :).
Thanks
<pre><code>
if (!process.env.page_token) {
console.log('Error: Specify page_token in environment');
process.exit(1);
}
if (!process.env.page_token) {
console.log('Error: Specify page_token in environment');
process.exit(1);
}
if (!process.env.verify_token) {
console.log('Error: Specify verify_token in environment');
process.exit(1);
}
if (!process.env.app_secret) {
console.log('Error: Specify app_secret in environment');
process.exit(1);
}
var Botkit = require('./lib/Botkit.js');
var wit = require('./node_modules/botkit-middleware-witai')({
token: process.env.wit,
minConfidence: 0.6,
logLevel: 'debug'
});
var os = require('os');
var commandLineArgs = require('command-line-args');
var localtunnel = require('localtunnel');
const ops = commandLineArgs([
{name: 'lt', alias: 'l', args: 1, description: 'Use localtunnel.me to make your bot available on the web.',
type: Boolean, defaultValue: false},
{name: 'ltsubdomain', alias: 's', args: 1,
description: 'Custom subdomain for the localtunnel.me URL. This option can only be used together with --lt.',
type: String, defaultValue: null},
]);
if(ops.lt === false && ops.ltsubdomain !== null) {
console.log("error: --ltsubdomain can only be used together with --lt.");
process.exit();
}
var controller = Botkit.facebookbot({
debug: true,
log: true,
access_token: process.env.page_token,
verify_token: process.env.verify_token,
app_secret: process.env.app_secret,
validate_requests: true, // Refuse any requests that don't come from FB on your receive webhook, must provide FB_APP_SECRET in environment variables
});
var bot = controller.spawn({
});
controller.setupWebserver(process.env.port || 3000, function(err, webserver) {
controller.createWebhookEndpoints(webserver, bot, function() {
console.log('ONLINE!');
if(ops.lt) {
var tunnel = localtunnel(process.env.port || 3000, {subdomain: ops.ltsubdomain}, function(err, tunnel) {
if (err) {
console.log(err);
process.exit();
}
console.log("Your bot is available on the web at the following URL: " + tunnel.url + '/facebook/receive');
});
tunnel.on('close', function() {
console.log("Your bot is no longer available on the web at the localtunnnel.me URL.");
process.exit();
});
}
});
});
controller.middleware.receive.use(wit.receive);
controller.hears(['hello'], 'direct_message', wit.hears, function(bot, message) {
bot.reply(message, 'I heard hello!');
});
function formatUptime(uptime) {
var unit = 'second';
if (uptime > 60) {
uptime = uptime / 60;
unit = 'minute';
}
if (uptime > 60) {
uptime = uptime / 60;
unit = 'hour';
}
if (uptime != 1) {
unit = unit + 's';
}
uptime = uptime + ' ' + unit;
return uptime;
}
Make sure you have a few conversations in Wit.ai beforehand so for example hello there and highlight the hello in that statement as something like, greetings.
Now i'm not sure what your intents are called in wit.ai but in your statement controller.hears(['hello'] you're actually listening to the wit.ai intents. So in the example i mentioned above, we'd be using hears(['greetings']) since that's the intent in wit.ai.
Also, instead of using direct_message use message_received this is what it should look like:
controller.hears(['hello'], 'message_received', wit.hears, function(bot, message) {
bot.reply(message, 'I heard hello!');
});
If you're struggling tracking down the problem you can stick a console statement in your controller so something like console.log("Wit.ai detected entities", message.entities); and see what you get back from that.
Let me know if you're still having any issues :)

How to ask permission in Actions on Google without the SDK?

I would like to know the name of the user, however I cannot use the nodejs sdk since I use another language.
How can I ask for permission?
I would prefer a way with the normal json responses.
I hacked this minimal script to get the JSON reponse which the nodejs sdk would return:
gaction.js:
const DialogflowApp = require('actions-on-google').DialogflowApp;
const app = new DialogflowApp({
request: {
body: {
result: {
action: 'Test',
contexts: []
}
},
get: (h) => h
},
response: {
append: (h, v) => console.log(`${h}: ${v}`),
status: (code) => {
return {send: (resp) => console.log(JSON.stringify(resp, null, 2))}
}
}
});
function testCode(app) {
app.askForPermission('To locate you', app.SupportedPermissions.DEVICE_PRECISE_LOCATION);
}
app.handleRequest(new Map().set('Test', testCode));
I'm still no node.js expert so this might be not an optimal solution. When you have installed node and run the command npm install actions-on-google, this will install the necessary dependencies.
When done you just need to run node gaction which will create this output:
Google-Assistant-API-Version: Google-Assistant-API-Version
Content-Type: application/json
{
"speech": "PLACEHOLDER_FOR_PERMISSION",
"contextOut": [
{
"name": "_actions_on_google_",
"lifespan": 100,
"parameters": {}
}
],
"data": {
"google": {
"expect_user_response": true,
"no_input_prompts": [],
"is_ssml": false,
"system_intent": {
"intent": "assistant.intent.action.PERMISSION",
"spec": {
"permission_value_spec": {
"opt_context": "To locate you",
"permissions": [
"DEVICE_PRECISE_LOCATION"
]
}
}
}
}
}
}
If you send now the JSON above you will be asked from Google Home. Have fun!
The request/response JSON formats for the API.AI webhooks with Actions is documented at https://developers.google.com/actions/apiai/webhook
As you've discovered, the data.google.permissions_request attribute contains two fields regarding the request:
opt_context contains a string which is read to give some context about why you're asking for the information.
permissions is an array of strings specifying what information you're requesting. The strings can have the values
NAME
DEVICE_COARSE_LOCATION
DEVICE_PRECISE_LOCATION
If you are using Java or Kotlin there is an Unofficial SDK. It matches the official SDK api nearly exactly.
https://github.com/TicketmasterMobileStudio/actions-on-google-kotlin

how to sync data from ydn-db web app to backend server?

With ydn-dn, i want to automatically synchronise data from my web app with my REST back end.
I read the documentation and searched in examples but i cannot make it work.
https://yathit.github.io/ydn-db/synchronization.html
http://dev.yathit.com/api/ydn/db/schema.html#sync
I tried to define a schema with sync configuration like that :
var schema = {
stores: [ {
name: 'contact',
keyPath: 'id',
Sync: {
format: 'rest',
transport: service,
Options: {
baseUri: '/'
}
}
}
]
};
and created a function for transport :
var service = function(args) {
console.log("contact synch");
};
but my service function is never called.
I certainly misunderstood how YDN-db work, but i didn't found any example.
To complete, here is a jsfiddle :
http://jsfiddle.net/asicfr/y7sL7b3j/
Please see the example http://yathit.github.io/ydndb-demo/entity-sync/app.html
Older example http://yathit.github.io/sprintly-service/playground.html from https://github.com/yathit/sprintly-service