Open modal using Slack command - node.js

I have a Slack command which displays a button. When I click on this button I need to display a modal. For this, after clicking it I do this:
const dialog = {
callback_id: "submit-ticket",
elements: [
{
hint: "30 second summary of the problem",
label: "Title",
name: "title",
type: "text",
value: "teste"
},
{
label: "Description",
name: "description",
optional: true,
type: "textarea"
},
{
label: "Urgency",
name: "urgency",
options: [
{ label: "Low", value: "Low" },
{ label: "Medium", value: "Medium" },
{ label: "High", value: "High" }
],
type: "select"
}
],
submit_label: "Submit",
title: "Submit a helpdesk ticket"
};
const modalInfo = {
dialog: JSON.stringify(dialog),
token, // this is correct
trigger_id: actionJSONPayload.trigger_id
};
// This is what I get confused with...
// Method 1
slack.dialog.open(modalInfo).catch(err => {
console.log("ERROR: ", err);
});
// end method 1
// Method 2
sendMessageToSlackResponseURL(actionJSONPayload.response_url, modalInfo);
...
function sendMessageToSlackResponseURL(responseURL: any, JSONmessage: any) {
const postOptions = {
headers: {
"Content-type": "application/json"
},
json: JSONmessage,
method: "POST",
uri: responseURL
};
request(postOptions, (error: any, response: any, body: any) => {
if (error) {
console.log("----Error: ", error);
}
});
}
// end method 2
I get always Error: invalid_trigger using method1 when this trigger is something that my button is generating automatically.
Method 2 doesn't throw any error but doesn't open any modal/dialog either.
The official documentation is not quite clear and I don't know if I need to call dialog.open or views.open. Either way, the last one is not available from Slack package
This is also the button I'm displaying before anything:
const message = {
attachments: [
{
actions: [
{
name: "send_sms",
style: "danger",
text: "Yes",
type: "button",
value: "yes"
},
{
name: "no",
text: "No",
type: "button",
value: "no"
}
],
attachment_type: "default",
callback_id: "alert",
color: "#3AA3E3",
fallback: "We could not load the options. Try later",
text: "Do you want to alert by SMS about P1 error/fix?"
}
],
text: "P1 SMSs"
};

Copy a modal from here
const headers = {
headers: {
"Content-type": "application/json; charset=utf-8",
"Authorization": "Bearer " + token
}
};
const modalInfo = {
"token": token,
"trigger_id": reqBody.trigger_id,
"view": slack.modal
};
axios
.post("https://slack.com/api/views.open", modalInfo, headers)
.then(response => {
const data = response.data;
if (!data.ok) {
return data.error;
}
})
.catch(error => {
console.log("-Error: ", error);
});
But most importantly, when we do some changes to our app we need to reinstall it and also when we do it, the token changes and this is something I couldn't find on the documentation

Related

Node.js FCM token is empty but it's not

async function sendNotif(title, body0, token) {
return await admin.messaging().send({
message: {
token:
"dHUKMkIxRbS3uIpdnA1Qef:APA91bHQd2XUpFyWzfdbKrpPV2T9b0uJx9TfKZcyF-O_oAbQ13yA5R-52t_RTb_QSPrMpxw1OV9z8sNFRth5wGuCAld_9VsKr4oRdSWsMzqhrbKcTLC2rAp5QLOUALqiTadyvyvcjTmb!",
notification: {
title: title,
body: body0,
},
data: {
hello: "world",
click_action: "FLUTTER_NOTIFICATION_CLICK",
},
// Set Android priority to "high"
android: {
priority: "high",
},
// Add APNS (Apple) config
apns: {
payload: {
aps: {
contentAvailable: true,
},
},
headers: {
"apns-push-type": "background",
"apns-priority": "5", // Must be `5` when `contentAvailable` is set to true.
"apns-topic": "io.flutter.plugins.firebase.messaging", // bundle identifier
},
},
},
});
}
I am wondering why I am getting this error
errorInfo: {
code: 'messaging/invalid-payload',
message: 'Exactly one of topic, token or condition is required'
},
I checked the token and it's a good one i add firebase-admin library and I initialized it but it still didn't work .
so any answers?

