anidiotsguide / discordjs-bot-guide Goto Github PK
View Code? Open in Web Editor NEWThe basic new coder friendly "idiot's guide", Created by Hindsight#2020 and maintained by the community.
Home Page: https://anidiots.guide
The basic new coder friendly "idiot's guide", Created by Hindsight#2020 and maintained by the community.
Home Page: https://anidiots.guide
Personally, I find the sections saying "./events/message.js" and "./commands/ping.js" unclear on where to put the folders. If someone could clear it up for me, it would be greatly appreciated.
In this line
const invite = guildInvites.find(i => ei.get(i.code).uses < i.uses);
if the invite was not used or had a count of 0 uses, It throws an error saying that it can not read the property of uses. Maybe update the guide?
let user; if (entry.extra.channel.id === message.channel.id && (entry.target.id === message.author.id) && (entry.createdTimestamp > (Date.now() - 5000)) && (entry.extra.count >= 1)) { user = entry.executor.username } else { user = message.author.username }
${user} return a bad value sometimes... (wrong user)
can you fix it please?
Hey, could you update https://github.com/AnIdiotsGuide/discordjs-bot-guide/blob/master/coding-guides/using-audit-logs.md to show how to do the same thing for 12.0.0, please?
I have made sure I haven't made any typos in my code (It doesn't look like I have). Whenever I try and run the command, it tells me that client is not defined. I don't know if this has been an issue in the past, and has already been solved. I looked briefly before creating an issue.
Hi, I'm trying to get this code snippet to work today. I have encountered an error that I have solved (https://github.com/AnIdiotsGuide/discordjs-bot-guide/blob/master/coding-guides/tracking-used-invites.md)
client.guilds.forEach(g => { ----> client.guilds.cache.forEach(g => {
This solved my first mistake
However when I invite another member I get this error
https://hastebin.com/obugufuqox.sql
Thank you for your help, good day to you
Just got confused because the documentation isnt up to date here. Wanted to save others the hassle.
https://github.com/AnIdiotsGuide/discordjs-bot-guide/blob/master/understanding/roles.md
How do I send them? If I try this: msg.react('1️⃣') it replies with an error telling me that this is an unknown emoji. What shall I do?
the raw events script for the emoji event handle is realy useful but since discordjs 12 he no work anymore. So it's possible to update it 😊🤞?
Best Regards
Can you pls make one about kick and ban
bruh
It keeps saying invalid token while i checked the token and i'm sure it's valid
my index.js looks like this.
const { Client, Intents } = require("discord.js");
const client = new Client({
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES]
});
const config = require("./config.json");
// Set the prefix
client.on("messageCreate", (message) => {
if (!message.content.startsWith(config.prefix) || message.author.bot) return;
if (message.content.startsWith(`${config.prefix}ping`)) {
message.channel.send("pong!");
} else
if (message.content.startsWith(`${config.prefix}foo`)) {
message.channel.send("bar!");
}
});
client.login("config.token");
hi I have an error when I type on my discord server +vckick here is my code and my error log
`client.on('message', async message => {
if (!message.guild) return;
// if the message content starts with "!ban"
if (message.content.startsWith('+vckick')) {
// Make sure the bot user has permissions to make channels and move members in the guild:
if (!message.guild.me.hasPermission(['MANAGE_CHANNELS', 'MOVE_MEMBERS'])) return message.reply('Missing the required Manage Channels
and Move Members
permissions.');
// Get the mentioned user/bot and check if they're in a voice channel:
const member = message.mentions.members.first();
if (!member) return message.reply('You need to @mention a user/bot to kick from the voice channel.');
if (!member.voiceChannel) return message.reply('That user/bot isn't in a voice channel.');
// Now we make a temporary voice channel, move the user/bot into the channel, and delete it:
const temp_channel = await message.guild.createChannel(user.id, 'voice', [
{ id: guild.id,
deny: ['VIEW_CHANNEL', 'CONNECT', 'SPEAK'], },
{ id: member.id,
deny: ['VIEW_CHANNEL', 'CONNECT', 'SPEAK'] }
]);
await member.setVoiceChannel(temp_channel);
await temp_channel.delete();
// Finally, pass some user response to show it all worked out:
msg.react('👌');
/* or just "message.reply", etc.. up to you!
}
});
`
the error:
(node:2541) UnhandledPromiseRejectionWarning: ReferenceError: user is not defined
at Client.client.on (/home/runner/index.js:121:56)
at Client.emit (events.js:185:15)
at MessageCreateHandler.handle (/home/runner/node_modules/discord.js/src/client/websocket/packets/handlers/MessageCreate.js:9:34)
at WebSocketPacketManager.handle (/home/runner/node_modules/discord.js/src/client/websocket/packets/WebSocketPacketManager.js:103:65)
at WebSocketConnection.onPacket (/home/runner/node_modules/discord.js/src/client/websocket/WebSocketConnection.js:333:35)
at WebSocketConnection.onMessage (/home/runner/node_modules/discord.js/src/client/websocket/WebSocketConnection.js:296:17)
at WebSocket.onMessage (/home/runner/node_modules/ws/lib/event-target.js:120:16)
at WebSocket.emit (events.js:180:13)
at Receiver._receiver.onmessage (/home/runner/node_modules/ws/lib/websocket.js:137:47)
at Receiver.dataMessage (/home/runner/node_modules/ws/lib/receiver.js:409:14)
(node:2541) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:2541) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
If someone could help me
thanks
Hippolyte
I've had an intermittent issue with this code, and I think I finally figured out what's wrong.
The wrong members were being credited with the invite. It would credit the same member multiple times in a row.
It appears that after a guildMemberAdd, the invite cache is not being updated. So I added this line
//update the *existing* invites for the guild.
client.invites.set(member.guild.id, new Map(newInvites.map((invite) => [invite.code, invite.uses])));
to the guildmemberadd event to update the invites. haven't tested yet but wanted to get this out there.
sudo apt-get install libav-tools
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package libav-tools is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source
However the following packages replace it:
ffmpeg
E: Package 'libav-tools' has no installation candidate
If I'm reading this correctly, does that mean I don't need libav tools as ffmpeg is now preferred? I'm on a raspberry pi model 3B+ on buster.
`if(message.content.startsWith('status')){
sent = new Array()
channel = message.channel
for(let sv of servers){
// GET INITIAL DATA TO SEND MESSAGES,
// THEN AFTER SENDING TRIGGER THE EDIT LOOP
let promise = getInfo(sv[0], sv[1])
promise.then(x => {
let info = {
name: x.name,
map: x.map,
pl: x.raw.numplayers,
fps: x.raw.rules.fps,
fpsavg: x.raw.rules.fps_avg,
maxpl: x.maxplayers
}
embed = createEmbed(info, sv, true)
// msgs.add(await message.channel.send({embed}))
message.channel.send({ embed }).then(c => {
sent.push(c)
console.log('Created', c.id)
})
// msg.catch(e => console.log(e, 'ERROR SENDING EMBED-----------'))
}).catch(e => {
embed = createEmbed([], sv, false)
// msgs.add(await message.channel.send({embed}))
message.channel.send({ embed }).then(c => {
sent.push(c)
console.log('Created', c.id)
})
console.error("120:" + e + ' @ ' + sv)
})
}`
I need to get:
client.on("ready", () => { client.user.setActivity(
${info.pl}/${info.maxpl}); });
I'm new on js script, can you explaim me how to get my request please?
in main file
client.commands = new Enmap();
fs.readdir("./commands/", (err, files) => {
if (err) return console.error(err);
files.forEach(file => {
if (!file.endsWith(".js")) return;
let props = require(`./commands/${file}`);
let commandName = file.split(".")[0];
console.log(`Attempting to load command ${commandName}`);
client.commands.set(commandName, props);
});
});
in commands/help.js
module.exports = (client, discord, message) => {
let embed = new discord.RichEmbed()
.setTitle("Commands of "+ client.user.username)
.setColor("BLUE")
message.channel.send(embed)
}
Help me
How can I send everyone ping in embed?
this code returns errors for first two member joins, i guess its creating a baseline, but theres no error handling. example:
You have triggered an unhandledRejection, you may have forgotten to catch a Promise rejection:
unhandledRejection: TypeError: Cannot read property 'get' of undefined
You have triggered an unhandledRejection, you may have forgotten to catch a Promise rejection:
unhandledRejection: TypeError: Cannot read property 'invite' of undefined
The last commit is three years ago so it can be deleted
I thought this was supposed to be minecraft. Diamond ore is broken on here, it wont load in, kthx
EDIT: please fix this, gold ore is broken too now
Do heroku no work with it?
Hmmm do the command outdated... Hmmmm HMMMMMMM mMMm mMmmmMm
when i try to install windows-build-tools it doesn't install, it says please wait this may take a while. I waited 3hrs and nothing happened. Please help me
How To Reset Database Scores guild?
im ues sql.prepare("DELETE FROM scores WHERE guild = ${message.guild.id}")
Error: SqliteError: no such table scores
I did everything thing:
npm i --vs2015 -g windows-build-tools
npm i node-gyp better-sqlite3
and i got this error (below)
if you want all of my code: https://pastebin.com/XKcH0Uau
ReferenceError: target is not defined
Hey folks -- awesome website!
Are you familiar with Repl.it? I'm the CEO and founder and we have a lot of users that are making Discord bots on our site. I know you have a guide on Glitch and they've been having troubles recently with bot hosting. Why I think Repl.it will not suffer the same consequences is because we built our infrastructure in a way that allows us to operate it more cheaply and because we're a sustainable business with multiple sources of revenue and have been around for a long time. We also have a close relationship with the folks at Discord and they even sponsored one of our competitions.
Let me know if you'd be interested in a guide. Happy to collaborate on one or contribute.
Thanks again for the great website. And sorry if a GitHub issue was not the best way to send this :)
// get role by name
let myRole = message.guild.roles.cache.find(role => role.name === "Moderators");
From my understanding, this doesn't get a role object. The find method just returns a boolean value of the role's existence.
Hi. I'm getting the error "TypeError: client.commands.set is not a function" and i cannot for the life of me figure out why. My code is almost exactly the same aside from my commands.js - here's my code, maybe someone can help me.
require('dotenv').config();
const fs = require('fs');
const Discord = require('discord.js');
const Enmap = require("nmap");
let client = new Discord.Client();
console.log('🤖 > Fortuno sta startando...');
client.login(process.env.TOKEN);
client.on('ready', readyDiscord);
function readyDiscord() {
console.log('🤖 > Ok! Fortuno è online!');
client.user.setActivity('Sohub Laib', { type: 'WATCHING'});
}
fs.readdir("./events/", (err, files) => {
if (err) return console.error(err);
files.forEach(file => {
const event = require(`./events/${file}`);
let eventName = file.split(".")[0];
client.on(eventName, event.bind(null, client));
});
});
client.commands = new Enmap();
fs.readdir("./commands/", (err, files) => {
if (err) return console.error(err);
files.forEach(file => {
if (!file.endsWith(".js")) return;
let props = require(`./commands/${file}`);
let commandName = file.split(".")[0];
console.log(`Attempting to load command ${commandName}`);
client.commands.set(commandName, props);
});
});
const prefix = "f!"
module.exports = async(client, message) => {
if (message.author.bot) return;
if (message.content.startsWith(prefix)) {
let messageArray = message.content.split(" "),
cmd = messageArray[0],
args = messageArray.slice(1),
commandfile = client.commands.get(cmd.slice(prefix.length)) || client.aliases.get(cmd.slice(prefix.length));
if(!commandfile) return;
commandfile.run(client,message,args);
}
}
module.exports = async function(message) {
if (message.author.bot) return;
if (!message.content.startsWith(prefix)) return;
const commandBody = message.content.slice(prefix.length);
const args = commandBody.split(' ');
const command = args.shift().toLowerCase(), found = false;
switch(command) {
// etc...
Thanks in advance if you do take the time to help me out!
I'm having problems with returning variables from functions, which I run in the external files, to the main part of the program.
The variable in question is joinstatus.
Here is the main part of the program:
bot.on('message', function(message){
**console.log('Main-message; joinstatus='+joinstatus);**
...
if(cmd) {
cmd.run(bot, message, args, servers, server, joinstatus);
}
else{
//console.log('Error! Else passed!');
return;
}
});
Here is the function that runs in the external file:
module.exports.run = async (bot, message, args, servers, server, joinstatus) => {
...
function play(connection, message){
...
server.dispatcher.on('finish', () => {
if(server.queue[0]){
play(connection, message);
} else {
connection.disconnect();
joinstatus='waiting';
console.log('Play-Else; joinstatus='+joinstatus);
servers[message.guild.id] = '';
}
});
**console.log('Play1; joinstatus='+joinstatus);**
**console.log('Play; returning servers, server and joinstatus');**
return servers, server, joinstatus;
}
if(joinstatus==='waiting'){
message.member.voice.channel.join().then(function(connection){
joinstatus='joined';
**console.log('Play2; joinstatus='+joinstatus);**
play(connection, message);
});
**console.log('Play3; joinstatus='+joinstatus);**
**console.log('Play; returning joinstatus');**
return joinstatus;
}
}
module.exports.config = {
command:'PLAY'
}
And this is the result of calling the play function
Main-message; joinstatus=waiting
Play3; joinstatus=waiting
Play; returning joinstatus
Main-message; joinstatus=waiting
Play2; joinstatus=joined
Play1; joinstatus=joined
Play; returning servers, server and joinstatus
Main-message; joinstatus=waiting
Main-message; joinstatus=waiting
What am I doing wrong?
Hi,
I'm quite new to the discord.js programming, and to the github repository, so please be gentle.
I'm working on my bot, and I'm currently working on 'creating a command handler'.
The first problem that I have is that every time I input the command I want, the function else runs, never function if.
The second problem that I have, that is probably an extension of the first problem, is that I put 'cmd.run(bot, message, args);' part under the else command, just to test it out, and I every time I input the command; I get the error from the title of the video.
What am I doing wrong?
Following is my code.
var Discord = require('discord.js');
var bot = new Discord.Client();
var fs = require('fs');
bot.commands = new Discord.Collection();
fs.readdir('./commands/', (err, files) => {
if(err){ console.error(err); }
var jsfiles = files.filter(f => f.split('.').pop() === 'js');
if(jsfiles.length <= 0) { return console.log('No commands found!'); }
else { console.log(jsfiles.length + ' commands found!'); }
jsfiles.forEach((f, i) => {
var cmds = require(`./commands/${f}`);
console.log(`Command ${f} loading...`);
bot.commands.set(cmds.config.command, cmds);
});
});
var prefix = process.env.prefix;
bot.on('message', function(message){
var input = message.content.toUpperCase();
if(input.startsWith(prefix)){
var cont = input.slice(prefix.length).split(' ');
console.log('input: '+input);
console.log('prefix: '+prefix);
console.log('cont: '+cont);
var args = cont.slice(1);
console.log('args: '+args);
var cmd = bot.commands.get(cont[0]);
console.log('cont[0]: '+cont[0]);
if(cmd) {
cmd.run(bot, message, args);
console.log('If passed!');
}
else{
cmd.run(bot, message, args);
console.log('Else passed!');
}
}
else{
console.log('Wrong prefix!');
return;
}
}
Any help would be much appreciated. :)
With kind regards,
David
.
I have done exactly as in the example but process.env.NODE_ENV is undefined when using npm run development
// process.env.NODE_ENV allows you to get the environment the node process is in
let ver = process.env.NODE_ENV;
I'm on macOS Catalina using Visual Studio
If I run my app like this: NODE_ENV=production node index.js
it works
Is it only on macOS Catalina it dosn't work or is it me what are doing some thing wrong?
In Tracking used invites there's this snippet of code
// Initialize the invite cache
const invites = {};
// A pretty useful method to create a delay without blocking the whole script.
const wait = require('util').promisify(setTimeout);
client.on('ready', () => {
// "ready" isn't really ready. We need to wait a spell.
wait(1000);
// Load all invites for all guilds and save them to the cache.
client.guilds.forEach(g => {
g.fetchInvites().then(guildInvites => {
invites[g.id] = guildInvites;
});
});
});
And I don't understand why wait(1000)
function is being used without await
, I think it doesn't do anything without awaiting for it..
I'm just trying to get the getting started bot up and running, but it doesn't seem like it recognizes the Intents import anymore. I checked Discord.js and all I could find were examples of GatewayIntentBits
. Has it been deprecated?
client.commands = new Discord.Collection(); <-- this line throws error Discord is undefined.
did you mean
client.commands = new Collection();
const cachedInvites = guildInvites.get(member.guild.id)
const newInvites = await member.guild.invites.fetch();
const usedInvite = newInvites.find(inv => cachedInvites.get(inv.code) < inv.uses)
newInvites.each(inv => cachedInvites.set(inv.code, inv.uses));
guildInvites.set(member.guild.id, cachedInvites);
Starting Discord.js 12 client.users
, client.guilds
, client.channels
, guild.channels
, guild.members
are now a Manager instead of a Collection, so you can't use Collection.get(id)
for them.
However you could use client.users.cache
, client.guilds.cache
, client.channels.cache
, guild.channels.cache
, guild.members.cache
instead.
Please update this guide: https://github.com/AnIdiotsGuide/discordjs-bot-guide/blob/master/understanding/collections.md
Edit: See https://discordjs.guide/additional-info/changes-in-v12.html
When uses is uses < 2 it will get this error for some reason that i cant figure out?
error : uses is not defined
TypeError: client.guilds.forEach is not a function HELP ME PLS
copy /pasted your code got the bot online but it does not reply. what am i not doing correctly
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.