discord.js v12 send message to first channel - javascript

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
})

Related

Cannot detect user leaving channel discord.js

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.

How can my Discord Bot assign a Role to new Users?

First im new to Coding, that means i mostly Copie and Paste things.
To my problem: i do exactly things like in Videos, switch on "SERVER MEMBERS INTENT" in the Discord Dev portal and so on. But my Bot won't assign a Role after someone Joins my DC.
My code looks like a mess BUT! the function i wanted first that the Bot reply "pong" after i type !ping worked finaly after many hours of re-coding stuff.
here my code:
global.Discord = require('discord.js')
const { Client, Intents } = require('discord.js');
const { on } = require('events');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
const prefix = "!";
const fs = require('fs');
const token = "my token";
client.commands = new Discord.Collection();
client.events = new Discord.Collection();
client.on('guildMemberAdd', guildMember =>{
let welcomeRole = guildMember.guild.roles.cache.find(role => role.name === 'anfänger');
guildMember.roles.add(welcomeRole);
guildMember.guild.channels.cache.get('930264184510361670').send(`Welcome <${guildMember.user.id}> to out Server!`)
});
client.once("ready", () => {
console.log(`Ready! Logged in as ${client.user.tag}! Im on ${client.guilds.cache.size} guild(s)!`)
client.user.setActivity({type: "PLAYING", name: "Learning Code"})
});
const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
for(const file of commandFiles){
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
client.on('messageCreate', message =>{
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.split(' ').slice(1);
const command = message.content.split(' ')[0].slice(prefix.length).toLowerCase();
if(command === 'is'){
client.commands.get('is').execute(message, args, Discord);
}
});
client.login(token);
Aha! there it is
you spelled guildMember as guildmember
client.on('guildMemberAdd', async guildMember => {
var i = "930263943597928508";
let role = guildMember.guild.roles.cache.find(r => r.id === i);
guildmember.roles.add(role); //here replace guildmember with guildMember
})

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 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();
});

Checking the channel name

const Discord = require('discord.js');
const client = new Discord.Client();
client.on('ready', (oldMessage, newMessage, role, args, guild) => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('message', message => {
if (message.content === '.') {
if (message.guild.channel === 'dot-wars') {
message.guild.members.forEach(member => {
var role = message.guild.roles.find(role => role.name === 'Dot Master!');
member.removeRole(role);
})
}
var role = message.guild.roles.find(role => role.name === 'Dot Master!');
message.member.addRole(role);
}
});
okay so what i want to do is when someone sends a '.' the bot will remove the 'Dot Master!' role from everyone in the server and then add the 'Dot Master!' role to the person that sent it, but only if it is in the 'dot-wars' channel.
A text channel has a name property for reading its name. However, make sure you're checking the channel the message was sent in, not the guild (Message#channel).
if (message.channel.name === 'dot-wars') {
...
}

Categories