MERN :: Mongoose Validation Errors :: How to Display Errors in React

I have set up Mongoose custom validation with errors and would like to display these error messages in React. I am unfortunately unable to retrieve the error messages. I have tried looking for solutions, but am unfortunately still having trouble.
My code is as follows:
Server-side:
- dataModel.js
const mongoose = require("mongoose");
const uniqueValidator = require("mongoose-unique-validator");
const moment = require("moment");
const dataSchema = mongoose.Schema(
{
name: {
type: String,
required: [true, "Name is required."],
validate: {
validator: function (name) {
return /^[a-zA-Z]+$/.test(name);
},
message: "Only alphabetic characters allowed.",
},
},
surname: {
type: String,
required: [true, "Surname is required."],
validate: {
validator: function (surname) {
return /^[a-zA-Z]+$/.test(surname);
},
message: "Only alphabetic characters allowed.",
},
},
idNumber: {
type: String,
required: [true, "ID Number is required."],
unique: true,
validate: [
{
validator: function (idNumber) {
return idNumber.toString().length === 13;
},
message: (idNumber) =>
`ID Number Must Have 13 Numbers. You entered ${
idNumber.value
}, which is ${idNumber.value.toString().length} numbers long.`,
},
{
validator: function (idNumber) {
return !isNaN(parseFloat(idNumber)) && isFinite(idNumber);
},
message: (idNumber) =>
`ID Number Can Only Contain Number Values. You entered ${idNumber.value}.`,
},
],
},
dateOfBirth: {
type: String,
required: [true, "Date of Birth is required."],
validate: {
validator: function (dateOfBirth) {
return moment(dateOfBirth, "DD/MM/YYYY", true).isValid();
},
message: "Invalid Date of Birth Format. Expected DD/MM/YYYY.",
},
},
},
{
timestamps: true,
}
);
dataSchema.plugin(uniqueValidator, { message: "ID Number Already Exists." });
module.exports = mongoose.model("Data", dataSchema);
- dataController.js
exports.addController = async (req, res) => {
const { firstName, surname, idNumber, dateOfBirth } = req.body;
const newData = new Data({
name: firstName,
surname,
idNumber,
dateOfBirth,
});
try {
await newData.save();
res.send({ message: "Data Added Successfully" });
} catch (error) {
if (error.name === "ValidationError") {
let errors = {};
Object.keys(error.errors).forEach((key) => {
errors[key] = error.errors[key].message;
});
console.log(errors)
return res.status(400).send(errors);
}
res.status(500).send("Something went wrong");
}
};
Output - console.log:
Client-side:
- dataForm.js
const addData = async () => {
try {
axios({
url: "/data/add",
method: "post",
data: {
firstName,
surname,
idNumber,
dateOfBirth,
},
headers: {
"Content-type": "application/json",
},
}).then(function (response) {
alert(response.data.message);
console.log(response.data.message);
});
} catch (error) {
console.log(error);
}
};
Output - Console:
Output - Postman (Initial):
{
"message": [
"Only alphabetic characters allowed.",
"ID Number Can Only Contain Number Values. You entered 888888888888a."
],
"error": {
"errors": {
"surname": {
"name": "ValidatorError",
"message": "Only alphabetic characters allowed.",
"properties": {
"message": "Only alphabetic characters allowed.",
"type": "user defined",
"path": "surname",
"value": "Bösiger"
},
"kind": "user defined",
"path": "surname",
"value": "Bösiger"
},
"idNumber": {
"name": "ValidatorError",
"message": "ID Number Can Only Contain Number Values. You entered 888888888888a.",
"properties": {
"message": "ID Number Can Only Contain Number Values. You entered 888888888888a.",
"type": "user defined",
"path": "idNumber",
"value": "888888888888a"
},
"kind": "user defined",
"path": "idNumber",
"value": "888888888888a"
}
},
"_message": "Data validation failed",
"name": "ValidationError",
"message": "Data validation failed: surname: Only alphabetic characters allowed., idNumber: ID Number Can Only Contain Number Values. You entered 888888888888a."
}
}
Output - Postman (Current):
I would appreciate any help that anyone is willing to offer.
I have managed to sort the problem out and return and display the Mongoose validation errors on the React frontend.
I amended the React post method as follows:
const addData = async () => {
try {
let response = await axios({
url: "http://localhost:8080/data/add",
method: "post",
data: {
firstName,
surname,
idNumber,
dateOfBirth,
},
headers: {
"Content-type": "application/json",
},
})
.then((response) => {
alert(response.data.message);
})
.then(() => {
window.location.reload();
});
alert(response.data.message);
} catch (error) {
alert(Object.values(error.response.data) + ".");
}
};
I had to format the method as the error code was not being reached and had to return and display the data using Object.values() as the responses were objects.
Thank you #cmgchess for pointing me in the right direction.

