How to get wix chat channel Id when user enterto my website - javascript

I want to get channel Id so I used corvid documentation and follow instructions
First I added wix chat app
then I added the following function :
export async function wixGetChannelId() {
let channel = await $w("#myChatbox").getChannel({type: "Business"});
console.log("channel id",channelId) }
and call wixGetChannelId function from onReady
But I got undefied, what I need to change?

So I tried the below code to loop for the channel id.
$w.onReady(function () {
setInterval( () => {
getId();
}, 1500);
});
function getId() {
$w("#wixChat1").getChannel({type: "Business"})
.then((channel) => {
console.log(channel);
})
.catch((err) => {
console.log(err);
});
}
Basically, I get error the first few times (you are receiving the undefined because you dont catch the error) but as soon as I click on the chatbox icon (which I think triggers the creation of the channel) I start getting the channel information.
So I think the user needs to first initiate a conversation which triggers a new channel creation.

Related

Start/stop cronjob on button click in Nodejs Express app

I have been working on a project which requires the start and stop of cron scheduler when a user clicks on a button on the front end. Basically when a user clicks on a button, the cron job will start. And clicking the stop button will stop the timer. It is as simple as that.
To achieve that, I am making post requests to the Nodejs/Express backend on button click which triggers start/stop function of the scheduler. This is how the endpoint looks like:
const cron = require('node-cron');
router.post('/scheduler', async (req, res) => {
// gets the id from the button
const id = req.body.id;
try{
// finds the scheduler data from the MongoDB
const scheduler = await Scheduler.find({ _id: id });
// checks whether there is a scheduler or not
if ( !scheduler ) {
return res.json({
error: 'No scheduler found.'
});
}
// creates the cronjob instance with startScheduler
const task = cron.schedule('*/10 * * * * *', () => {
console.log('test cronjob running every 10secs');
}, {
scheduled: false
});
// checks if the scheduler is already running or not. If it is then it stops the scheduler
if ( scheduler.isRunning ) {
// scheduler stopped
task.stop();
return res.json({
message: 'Scheduler stopped!'
});
}
// starts the scheduler
task.start();
res.json({
message: 'Scheduler started!'
});
}catch(e) {
console.log(e)
}
});
Right now the scheduler runs perfectly but it doesn't stop on second button click. It keeps on running. I feel like I'm not calling task.start() and task.stop() at correct places where it would work. And I don't know where the correct places are. I'm actually new to cronjobs.
It would be great if someone tells me what I am doing wrong.
Thanks in advance.
Every time you hit the scheduler api a new instance of cron-job is made and you are stopping the newly defined instance of cron-job not the previous one.
Solution is to define the cron-job out of the scope of router so that whenever you hit the scheduler api the instance won't change
Like this:
const cron = require('node-cron');
// creates the cronjob instance with startScheduler
const task = cron.schedule('*/10 * * * * *', () => {
console.log('test cronjob running every 10secs');
}, {
scheduled: false
});
router.post('/scheduler', async (req, res) => {
// gets the id from the button
const id = req.body.id;
try{
// finds the scheduler data from the MongoDB
const scheduler = await Scheduler.find({ _id: id });
// checks whether there is a scheduler or not
if ( !scheduler ) {
return res.json({
error: 'No scheduler found.'
});
}
// checks if the scheduler is already running or not. If it is then it stops the scheduler
if ( scheduler.isRunning ) {
// scheduler stopped
task.stop();
return res.json({
message: 'Scheduler stopped!'
});
}
// starts the scheduler
task.start();
res.json({
message: 'Scheduler started!'
});
}catch(e) {
console.log(e)
}
});
The problem might come from the line:
const task = cron.schedule('*/10 * * * * *', () => {
which, actually, creates a new task and uses a new Scheduler if you read the source code of node-cron:
https://github.com/node-cron/node-cron/blob/fbc403930ab3165ffef7d53387a29af92670dfea/src/node-cron.js#L29
function schedule(expression, func, options) {
let task = createTask(expression, func, options);
storage.save(task);
return task;
}
(which, internally, uses: https://github.com/node-cron/node-cron/blob/fbc403930ab3165ffef7d53387a29af92670dfea/src/scheduled-task.js#L7:
let task = new Task(func);
let scheduler = new Scheduler(cronExpression, options.timezone, options.recoverMissedExecutions);
So, when you call:
task.stop();
As far as I understand, what you do is calling the method "stop" of a brand new task, not the method stop of the task you launched the first time you clicked the button.
Judging by your code, the problem is that you are not actually using your scheduler while using the task.
PS:
The module also exposes a function that lets you retrieve tasks from its storage: https://github.com/node-cron/node-cron/blob/fbc403930ab3165ffef7d53387a29af92670dfea/src/node-cron.js#L58
But as I haven't found any documentation about it, I do not recommend using it.

Remove a specific reaction emote on any message (Discord.js)

I want to make a "banned reaction". I got the following code working, but it only removes reactions for messages the bot sends.
client.on('messageReactionAdd', async (reaction, user) => {
console.log(reaction);
if(reaction.emoji.name === 'pinkphallicobject')
reaction.remove();
});
How can I get it to remove a specific reaction for all messages from anyone?
For the messageReactionAddevent to fire on old messages you will need to cache the old messages in the server when the ready event is fired you can do it like this:
client.once('ready', () => {
var guild = client.guilds.cache.first();// you can find the server you want it to work on in a different way or do this for all servers
guild.channels.cache.forEach(channel => {
if(channel.type == 'text'){//do this for text channels only
channel.messages.fetch({limit: 100}).then(() => {
console.log('cached 100 or less messages from the: ' + channel.name + 'text channel.');
});
}
});
}

Twilio Chat: Trying to get notification of Member Reachability on a Channel

I'm trying get notifications to other members of a channel when a member of a chat channel has left the room. Specifically if they navigate away from the page in their browser. I have "Reachability Enabled" on the service, and am getting verification of that by checking the Client.reachabilityEnabled member.
I'm able to access a list of all of the members of the channel by calling on Channel.getMembers(), but the userInfoUpdated event does not fire when a member enters or leaves the chat page.
A side, but possibly relevant item is that the member.state.attributes object is empty when I inspect any member in the console.(reference this question Twilio chat member online status is always null -- it shows an image of the console inspector that has values including online status in the member.state.attributes object) -
Running the code below, I get my notification that Reachability is enabled and my console log of the members, but when I have some other member enter/exit the page no event fires.
/*twilioChat is the return from require: https://media.twiliocdn.com/sdk/js/chat/v3.3/twilio-chat.min.js*/
function chatInit(twilioChat){
$scope.twilioChat = twilioChat;
$scope.twilioChat.Client.create($scope.TOKEN).then(client => {
console.log('Created chat client');
$scope.chatClient = client;
$scope.chatClient.getSubscribedChannels().then(function(){
$scope.chatReady = true;
console.log('chat is ready');
createOrJoinMonitorChannel();
});
}).catch((err) =>{
console.error(err);
})
}
function createOrJoinMonitorChannel(){
$scope.chatClient.getChannelByUniqueName($scope.monitor_listen)
.then(function(channel){
$scope.monitorListenChannel = channel;
setupMonitorChannel();
}).catch(function(err){
console.log(err);
$scope.chatClient.createChannel({
uniqueName: $scope.monitor_listen,
friendlyName: $scope.monitor_listen,
}).then(function(channel){
$scope.monitorListenChannel = channel;
setupMonitorChannel();
}).catch(function(err){
console.log('Monitor Channel could not be created');
console.log(err);
});
});
}
function setupMonitorChannel(){
var status = $scope.monitorListenChannel.state.status;
if(status !== 'joined'){
$scope.monitorListenChannel.join().then(function(channel){
});
}else{
}
$scope.monitorListenChannel.on('memberJoined',function(m){
console.log('member joined');
});
$scope.monitorListenChannel.on('memberLeft',function(m){
console.log('member left');
});
if($scope.chatClient.reachabilityEnabled){
console.log('Enabled');
}else{
console.log('Not Enabled');
}
$member_promise = $scope.monitorListenChannel.getMembers();
$member_promise.then(members=>{
console.log(members);
members.forEach(member=>{
member.on('userInfoUpdated',function(user){
console.log('user info updated') ;
});
})
});
$scope.monitorListenChannel.on('messageAdded', function(message){
var data = isJSONSTR(message.body);
$handler.classroomMonitor(data);
});
}
When you enable Reachability it fires off an event when a user is online or not. You can use the user.on("updated", ({user, updateReasons}) => {}) event listener. Depending on which version you are using, userInfoUpdated might not be supported.
When you are listening for when a member has left a channel, you have to call channel.leave() yourself. Does this help?
https://media.twiliocdn.com/sdk/js/chat/releases/4.0.0/docs/User.html

Error callback using echo-laravel and react

I'm trying to add a callback for a pusher:subscription_error with echo-laravel. The client is done in react. The broadcaster is Pusher and I subscribe to a channel like this:
echo.private('User.' + this.props.user.id).listen("NewMessage", (newMessage) => {
if (newMessage.message.message_room_id === this.state.selectedMessage.id) {
this.props.newMessageInOpenBox(newMessage);
} else {
this.props.newMessage(newMessage);
}
}
)
Im trying to get the failed subscription callback working so i can trigger a token refresh. How would i catch the subscription error? i couldn't find anything in the docs or elsewhere.
for anyone having the same problem i found that you have to go into the channel like this
echo.connector.pusher.channels.channels['private-' + channelName].bind('pusher:subscription_error', () => {
alert('sub error')
})

How to tag users using Discord.JS?

I am looking to create a command in order to tag certain users automatically using their username eg. "#RYAN#9602" whenever a switch statement case is executed. Currently the problem that I'm experiencing in that whenever I do try to tag users, it just writes "#RYAN#9602" into the text channel and doesn't actually tag them.
This is what I have tried:
var players = [
"#RYAN#9602"
]
switch(args[0].toLowerCase()){
case "play":
message.channel.send(players.join('\n'));
break;
}
So in summary, using Discord.JS, how do I make the bot actually tag the user so that they will get 'pinged' instead of just sending a message of their name into the text channel?
You have two options.
You can either use the toString method on the User object, or form the mention yourself using the user's ID.
Here's an example using toString:
client.on("message", => {
const channel = message.channel;
channel.send(message.author.toString());
});
And here's an example using the ID
client.on("message", => {
const channel = message.channel;
channel.send("<#" + message.author.id + ">");
});
Try using the toString method.
client.on("message", => {
const channel = message.channel;
channel.send(message.author.toString());
});
Update 2023: Now you can use userMention()
const { Client, userMention } = require('discord.js');
client.on('interactionCreate', async interaction => {
if (!interaction.isChatInputCommand()) return;
...
interaction.reply(userMention(member.id));
});

Categories