Discord move bot - javascript

I'm trying to make a boot that, after entering the command >summon #nick, starts moving the user from one rooom to another, here's the problem:
CODE:
const Discord = require('discord.js');
const client = new Discord.Client();
const guild = new Discord.Guild(client, Object);
module.exports = {
name: 'summon',
description: "Vyvolá člověka",
execute(message, args) {
const times = 6;
let i = 0;
const member = message.mentions.members.first();
const channel1 = message.guild.members.cache.get("689511445519794177");
const channel2 = message.guild.members.cache.get("774780272738566194");
if(member == null){
message.channel.send("Nezadal jsi uživatele!");
console.log("Špatné použití příkazu.");
} else {
Discord.GuildMember.setVoiceChannel(channel1);
message.channel.send("debug1");
Discord.GuildMember.setVoiceChannel(channel2);
message.channel.send("debug2");
}}
};
ERROR IS:
PS C:\Users\-----\Desktop\------\----> node .
MilanCXL je online!
C:\Users\----\Desktop\-----\------\commands\summon.js:26
Discord.GuildMember.setVoiceChannel(channel1);
^
TypeError: Discord.GuildMember.setVoiceChannel is not a function
at Object.execute (C:\Users\----\Desktop\----\-----\commands\summon.js:26:33)
at Client.<anonymous> (C:\Users\---\Desktop\----\-----\main.js:39:39)
Thanks for respond,
ancle FIX

Presumably you want member.setVoiceChannel(channel1) and not Discord.GuildMember.setVoiceChannel(channel1);?

Related

Discord.js Replit, cannot get my bot to respond to commands

I am currently developing a Discord bot for replit, and I am able to get it to post and even get it to send an intro message when joining a server, however whenever I try to get it to respond to a command I type it won't respond. The message for the first one client.on guild create works. However the client.on for async message will not work.
This is what I have so far.
const { Client } = require('discord.js');
const client = new Client({ intents: 32767 });
//const Discord = require('discord.js');
const keepAlive = require('./server');
require("dotenv").config();
//const client = new Discord.Client();
//const fetch = require('node-fetch');
const config = require('./package.json');
const prefix = '!';
const guild = "";
client.once('ready', () => {
console.log('Jp Learn Online');
});
// let defaultChannel = "";
// guild.channels.cache.forEach((channel) => {
// if(channel.type == "text" && defaultChannel == "") {
// if(channel.permissionsFor(guild.me).has("SEND_MESSAGES")) {
// defaultChannel = channel;
// }
// }
// })
//defaultChannel.send("This is a test message I should say this message when I join");
//if(guild.systemChannelId != null) return guild.systemChannel.send("This is a test message I should say this message when I join"), console.log('Bot entered new Server.')
// client.on('guildCreate', (g) => {
// const channel = g.channels.cache.find(channel => channel.type === 'GUILD_TEXT' && channel.permissionsFor(g.me).has('SEND_MESSAGES'))
// channel.send("This is a test message I should say this message when I join");
// });
client.on('guildCreate', guild => {
guild.systemChannel.send('this message wil print')
});
client.on('message', async message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/); // This splits our code into to allow multiple commands.
const command = args.shift().toLowerCase();
if (command === 'jhelp') {
message.channel.send('こんにちは、私はDiscordロボットです。始めたいなら、!jhelp タイプしてください。 \n\n Hello I am a discord bot built to help learn the Japanese language! \n\n If you want to access a japanese dictionary type !dictionary \n\n If you would like to learn a random Japanese Phrase type !teachme \n\n If you would like to answer a challenge question type !challenge1 through 5 each different numbered challnege will ask a different question \n (ie. !challenge1) this will ask the first question.')
}
please note. the lower parts of the code are simply commands. That expand further from jhelp I want to know mainly why my second client.on with messages wont work specifically in the context of working with replit.
Thanks for the help in advance.
I expected that maybe changing intents might work, I even went into the discord developer portal, and enabled options, and am still not able to get it working.
After Discord separated out the message intent as a privileged one, the bit field you need to use for all intents has changed. You need to use 131071.
I.e.
const { Client } = require('discord.js');
const client = new Client({ intents: 131071 });
//const Discord = require('discord.js');
const keepAlive = require('./server');
require("dotenv").config();
//const client = new Discord.Client();
//const fetch = require('node-fetch');
const config = require('./package.json');
const prefix = '!';
const guild = "";
client.once('ready', () => {
console.log('Jp Learn Online');
});
// let defaultChannel = "";
// guild.channels.cache.forEach((channel) => {
// if(channel.type == "text" && defaultChannel == "") {
// if(channel.permissionsFor(guild.me).has("SEND_MESSAGES")) {
// defaultChannel = channel;
// }
// }
// })
//defaultChannel.send("This is a test message I should say this message when I join");
//if(guild.systemChannelId != null) return guild.systemChannel.send("This is a test message I should say this message when I join"), console.log('Bot entered new Server.')
// client.on('guildCreate', (g) => {
// const channel = g.channels.cache.find(channel => channel.type === 'GUILD_TEXT' && channel.permissionsFor(g.me).has('SEND_MESSAGES'))
// channel.send("This is a test message I should say this message when I join");
// });
client.on('guildCreate', guild => {
guild.systemChannel.send('this message wil print')
});
client.on('messageCreate', async message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/); // This splits our code into to allow multiple commands.
const command = args.shift().toLowerCase();
if (command === 'jhelp') {
message.channel.send('こんにちは、私はDiscordロボットです。始めたいなら、!jhelp タイプしてください。 \n\n Hello I am a discord bot built to help learn the Japanese language! \n\n If you want to access a japanese dictionary type !dictionary \n\n If you would like to learn a random Japanese Phrase type !teachme \n\n If you would like to answer a challenge question type !challenge1 through 5 each different numbered challnege will ask a different question \n (ie. !challenge1) this will ask the first question.')
}
Yes! its the problem with your intents, for guildMemberAdd/Remove you require GuildMembers intents