Must provide source or customer stripe live mode

this is my first time using stripe and I am getting an error Must provide source or customer. once I went live. In the test mode I used "tok_mastercard" as my source but clearly when I went live it isn't valid. What am I missing here please help.
This is my POST request in the backend
stripe.charges
.create({
amount: req.renter.rent * 100,
currency: "usd",
source: req.body.token,
application_fee_amount: req.renter.rent * 0.05 * 100,
transfer_data: {
//the destination needs to not be hard coded it needs to
//come from what property the renter is in
destination: req.renter.stripeConnectId,
// destination: "acct_1GOCMqDfw1BzXvj0",
},
})
.then((charge) => {
console.log(req.renter);
res.send(charge);
})
.catch((err) => {
console.log(err);
});
});
this is my two functions in the frontend using react-native and node
handleCardPayPress = async () => {
try {
this.setState({ loading: true, token: null });
const token = await stripe.paymentRequestWithCardForm({
// Only iOS support this options
smsAutofillDisabled: true,
requiredBillingAddressFields: "full",
prefilledInformation: {
billingAddress: {
name: "",
line1: "",
line2: "",
city: "",
state: "",
country: "US",
postalCode: "",
email: "",
},
},
});
this.setState({ loading: false, token });
} catch (error) {
this.setState({ loading: false });
}
};
makePayment = async () => {
try {
//Mate the payment
const response = await unitApi.post("/payments", {
data: {
amount: this.state.renter.rent,
currency: "usd",
token: this.state.token,
},
});
Alert.alert("Success!", `Confirmation ID: ${response.data.id}`, [
{ text: "Done" },
]);
console.log(response.data);
// navigate("Home");
} catch (err) {
//failiur and showing the error message
console.log(err);
Alert.alert("Failed!", "Card declined.", [{ text: "Declined" }]);
}
};
Odds are pretty good that this.state.token doesn't contain what you think it does in the unitApi.post() function call; I'd recommend logging that and seeing if that helps, and also logging req.body.token server-side.

How to insert multiple JSON document in elastic search

