Swampdragon: how to determine a channel the message was published to? - javascript

In my project backend sends a lot of messages published to different channels.
I can see from browser console the message arrived has channel property.
But the problem is a callback passed to swampdragon.onChannelMessage doesn't get that channel information. It gets strange channels list instead.
So when a message arrives (in browser) I can't figure out the channel it was published to and therefore handle it properly.
I found the code where that channel info is stripped off https://github.com/jonashagstedt/swampdragon/blob/master/swampdragon/static/swampdragon/js/dist/swampdragon.js#L261
if ('channel' in e.data) {
var channel = swampDragon.channels[e.data.channel];
delete(e.data['channel']);
swampDragon.settings.onchannelmessage(channel, e.data);
return;
}
So my question is how frontend developer can figure out what channel the message arrived was published to in order to be able to handle the message properly?

A little late, but in case you weren't able to solve this:
swampdragon.open(function() {
swampdragon.subscribe('notification', 'notification', null, function (context, data) {
// Successfully subscribed to the notification channel
}, function () {
console.error('Error', arguments);
});
});
swampdragon.onChannelMessage(function(channels, message) {
if (channels.indexOf('notification') > -1) {
// Message sent on the notification channel
}
});
In onChannelMessage the channels argument is an array of channels the incoming messages was sent to. You can use indexOf to check the channel you are interested in exists in the list.

Related

Discord bot log

So, I created a discord.js bot and added the following into index.js:
client.on("guildCreate", guild = {
const logsServerJoin = client.channels.get('757945781352136794');
console.log(`The bot just joined to ${guild.name}, Owned by ${guild.owner.user.tag}`);
client.channels.cache.get('channel id paste here').send(`The bot just joined to ${guild.name}, Owned by ${guild.owner.user.tag}`);
var guildMSG = guild.channels.find('name', 'general');
if (guildMSG) {
guildMSG.send(` Hello there! My original name is \`Bryant\`!\n\ This bot created by **R 1 J 4 N#7686**\n\ For more info
type \`/help\`!\n\ \`Bryant - Official Server:\`
https://discord.gg/UsQFpzy`);
} else {
return;
}
});
// Logs of the bot leaves a server and changed the game of the bot
client.on("guildDelete", guild = {
client.channels.cache.get('757945781352136794').send(`The bot just
left ${guild.name}, Owned by ${guild.owner.user.tag}`);
console.log(`The bot has been left ${guild.name}, Owned by ${guild.owner.user.tag}`);
logsServerLeave.send(`The bot has been left ${guild.name}, Owned by ${guild.owner.user.tag}`);
});
It does not show any error in the terminal. It is supposed to log me where the bot joined and left in the mentioned channel but does not 🤷‍♂️. Can anyone help me out with this?
If you are getting no console log and no message in the channel / an error telling you that the channel could not be found, the issue is most likely in how you are registering the events, make sure client is an instance of the discord.js Client, below is a minimal working example
const { Client } = require("discord.js")
const client = new Client()
client.on("guildCreate", guild => {
console.log(`The bot just joined to ${guild.name}, Owned by ${guild.owner.user.tag}`)
})
client.login("yourtoken")
If you are trying to get the logs from your bot alert you in your home discord server you can do this multiple ways: Getting the channel from cache, Constructing the channel or Using webhooks. Currently you are trying to fetch the channel from cache. Although a decent solution it can fall down when using sharding later down the line. Personally I prefer webhooks as they are the easiest and most isolated.
Channel from cache
This technique is very similar to the way you were doing it.
const channel = client.channels.cache.get('757945781352136794')
channel.send('An Event occurred')
Just place this code anywhere you want to log something and you'll be fine.
Constructing the channel
const guild = new Discord.Guild(client, { id: '757945781352136794' });
const channel = new Discord.TextChannel(guild, { id: '757945781352136794' });
channel.send('An Event occurred')
This method is similar to fetching the channel from cache except it will be faster as you are constructing your home guild and channel and then sending to it. Mind you will need a client which you can get from message.client
Webhooks
My Favourite method uses webhooks. I recommend you read up on how discord webhooks work in both Discord and Discord.js
You will also need to create a webhook. This is very easy. Go into the channel you want the webhooks to be sent to and then go to integrations and create a new webhook. You can change the name and profile as you wish but copy the url and it should look something like this:
https://discord.com/api/webhooks/757945781352136794/OkMsuUHwdStR90k7hrfEi5*********
The last part of the path is the webhook token and the bit before is the channel ID
I recommend you create a helper function that can be called like this:
sendWebhook('An event occurred');
And then write the function to create and then send to the webhook
function sendWebhook(text) {
const webhook = new Discord.WebhookClient('757945781352136794', 'OkMsuUHwdStR90k7hrfEi5*********');
webhook.send(text);
webhook.destroy();
}
This will not be very dynamic and will be a pain to change the channel but for constant logging ( like guild joins and leaves ) I think it is the best solution
The problem is probably that you don't have "Privileged Gateway Intents" enabled. To turn them on, go to https://discord.com/developers, click on your application, then on "Bot" then scroll down and enable "PRESENCE INTENT" and "SERVER MEMBERS INTENT" and save. It should probably work for you now.

