How to post mentions to slack incoming webhooks - javascript

The mentions I send to the incoming webhook renders as plain text.
Note: Sending post request using the request package.
Tried the following:
sending mentions as <#userid>
Result: <#userid> // as plain text
request.post(
`${channels[message.channel.name]}`,
{
json: {
text:
'To: ' + mapDiscordToSlackNames(message.mentions.users) + '\n' +
'Discord channel: #' + message.channel.name + '\n' +
'Link: <' + message.url + '|Link to post>' + '\n' +
Result: To: #soda // as plain text not as mention to #soda user
Entire Code
// require the discord.js module
const Discord = require('discord.js');
const devs = require('./devs.json');
const channels = require('./channels.json');
const dotenv = require('dotenv');
const path = require('path');
var request = require('request');
dotenv.load({
path: path.join(__dirname, `.env`),
silent: true
});
// create a new Discord client
const client = new Discord.Client();
// Map discord usernames of devs to slack usernames
function mapDiscordToSlackNames(discordUsers) {
return discordUsers.map( user => {
return '#' + devs[user.username];
})
}
// when the client is ready, run this code
// this event will only trigger one time after logging in
client.once('ready', () => {
console.log('Discord Connected!');
});
// on message on discord
client.on('message', message => {
console.log(channels[message.channel.name]);
request.post(
`${channels[message.channel.name]}`,
{
json: {
text:
'To: ' + mapDiscordToSlackNames(message.mentions.users) + '\n' +
'Discord channel: #' + message.channel.name + '\n' +
'Link: <' + message.url + '|Link to post>' + '\n' +
'Original Message: \n' +
'\t"' + message.author.username + ': ' + message.cleanContent + '"\n' +
`Attachements: ${message.attachments.map(attachment => attachment.url)}`
},
},
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
}
);
});
// login to Discord with app's token
client.login(process.env.DISCORD_TOKEN);
devs is a json object which has returns slack usernames corresponding to discord usernames.

Turns out I was sending userid by escaping '<' & '>' in string like
'&lt#userid&gt' and so it was passing as plain text.
To mention someone in slack do 'To: <#' + userid + '>'
The userid starts with U and can be found after the team/ in url of
your workspace eg: Cxxxxx/team/Uxxxxx/

Related

Unable to send any HTML elements other than <h1> as a function response to HTTPS request using node.js (Express)

If I change "< h1 >" to any other HTML tag such as "< h2 > or < p >" it fails to render them. I have no idea what's wrong.
const express = require("express");
const https = require("https");
const app = express();
// home page
app.get("/", function (req, res) {
res.sendFile(__dirname + "/index.html");
});
app.post("/", function (req, res) {
const queryCity = "London";
// const queryCity = String(req.body.cityName);
const apiKey = "lorem";
const url =
"https://api.openweathermap.org/data/2.5/weather?q=" +
queryCity +
"&appid=" +
apiKey +
"&units=metric";
https.get(url, function (response) {
response.on("data", function (data) {
const weatherData = JSON.parse(data);
const temp = weatherData.main.temp;
const feel = weatherData.main.feels_like;
const weatherIcon = weatherData.weather[0].icon;
const iconUrl =
"https://openweathermap.org/img/wn/" + weatherIcon + "#2x.png";
res.write(
"<h1>Temperature in " + queryCity + " is " + temp + "deg Celsius.</h1>"
);
res.write("It feels like " + feel + "deg Celsius.");
res.write("<img src=" + iconUrl + ">");
res.send(); // there can only be one res.send()
});
});
});
// server port
app.listen(3000, function () {
console.log("Server live on port 3000");
});
this is what happens when I change h1 to h2 or p. Img tag fails too. What am I doing wrong here?
This code never fail:
var express = require('express');
var app = express();
app.get('/', function(req, res) {
res.type('text/html');
res.send('<h1>I am html</h1>');
});
app.listen(process.env.PORT || 8080);
Try to test your html generation with this basic code to be sure that error is not a nodejs issue.
Another tips:
replace res.write to res.send like my example
don't call res.write several times, just one time sending a string previously created with your html lines
add content type text/html to your response
Had this error as well earlier. Was able to fix it by adding an html tag on the first res.write.
Using your code, it would be like this;
res.write(
"<html><h1>Temperature in " + queryCity + " is " + temp + "deg Celsius.</h1></html>"
);

Can't send sms with Twilio, Node.js and Sequelize

I have a program which respond automatically a sms when receive an income message.
It works when I don't use Sequelize to save data to the database. But when I add the code below, the twiml.message(msg) is never executed.
The problem is when call twiml.message(msg) inside the then it doesn't work. So how to resolve this problem? Thanks
Info.create(param)
.then(info => {
var msg = 'Numero: ' + info.id +
' Nom:' + info.nom +
' Date: ' + info.datesms);
var twiml = new MessagingResponse();
twiml.message(msg);
});

Javascript - accessing password in ssh2 connection

I have a class which is being used to connect to a device. I have made in instance of the class in my application
app.js
myConn = new myConnection();
myConnection.js
function myConnection(){
this.settings = {
host: '192.168.225.195',
port: 22,
username: 'sysadmin',
password: 'pass'
};
}
I have a function within said class that executes a command on the remote device but that requires a password. When this happens stderr.on is executued and I send the password and a newline char.
myConnection.prototype.installPatch = function(callback){
this.conn.exec('sudo -S bash /tmp/update.sh', function(err, stream){
var standardMsgs = '';
var errorMsgs = '';
if(err) throw err;
stream.on('close', function(code, signal) {
callback(standardMsgs, errorMsgs);
}).on('data', function(data) {
standardMsgs += "<br>" + data;
console.log('STDOUT: ' + data);
}).stderr.on('data', function(data) {
errorMsgs += data;
console.log('STDERR: ' + data);
stream.write(myConn.conn.config.password + '\n');
});
});
}
While this works I am not a fan of accessing the password with
stream.write(myConn.conn.config.password + '\n');
since a change to the name "myConn" in app.js would required the same change in the "installPatch" function.
I had intended to use
stream.write(this.settings.password + '\n');
Do I have any other options that will allow me to retrieve the password from within the myConnection class? I hope I am just overlooking the obvious.
Ok, so I believe it was starring me in the face.
Change
stream.write(myConn.conn.config.password + '\n');
to
stream.write(stream._client.config.password + '\n');

can we modify fs.readFileSync(__dirname + '/index.html');?

Can we modify fs.readFileSync(__dirname + '/game.php'); to fs.readFileSync(__dirname + '/game.php?id='+id); ?
It gives me an error:
fs.js:549 return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
Is there any other way?
I suppose you're trying to do a GET call to your php service, which runs on its own (like you have a webserver which provides php pages on localhost/game.php or similar).
If this is the case, you need to use the http library, and I think something like this can work for you:
"use strict";
var http = require("http");
var id = 123;
var options = {
host: "localhost",
port: 80,
path: 'game.php?id=' + id,
method: "GET"
};
var req = http.request(options, function(res) {
console.log("STATUS: " + res.statusCode);
console.log("HEADERS: " + JSON.stringify(res.headers));
res.on("data", function (chunk) {
console.log("BODY: " + chunk);
});
});
req.end();

websocket rails javascript not working

I use websocket rails channel and trigger it from a sidekiq worker. the trigger get logged in the websocket-rails log correctly, like this, with a removed < before StationSongs:
I [2014-12-31 16:19:28.788] [Channel] [station10938] #StationSongs _id: 54a41400446562680e17c102, name: "Fedde & Di-Rect Le Grand", title: "Dream Dance Vol.73 - 14 - Where We Belong", info: nil, week: 1, year: 2014, date: 2014-12-31 15:19:28 UTC, station_id: 10938>
It get triggered like this:
channel = "station" + station_id.to_s
WebsocketRails[:"#{channel}"].trigger(:new, stationsong)
I then set subscribe for the channel station10938, the javascritp code looks like this:
var dispatcher = new WebSocketRails('localhost/websocket');
var stationid = $('#songhistorylist').data("id"); // is 10938
var stationname = 'station' + String(stationid);
var channel = dispatcher.subscribe(stationname);
console.log(channel);
channel.bind('new', function (song) {
console.log(song);
console.log('a new song about ' + song.name + " - " + song.title + ' arrived!');
});
This will only print out channel, not anything else, even if the channel comes up in the log all the time.
What have I done wrong?
On the line: WebsocketRails[:"#{channel}"].trigger(:new, stationsong), remove the ":".
It should be: WebsocketRails["station#{station_id}"].trigger(:new, stationsong)
In your JS, your dispatcher should look like this:
var dispatcher = new WebSocketRails(window.location.host + '/websocket') because your server port might change.
Your server should have (assuming stationsong is set correctly):
channel = "station" + station_id.to_s
WebsocketRails["#{channel}"].trigger(:new, stationsong)
Your client JS should have:
var dispatcher = new WebSocketRails(window.location.host + '/websocket')
var stationid = $('#songhistorylist').data("id"); // is 10938
var stationname = 'station' + String(stationid);
var channel = dispatcher.subscribe(stationname);
console.log(channel);
channel.bind('new', function (song) {
console.log(song);
console.log('a new song about ' + song.name + " - " + song.title + ' arrived!');
});

Categories

Resources