Can I create a channel at bot on startup? - javascript

I'm trying to create a channel with Discord.js using the message.guild.createChannel function. But, I need to send a message on the server for the bot to do that. How can I do it at the bot startup ? I think I need to implement my code into the bot.on('ready', () => { function, but I don't know how. Thanks !
This is my code:
var firstLog = false;
bot.on('message', msg => {
if (!firstLog) {
msg.guild.createChannel('raidprotect-logs', "text")
} firstLog = true;
});

You need use somethink like this if you want use it on message
var firstLog = false;
bot.on('message', msg => {
if (!firstLog) msg.guild.createChannel('new-general', { type: 'text' })
firstLog = true;
});
If you want you use it when bot start , you need get guild fist.
bot.on('ready', () => {
let myGuild = bot.guilds.get('GUILDID HERE')
myGuild.createChannel('new-general', { type: 'text' })
.then(console.log(“done”))
.catch(console.error);
});

You're almost there. Here's how you do it
bot.on('ready', () => {
guild.createChannel('new-general', { type: 'text' })
.then(console.log)
.catch(console.error);
});
As they suggested here
You can find more help on Discord.js Official discord server

Related

My code for autorole doesn't work and I can't figure out why

const { Client, Intents } = require("discord.js");
const client = new Client({
intents: ["DIRECT_MESSAGES", "GUILDS", "GUILD_MEMBERS"],
presence: {
status: "online",
activities: [{
name: "markets",
type: "WATCHING"
}]
},
});
client.on('ready', () => {
console.log(`Launched as a bot: ${client.user.tag}!`);
});
client.on('guildMemberAdd', member => {
function roleAdd() {
member.roles.add(member.guild.roles.cache.get(process.env.SERVER_ROLE_ID));
}
roleAdd();
});
client.login(process.env.DJS_TOKEN);
Guys I wrote this code but it is not working. I am not getting any errors. I want it to add a role whenever a user joins to my server. the status of the bot is working. I think the issue is on the guildMemberAdd part.
Im not quite sure why you're using the approach of nested functions for this. If you want the event to call the function move the function outside of the event and then create the GuildMember in a parameter.
Or discard the event entirely and leave the plain #<GuildMemberRoleManager>.add method by itself.
I suggest the latter as I assume the nested function declaration wont work.
If you wanted to use auto role add for your server, try the easiest method to do the role add, same way as giving role to a member
When you giving a role to specific member should look like this:
const role = message.guild.roles.cache.find(role => role.id === process.env.SERVER_ROLE_ID)
const target = message.mentions.members.first() || await message.guild.members.cache.get(args[0])
If a bot giving a role higher than the bot or equal to bot. You will get an error such as Missing Permissions To prevent this you need to put a code to return it
if(!target.moderatable) return message.reply("I can't mute this person!")
This command is a same way for auto give role, just a few code lines added/edited/removed.
client.on('guildMemberAdd', member => {
function roleAdd() {
member.roles.add(member.guild.roles.cache.get(process.env.SERVER_ROLE_ID));
}
roleAdd();
});
- function roleAdd() {}
+ let role = member.guild.roles.cache.find(role => role.id == process.env.SERVER_ROLE_ID)
+ member.roles.add(role).catch()
The .catch() line is to prevent on giving error and shutdown your bot.
client.on('guildMemberAdd', member => {
let role = member.guild.roles.cache.find(role => role.id == process.env.SERVER_ROLE_ID)
member.roles.add(role).catch()
});

How do I create a slash command in discord using discord.js

I am trying to create a slash command for my discord bot, but I don't know how to execute code when the command is exuted
The code I want to use will send a message to a different channel (Args: Message)
Here is the code I want to use
const channel = client.channels.cache.find(c => c.id == "834457788846833734")
channel.send(Message)
You need to listen for an event interactionCreate or INTERACTION_CREATE. See the code below, haven't tested anything, hope it works.
For discord.js v12:
client.ws.on("INTERACTION_CREATE", (interaction) => {
// Access command properties
const commandId = interaction.data.id;
const commandName = interaction.data.name;
// Do your stuff
const channel = client.channels.cache.find(c => c.id == "834457788846833734");
channel.send("your message goes here");
// Reply to an interaction
client.api.interactions(interaction.id, interaction.token).callback.post({
data: {
type: 4,
data: {
content: "Reply message"
}
}
});
});
For discord.js v13:
client.on("interactionCreate", (interaction) => {
if (interaction.isCommand()) {
// Access command properties
const commandId = interaction.commandId;
const commandName = interaction.commandName;
// Do your stuff
const channel = client.channels.cache.find(c => c.id == "834457788846833734")
channel.send("your message goes here");
// Reply to an interaction
interaction.reply("Reply message");
}
});

Discord.js Embed error Cannot send an empty message