Node-slack web api: chat.delete returns channel_not_found for all channels although channels.list returns all channels

I have been working on a simple chat bot using the slack-node web api and botkit, but am having some trouble using the chat.delete functionality. I am able to list out all of my channels properly, seeing their channel Id's and names, but when I try to send along the message channel with the chat.delete function, it returns "channel_not_found".
I have also tried to send along the channel name, testing with "general" and the actual channel name that I am targeting, both of which return the same error.
My bot is using a token of the admin user, which should allow deletion of any message. My bot has scope access for chat:write:bot and chat:write:user as well.
Below is a snippet of my code - I have also tried this in other places for deleting messages sent directly from the bot and get the same error, so I don't believe it has to do with permissions. I've looked into the docs and the usage seems to be correct for what I have below, but I may be missing a piece.
controller.on('ambient', function(bot, message) {
web.channels.list().then((res) => {
console.log(res); // this prints out all of the channels
// listed channels show a match for the channel ID given in message.channel
});
// this call returns an error "error: Response not OK: channel_not_found"
web.chat.delete(message.channel, message.ts).then((res) => {
console.log(res + " was deleted bc it was not tagged");
}).catch((err) => { console.log(err) });
});
The docs are a bit confusing on this, but the chat.delete method of the official #slack/client library take the parameters in a different order:
You'll want to change your code to be:
web.chat.delete(message.ts, message.chanel).then(...)
See here:
https://slackapi.github.io/node-slack-sdk/reference/ChatFacet#ChatFacet+delete

WebRTC - 'RTCPeerConnection': The ICE candidate could not be added

