im trying to send sms message to slack, i have it where the message is posted. the problem im having is that the twilio console gives a 11200 error on every message.
/**
* Dependencies:
* Dotenv, Express, BodyParser, Slack Web Client, Slack Events API
*/
require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const createSlackEventAdapter = require('#slack/events-api').createSlackEventAdapter;
//a new export, ErrorCode, is a dictionary of known error types
const { WebClient } = require('#slack/client');
const twilio = require('twilio');
const firebase = require('firebase');
// Creates our express app
const app = express();
// The channel we'll send TalkBot messages to
const channel = 'CBY5883L3';
// The port we'll be using for our Express server
const PORT = 3000;
// Use BodyParser for app
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
/**
* Tokens:
* Slack, Firebase, Twilio
*/
//Retrieve bot token from dotenv file
const bot_token = process.env.SLACK_BOT_TOKEN || '';
// Authorization token
const auth_token = process.env.SLACK_AUTH_TOKEN || '';
// Verification token for Events Adapter
const slackEvents = createSlackEventAdapter(process.env.SLACK_VERIFICATION_TOKEN);
//Slack web client
const web = new WebClient(auth_token);
const bot = new WebClient(bot_token);
//Twilio tokens
const twilio_sid = process.env.TWILIO_SID || '';
const twilio_auth = process.env.TWILIO_AUTH_TOKEN || '';
// Initialize Twilio client using our Twilio SID and Authorization token
const twilioClient = twilio(twilio_sid, twilio_auth);
app.listen(PORT, function (err) {
if (err) {
throw err
}
console.log('Server started on port 3000')
})
// Handles incoming SMS to Twilio number
app.post('/sms', function (req, res) {
const body = req.body.Body
const num = req.body.From
// Sends message to Slack - in format from {
// `res` contains information about the posted message
console.log('Message sent: ', res.ts);
})
.catch(console.error);
}
You get this error
Error - 11200 HTTP retrieval failure
because Twilio expects a response as it makes the POST request to your /sms endpoint.
The response needs to be a valid TwiML (XML).
Change your code:
// Handles incoming SMS to Twilio number
app.post('/sms', function (req, res) {
const body = req.body.Body
const num = req.body.From
// Sends message to Slack - in format from {
// `res` contains information about the posted message
console.log('Message sent: ', res.ts);
})
.catch(console.error);
}
to this:
// Handles incoming SMS to Twilio number
app.post('/sms', function (req, res) {
const body = req.body.Body
const num = req.body.From
// Sends message to Slack - in format from {
// `res` contains information about the posted message
const twiml = new twilio.twiml.MessagingResponse();
twiml.message('Your SMS was forwarded to Slack...');
res.writeHead(200, { 'Content-Type': 'text/xml' });
res.end(twiml.toString());
});
If don't want to respond to the sender then you just comment out this line
// twiml.message('Your SMS was forwarded to Slack...');
I hope this helps.
Related
I'm trying to subscribe to my user channel on coinbase pro, in order to get message from filled orders I place. However after doing the subscription process without issues I'm not receiving any message from orders I'm creating or placing.
I did the following request to subscribe to my user channel.
const WebSocket = require("ws");
const ws = new WebSocket("wss://ws-feed.exchange.coinbase.com", {
perMessageDeflate: false,
});
ws.on("open", function open() {
const timestamp = Date.now() / 1000;
const key = "my_key";
const passphrase = "my_pass";
const secret = "my_secret";
const method = "GET";
const request_path = "/users/self/verify";
const string_to_sign = `${timestamp}${method}${request_path}`;
const b_secret = Buffer.from(secret, "base64");
const signature = crypto
.createHmac("sha256", b_secret)
.update(string_to_sign)
.digest("base64");
ws.send(
JSON.stringify({
type: "subscribe",
product_ids: ["ETH-USD"],
channels: ["user"],
signature,
key,
passphrase,
timestamp,
})
);
});
Everything is perfect until this point because I got successfully subscribed, but when I place or create a new order for ETH-USD I'm not receiving anything!
Please, can you help me?
I tried this to listen messages:
ws.on("message", function message(data) {
console.log("received: %s", data);
});
No messages received =(
Trying to listen for a websocket event on frontend using the following code
var socket = new WebSocket(`wss://${window.location.host}`);
socket.onmessage = function (event) {
this.step2Text = event.data
}
and firing from backend using
let app = express()
let server = http.createServer(app)
const WebSocket = require('ws')
let wss = new WebSocket.Server({ server });
wss.on('connection', function (ws, req) {
ws.send('some-data')
var stream = new WebSocketJSONStream(ws);
})
the registered function dosen't gets called but says
"Ignoring unrecognized message 'some-data'"
I'm new to socket.io and was trying to send a message from server to client while following the instructions of basic emit on https://socket.io/docs/v4/emitting-events/. I expected when I connected to the socket, I would have the word 'world' printed on the console but I failed without knowing why. Did I do something wrong?
Server
const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const port = process.env.PORT || 3000;
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', (socket) => {
io.emit('welcome', 'world');
});
http.listen(port, () => {
console.log(`Socket.IO server running at http://localhost:${port}/`);
});
Client
var socket = io();
socket.on('welcome', (arg) => {
console.log(arg);
}
After io.on('connection') You have to receive message from client using
socket.on('welcome',(data) {
//from there emit to client receive message
}) ;
I've successfully deployed a CRUD app on Heroku. And everything works fine on the deployed web app until I send a POST request to Heroku to post a picture to the server that then sends to S3. Everything works fine, including the picture post request, locally. However I get the following error message when I hit the deployed heroku server.
POST https://backend.herokuapp.com/ 503 (Service Unavailable)
Access to fetch at 'https://backend.herokuapp.com/' from origin 'https://frontend.netlify.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
bundle.esm.js:63 Uncaught (in promise) Error: Network error: Failed to fetch
at new t (bundle.esm.js:63)
at Object.error (bundle.esm.js:1030)
at g (Observable.js:140)
at O (Observable.js:179)
at e.value (Observable.js:240)
at bundle.esm.js:869
at Set.forEach (<anonymous>)
at Object.error (bundle.esm.js:869)
at g (Observable.js:140)
at O (Observable.js:179)
This is my code to save the POSTed picture on the server, send it to S3, and then delete the photo on the server.
import * as shortid from "shortid";
import { createWriteStream, createReadStream, unlinkSync } from "fs";
const aws = require("aws-sdk");
aws.config.update({
accessKeyId: process.env.AWS_accessKeyId,
secretAccessKey: process.env.AWS_secretAccessKey
});
const BUCKET_NAME = "dormsurf";
const s3 = new aws.S3();
const storeUpload = async (stream: any, mimetype: string): Promise<any> => {
// aseq2
const extension = mimetype.split("/")[1];
console.log("extension: ", extension);
const id = `${shortid.generate()}.${extension}`;
const path = `src/images/${id}`;
console.log("path", path);
return new Promise((resolve, reject) =>
stream
.pipe(createWriteStream(path))
.on("finish", () => resolve({ id, path }))
.on("error", reject)
);
};
export const processUpload = async (upload: any) => {
const { stream, mimetype } = await upload;
const { id } = await storeUpload(stream, mimetype);
console.log("id");
console.log(id);
var params = {
Bucket: BUCKET_NAME,
Key: `listings_images/${id}`,
Body: createReadStream(`src/images/${id}`)
};
s3.upload(params, function(err, data) {
if (err) {
console.log("error in callback");
console.log(err);
}
console.log("success");
console.log(data);
try {
unlinkSync(`src/images/${id}`);
//file removed
} catch (err) {
console.error(err);
}
});
return id;
};
Thank you so much for the help!
this error is a CORS error fix this error using proxy
call you backend api using this proxy https://cors-anywhere.herokuapp.com/
in your front call api like this
https://cors-anywhere.herokuapp.com/https://backend.herokuapp.com/
My question was voted down, so i am rewriting it hopefully this is more succinct
I am stuck at writing a javascript function to list messages in inbox.
Using - official "google-api-nodejs-client", node.js, electron, (and javascript)
Goal: list messages in gmail inbox
For that to work i need to authorize first then ask for the messages
Authorize
- I copied the code from google node.js quickstart
- this works in electron (well actually node.js as it is a command line script).
Ask for Messages
- Google has an example, i copied it adjusted some parts but doesn't work. I think the example i am working from is not designed for the node.js "google-api-nodejs-client".
- Maybe it needs a different authorize
This is the listmessages function from the google example, i can't seem to figure out how to make this work with the authorize from list labels. This is what i have tried
changing gapi to google
changing userId to 'me'
changing givig it a query
Does not use a client library.
Does not use a client library.
/**
* Retrieve Messages in user's mailbox matching query.
*
* #param {String} userId User's email address. The special value 'me'
* can be used to indicate the authenticated user.
* #param {String} query String used to filter the Messages listed.
* #param {Function} callback Function to call when the request is complete.
*/
function listMessages(userId, query, callback) {
var getPageOfMessages = function(request, result) {
request.execute(function(resp) {
result = result.concat(resp.messages);
var nextPageToken = resp.nextPageToken;
if (nextPageToken) {
request = gapi.client.gmail.users.messages.list({
'userId': userId,
'pageToken': nextPageToken,
'q': query
});
getPageOfMessages(request, result);
} else {
callback(result);
}
});
};
var initialRequest = gapi.client.gmail.users.messages.list({
'userId': userId,
'q': query
});
getPageOfMessages(initialRequest, []);
}
This is the aurhorize function that works to list labels.
var fs = require('fs');
var readline = require('readline');
var google = require('googleapis');
var googleAuth = require('google-auth-library');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/gmail-nodejs-quickstart.json
var SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'];
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'gmail-nodejs-quickstart.json';
// Load client secrets from a local file.
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
if (err) {
console.log('Error loading client secret file: ' + err);
return;
}
// Authorize a client with the loaded credentials, then call the
// Gmail API.
authorize(JSON.parse(content), listLabels);
});
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
*
* #param {Object} credentials The authorization client credentials.
* #param {function} callback The callback to call with the authorized client.
*/
function authorize(credentials, callback) {
var clientSecret = credentials.installed.client_secret;
var clientId = credentials.installed.client_id;
var redirectUrl = credentials.installed.redirect_uris[0];
var auth = new googleAuth();
var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, function(err, token) {
if (err) {
getNewToken(oauth2Client, callback);
} else {
oauth2Client.credentials = JSON.parse(token);
callback(oauth2Client);
}
});
}
/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
*
* #param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
* #param {getEventsCallback} callback The callback to call with the authorized
* client.
*/
function getNewToken(oauth2Client, callback) {
var authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES
});
console.log('Authorize this app by visiting this url: ', authUrl);
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter the code from that page here: ', function(code) {
rl.close();
oauth2Client.getToken(code, function(err, token) {
if (err) {
console.log('Error while trying to retrieve access token', err);
return;
}
oauth2Client.credentials = token;
storeToken(token);
callback(oauth2Client);
});
});
}
/**
* Store token to disk be used in later program executions.
*
* #param {Object} token The token to store to disk.
*/
function storeToken(token) {
try {
fs.mkdirSync(TOKEN_DIR);
} catch (err) {
if (err.code != 'EEXIST') {
throw err;
}
}
fs.writeFile(TOKEN_PATH, JSON.stringify(token));
console.log('Token stored to ' + TOKEN_PATH);
}
/**
* Lists the labels in the user's account.
*
* #param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
function listLabels(auth) {
var gmail = google.gmail('v1');
gmail.users.labels.list({
auth: auth,
userId: 'me',
}, function(err, response) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
var labels = response.labels;
if (labels.length == 0) {
console.log('No labels found.');
} else {
console.log('Labels:');
for (var i = 0; i < labels.length; i++) {
var label = labels[i];
console.log('- %s', label.name);
}
}
});
}
The flow of your program should look like this:
Then you can use the api to list messages. (just to get you started):
export function listMessages(oauth2Client, userId, query, callback) {
const gmail = google.gmail('v1');
gmail.users.messages.list({
auth: oauth2Client,
userId: 'me',
}, (err, response) => {
console.log(response);
});
}
Notice the oauth2Client parameter. This is the object you get from your function authorize. Let me know if you have any questions.