discord.js "TypeError: Cannot read property 'execute' of undefined" with async function in command file

I'm trying to add a command code under the command file, but i'm unable to get it to work. The problem arises at this line => if (command == 'checkin' || command == 'ch') {
client.commands.get('chk').execute(message).
Without that line, the code works fine with the other 2 commands. I think it has to do with the async function but I'm not sure how to solve this problem. I don't want to include the whole chunk of code in the main file either, as it gets very long and cluttered. I'm new to coding, so it might be something I can't understand yet - please help me!
bot.js (the main .js file)
const { token, prefix } = require('./config.json');
const fs = require('fs');
const db = require('quick.db');
const ms = require('parse-ms-2')
const { Client, Intents, Message, Collection } = require("discord.js");
const client = new Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES
]
});
client.commands = new Discord.Collection();
// filter commands
const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
// fetch commands
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
client.once("ready", () => {
console.log("online.");
client.user.setPresence({ activties: [{ name: 'with commands' }] });
})
client.on('messageCreate', async message => {
// definite command components
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase()
if (command == 'help' || command == 'h') {
client.commands.get('help').execute(message)
}
if (command == 'bal') {
client.commands.get('bal').execute(message)
}
if (command == 'checkin' || command == 'ch') {
client.commands.get('chk').execute(message)
}
})
client.login(token)
chk.js (where the command is)
const db = require('quick.db')
const nm = require('parse-ms-2')
module.exports = {
name: "check in",
descrption: "daily check in rewards.",
async execute(message) {
let user = message.mentions.users.first() || message.author;
let daily = await db.fetch(`daily_${message.author.id}`);
let money = db.fetch(`money_${user.id}`);
let cooldown = 1000*60*60*20
let amount = Math.floor(Math.random() * 500) + 250
if (daily != null && cooldown - (Date.now() - daily) > 0) {
let time = ms(cooldown - (Date.now() - daily));
message.channel.send(`You have already collected the daily check in reward, please check in again in **${time.hours}h ${time.minutes}m ${time.seconds}s**`)
} else {
let embed = new Discord.MessageEmbed()
.setTitle('Daily Check In')
.setDescription(`Here is the amount collected today: ${amount}`)
.setColor('#ffc300')
message.channel.send({embeds: [embed]})
db.add(`money_${message.author.id}`, amount)
db.add(`daily_${message.author.id}`, Date.now())
}
}}
Cannot read property 'execute' of undefined"
Means client.commands.get('chk') is returning undefined.
Presumably, this means the chk command can't be found.
So, let's look at where you're setting the commands:
// fetch commands
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
And let's check your chk.js file which is being imported.
module.exports = {
name: "check in",
// ...
What I can see is, you're exporting the module and setting the command with the name "check in" but later in the script, you're asking for a command called "chk". The command can't be found, returns undefined, and kills your code as it isn't handled.
The solution in this case is to just change your name property to "chk", or request client.commands.get("check in") instead.

discord bot not processing the command

I was adding some new commands to my discord v12 bot. But it's not responding to the code I typed. Any help is appreciated.
This section is inside index.js
client.admins = new discord.Collection();
const admins = fs.readdirSync('./custom/admin').filter(file => file.endsWith('.js'));
for (const file of admins) {
const admin = require(`./custom/admin/${file}`);
client.admins.set(admin.name.toLowerCase(), admin);
};
This is the code to process the above lines
if (message.author.bot || message.channel.type === 'dm') return;
const prefix = client.config.discord.prefix;
if (message.content.indexOf(prefix) !== 0) return;
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const admin = args.shift().toLowerCase();
const adm = client.admins.get(admin) || client.admins.find(adm => adm.aliases && adm.aliases.includes(admin));
if (adm) adm.execute(client, message, args);
And the function which I am trying the bot to do is named delete.js
module.exports = {
name: 'snap' ,
aliases: [],
category: 'admin',
utilisation: '{prefix}snap [number]',
execute(message, args) {
if(isNaN(args)) return message.reply("Bruh,Specify how much message should I delete")
if(args>99) return message.reply("You ain't making me do that much work boi")
if (message.member.hasPermission('ADMINISTRATOR') ){
const {MessageAttachment} = require('discord.js');
const snaping = new MessageAttachment('./snap.gif')
message.channel.send(snaping)
setTimeout(snapCommand , 9000 ,args, message)
}
else
{
message.channel.send("-_- you are not an admin,Then why are you trying to use admin commands");
}
function snapCommand(args, message){
var del= args ;
del = parseInt(del , 10)
message.channel.bulkDelete(del+2);
}
}
}
when I launch the bot it shows no error msg, So that's a good sign I think, but when I use !snap 5
'!' which is my prefix. The bot does nothing. No error in the console also. Does anyone have any idea to solve this?
Never mind, I fixed it by adding client to the delete.js code
execute(client, message, args) {
if(isNaN(args)) return message.reply("Bruh,Specify how much message should I delete")
if(args>99) return message.reply("You ain't making me do that much work boi")

Discord.js Cannot Read property 'run' of undefined

Im created a bot for discord using Discord.js, and every time I try to run my Bal command through my command handler it rejects it with the error Cannot read property 'run' of undefined
here is my code for Index.js
const Discord = require('discord.js');
const db = require("#replit/database")
const client = new Discord.Client();
const token = process.env.TOKEN;
const keep_alive = require('./keep_alive.js')
const PREFIX = "orb ";
const fs = require('fs');
const activities_list = [
"orb help.",
`${client.guilds.cache.size} servers!`,
"n 3^o7 !"
];
client.commands = new Discord.Collection();
const ecocommandFiles = fs.readdirSync('./ecocommands/').filter(file => file.endsWith('.js'));
for(const file of ecocommandFiles){
const command = require(`./ecocommands/${file}`);
client.commands.set(command.name, command);
}
client.on('ready', () => {
console.log("Orbitus online");
setInterval(() => {
const index = Math.floor(Math.random() * (activities_list.length - 1) + 1);
client.user.setActivity(activities_list[index], { type: 'WATCHING' });
}, 30000);
});
//Command Handler\\
client.on('message', message =>{
if(!message.content.startsWith(PREFIX) || message.author.bot) return;
const args = message.content.slice(PREFIX.length).split(/ +/);
const command = args.shift().toLowerCase();
if(command === 'bal'){
client.commands.get('bal').run(message, args, Discord);
}
});
client.login(token);
And here is my code for Bal.js
module.exports.run = async (message, args, Discord) => {
if(!message.content.startsWith(PREFIX))return;
let user = message.mentions.members.first() || message.author;
let bal = db.fetch(`money_${message.guild.id}_${user.id}`)
if (bal === null) bal = 0;
let bank = await db.fetch(`bank_${message.guild.id}_${user.id}`)
if (bank === null) bank = 0;
let moneyEmbed = new Discord.RichEmbed()
.setColor("#FFFFFF")
.setDescription(`**${user}'s Balance**\n\nPocket: ${bal}\nBank: ${bank}`);
message.channel.send(moneyEmbed)
};
I really need help because I want to continue development on my bot.
Thanks for your time
so uuh , i think you should follow the official guide:
https://discordjs.guide/command-handling/
your's seems bit similar but maybe got from yt (etc)
anyway the issue is
you dont export name from Bal.js only run (function)
module.exports.run = .....
and as name is undefined
your here setting undefined as the key with your run function to client.commands (collection)
for(const file of ecocommandFiles){
const command = require(`./ecocommands/${file}`);
client.commands.set(command.name, command);
^^^^^^^^
}
now only key in the client.commands collection is undefined
client.commands.get('bal') this will come undefined as there is not command called bal in your collection (only undefined)
what you could do is add
module.exports.name = 'bal' into bal.js
every command from now on should have this (if you decide to use this way)
Again I would suggest you read the discord.js official guide as it very beginner friendly and has a command handler and dynamic command handling tutorials with additional features, I will leave the links down below if you need them :)
Links
Official-docs: Click-here
official guide (this is the official guide for beginners with d.js): Click-here
Command-Handling (guide): Click-here
Dynamic-Command-Handling(guide) : Click-here
Additional-Features) (guide): Click-here
Other guides:
Event handling (from the same official guide): Click-here
An-idiots-Guide (use jointly with the official guide): Click-here

