Bot sends a embed when joins a server - discord

Im trying to make my bot send a embed in the server that it joins (E.G a thank you for inviting and what the bot can do).This is the error that I am getting.
const channel = message.guild.channels.cache.find(channel => channel.type === 'text' && client.user.me.permissions.has("send_messages"))
^
TypeError: Cannot read properties of undefined (reading 'channels')
this is the code that i am using in the index.js file
client.on('guildCreate', message => {
const channel = message.guild.channels.cache.find(channel => channel.type === 'text' && client.user.me.permissions.has("send_messages"))
const embed = new MessageEmbed()
.setColor('GREEN')
.setTitle('Thank You')
.setDescription("Thank you for inviting Rynwin to your server. To get the command list please do /help.\n \n The default Bot prefix is ```<```")
.addFields([
{
name: "Our Support Server",
value: "If you require assistance or would like to get daily bot updates please join our support discord [here] ()"
},
{
name: "Commands",
value: "Try some of these commands; \n\n**/prefix <prefix>** - Sets the server prefix\n\n**/help** - Get the command list or information on a command \n\n**/botinfo** - Shows info on the bot"
},
channel.send({ embeds: [embed] })
])

There are a few things wrong on the first 2 lines. Firstly, guildCreate gives a Guild instance, not a message. Secondly, you aren't checking the correct channel type or permission. Here is the fixed code:
client.on('guildCreate', guild => {
const channel = guild.channels.cache.find(channel => channel.type === 'GUILD_TEXT' && guild.me.permissions.has("SEND_MESSAGES"))
// GUILD_TEXT channel type, guild.me for client guild member, and uppercase permission
// rest of code...
}

Related

Always getting back an, "Internal Server Error," when trying to run ban command on my Discord bot

I have tried many different ways of formatting the code, however, whenever I add code so that I must provide a reasoning to ban someone, I am always given an Internal Server Error. Here is my code.
module.exports.run = async (client, message, args) => {
const member = message.mentions.members.first();
const reason = args.slice(1).join(" ")
if (!message.member.hasPermission("BAN_MEMBERS")) {
return message.reply("you lack sufficiant permissions to execute this command.");
} else if (member.hasPermission("ADMINISTRATOR")) {
message.reply("you cannot ban this member.")
}
member.ban(reason).then((member) => {
message.channel.send(`${member} has been banned.`);
});
I use a command handler, and all my other commands work fine.
first step: Define the user
let user = message.mentions.members.first() || message.guild.members.cache.get(args.join(' '));
Second step: Create embed message or normal message
const userbanned = new Discord.MessageEmbed()
.setColor('#FF0000')
.setAuthor('User Banned')
.setDescription(`**${user.user.username}#${user.user.discriminator}** is now banned from this server`)
.setFooter(`bot_name`);
Third step: Send message
user.send(`You were banned from **${message.guild.name}** by ${message.author.username}#${message.author.discriminator}`)
return user
.ban()
.then(() => message.channel.send(userbanned))
.catch(error => message.reply("ERROR"));
Try changing
member.ban().then((member) =>//
to
member.ban({reason : args.slice(1).join(' ')}).then((member) =>//

Send DMed files and links to channel in server

Okay. This might be a strange question, but I need help as I could not find anything online. I have a discord bot and server that is hosts a competition, and users submit their submissions by Direct Messaging me a link or file of their submission. I would like to change this to them DMing the bot instead, and the bot posting the links and files in a certain channel in the server. I have absolutely no clue how to achieve this as I am kind of a novice when it comes to this sort of thing. Please comment if I need to change my wording or need to clarify anything!
Replace channel id with the actual id of the channel that you want to send the submissions to.
For Discord.js v12/v13 (the latest version):
client.on('message', ({attachments, author, content, guild}) => {
// only do this for DMs
if (!guild) {
// this will simply send all the attachments, if there are any, or the message content
// you might also want to check that the content is a link as well
const submission = attachments.size
? {files: [...attachments.values()], content: `${author}`}
: {content: `${content}\n${author}`}
client.channels.cache.get('channel id').send(submission)
}
})
For Discord.js v11 replace
client.channels.cache.get('channel id').send(submission)
with
client.channels.get('channel id').send(submission)
In the message event, you can check if the message is in a dm channel then you can take the message content and send it to a specific channel as an embed.
Your solution would be:
client.on('message', (message) => {
if (message.channel.type === 'dm') {
const channel = client.guilds.cache.get("GUILD_ID").channels.cache.get("CHANNEL_ID");
const embed = new Discord.MessageEmbed()
.setAuthor(message.author.tag, message.author.avatarURL())
.setColor('RANDOM')
.setDescription(message.content)
channel.send(embed);
if (message.attachments.array().length) {
message.attachments.forEach((attachment) => channel.send({ files: [ attachment ] }))
}
}
})

Add roles to users in specific guild through DM

When I try
message.member.roles.add('695699359634817094');
I get the following error:
TypeError: Cannot read property 'add' of undefined
Is there a specific way to add my guild ID and update their role to that specific server through DM?
My function works within the guild by calling the command, however, through DM it doesn't.
You could do this by using message.author.id to get the user's ID and then using guild.get(guild_ID).members.fetch(user_ID) to access the GuildMember of that user.
You also mentioned that you give users the ability to run that command either in DM or a text channel in your guild.
If that is the case I would suggest adding a check to see if the command is being sent to a text channel or dm channel.
if (message.channel.type === "dm") {
const member = await client.guilds.get(guild_ID).members.fetch(message.author.id);
member.roles.add(role_ID);
} else {
message.member.roles.add('695699359634817094');
}
Ignore the if statement if you intend on having the command only run from dm.
By using the info given from Syntle and tipakA this is the solution.
if (message.channel.type === "dm") {
client.guilds.get('[SeverId]').members.fetch(message.author.id).then(async () => {
await client.guilds.get('[ServerId]').members.fetch(message.author.id).then((memberid) => {
memberid.roles.add('[roleid]');
}).catch((err) => {
console.log("ERROR");
});
});
}
else
{
message.member.roles.add('[roleid]');
}

DiscordJS Backdoor Command

I have had reports off my support server of my discord js bot of my bot being abused in multiple ways.
I want to have a way upon launch of my bot to see a list of servers as well as invite links to those servers. I do not know the id of server or anything.
The most I've managed to find out how to do is this
var server = client.guilds.get("idk the id part");
console.log('I am in the following servers:');
server.createInvite().then(invite =>
console.log(server.name + "-" + invite.url)
);
});```
In your ready event (client.on('ready', () => {}), add the following lines:
client.guilds.tap(guild => {
console.log(`Name: ${guild.name} ID: ${guild.id}`);
})
This should output
Name: Test1 ID: 00000000000000
in the console for each server.
Also, considering that making a lot of invites might clog up your bot, and is generally more of a hindrance than help to server admins, you might consider making a createinvite command:
const svID = args[0];
const guild = client.guilds.find(guild => guild.id === svID);
const channel = guild.channels.find(channel => channel.position === 1);
channel.createInvite()
.then(invite => message.reply(invite.code));
You can either wait for the bot to emit it's ready event and loop through the guild collection:
client.once('ready', () => {
// client.guilds should be ready
});
or handle each guild individually:
client.on('guildCreate', (guild) => {
// The guild the bot just joined/connected to
// Should also be emitted when the bot launches
});
Either should work, but my recommendation would be the second approach, as this will also allow you to track join events whilst the bot is running.

Send is not a function discord.js

I am trying to send a message to channel but I keep getting Error: send is not a function.I have been stuck on this problem for over an hour.
What I have tried:
using sendMessage
tried reading the discord.js documentation but it doesnt seem to be working at all.
Here is my code:
//Grab the Discord Library
const Discord = require("discord.js");
//What will connect to the server.
const bot = new Discord.Client();
//
bot.on('ready', () => {
console.log("Connected as " + bot.user.tag)
//Shows and set the activity of the user.
bot.user.setActivity("El Professor build me", {type: "Watching"})
//Inform you of the servers this bot is connected to.
bot.guilds.forEach((guild) => {
console.log(guild.name)
guild.channels.forEach((channel) => {
console.log(` - ${channel.name} ${channel.type} ${channel.id}`)
})
//Voice Channel ID =
})
var generalChannel = bot.channels.get("123456789").send("Hello World")
})
Error message:
C:\Users\F4_ALFA\documents\FirstDiscordBot\index.js:21
var generalChannel = bot.channels.get("123456789").send("Hello World")
^
TypeError: bot.channels.get(...).send is not a function
at Client.bot.on (C:\Users\F4_ALFA\documents\FirstDiscordBot\index.js:21:63)
at Client.emit (events.js:194:15)
at WebSocketConnection.triggerReady (C:\Users\F4_ALFA\documents\FirstDiscordBot\node_modules\discord.js\src\client\websocket\WebSocketConn
ection.js:125:17)
at WebSocketConnection.checkIfReady (C:\Users\F4_ALFA\documents\FirstDiscordBot\node_modules\discord.js\src\client\websocket\WebSocketConn
ection.js:141:61)
at GuildCreateHandler.handle (C:\Users\F4_ALFA\documents\FirstDiscordBot\node_modules\discord.js\src\client\websocket\packets\handlers\Gui
ldCreate.js:13:31)
at WebSocketPacketManager.handle (C:\Users\F4_ALFA\documents\FirstDiscordBot\node_modules\discord.js\src\client\websocket\packets\WebSocke
tPacketManager.js:103:65)
at WebSocketConnection.onPacket (C:\Users\F4_ALFA\documents\FirstDiscordBot\node_modules\discord.js\src\client\websocket\WebSocketConnecti
on.js:333:35)
at WebSocketConnection.onMessage (C:\Users\F4_ALFA\documents\FirstDiscordBot\node_modules\discord.js\src\client\websocket\WebSocketConnect
ion.js:296:17)
at WebSocket.onMessage (C:\Users\F4_ALFA\documents\FirstDiscordBot\node_modules\ws\lib\event-target.js:120:16)
at WebSocket.emit (events.js:189:13)
Discord.js uses cache and your code has no '.cache', you should try
bot.channels.cache.get('id').send('Hello world!')
The channels property returns a Collection with pair of ID and Channel object.
The Channel class could represent any channel in discord. You couldn't send any messages through it because it doesn't have send() method.
I’ve used this before client.guilds.find(x => x.name === "ChatLogs").channels.find(y => y.name === "server-testing1").send(botEmbed) try that

Resources