I am trying to send a standard/urgent message to my Viewsonic TV using its Open API
everything is working fine but when I try sending a message that is longer than 16 characters, I am getting an error message that says {message: 'Invalid Request Body'}.
I am realy confused as to why this is happening, it clearly says on the documentation that 300 characters is maximum for standard message.
Here is the sample snippet that I have
//this one can be converted using JSON.stringify()
const inputBody = '{
"deviceIds": [
"8jy9sne7-esbu-qrf7-d62f-c46srimnjcnn"
],
"entityId": "o39onp8a-um26-dgxf-v3iy-4xqqr2aqzw2h",
"message": "Hello world This is a really long message",
"type": "standard",
"siren": false,
"loops": 2
}';
const headers = {
'Content-Type':'application/json',
'Accept':'application/json',
'Authorization':'bearer ************'
};
fetch('https://oapi.myviewboard.com/devices/broadcast',
{
method: 'POST',
body: inputBody,
headers: headers
})
.then(function(res) {
return res.json();
}).then(function(body) {
console.log(body);
});
Also, I noticed on the sample code from the documentation, what does this symbol mean u)s]? Maybe it has something to do with this issue.
const inputBody = '{
"deviceIds": [
"8jy9sne7-esbu-qrf7-d62f-c46srimnjcnn",
"jb9a2hpd-h2qc-hp9m-4i36-2m5wzqmn7o9w"
],
"entityId": "o39onp8a-um26-dgxf-v3iy-4xqqr2aqzw2h",
"message": "u)s]",
"type": "standard",
"siren": true,
"loops": 84479723
}';
Related
I've had this script working for over 3 months with no issues, however, last week it started throwing out this:
Error
Exception: Request failed for https://hooks.slack.com returned code 400. Truncated server response: invalid_blocks (use muteHttpExceptions option to examine full response)
Here's the relevant part of the script i think.
for (let i = 0; i in vistasVencimiento; i++){
if (vistasVencimiento[i][0] instanceof Date == true){
let differenceInMs = dateToday - vistasVencimiento[i][0];
let differenceInDaysRaw = differenceInMs / (1000 * 60 * 60 * 24);
if(differenceInDaysRaw >= 0 && statusColumn[i] !== "Pendiente_de_despacho"){
//agregar a array de vencidos
result.push(sumariantesVistas[i], causasCaratulas[i], '\n');
}
}
};
console.log(result);
if (result === undefined || result.length === 0 ){
let payload ={
"blocks": [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": ":bell: *Cuales Vistas estan vencidas?* :bell:"
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text":"Aparentemente, ninguna"
}
},
]
}
let headers = {
'Content-type': 'application/json'
};
let options = {
headers : headers,
method: 'POST',
payload: JSON.stringify(payload)
};
UrlFetchApp.fetch(url, options);
}else{
let result_string = result.join('\n');
let payload ={
"blocks": [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": ":bell: *Cuales Vistas estan vencidas?* :bell:"
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text":"Estas: "
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": result_string
}
},
]
}
let headers = {
'Content-type': 'application/json'
};
let options = {
muteHttpExceptions: false,
headers : headers,
method: 'POST',
payload: JSON.stringify(payload)
};
UrlFetchApp.fetch(url, options);
};
Now, I know its related to "text": result_string because ive tried replacing that with something like "text": "test" and it works, but the whole point of the notifications is to send that formatted string to a slack workplace channel, and thats where ive basically no clue on why it would start failing out of a sudden like that
edit:
Theres something genuinely very weird going on here, first of all going causasCaratulas[i].replace(/"/g, "'") doesnt fix anything, second, causasCaratulas has two columns inside, if i load only one column (doesnt matter which) the script works, ive even tried splitting the array into two sorta-lists, in that case, it still throws out the error.
So the error happens somewhere between trying to send out those two columns to the slack api at the same time? im clueless as to whats happening here
edit 2:
the data is structured something like this. the problem seems to be that whenever i try sending both Case Number and Case Name at the same time i get an error, however, this seems to be dependant on some kind of mystery symbol idk how to identify, if it even is a symbol.
Perhaps your text data contains &<>? Try this:
let result_string = result
.join('\n')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>');
See Escaping text at Slack API reference.
You should also search your data for markdown symbols that could throw a spanner in the works.
I have set up what I think should be a working JSON output to send a message in slack but Slack keeps rejecting it.
I have tried multiple different message layout formats using the guides on slack's api site, but so far the only method that has successfully sent is a fully flat JSON with no block formatting.
function submitValuesToSlack(e) {
var name = e.values[1];
var caseNumber = e.values[2];
var problemDescription = e.values[3];
var question = e.values[4];
var completedChecklist = e.values[5];
var payload = [{
"channel": postChannel,
"username": postUser,
"icon_emoji": postIcon,
"link_names": 1,
"blocks": [
{
"type": "section",
"fields": [
{
"type": "mrkdwn",
"text": "*Name:*\n " + name
}
]
}]
}];
console.log(JSON.stringify(payload, null, "\t"));
var options = {
'method': 'post',
'payload': JSON.stringify(payload)
};
console.log(options)
var response = UrlFetchApp.fetch(slackIncomingWebhookUrl, options);
}
When I run this, I get the following output:
[
{
"channel":"#tech-support",
"username":"Form Response",
"icon_emoji":":mailbox_with_mail:",
"link_names":1,
"blocks":[
{
"type":"section",
"fields":[
{
"type":"mrkdwn",
"text":"*Name:*\n test"
}
]
}
]
}
]
Which I believe is correct, however slack api just rejects it with an HTTP 400 error "no text"
am I misunderstanding something about block formatting?
EDIT:
To Clarify, formatting works if I use this for my JSON instead of the more complex format:
{
"channel":"#tech-support",
"username":"Form Response",
"icon_emoji":":mailbox_with_mail:",
"link_names":1,
"text":"*Name:*\n test"
}
The reason you are getting the error no_text is because you do not have a valid message text property in your payload. You either need to have a text property as top line parameter (classic style - your example at the bottom) or a text block within a section block.
If you want to put to use blocks only (as you are asking) the section block is called text, not fields. fields is another type of section bock that has a different meaning.
So the correct syntax is:
[
{
"channel":"#tech-support",
"username":"Form Response",
"icon_emoji":":mailbox_with_mail:",
"link_names":1,
"blocks":[
{
"type":"section",
"text":[
{
"type":"mrkdwn",
"text":"*Name:*\n test"
}
]
}
]
}
]
Also see here for the official documentation on it.
Blocks are very powerful, but can be complicated at times. I would recommend to use the message builder to try out your messages and check out the examples in the docu.
I have this codes to get access token:
Future<Null> getData() async {
var url = "http://192.168.1.23:7070/api/v2/token";
http.post(url, body:{
"grant_type": "string",
"branchcode": "string",
"password": "string",
"username": "string",
"dbname": "string",
"dbuser": "string",
"dbpassword": "string",
"dbtype": "string"
}).then((response){
print("Response Status: ${response.statusCode}");
print("Response Body: ${response.body}");
});
}
And after run this code block it returns something like this:
Response Body: {"access_token":"AQAAANCMnd8BFdERjHoAwE_Cl-sBAAAAgUTYyajkrEKWAWNrBvgpHQAAAAACAAAAAAAQZgAAAAEAACAAAAB-c92RaHBUfb0aNvnWFqx3JW29bBeQPIouZVDHsTsg8QAAAAAOgAAAAAIAACAAAAC7JdwAlRh8ckP3gAG4vc6H-nULfmjfpBF-gleCcFXeFzABAACJft4ZnsMt1clpRHUTAbiWQIqo5Zmt7_Qc7-pDPwA33O7z3VgFhkx2ITLn5xWGKcVHTkxOxPeRe4qrgEDbsd8V6DHcuwirPkAZye5zECUllxE6IDkNetLkTQsLuK2CpSWxAksFzUS6vhiU7fqkNKsXegtOV--0wFzWsq-ikTjYWnr4LsdAiSUfy_HsTMvLxoIjIqDSxw0QyMM1I2eVIE2wSsZSpoYn3CQIGejQAlG_mUIgzt3PBqEZ6kqIX-Qhx4jpcypUOG5GFNMKLUJa5mti1UiTi8ETpVN_8y_tDhVi-9AS2MJpJN7-Gao_fIB5s0yaH_m9fHkwFgXF1N-Y5GevDypdNryQWbHXQkf88DKZnljMSGzJkJhpzls3PTN8iwss32CXbeO1zaWm-iJAgMK_QAAAACVQGecH57e1QB-FRu2iCt-d6x37x6MJ-_H_H8uYOKbZYBX0lA1b8WxteCLWPM5mAJR1p3tHE_VBqQqvS4pKGHM","token_type":"bearer","expires_in":1199,"refresh_token":"f8de12c7a90b401b9400b93b4cf2c128"
My question is, how to retrieve the value of "access_token" in this code blocks?
You can access the response in the following ways
1.If it's from response headers you can access it by using
response.headers['access-token']
2.If it's from response body you can access it by using
print('access token is -> ${json.decode(response.body)['access_token']}');
3.If you are getting the object you can parse it and cast to required type by using this
final Map<String, dynamic> data = json.decode(response.body)['user'].cast<String, dynamic>();
According to the react-native-fcm package you can include a custom nested object within the data object for a FCM messaging payload.
according to this post by the package author
Like this:
var payload = {
data: {
custom_notification: {
title: 'title',
body: 'body',
priority: 'high',
id: 'id',
group: 'group'
}
}
};
This is for the purpose of receiving heads up notifications in all app states, which will not happen if you do just a notification payload or data payload.
When I implement this in my cloud function I get the following error:
Error: Messaging payload contains an invalid value for the "data.custom_notification" property. Values must be strings.
So I'm at a loss as to how others can be using this successfully?
I wonder if there's some issue going on with my environment or something as the following test payload which was given to me by firebase support (and is in the docs) errors out:
var payload = {
"to":"FCM_TOKEN",
"data": {
"type":"MEASURE_CHANGE",
"body": "test body",
"title": "test title",
"color":"#00ACD4",
"priority":"high",
"id": "id",
"show_in_foreground": true
}
};
I get the following error:
Error sending message stringify: {"code":"messaging/invalid-payload","message":"Messaging payload contains an invalid \"to\" property. Valid properties are \"data\" and \"notification\"."}
Been at this for days so hopefully I can get a bit of help on this.
Thanks in advance!
So I realised just now (after days of searching) that the package react-native-fcm is using a different send method than admin.messaging().sendToDevice(token, payload, options). I had been using that for a while now and didn't realize that it was not actually what was intended to be used with this library or atleast in this scenario. Mainly because everything was working fairly well using admin.messaging() up until I wanted heads up notifications in all app states.
The other method is like this
sendData(token) {
let body = {
"to": token,
"data":{
"title": "Simple FCM Client",
"body": "This is a notification with only DATA.",
"sound": "default",
"click_action": "fcm.ACTION.HELLO",
"remote": true
},
"priority": "normal"
}
this._send(JSON.stringify(body), "data");
}
_send(body, type) {
let headers = new Headers({
"Content-Type": "application/json",
"Content-Length": parseInt(body.length),
"Authorization": "key=" + FirebaseConstants.KEY
});
fetch(API_URL, { method: "POST", headers, body })
.then(response => console.log("Send " + type + " response", response))
.catch(error => console.log("Error sending " + type, error));
}
You can use nested objects within the data object using this method. The documentation is not super clear on this unfortunately, I didn't even realise there was an example until now. Of course this could have just been me.
When using the data message payload, it is stated to use key value pairs that are String, so what you could do is have the value of your custom_notification as JSON String by enclosing them in " ".
For the sample payload provided, are you actually using the FCM_TOKEN in the to parameter? You're supposed to replace it with an actual token.
I'm attempting to do the following with the Content Management API for Contentful:
Get an entry (entry1)
Find another entry (entry2) using data from a field in entry1
Update entry1 with data from entry2
My code looks like this:
client.getSpace("xxxxxxxx").then(function(space){
space.getEntries({
"content_type": "xxxxxxxx",
"sys.id": "2KEZYJOgDSeQMCQIE0Oo88",
"limit": 1
}).then(function(places){
//search for relevant category entry
space.getEntries({
"content_type": contentType.category,
"sys.id": places[0].fields.category["en-GB"],
"limit": 1
}).then(function(category){
//update place object
places[0].fields.categoryNew = {
"en-GB": [
{ sys: { type: "Link", linkType: "Entry", id: category[0].sys.id } }
]
};
//update place
request({
method: 'PUT',
url: 'https://api.contentful.com/spaces/xxxxxxxx/entries/' + places[0].sys.id,
headers: {
'Authorization': 'Bearer xxxxxxxx',
'Content-Type': 'application/vnd.contentful.management.v1+json',
'X-Contentful-Content-Type': 'xxxxxxxx'
},
body: JSON.stringify({fields:places[0].fields})
}, function (error, response, body) {
console.log(body);
});
});
});
});
Steps 1 and 2 work fine but the final step, updating the original entry, keeps returning the following error:
Response: {
"sys": {
"type": "Error",
"id": "VersionMismatch"
},
"requestId": "content-api:2PSSF6RtpSs2YyaaisK2wc"
}
How do I stop this happening? I've tried everything I can think of including manually updating the sys.version number, but when updating it seems to ignore any sys data I provide.
Refer to https://www.contentful.com/developers/docs/references/content-management-api/#/introduction/updating-and-version-locking
You need to pass the version as a header parameter called "X-Contentful-Version" with the PUT request.