How to fix Discord API: Unknown Message error?

I'm trying to make a meme command but whenever I try to use it I get this error "DiscordAPIError: Unknown Message".
This was working earlier but when I came back to my PC it started glitching out.
Here's my code
const { RichEmbed } = require("discord.js");
const randomPuppy = require("random-puppy");
const usedCommandRecently = new Set();
module.exports = {
name: "meme",
aliases: ["memes", "reddit"],
category: "fun",
description: "Sends a random meme",
run: async (client, message, args) => {
if (message.deletable) message.delete();
var Channel = message.channel.name
//Check it's in the right channel
if(Channel != "memes") {
const channelembed = new RichEmbed()
.setColor("BLUE")
.setTitle(`Use me in #memes`)
.setDescription(`Sorry ${message.author.username} this command is only usable in #memes !`)
return message.channel.send(channelembed);
}
//Check cooldown
if(usedCommandRecently.has(message.author.id)){
const cooldownembed = new RichEmbed()
.setColor("GREEN")
.setTitle("Slow it down, pal")
.setDescription(`Sorry ${message.author.username} this command has a 30 second cooldown per member, sorry for any inconvenice this may cause`)
message.channel.send(cooldownembed)
} else{
//Post meme
const subReddits = ["dankmeme", "meme", "me_irl"];
const random = subReddits[Math.floor(Math.random() * subReddits.length)];
const img = await randomPuppy(random);
const embed = new RichEmbed()
.setColor("RANDOM")
.setImage(img)
.setTitle(`From /r/${random}`)
.setURL(`https://reddit.com/r/${random}`);
message.channel.send(embed);
}
}
}
Im not sure, but maybe problem in your require block.
const { RichEmbed } = require("discord.js");
the right way its:
const Discord = require("discord.js");
let cooldownembed = new Discord.RichEmbed();
and why you use return here
return message.channel.send(channelembed);

Categories

Resources