The error I am getting in the browser console (only appears in chrome, no errors in firefox) is Error: Failed to execute 'addIceCandidate' on 'RTCPeerConnection': The ICE candidate could not be added.
I followed a tutorial and was able to get p2p video chat to work using nodejs. Now I am using Flask and python on the server side and angularjs on client side.
Signaling process for two peers is being done with angular-socketio.
console.log("The user connected to the socket");
socket.emit('readyToJoinRoom', {"signal_room": SIGNAL_ROOM});
//Send a first signaling message to anyone listening
//This normally would be on a button click
socket.emit('signal',{"type":"user_joined", "message":"Are you ready for a call?", "room":SIGNAL_ROOM});
socket.forward('signaling_message', $scope);
$scope.$on('socket:signaling_message', function (ev, data) {
displaySignalMessage("Signal received: " + data.type);
// Setup the RTC Peer Connection object
if (!rtcPeerConn) {
startSignaling();
}
if(data.type != "user_joined") {
console.log(data.message);
var message = JSON.parse(data.message);
console.log(message);
if(message.sdp) {
console.log("inside 2nd if statement");
rtcPeerConn.setRemoteDescription(new RTCSessionDescription(message.sdp), function () {
// if we received an offer, we need to answer
if(rtcPeerConn.remoteDescription.type === 'offer') {
console.log("inside third if for remoteDescription."); // This never executes, error happens right before this line
rtcPeerConn.createAnswer(sendLocalDesc, logError);
}
}, logError);
}
else {
console.log("addedddddddd ice candidate.");
rtcPeerConn.addIceCandidate(new RTCIceCandidate(message.candidate));
}
}
});
Once two people join the room the startSignaling() method is called. It sets the local description and completes 3 ice candidates then I receive an SDP but this is never true if(rtcPeerConn.remoteDescription.type === 'offer') even though it prints the SDP in the console with a type equal to offer. I am not sure why it never goes inside this if statement. I am not sure why I am getting an error. If you have any questions just ask. Thanks for the help.
I think
rtcPeerConn.setRemoteDescription(new RTCSessionDescription(message.sdp),...
will not work because the constructor of RTCSessionDescription needs the information about the type and the sdp. Try:
var desc = new RTCSessionDescription();
desc.sdp = message.sdp;
desc.type = "offer";
rtcPeerConn.setRemoteDescription(desc,.....
I had some issues constructing the RTCSessionDescription from JSON as well.
Hope this helps...

Slack Botkit - How to get a message's content from a 'reaction_added' event

I'm using the botkit framework to respond when a reaction is added to a message but I'm not sure how to extract the message's content when the event is triggered. Below is what I currently have:
controller.on('reaction_added',function(bot, event) {
if (event.reaction == 'x') {
// bot reply with the message's text
}
});
According to the Slack API, I can only get data like event.item which has the type, channel, and ts of the message. Does anyone know how to accomplish this?
Figured it out. Given the timestamp and the channel, I was able to manually search for the message in the channel history and extract the data I needed.
function getTaskID(channel_id, timestamp, callback) {
slack.api("channels.history", {
channel: channel_id,
latest: timestamp,
count: 1,
inclusive: 1
}, function(err, response) {
// do something with the response
});
}

ARI JS client mute error

Am currently developing a mute function for asterisk which I can run from my web front end using asterisk ARI.
But every time I try to run/call the mute function it gives me the following error:
Error: {
"message": "Channel not in Stasis application"
}
But it is, as far as am aware am passing the channel data directly to this function but to no avail.
Any one any suggestions or used to working with the ARI JS client?
Client Side
When mute button is clicked emit the data found in td to the server side.
$(document).on('click', '.mute', function () {
var mute = $(this).closest('td').siblings(':first-child').text();
socket.emit('muting', mute);
if ($(this).hasClass('mute')) {
$(this).removeClass('mute').addClass('unmute').find('span').text('Unmute');
} else {
console.log("Error");
}
});
Server Side
Store the data received from client side into a var and then call the stasis function.
io.sockets.on('connection', function (socket) {
updateSip();
socket.on('muting', function (data) {
mute(data);
console.log("Reached listener for muting")
});
});
Stasis function
Mute the channel which you have just passed from client to server side using ARI client commands, user will be muted and will show in stasis application.
function mute(mutval) {
console.log("Muting:" + mutval);
client.channels.mute
({
channelId : mutval
},
function (err) {
if (err) {
throw err;
}
});
}
The channel is in the application and being passed to the mute function, so am not sure as to way its not working currently.
EDIT: I have a hangup/kick function being handled in the same way and it works fine. Below is all my debugging.
Channel Dump
Free PBX Logs
Asterisk CLI Debug Level 5
Socket.io Error
I have also tried running it via socket.io and without it and the outcome is the same, I have other functions and they all work just fine, its just the mute function.
Turns out it would not run because it needed channel ID and not channel name, but functions would run with channel name.
It is inconsistency with the Asterisk ARI as it should work with channel name and not just channel ID like other functions did such as hangup and originate functions.

Categories

Resources