How can I create automatic message in the streamui from an another system. For instance, to create alerts based on log created by our HR platform ?
Use this endpoint to create an entry in the stream wall.
What you need is to get previously the authentication token and the html of the message.
$.ajax({
type: "POST",
url: « //the-url.ofyour.portal/streamui",
data: { "jsonstring": JSON.stringify(_jsonstring) },
success: function (data) {
console.log(data);}
});
With _jsonstring as :
{"Token": , -> authentication cookie
"FilChartId": "", -> leave empty
"DashboardId": , -> id of the story
"ChartId": , -> leave empty
"html":"<p>test stream</p>",
"json":{"Token": , -> authentication cookie
"DataView": "", -> Name of the datatable
"Universe": "" -> universe cookie
}
}
Related
Wan we add charts in the Veeml pin’s wall of some users programmatically ?
We will use the api to synchronize the users with our existing users and we would like to automaticaly initialize the pin’s wall for these new users.
Use the endpoint /pinchart to add a chart in a Veeml pin’s wall.
What you need is to get previously the authentication token and the html of the message.
$.ajax({
type: "POST",
url: « //the-url.ofyour.portal/pinchart",
data: { "jsonstring": JSON.stringify(_jsonstring) },
success: function (data) {
console.log(data);
}
});
With _jsonstring as :
{
"Token":"", -> autentication cookie
"DataView":"", -> leave it empty
"Universe": {}, -> universe cookie
"ChartId": 1234, -> Id of the chart
"DashboardId": 1234 -> Id of the story
}
I am unable to accomplish a successful ReactJs using Axios Post call where the data is passed to my asp.net core 2.2 web api. The call will only successfully hit my API endpoint when all compound word (last-name) properties are hyphenated, however the data does not get through. Only single word (company) properties receive the data. I believe it is because with the hyphens the properties no longer match. However, if the properties are not hyphenated I receive a 400 error or 415 error. When sending the call via Postman, where all properties are pascal cased, I don't have any issue at all.
I have tried many things to get it to work without solutions. I have added Json Attributes to my .net object properties. I have modified the attribute to also have the hyphens. I have tried changing both my properties in my react to single word and matching them with the Json attribute, e.i created vs CreatedDate. I have also pasted into my post method the exact same json object used in my PostMancall that was successful.
.net post
[HttpPost]
[Route("AddThreshold", Name = "AddThreshold")]
public ActionResult<ThresholdDTO> AddThreshold([FromBody] ThresholdDTO threshold)
{
var thr = _thresholdService.AddThreshold(threshold);
if (thr == null)
return NoContent();
return Ok(threshold);
}
const handleAddSubmit = e => {
e.preventDefault();
let current_datetime = new Date();
let formatted_date =
current_datetime.getFullYear() +
"-" +
(current_datetime.getMonth() + 1) +
"-" +
current_datetime.getDate() +
" " +
current_datetime.getHours() +
":" +
current_datetime.getMinutes() +
":" +
current_datetime.getSeconds();
console.log(location);
let threshold = JSON.stringify({
"Threshold-Id": "",
Company: company.toString(),
"Threshold-Type": thresholdType.toString(),
"Threshold-Value": thresholdValue.toString(),
"Account-Number": account.toString(),
"Location-Number": location == "undefined" ? "" : location.toString(),
"Expected-Amount": expectedAmount.toString(),
"Created-Date": formatted_date.toString(),
"Created-By": "System",
"Updated-Date": "1900-00-00 00:00:00.000",
"Updated-By": ""
});
Axios({
method: "post",
url: "https://localhost:44394/Threshold/AddThreshold/",
data: threshold,
headers: { "Content-Type": "application/json" }
})
.then(function(response) {
//handle success
console.log(threshold);
props.handleAddClose();
})
.catch(function(response) {
//handle error
console.log(threshold);
});
};
AccountNumber: "87605177 (CenturyLink)"
Company: "Deere Employees Credit Union"
CreatedBy: "System"
CreatedDate: "2019-10-27 16:1:51"
ExpectedAmount: "90000"
LocationNumber: "5000"
ThresholdId: ""
ThresholdType: "Invoice Processing"
ThresholdValue: "10"
UpdatedBy: ""
UpdatedDate: "1900-00-00 00:00:00.000"
The above object is exactly what postman is successful with but I receive a 400 code when using axios
The problem was my UpdatedDate value did not have an format acceptable to the Json Attribute causing the whole post to fail.
In my project , the Contact Request Form is sent to an HTTP Firebase function ( Google Cloud Function wrapper...) the received data should be sent to a gmail user contact#mydomain.org (G Suite account)
( I am trying NOT to use another service like SendGrid... )
Currently I send the message with gmail.users.messages.send() , obviously GMail API is overwriting the From: original sender email with Googlea account admin email...
I tried to run before a gmail.users.settings.sendAs.create() to add the original from: email address, but in this case I need also to setup an smtpMsa server to be used as a relay ...
Is there anyway to BUILD a mail message from the data received ( from: msg_text: ) and INSERT IT DIRECTLY into my contact#mydomain.org gmail box to 'simulate' a received message with the correct information ? or should it be sent only by an smtp server ?
UPDATE
I can use users.message.import() ...
but I get an error when if I import into another email address ( contact# ) than the account admin ...
{"infos":"Delegation denied for admin#mydomain.org"}
THIS WORKS
return gmail.users.messages.import({
userId: config_key.admin_email,
resource: {
raw: encodedMessage
}
});
THIS DON't WORK
return gmail.users.messages.import({
userId: config_key.contact_email,
resource: {
raw: encodedMessage
}
});
YES WE CAN !
I succeeded finally ... inserting directly a message into my Google Suite email address .. and the from: address is actually the original contact form sender email address !
function gMailInserMessage (sender_name, sender_email, msg_text) {
// Create a new JWT client using the key file downloaded from the Google Developer Console
const jwtClient = new google.auth.JWT(
postoffice_key.client_email, // service account with Domain-Wide delagation of Authority
null,
postoffice_key.private_key,
_.values(config_key.scopes.postoffice),
config_key.admin_email // subject (or sub) impersonated user
);
return jwtClient.authorize().then(tokens => {
// Obtain a new gmail client, making sure we pass along the auth client
const gmail = google.gmail({
version: 'v1',
auth: jwtClient
});
// Base64-encode the mail and make it URL-safe
// (replace all "+" with "-" and all "/" with "_")
var encodedMessage = btoa([
'From: ' + sender_email + '\r\n',
'To: ' + config_key.admin_email + '\r\n',
'Subject: Contact\r\n\r\n',
msg_text
].join("")).replace(/\+/g, '-').replace(/\//g, '_');
//Make an authorized request to insert a User Messages
return gmail.users.messages.insert({
userId: 'me', // impersonated authorized user
resource: {
raw: encodedMessage
}
});
}).then(res => res.data);
}
the response is :
{"status":200,"infos":
{"id":"1639b41c26584963","threadId":"1639b41c26584963"}}
I want to pass some values to frontend in form of context variables in IBM Watson through my Node app. How can I achieve it?
I tried to add the value I want to add to current context variable object and sent that back. Still no help. Is there any way I can do it?
Edit:
Right now, I am adding the required value as a new key-value pair to the context object from Node app as follows.
...
let user_name = "MJ"
context.user_name = user_name
response.send({
output: output,
context: JSON.stringfy(context)
})
...
And in Watson Console, in one of the dialogue nodes I have used like,
Hey $user_name, How are you?
But the output I am getting is,
Hey , How are you?
I can see user_name value in the context object, but I can't use it in the way I mentioned above. Is there any other way to do so?
Any help is appreciated. Thanks in advance!
I was having the same problem. My solution was changing the code when you call the IBM server and request .json:
...
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
text,
context: {username : variable},
...
The username I set in Watson Assistant as well as a context, the variable I used a function to get the name though Query (Because in my application, I am calling the chatbot though an IFrame.), but you can use any variable set on javascript.
You can add any value to the Context object, which can be accessed in your Node.JS app and if you send that value to the front-end, then it should be accessible in the UI as well.
Below I've mentioned a sample welcome response from Conversation service. You can access the Context object from the response of Conversation service and add a new key-value pair to that object. In the response, you'll see that I'm accessing a context variable username that has the value MJ, which has been added dynamically to the context.
`
{
"intents": [],
"entities": [],
"input": {
"text": ""
},
"output": {
"text": ["Hello MJ! How can I help you today?"],
"nodes_visited": ["Conversation Start"],
"log_messages": []
},
"context": {
"username": "MJ",
"conversation_id": "5835fa3b-6a1c-4ec5-92f9-22844684670e",
"system": {
"dialog_stack": [{
"dialog_node": "Conversation Start"
}],
"dialog_turn_counter": 1,
"dialog_request_counter": 1,
"_node_output_map": {
"Conversation Start": [0]
}
}
}
`
Now to update the context, fetch the response and add a new key-value pair
`
var convResponse = <responseObj from Conversation call>;
var context = convResponse.context;
//add new value to context
context["new_key"] = "new value";
`
Now the next call that you make to Conversation, use this updated context instead of the context you received from the previous call. You can send back the response from Conversation to the front-end as well which can then be shown to the user.
var payload = {
assistantId: assistantId,
sessionId: req.body.session_id,
context: {
skills: {
"main skill": {
user_defined: {
username: 'John Doe'
}
}
}
},
input: {
message_type: 'text',
text: "blah",
},
};
works for me. Seen here: https://medium.com/#pranavbhatia_26901/watson-assistant-v2-context-sharing-3ca18626ed0d
I am trying to set up a minimal layer of authentication between my Rails backend and my React front end, but I am running into some problems.
I cannot seem to find the cookie key value that the server passes down to my client. In the network tab, I see it in the response: Set-Cookie:_skillcoop_session=...., but when I use js-cookie to look for the above cookie, _skillcoop_session, I only see one called identity-token=... and its value is different from _skillcoop_session. How do I access _skillcoop_session in the browser?
What header key do I pass up to the server to signal to my backend to use 'this' header key to match up with the session it has stored off? In this post, Justin Weiss seems to suggest that I make the request to the server with a header like: Cookie: _skillcoop_session=....
Am I doing this all wrong? Would I be better off using a gem like devise?
Also in order to load the session in my other controllers, I have had to do something like session['init'] = true, and I learned to do this from this SO post. This seems hacky. Why do I have to manually reload the session in separate controller actions after I've set it previously in a different controller action in a different request?
I'm currently just stubbing out the user and the authentication -- all I want to do to get the plumping in place is set a session[:user_id] and be able to read that session data in other controller actions. For this I have two main files for consideration: UsersController and Transport.js. In UsersController I am just stubbing the session[:user_id] with the number 1 and in Transport.js I'd like to pass the cookie received from the server so that the backend can maintain a session between requests with a client.
Here is my controller:
class UsersController < ApplicationController
def create
session[:user_id] = 1
render json: user_stub, status: :ok
end
def show
puts "user id: #{session[:user_id]}"
# should return, 1, but is returning, nil...why?
render json: user_stub, status: :ok
end
private
def user_stub
{
id: 1,
email: params['email'] || 'fakeemail#gmail.com',
password: params['password'] || 'fake password'
}
end
end
Here is the main location of my app where I make my request to the server - it's in an abstraction I call Transport.js:
require('es6-promise').polyfill();
require('isomorphic-fetch');
var cookie = require('js-cookie');
const GET = 'GET';
const POST = 'POST';
function Transport() {
}
Transport.prototype.get = function(url, options = {}) {
return this.query(GET, url, null, options);
};
Transport.prototype.post = function(url, dataString, options = {}) {
return this.query(POST, url, dataString, options);
};
Transport.prototype.query = function(method, url, dataString, options = {}) {
var data;
if (dataString) {
data = JSON.parse(dataString);
}
switch(method) {
case GET:
return fetch(url, Object.assign({headers: {'Cookie': cookie.get('_skillcoop_session')}}, options, {
method: method
}));
case POST:
return fetch(url, Object.assign({
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
}, options, {
method: method
}));
default:
throw new Error("This HTTP Method is not supported.");
}
};
module.exports = Transport;
According to this SO post, one cannot access the Set-Cookie header in JS. Thus, I suppose my attempts to handle Set-Cookie in the response headers was a fools effort.
According to the NPM package that I'm using to make HTTP requests, I need to pass {credentials: 'same-origin'} key value pair in the second argument to fetch, which will 'automatically send cookies for the current domain'. That did the trick -- the session object is available and contains the user_id that was set in the session in the previous request in a different action.
Yes. I changed up how I approached this problem. I leaned very heavily on this Reddit post. In short, I use ruby-jwt on the backend and store the token in localStorage on the front end. Each request out to the server will include the token in a header AUTHORIZATION.
In following steps 1 and 2, it looks like I no longer have to 'reload the session'.