Input Data
[{
"_index": "abc",
"_type": "_doc",
"_id": "QAE",
"_score": 6.514091,
"_source": {
"category": "fruits",
"action": "eating",
"metainfo": {
"hash": "nzUZ1ONm0e167p"
},
"createddate": "2019-10-03T12:37:45.297Z"
}},
{
"_index": "abc",
"_type": "_doc",
"_id": "PQR",
"_score": 6.514091,
"_source": {
"category": "Vegetables",
"action": "eating",
"metainfo": {
"hash": "nzUZ1ONm0e167p"
},
"createddate": "2019-10-03T12:37:45.297Z"
}
}-----------------
----------------]
I have around 30,000 records as input data. How to insert this data in a single query. I tried by
var elasticsearch = require('elasticsearch');
var client = new elasticsearch.Client({
host: '********',
log: 'trace'
});
client.index({
index: "abc",
body: ****input data*****
}).then((res) => {
console.log(res);
}, (err) => {
console.log("err", err);
});
In this code, send input data in the body. but it returns an error. Please suggest to me.
This seems like what are you looking for:
'use strict'
require('array.prototype.flatmap').shim()
const { Client } = require('#elastic/elasticsearch')
const client = new Client({
node: 'http://localhost:9200'
})
async function run () {
await client.indices.create({
index: 'tweets',
body: {
mappings: {
properties: {
id: { type: 'integer' },
text: { type: 'text' },
user: { type: 'keyword' },
time: { type: 'date' }
}
}
}
}, { ignore: [400] })
const dataset = [{
id: 1,
text: 'If I fall, don\'t bring me back.',
user: 'jon',
date: new Date()
}, {
id: 2,
text: 'Winter is coming',
user: 'ned',
date: new Date()
}, {
id: 3,
text: 'A Lannister always pays his debts.',
user: 'tyrion',
date: new Date()
}, {
id: 4,
text: 'I am the blood of the dragon.',
user: 'daenerys',
date: new Date()
}, {
id: 5, // change this value to a string to see the bulk response with errors
text: 'A girl is Arya Stark of Winterfell. And I\'m going home.',
user: 'arya',
date: new Date()
}]
// The major part is below:
const body = dataset.flatMap(doc => [{ index: { _index: 'tweets' } }, doc])
const { body: bulkResponse } = await client.bulk({ refresh: true, body })
//
if (bulkResponse.errors) {
const erroredDocuments = []
// The items array has the same order of the dataset we just indexed.
// The presence of the `error` key indicates that the operation
// that we did for the document has failed.
bulkResponse.items.forEach((action, i) => {
const operation = Object.keys(action)[0]
if (action[operation].error) {
erroredDocuments.push({
// If the status is 429 it means that you can retry the document,
// otherwise it's very likely a mapping error, and you should
// fix the document before to try it again.
status: action[operation].status,
error: action[operation].error,
operation: body[i * 2],
document: body[i * 2 + 1]
})
}
})
console.log(erroredDocuments)
}
const { body: count } = await client.count({ index: 'tweets' })
console.log(count)
}
run().catch(console.log)
Reference link: https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/bulk_examples.html

Ionic 3 http post - reading body data in nodejs

I am trying to send a http post body data. It worked well with angular but now I am using ionic. Any help is appreciated.
let newMember = {
"sendData": [{
name: "first_name",
val: "mike"
},
{
name: "last_name",
val: "tester"
},
{
name: "city",
val: "new york"
},
{
name: "state",
val: "NY"
},
{
name: "zip",
val: "10001"
}]
}
let body = new FormData();
body.append('newMember', JSON.stringify(newMember));
this.http.post('https://data.testme.com/setup',newMember,{headers: headers
}, body)
.map(res => res.json())
.subscribe(data => {
console.log(data);
});
}
This is how I am trying to send it to a nodejs server.
My nodejs sever it getting this in the body.
console.log("sendData req.body --> " , req.body);
{sendData: [{
name: 'first_name',
val: 'mike'
},
{
name: 'last_name',
val: 'tester'
},
{
name: 'city',
val: 'new york'
},
{
name: 'state',
val: 'NY'
},
{
name: 'zip',
val: '10001'
}]
}
I found this in my out log. I was looking at my error logs before. Showing error because it could read:
var newMember = req.body.newMember;
How do I read newMember in Node.js ??
Thanks
Phil
You've mismatch parameters. see documentation
try this
this.http.post('https://data.testme.com/setup', body, {
headers: headers
})
and add plugin
Allow-Control-Allow-Origin: *
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi
this.http.post(https://data.testme.com/setup/', newMember).map(res => res.json()).subscribe(data => {
console.log('error'+data);
},err => {
console.log('error'+err);
});

Resources