so I'm trying to make a help command with list of commands showed in embed. My code kinda works but it throws an error "DiscordAPIError: Cannot send an empty message" and I've tried already everything I know and what I've found but I can't fix it.
Here's the code
const Discord = require('discord.js');
const { prefix } = require('../config.json');
module.exports = {
name: 'help',
description: 'List all of my commands or info about a specific command.',
aliases: ['commands', 'cmds'],
usage: '[command name]',
cooldown: 5,
execute(msg, args) {
const data = [];
const { commands } = msg.client;
if (!args.length) {
const helpEmbed = new Discord.MessageEmbed()
.setColor('YELLOW')
.setTitle('Here\'s a list of all my commands:')
.setDescription(commands.map(cmd => cmd.name).join('\n'))
.setTimestamp()
.setFooter(`You can send \`${prefix}help [command name]\` to get info on a specific command!`);
msg.author.send(helpEmbed);
return msg.author.send(data, { split: true })
.then(() => {
if (msg.channel.type === 'dm') return;
msg.reply('I\'ve sent you a DM with all my commands!');
})
.catch(error => {
console.error(`Could not send help DM to ${msg.author.tag}.\n`, error);
msg.reply('it seems like I can\'t DM you! Do you have DMs disabled?');
});
}
const name = args[0].toLowerCase();
const command = commands.get(name) || commands.find(c => c.aliases && c.aliases.includes(name));
if (!command) {
return msg.reply('that\'s not a valid command!');
}
data.push(`**Name:** ${command.name}`);
if (command.aliases) data.push(`**Aliases:** ${command.aliases.join(', ')}`);
if (command.description) data.push(`**Description:** ${command.description}`);
if (command.usage) data.push(`**Usage:** ${prefix}${command.name} ${command.usage}`);
data.push(`**Cooldown:** ${command.cooldown || 3} second(s)`);
msg.channel.send(data, { split: true });
},
};
You should try replace this line :
msg.channel.send(data, { split: true });
with
msg.channel.send(data.join(' '), { split: true }); since your data variable is an array and not a string
The problem is as the error states. You are trying to send an empty message somewhere.
You can try replacing msg.channel.send(data) with msg.channel.send(data.join('\n')), since the data variable is an array.
I don't see why sending an array doesn't work though.

How to exclude something from forEach on discord.js

so I am in discord.js and was making a command, which would kick everybody from the server. The thing is, I wanted to kick everyone except me, and I don't know how to do that, nor did I find any tutorial on it. Here is my code:
bot.on("message", async message => {
if(message.content.startsWith(`${prefix}gone`)) {
message.guild.members.cache.forEach(member => member.ban())
}
}
)
I would love is someone would help. Thank you in advance+
Try something like this:
const MY_USER_ID = 'your user id'
bot.on("message", async message => {
if(message.content.startsWith(`${prefix}gone`)) {
message.guild.members.cache.forEach(member => {
if (member.id !== MY_USER_ID) {
member.ban()
}
})
}
})
In your .forEach() loop you need to add a check to see if the member has the same ID as you so you could do this two ways:
Either by making the bot ignore the user who typed in the command:
message.guild.members.cache.forEach(member => {
if (member.id !== message.author.id) member.ban()
})
Or if you want to just make it not ban you specifically then:
message.guild.members.cache.forEach(member => {
if (member.id !== 'USER_ID') member.ban()
})
You can also write those checks inside of a .filter() like so:
message.guild.members.cache.filter(member => member.id !== 'USER_ID').forEach(member => member.ban())

Javascript SlackBot postMessage function is spamming messages

I am trying to set up a slack bot using javascript and a few helpful libraries.
All it does is run a postMessageToChannel Method when a user of the channel mentions a certain keyword " help"
My issue is when the runHelp() function is called it doesn't just post one message to the slack #channel but many. Maybe i am missing something here that someone can help me figure out.
Thanks,
Here's the js:
const SlackBot = require('slackbots');
const axios = require('axios')
const dotenv = require('dotenv')
dotenv.config()
const bot = new SlackBot({
token: `${process.env.BOT_TOKEN}`,
name: 'helpit-bot'
});
// Start Handler
bot.on('start', () => {
const params = {
icon_emoji: ':nerd_face:'
}
bot.postMessageToChannel('slack-bot', 'HELP IS ON THE WAY', params);
})
// Error Handler
bot.on('error', (err) => {
console.log(err);
});
// Message Handler
bot.on('message', (data) => {
if(data.type !== 'message') {
return;
}
handleMessage(data.text);
return;
})
// Response Handler
function handleMessage(message) {
if(message.includes(' help')) {
runHelp();
} else {
// Run something else
}
}
// Show Help
function runHelp() {
const params = {
icon_emoji: ':question:'
}
bot.postMessageToChannel('slack-bot', 'This is an automated help message', params);
}
Result:
Created an infinite loop because "This is an automated help message" includes the text "help" which triggers the bot. -.-

Categories