Cannot detect user leaving channel discord.js - javascript

I have connected two discord bot accounts to one script and i want to kick a user when they leave a voice channel but it doesn't work.
code:
const { Client, Intents, ClientUser } = require('discord.js');
const cli = require('nodemon/lib/cli');
const clients = [ new Client({ intents: [Intents.FLAGS.GUILDS] }), new Client({ intents: [Intents.FLAGS.GUILDS] }) ];
const Tokens = ["token1", "token2"]
clients.forEach(function(client, index) {
client.login(Tokens[index])
let clientcount = index + 1
client.on("ready", () => {
client.user.setUsername("PartyChat Bot")
client.user.setActivity(`PartyChat Bot #${clientcount}`)
console.log(`PartyBot #${clientcount} is online`)
})
});
clients.forEach(function(client, index) {
client.on('voiceStateUpdate', (oldState, newState) => {
let newUserChannel = newState.voiceChannel
let oldUserChannel = oldState.voiceChannel
if(oldUserChannel === undefined && newUserChannel !== undefined) {
// User Joins a voice channel
} else if(newUserChannel === null){
console.log("user left")
newState.member.kick()
}
})
});

if(oldState.channel && !newState.channel){
// code block
}
this detects if user was in channel and left without joining new channel.

Related

Discord bot enter the voice channel, but it doesn't play any audio

