ROBLOX Discord bot - javascript

I'm trying to create a discord bot that connects to a Roblox account that I made.
I'm trying to create a command that will shout a message in a group, but there's a problem at the login and I can't figure out how to fix the problem.
let roblox = require('noblox.js');
const { Client } = require("discord.js");
const { config } = require("dotenv");
const client = new Client({
disableEveryone: true
});
config({
path: __dirname + "/.env"
});
let prefix = process.env.PREFIX
let groupId = groupid;
client.on("ready", () => {
console.log("I'm Ready!");
function login() {
roblox.cookieLogin(process.env.COOKIE)
}
login()
.then(function () {
console.log(`Logged in to ${username}`);
})
.catch(function (error) {
console.log(`Login error: ${error}`);
});
client.on("message", async message => {
console.log(`${message.author.username} said: ${message.content}`);
if (message.author.bot) return;
if (message.content.indexOf(prefix) !== 0) return;
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if (command === "shout") {
if (!args) {
return;
message.reply("You didn't specify a message to shout.")
}
const shoutMSG = args.join(" ");
roblox.shout(groupId, shoutMSG)
.then(function() {
console.log(`Shouted ${shoutMSG}`);
})
.catch(function(error) {
console.log(`Shout error: ${error}`)
});
}
})
client.login(process.env.TOKEN);
It gives me the error:
Shout error: Error: Shout failed, verify login, permissions, and message

At the first you don`t close you client.on('ready') state.
if (!args) {
return;
message.reply("You didn't specify a message to shout.")
}
This funcyion will never reply, because you use return, before reply.
Your groupId looks like undefined, because you declarate it let groupId = groupid;, so this is the one way, why got you got this error.
let roblox = require('noblox.js');
const { Client } = require("discord.js");
const { config } = require("dotenv");
const client = new Client({
disableEveryone: true
});
config({
path: __dirname + "/.env"
});
let prefix = process.env.PREFIX
let groupId = groupid;
client.on("ready", () => {
console.log("I'm Ready!");
})
function login() {
roblox.cookieLogin(process.env.COOKIE)
}
login()
.then(function () {
console.log(`Logged in to ${username}`);
})
.catch(function (error) {
console.log(`Login error: ${error}`);
});
client.on("message", async message => {
console.log(`${message.author.username} said: ${message.content}`);
if (message.author.bot) return;
if (message.content.indexOf(prefix) !== 0) return;
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if (command === "shout") {
if (!args) return message.reply("You didn't specify a message to shout.")
const shoutMSG = args.join(" ");
roblox.shout(groupId, shoutMSG)
.then(function() {
console.log(`Shouted ${shoutMSG}`);
})
.catch(function(error) {
console.log(`Shout error: ${error}`)
});
}
})
client.login(process.env.TOKEN);

Related

TypeError: command.run is not a function

I'm kinda new to coding and i cannot figure this out. im trying to add permission handler and when i run a slash command, it responds within the error given below.
error:
D:\VS Code\######\events\interactionCreate.js:9
command.run(client, inter)
^
TypeError: command.run is not a function
code (interactionCreate):
const { MessageEmbed, Message, Interaction } = require("discord.js")
const client = require("../index").client
client.on('interactionCreate', async inter => {
if(inter.isCommand()) {
const command = client.commands.get(inter.commandName);
if(!command) return;
command.run(client, inter)
if (command.help?.permission) {
const authorPerms = inter.channel.permissionsFor(inter.member);
if (!authorPerms || !authorPerms.has(command.permission)) {
const noPerms = new MessageEmbed()
.setColor('RED')
.setDescription(`bruh no perms for ya: ${command.permission}`)
return inter.editReply({embeds: [noPerms], ephemeral: true})
.then((sent) =>{
setTimeout(() => {
sent.delete()
}, 10000)
})
return;
}
}
}
}
)
this is how one of my command file looks like, its a handler which goes "commands > moderation > ban.js"
const { MessageEmbed, Message } = require("discord.js")
module.exports.run = async (client, inter) => {
const user = inter.options.getUser('user')
let BanReason = inter.options.getString('reason')
const member = inter.guild.members.cache.get(user.id)
if(!BanReason) reason = 'No reason provided.'
const existEmbed = new MessageEmbed()
.setColor('#2f3136')
.setDescription('<:pending:961309491784196166> The member does not exist in the server.')
const bannedEmbed = new MessageEmbed()
.setColor('#46b281')
.setDescription(`<:success:961309491935182909> Successfully banned **${user.tag}** from the server with the reason of: **${BanReason}**.`)
const failedEmbed = new MessageEmbed()
.setColor('#ec4e4b')
.setDescription(`<:failed:961309491763228742> Cannot ban **${user.tag}**. Please make sure I have permission to ban.`)
if(!member) return inter.reply({ embeds: [existEmbed]})
try {
await inter.guild.members.ban(member, { reasons: BanReason })
} catch(e) {
return inter.reply({ embeds: [failedEmbed]})
}
inter.reply({ embeds: [bannedEmbed]})
}
module.exports.help = {
name: 'ban',
permission: 'BAN_MEMBERS'
}
btw inter = interaction

ReferenceError: client is not defined Discord.js

I cannot figure out why its saying this error here, its telling me that client isnt defined when it is defined right here though im also unsure of anything else that im missing because all of my code so far has been from the offical documentation of discord.js
(The guild and client id's have been removed for privacy reasons)
Code:
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { token } = require('./config.json');
const fs = require('fs');
const commands = [];
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
// Place your client and guild ids here
const clientId = '';
const guildId = '';
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
commands.push(command.data.toJSON());
}
const rest = new REST({ version: '9' }).setToken(token);
(async () => {
try {
console.log('Started refreshing application (/) commands.');
await rest.put(
Routes.applicationCommands(clientId),
Routes.applicationGuildCommands(clientId, guildId),
{ body: commands },
);
console.log('Successfully reloaded application (/) commands.');
} catch (error) {
console.error(error);
}
})();
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.data.name, command);
}
client.once('ready', () => {
console.log(`${client.user.tag}`)
});
const eventFiles = fs.readdirSync('./events').filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const event = require(`./events/${file}`);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args));
} else {
client.on(event.name, (...args) => event.execute(...args));
}
}
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
return interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
});
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const { commandName } = interaction;
if (commandName === 'ping') {
await interaction.reply('Pong!');
} else if (commandName === 'server') {
await interaction.reply(`Server name: ${interaction.guild.name}\nTotal members: ${interaction.guild.memberCount}`);
} else if (commandName === 'user') {
await interaction.reply(`Your tag: ${interaction.user.tag}\nYour id: ${interaction.user.id}`);
}
});
client.on('interactionCreate', interaction => {
if (!interaction.isCommand()) return;
console.log(interaction);
});
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
if (interaction.commandName === 'ping') {
await interaction.reply('Pong!');
}
});
client.login(token);
You need to instantiate a Discord.Client in order to get access to discord.js apis.
const {Client, Intents} = require('discord.js')
const client = new Client({intents: [/* Your intents here */]})
client.login(/* your token */)
client.on('ready', function () {
/* client is ready */
}
Since discord.js v12, intents were introduced, so you will also need to use them.
More about intents: https://discordjs.guide/popular-topics/intents.html#error-disallowed-intents

Discord.js: Add role to message sender

i am trying to make a discord.js bot that adds a role to a user when they type: +rolename .
This is what I have come up with:
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"
});
client.on("ready", () => {
console.log(`Hi, ${client.user.username} is now online!`);
client.user.setStatus('online');
client.user.setActivity('me getting developed', { type: "WATCHING"})
.then(() => console.log('bot status set'))
.catch(console.error);
});
client.on("message", (message) => {
if (message.content.startsWith("+")) {
var args = message.content.split(' ');
if (args.length == 1) {
console.log(`message is created -> ${message}`);
const { guild } = message;
var passrole = args[0];
var roleid = passrole.substring(1);
var role = message.guild.roles.cache.find((role) => {
return role.name == roleid;
});
console.log('role found')
var authoruser = message.author.id;
if (!role) {
message.reply('this role does not exist')
console.log('role does not exist')
return;
}
console.log(target)
authoruser.roles.add(role)
console.log("role added")
} else {
message.reply('invalid argument length passed')
return;
}
} else {
return;
}
});
client.login(process.env.TOKEN);
When running the code i get the following error:
TypeError: Cannot read property 'add' of undefined
This doesn't happen when I use this code and type +test #DiscordName#0001:
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"
})
client.on("ready", () => {
console.log(`Hi, ${client.user.username} is now online!`);
client.user.setStatus('online');
client.user.setActivity('me getting developed', { type: "WATCHING"})
.then(presence => console.log('bot status set'))
.catch(console.error);
});
client.on("message", (message) => {
let target = message.mentions.members.first();
if (message.content.startsWith("+")) {
var args = message.content.split(' ');
if(args.length == 2){
console.log(`message is created -> ${message}`);
const { guild } = message;
var passrole = args[0]
var roleid = passrole.substring(1);
var role = message.guild.roles.cache.find((role) => {
return role.name == roleid;
})
console.log('role found')
if (!role) {
message.reply('role does not exist')
console.log('role does not exist')
return;
}
console.log(target)
target.roles.add(role)
console.log("role added")
} else {
message.reply('invalid argument length passed')
return;
}
} else {
return;
}
});
client.login(process.env.TOKEN);
My question is: How can I add the role to the message author.
Thanks in advance
The problem is that your authoruser is the users id (= string) not the member. You cannot add roles to users. Also if you get the role's id and not the name of the role you can add the role with the role's id.
client.on("message", message =>{
if (message.content.startsWith("+")) {
var args = message.content.split(' ');
if (args.length !== 1) {
message.reply('invalid argument count passed');
return;
}
if (!message.member ||!message.guild) {
message.reply('can only be used in guilds');
return;
}
console.log(`message is created -> ${message}`);
const { guild } = message;
var passrole = args[0];
var roleid = passrole.substring(1);
// If you get the role's id then you won't need this
var role = message.guild.roles.cache.find((role) => role.name == roleid);
if (!role) {
message.reply('this role does not exist');
console.log('role does not exist');
return;
}
console.log('role found');
console.log(target);
message.member.roles.add(role);
// If you get the role's id use this:
message.member.roles.add(roleid);
console.log('role added');
});

I'm having issues in Discord.js with functions like client.users.cache.size

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

Discord.js Cannot read property 'name'

can someone help me fix this error? It's causing me some critical damage.
const Discord = require('discord.js');
const config = require('./config.json');
const bot = new Discord.Client();
const cooldowns = new Discord.Collection();
const fs = require('fs');
bot.commands = new Discord.Collection();
fs.readdir('./commands/', (err, files) => {
if (err) console.log(err);
let jsfile = files.filter((f) => f.split('.').pop() === 'js');
if (jsfile.length <= 0) {
console.log('No Commands fonud!');
return;
}
jsfile.forEach((f, i) => {
let props = require(`./commands/${f}`);
console.log(`${f} loaded!`);
bot.commands.set(props.help.name, props);
});
fs.readdir('./events/', (error, f) => {
if (error) console.log(error);
console.log(`${f.length} Loading events...`);
f.forEach((f) => {
const events = require(`./events/${f}`);
const event = f.split('.')[0];
client.on(event, events.bind(null, client));
});
});
});
let statuses = ['By LeRegedit#1281', 'Prefix => !', 'V1.0', 'Coming Soon'];
bot.on('ready', () => {
console.log(bot.user.username + ' is online !');
setInterval(function() {
let status = statuses[Math.floor(Math.random() * statuses.length)];
bot.user.setPresence({ activity: { name: status }, status: 'online' });
}, 10000);
});
bot.on('message', async (message) => {
if (message.author.bot) return;
if (message.channel.type === 'dm') return;
let content = message.content.split(' ');
let command = content[0];
let args = content.slice(1);
let prefix = config.prefix;
let commandfile = bot.commands.get(command.slice(prefix.length));
if (commandfile) commandfile.run(bot, message, args);
if (!message.content.startsWith(prefix)) return;
});
bot.login(config.token);
Type Error: Cannot read property 'name' of undefined

Categories