client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(' ');
const command = args.shift().toLowerCase();
if (command === 'say') {
if (!args.length) {
return message.channel.send(`Please tell the bot what to say, ${message.author}`);
}
const { Client, MessageEmbed } = require('discord.js');
const embed = new MessageEmbed()
.setTitle(`${args}`)
.setColor('RED')
message.channel.send(embed);
}
})
but whenever i type !say subscribe today it comes out as subscribe,today
can someone please tell me a way to separate the argument so the commas arent there and its more than one word?
if (command === 'say') {
if (!args.length) {
return message.channel.send(`Please tell the bot what to say, ${message.author}`);
}
let text = args.join(' '); //Join the array of strings with a space to create a text to send
const { Client, MessageEmbed } = require('discord.js');
const embed = new MessageEmbed()
.setTitle(text)
.setColor('RED')
message.channel.send(embed);
}
More on array.join() method here
const Discord = require('discord.js');
const client = new Discord.Client();
const prefix = '!';
client.on('message', (message) => {
let args = message.content.substring(0, prefix.length).split(' ');
let command = args.shift();
});
Related
Here is the code I am testing and there are no errors if i compile it?
const {
Client,
GatewayIntentBits,
EmbedBuilder,
PermissionsBitfield,
Permissions,
} = require("discord.js");
const prefix = ">";
//Intents Huren
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
],
});
//Message Reaction
client.on("messagCreate", (message) => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
//message Array
const messageArray = message.content.split(" ");
const argument = messageArray.slice(1);
const cmd = messageArray[0];
//test Command
if (command === "test") {
message.channel.send("Bot is working!");
}
});
//Client is Ready
client.once("ready", () => {
console.log("Bot Ready");
});
client.login("");
There is no messagCreate event. Please change it to messageCreate then it should work.
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
})
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();
});
Whenever I try to use a function like client.users.cache.size or client.guilds.size, they keep giving me an error like "TypeError: Cannot read property 'guilds' of undefined" or "TypeError: Cannot read property 'cache' of undefined".
I was also trying to use let guilds = client.guilds.cache.array().join('\n') but it also throws the same error.
Command's code:
const Discord = require('discord.js');
module.exports = {
name: 'stats',
description: 'Views the bot\'s stats',
execute(client, message) {
const embed = new Discord.MessageEmbed
.setDescription(`In ${client.guilds.size} servers`)
.setTimestamp()
.setFooter(message.member.user.tag, message.author.avatarURL());
message.channel.send(embed)
}
}
Bot's main file:
const path = require('path');
const fs = require("fs");
const { token, prefix } = require('./config.json');
const Discord = require('discord.js');
const db = require ('quick.db');
const client = new Discord.Client
client.commands = new Discord.Collection();
const isDirectory = source => fs.lstatSync(source).isDirectory();
const getDirectories = source => fs.readdirSync(source).map(name => path.join(source, name)).filter(isDirectory);
getDirectories(__dirname + '/commands').forEach(category => {
const commandFiles = fs.readdirSync(category).filter(file => file.endsWith('.js'));
for(const file of commandFiles) {
const command = require(`${category}/${file}`);
client.commands.set(command.name, command);
}
});
client.on("ready", () => {
console.log(`ready!.`);
console.log(token);
// Activities
const activities_list = [
`Serving Tacos | .help`,
`Preparing Orders | .help`
];
setInterval(() => {
const index = Math.floor(Math.random() * (activities_list.length - 1) + 1);
client.user.setActivity(activities_list[index]);
}, 10000);
});
//Joined Guild
client.on("guildCreate", (guild) => {
const EmbedJoin = new Discord.MessageEmbed()
.setColor('#FFFF33')
.setTitle(`Joined Guild: ${guild.name}!`)
.setTimestamp()
console.log(`Joined New Guild: ${guild.name}`);
client.channels.cache.get(`746423099871985755`).send(EmbedJoin)
});
//Left Guild
client.on("guildDelete", (guild) => {
const EmbedLeave = new Discord.MessageEmbed()
.setColor('#FFFF33')
.setTitle(`Left Guild: ${guild.name}.`)
.setTimestamp()
console.log(`Left Guild: ${guild.name}`);
client.channels.cache.get(`746423099871985755`).send(EmbedLeave)
});
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const commandName = args.shift().toLowerCase();
const command = client.commands.get(commandName)
|| client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));
if (!command) return;
if (command.guildOnly && message.channel.type === 'dm') {
return message.reply('I can\'t execute that command inside DMs!');
}
if (command.args && !args.length) {
let reply = `${message.author}, wrong usage`;
if (command.usage) {
reply += `\nThe proper usage would be: \`${prefix}${command.name} ${command.usage}\``;
}
return message.channel.send(reply);
}
try {
command.execute(message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
});
process.on("error", () => {
console.log("Oops something happened!");
});
client.login(token);
In your code, client.guilds returns a manager, so you have to use client.guilds.cache.size. The rest of the code works fine.
const Discord = require('discord.js');
module.exports = {
name: 'stats',
description: 'Views the bot\'s stats',
execute(message, args, client) {
const embed = new Discord.MessageEmbed
.setDescription(`In ${client.guilds.cache.size} servers`)
.setTimestamp()
.setFooter(message.member.user.tag, message.author.avatarURL());
message.channel.send(embed)
}
}
In your main bot file you're only passing the message and the args (in this order) to command.execute(). You can add the client too, and update the parameters in your command's code to match this order.
try {
command.execute(message, args, client);
} catch (error) {
...
}
I'm using Discord.js for a discord bot and I'm trying to make it so that when you do the command !avatar #user
It will reply back with an embedded image of the mentioned user's avatar. I keep getting:
(node:3168) UnhandledPromiseRejectionWarning: DiscordAPIError: Invalid Form Body embed.image.url: Not a well formed URL.
This is the code I have so far, however I'm unaware of how else to grab the user's avatar?
const Discord = require('discord.js');
const config = require('./config.json');
const client = new Discord.Client();
function getUserFromMention(mention) {
if (!mention) return;
if (mention.startsWith('<#') && mention.endsWith('>')) {
mention = mention.slice(2, -1);
if (mention.startsWith('!')) {
mention = mention.slice(1);
}
return client.users.get(mention);
}
}
function getUserFromMentionRegEx(mention) {
const matches = mention.match(/^<#!?(\d+)>$/);
const id = matches[1];
return client.users.get(id);
}
client.once('ready', () => {
console.log('Ready!');
});
const prefix = "!";
client.on('message', message => {
if (!message.content.startsWith(prefix)) return;
const withoutPrefix = message.content.slice(prefix.length);
const split = withoutPrefix.split(/ +/);
const command = split[0];
const args = split.slice(1);
if (command === 'avatar') {
if (args[0]) {
const user = getUserFromMention(args[0]);
const userAvatar = user.displayAvatarURL;
if (!user) {
return message.reply('Please use a proper mention if you want to see someone else\'s avatar.');
}
const avatarEmbed = new Discord.RichEmbed()
.setColor('#275BF0')
.setImage('userAvatar');
message.channel.send(avatarEmbed);
}
return message.channel.send(`${message.author.username}, your avatar: ${message.author.displayAvatarURL}`);
}
});
client.login(config.token);
you dont need parse mentions with another function, discord have method for this. You can use message.mentions.members.first()
And you try to set image a string, with text userAvatar so sure you got error.
You can get mention member avatar and send it with this code.
const Discord = require('discord.js');
const config = require('./config.json');
const client = new Discord.Client();
client.once('ready', () => {
console.log('Ready!');
});
const prefix = "!";
client.on('message', message => {
if (!message.content.startsWith(prefix)) return;
const withoutPrefix = message.content.slice(prefix.length);
const split = withoutPrefix.split(/ +/);
const command = split[0];
const args = split.slice(1);
if (command === 'avatar') {
let targetMember;
if(!message.mentions.members.first()) {
targetMember = message.guild.members.get(message.author.id);
} else {
targetMember = message.mentions.members.first()
}
let avatarEmbed = new Discord.RichEmbed()
.setImage(targetMember.user.displayAvatarURL)
.setColor(targetMember.displayHexColor);
message.channel.send(avatarEmbed);
}
});