My discord bot that i'm creating it doesn't play any audio when he joins a voice channel, this is my code.
What i want it is to get the youtube url from the message and plays it. (I'm totally new to javascript so idk if the code is right?)
const { Distube } = require('distube')
const distube = require('distube').Distube
const { joinVoiceChannel, createAudioPlayer } = require('#discordjs/voice')
const player = createAudioPlayer()
module.exports = (client) => {
const targetChannelId = '431197967337390081'
const prefix = '-'
client.on('messageCreate', msg => {
if (msg.channel.id === targetChannelId) {
if (msg.content.startsWith(prefix)) {
const command = msg.content.slice(prefix.length).split(' ')[0]
const args = msg.content.slice(prefix.length).split(' ')[1]
if (command === 'play') {
const connection = joinVoiceChannel({
channelId: msg.member.voice.channel.id,
guildId: '354279496502738947',
adapterCreator: msg.guild.voiceAdapterCreator,
}).subscribe(audioPlayer)
}
}
}
})
}

How do I make my custom discord bot to delete an embed it sent out in a few seconds after the msg has been sent

I want my bot to delete an embed it sends out when someone uses a cuss word. I want it to delete that embed in 5-6 seconds take 5 or 6 so it takes up less space in the area.
const Discord = require('discord.js');
const { Client, MessageEmbed } = require('discord.js');
const bot = new Client();
const token = 'tokenhere';
bot.on('ready', () =>{
bot.user.setActivity('YOU', { type: 'WATCHING' });
console.log('This bot is online!');
});
bot.on('message', message=>{
const user = message.author;
const swearWords = ["fuck", "dick", "pussy", "vagina", "bsdk", "saale", "kutte", "bitch", "die", "mf", "bish", "fag","ass","nigga","nigger","fack"];
if (swearWords.some(word => message.content.toLowerCase().includes(word)) ) {
const embed = new MessageEmbed()
.setTitle('Chat F!lter')
.setColor(0xff0000)
.setDescription('<#' + message.author.id + '> You have been caught being toxic! , You are muted for a minute');
message.channel.send(embed);
const role = message.guild.roles.cache.find(x => x.name == 'muted');
message.member.roles.add(role);
setTimeout(() => {message.member.roles.remove(role)}, 60*1000);
}});
bot.login(token);
message.channel.send() returns a promise, you can resolve the promise and then use the <message>.delete({ timeout: 'time-goes-here' }) method, so your code would look like this.
const Discord = require('discord.js');
const { Client, MessageEmbed } = require('discord.js');
const bot = new Client();
const token = 'token-goes-here';
bot.on('ready', () =>{
bot.user.setActivity('YOU', { type: 'WATCHING' });
console.log('This bot is online!');
});
bot.on('message', message=>{
const user = message.author;
const swearWords = ["fuck", "dick", "pussy", "vagina", "bsdk", "saale", "kutte", "bitch", "die", "mf", "bish", "fag","ass","nigga","nigger","fack"];
if (swearWords.some(word => message.content.toLowerCase().includes(word)) ) {
const embed = new MessageEmbed()
.setTitle('Chat F!lter')
.setColor(0xff0000)
.setDescription('<#' + message.author.id + '> You have been caught being toxic! , You are muted for a minute');
// send and deleting the embed
message.channel.send(embed).then(msg => msg.delete({ timeout: 5000 })); // delete embed after 5 seconds (5000 ms)
const role = message.guild.roles.cache.find(x => x.name == 'muted');
message.member.roles.add(role);
setTimeout(() => {message.member.roles.remove(role)}, 60*1000);
}});
bot.login(token);

Discord.js: Asynchronous message Cooldown / Antispam

I am making a Discord Bot that informs Moderators when a user joins a specific voice channel. The Bot is supposed to also have a spam protection that the bot will only log a message once per minute per user.
This is what I have tried before: 
const { Client } = require("discord.js");
const { config } = require("dotenv");
const fs = require('fs');
const client = new Client({
partials: ['MESSAGE', 'CHANNEL', 'REACTION']
});
config({
path: __dirname + "/.env"
})
var supportchannel = '827574015526567947'
var dutychannel = '847445933969113118'
var ondutyrole = '847447374925398016'
client.on("ready", () => {
console.log(`Hi, ${client.user.username} is now online!`);
global.timer = 0;
client.user.setStatus('online');
client.user.setActivity('me getting developed', { type: "WATCHING"})
.then(presence => console.log('status set'))
.catch(console.error);
});
client.on('voiceStateUpdate', (oldMember, newMember) => {
let newUserChannel = newMember.channelID;
let oldUserChannel = oldMember.channelID;
if(newUserChannel === supportchannel)
{
if (timer == 0){
timer = 1
setTimeout(() => {
timer = 0
}, 60000);
const Userfm = client.users.cache.get(newMember.id);
if (Userfm) {
const channelfx = client.channels.cache.get(dutychannel)
let roleId = ondutyrole
channelfx.send(`<#&${roleId}> **${Userfm.tag}** requires Support`);
}
}else{
return;
}
}
console.log("User joined vc with id "+newUserChannel)
});
client.login(process.env.TOKEN);
This doesn't work the way intended because the cooldown is not separate for every user but sets a countdown that blocks every user from getting the Moderator's attention for 60 seconds (the users all share a cooldown).
I thought that the code ran asynchronously for every user.
The same goes for this code in which I made use of the wait-sync npm library:
const { Client } = require("discord.js");
const { config } = require("dotenv");
const fs = require('fs');
const waitSync = require('wait-sync');
const client = new Client({
partials: ['MESSAGE', 'CHANNEL', 'REACTION']
});
config({
path: __dirname + "/.env"
})
var supportchannel = '827574015526567947'
var dutychannel = '847445933969113118'
var ondutyrole = '847447374925398016'
client.on("ready", () => {
console.log(`Hi, ${client.user.username} is now online!`);
global.timer = 0;
client.user.setStatus('online');
client.user.setActivity('me getting developed', { type: "WATCHING"})
.then(presence => console.log('status set'))
.catch(console.error);
});
client.on('voiceStateUpdate', (oldMember, newMember) => {
let newUserChannel = newMember.channelID;
let oldUserChannel = oldMember.channelID;
if(newUserChannel === supportchannel)
{
const Userfm = client.users.cache.get(newMember.id);
if (Userfm) {
const channelfx = client.channels.cache.get(dutychannel)
let roleId = ondutyrole
channelfx.send(`<#&${roleId}> **${Userfm.tag}** requires Support`);
waitSync(60);
}
}
console.log("User joined vc with id "+newUserChannel)
});
client.login(process.env.TOKEN);
If you know how to solve this problem please let me know.
Thanks in advance ;)
What you can do is probably to have some sort of mapping that keeps track of the timer for each user and have the user IDs be the keys:
const timers = {};
client.on('voiceStateUpdate', (oldMember, newMember) => {
...
// If we don't have any timer set for this user, go ahead and set it
if (!timers[newMember.id]) {
timers[newMember.id] = 1;
setTimeout(() => {
// Delete the timer from the mapping
delete timers[newMember.id];
}, 60000);
...

discord.js deleting only user messages and bot

I want to make my bot to delete only user's messages in a certain channel and not the bot's. I tried doing it using the code below but it kept on deleting the both the bot's messages and mine.
const Discord = require("discord.js");
const client = new Discord.Client();
const { MessageEmbed } = require("discord.js");
const avalibleFormats = ['png', 'gif', 'jpeg', 'jpg']
client.on("ready", () => {
console.log("I am ready!");
});
client.on("message", message => {
if (message.channel.id == '829616433985486848') {
message.delete();
}
if (message.channel.id !== '829616433985486848') {
return;
}
let image = getImage(message)
if (!image) {
return;
}
let embed = new MessageEmbed();
embed.setImage(image.url)
embed.setColor(`#2f3136`)
message.channel.send(embed)
});
const getImage = (message) => message.attachments.find(attachment => checkFormat(attachment.url))
const checkFormat = (url) => avalibleFormats.some(format => url.endsWith(format))
client.login(token);
Well, you only say that if the channel id is 829616433985486848, delete the message. you should also check if the author is a bot using the message.author.bot property:
const avalibleFormats = ['png', 'gif', 'jpeg', 'jpg'];
const checkFormat = (url) => avalibleFormats.some((format) => url.endsWith(format));
const getImage = (message) => message.attachments.find((attachment) => checkFormat(attachment.url));
client.on('message', (message) => {
const certainChannelId = '829616433985486848';
// if the channel is not 829616433985486848, return to exit
if (message.channel.id !== certainChannelId)
return;
// the rest of the code only runs if the channel is 829616433985486848
const image = getImage(message);
// if author is not a bot, delete the message
if (!message.author.bot)
message.delete();
if (!image)
return;
const embed = new MessageEmbed()
.setImage(image.url)
.setColor('#2f3136');
message.channel.send(embed);
});
Actually, if the message is posted by a bot, you don't even need to run anything in there so you can check that right at the beginning and exit early:
client.on('message', (message) => {
if (message.author.bot || message.channel.id !== '829616433985486848')
return;
const image = getImage(message);
if (image) {
const embed = new MessageEmbed()
.setImage(image.url)
.setColor('#2f3136');
message.channel.send(embed);
}
message.delete();
});
If you want it to work in multiple channels, you can create an array of channel IDs and use Array#includes() to check if the current channel ID is in that array:
client.on('message', (message) => {
const channelIDs = ['829616433985486848', '829616433985480120', '829616433985485571'];
if (message.author.bot || !channelIDs.includes(message.channel.id))
return;
const image = getImage(message);
if (image) {
const embed = new MessageEmbed()
.setImage(image.url)
.setColor('#2f3136');
message.channel.send(embed);
}
message.delete();
});

discord.js v12 send message to first channel

Hi how can i send message to first channel where bot can send messages in Discord.js v12.
Please help me.
This didnt work for me:
client.on("guildCreate", guild => {
let channelID;
let channels = guild.channels;
channelLoop:
for (let c of channels) {
let channelType = c[1].type;
if (channelType === "text") {
channelID = c[0];
break channelLoop;
}
}
let channel = client.channels.get(guild.systemChannelID || channelID);
channel.send(`Thanks for inviting me into this server!`);
});
You can do it like this.
const Discord = require("discord.js");
const client = new Discord.Client();
client.on("guildCreate", (guild) => {
const channel = guild.channels.cache.find(
(c) => c.type === "text" && c.permissionsFor(guild.me).has("SEND_MESSAGES")
);
if (channel) {
channel.send(`Thanks for inviting me into this server!`);
} else {
console.log(`can\`t send welcome message in guild ${guild.name}`);
}
});
Updated for Discord v13
Note the c.type has been changed from text to GUILD_TEXT
const Discord = require("discord.js");
const client = new Discord.Client();
client.on("guildCreate", (guild) => {
const channel = guild.channels.cache.find(
(c) => c.type === "GUILD_TEXT" && c.permissionsFor(guild.me).has("SEND_MESSAGES")
);
// Do something with the channel
});
Update for from v13 to v14
on event of guildCreate is now Events.GuildCreate
c.type changed from GUILD_TEXT to ChannelType.GuildText
guild.me is now guild.members.me
const { Events, ChannelType } = require('discord.js')
const client = new Client({
//your intents here
intents: []
})
client.on(Events.GuildCreate, guild => {
const channel = guild.channels.cache.find(c =>
c.type === ChannelType.GuildText &&
c.permissionsFor(guild.members.me).has('SEND_MESSAGES')
)
//do stuff with the channel
})

Categories