I am trying to create a bot, which will be given the role when user joins the server by link, but this doesn't work.
Error:
C:\DGhostsBot\bot.js:45
bot.on("guildMemberAdd", (member) => {
^
ReferenceError: bot is not defined
at Object.<anonymous> (C:\DGhostsBot\bot.js:45:1)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:743:3)
My code here:
const Discord = require('discord.js');
const client = new Discord.Client();
var prefix = "dg!"
client.login(`**************************************************************`);
client.on("message", (message) => {
if(message.content == prefix + "test") {
message.reply("just a command that is used for performance testing. Do not pay attention.");
}
});
client.on("message", (message) => {
if(message.content == prefix + "cake") {
message.reply("here's your cake :3 :cake: ");
}
});
client.on("message", (message) => {
if(message.content == prefix + "help") {
message.reply("it's in development");
}
});
client.on("message", (message) => {
if(message.content == prefix + "kick") {
if(message.member.roles.some(r=>["Developer", "devadmin"].includes(r.name)) ) {
const user = message.mentions.users.first();
if (user) {
const member = message.guild.member(user);
if (member) {
member.kick()
}
}
} else {
message.reply("!!!!ACCESS_DENIED!!!!").then(sentMessage => sentMessage.delete("delete"));
}
}
});
bot.on("guildMemberAdd", (member) => {
if (member.id == bot.user.id) {
return;
}
let guild = member.guild
guild.fetchInvites().then(invdat => {
invdat.forEach((invite, key, map) => {
console.log(invite.code)
if (invite.code === "qQAkqFQ") {
return member.addRole(member.guild.roles.find(role => role.name === "Member"));
}
})
})
});
I check a lot of answers on the internet, but nothing of all this doesn't work.
So, I do not know how to fix this error.
Instead of bot use client like you did all the times before.
There are people who do const client = new Discord.Client(); but there are also people who name it bot or even something really weired.
If you want to learn how to make your own bot, you can use the open-source guide created by the members and creators of discord.js wich can be found here: https://discordjs.guide/
You have to change bot.on(...) to client.on(...)
You didn't define bot in previous code, so you can't use it. You defined your Discord client as client in the following line:
const client = new Discord.Client();
That's why you have to use client. You can't create a listenener for a non existing client.
For further details about all events of Discord.js, you can have a look at the official discord.js documentation: https://discord.js.org/#/docs/main/stable/class/Client
There you can also find all details on how to listen to events etc.
Related
My code for a translator bot is as such, everything works well, except for the "command" command, which I decided to turn into an embed to make it look more slick than unaligned string on the screen. the code is as such:
const Discord = require('discord.js');
const language = require('./langOptions');
const translate = require('#vitalets/google-translate-api');
const config = require('./config.json');
const speech = require('./messages');
const client = new Discord.Client();
const prefix = config.prefix;
const { MessageEmbed } = require('discord.js
');
const express = require("express");
const server = express();
server.all("/", (req, res) => {
res.send("Bot is running!")
})
function keepAlive() {
server.listen(3000, () => {
console.log("Server is ready.")
})
}
module.exports = keepAlive
client.on("ready", () => {
console.log("The bot is ready.");
});
client.on("message", (message) => {
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
// It can be a regular ! message. This says to not bother if it doesn't have a prefix, and
// to not trigger if a bot gives a command.
if (!message.content.startsWith(prefix) || message.author.bot) {
return;
}
// Auto-translates the text into the command's language like !japanese, or !french
if (language.some(ele => ele.name === command)) {
if (args.length === 0) {
message.reply(speech.BOT_FULLNAME_AUTO_ERROR);
} else {
let lang_to = language.filter(ele => ele.name===command)[0].abrv;
let text = args.slice(0).join(' ');
translate(text, {to: lang_to})
.then(res => message.channel.send(res.text))
.catch(err => message.channel.send(speech.BOT_TRANSLATION_ERROR + err));
}
}
// Auto translates with abbreviation like !ko, !en, or !de
if (language.some(ele => ele.abrv=== command)) {
if (args.length === 0) {
message.reply(speech.BOT_ABBR_AUTO_ERROR);
} else {
let lang_to = language.filter(ele => ele.abrv===command)[0].abrv;
let text = args.slice(0).join(' ');
translate(text, {to: lang_to})
.then(res => message.channel.send(res.text))
.catch(err => message.channel.send(speech.BOT_TRANSLATION_ERROR + err));
}
}
// Specifies the text's language and translates it into a specific language
if (command === "translate") {
if (args.length < 3) {
message.reply(speech.BOT_TRANS_SPECIFIC_ERROR);
} else {
let argFrom = args[0].toLowerCase();
let argTo = args[1].toLowerCase();
let lang_from = language.filter(ele => ele.name === argFrom)[0].abrv;
let lang_to = language.filter(ele => ele.name=== argTo)[0].abrv;
let text = args.slice(2).join(' ');
translate(text, {from: lang_from, to: lang_to})
.then(res => message.channel.send(res.text))
.catch(err => console.log(speech.BOT_TRANSLATION_ERROR + err));
}
}
if (command === "commands") {
const embed = new MessageEmbed()
.setTitle(`Help has arrived`)
.setDescription(`Here are the proper syntax when using Kitsune Saiguu's polyglotirific abilities (I swear that's a word, don't quote me on that though.)`)
.setTimestamp();
message.reply({ content: `**For a list of names and abbreviates go here: **<https://cloud.google.com/translate/docs/languages>
Here are the appropriate syntaxes when using commands:
*!translate from to text*
=>!translate english italian <english-text-here>
Note: This command, like it shows, turns inputted english text to italian.
*!language auto-translate-text*
=>!french english-text-here turns english to french
Note: This shortens the translation process, however, it does not auto-detect different languages.
*!abrv auto-translate-text*
=>!de english-text-here turns english to german
Note: Can work for the first and second examples, and shortens the syntax even further.`, embeds: [embed]});
}
})
client.login(config.token);
And I'm getting this error no matter which embed type I'm using (note that all three types of embed are from the discord.js guide for v13:
/home/runner/Kitsune-Saiguu-2/node_modules/discord.js/src/structures/MessageEmbed.js:13
Object.defineProperty(this, 'client', { value: message.client });
^
TypeError: Cannot read properties of undefined (reading 'client')
at new MessageEmbed (/home/runner/Kitsune-Saiguu-2/node_modules/discord.js/src/structures/MessageEmbed.js:13:60)
at Client.<anonymous> (/home/runner/Kitsune-Saiguu-2/app.js:86:17)
at Client.emit (node:events:390:28)
at MessageCreateHandler.handle (/home/runner/Kitsune-Saiguu-2/node_modules/discord.js/src/client/websocket/packets/handlers/MessageCreate.js:9:34)
at WebSocketPacketManager.handle (/home/runner/Kitsune-Saiguu-2/node_modules/discord.js/src/client/websocket/packets/WebSocketPacketManager.js:103:65)
at WebSocketConnection.onPacket (/home/runner/Kitsune-Saiguu-2/node_modules/discord.js/src/client/websocket/WebSocketConnection.js:330:35)
at WebSocketConnection.onMessage (/home/runner/Kitsune-Saiguu-2/node_modules/discord.js/src/client/websocket/WebSocketConnection.js:293:17)
at WebSocket.onMessage (/home/runner/Kitsune-Saiguu-2/node_modules/ws/lib/event-target.js:120:16)
at WebSocket.emit (node:events:390:28)
at Receiver._receiver.onmessage (/home/runner/Kitsune-Saiguu-2/node_modules/ws/lib/websocket.js:145:47)
~/Kitsune-Saiguu-2$ node app.js
The bot is ready.
/home/runner/Kitsune-Saiguu-2/node_modules/discord.js/src/structures/MessageEmbed.js:13
Object.defineProperty(this, 'client', { value: message.client });
^
TypeError: Cannot read properties of undefined (reading 'client')
at new MessageEmbed (/home/runner/Kitsune-Saiguu-2/node_modules/discord.js/src/structures/MessageEmbed.js:13:60)
at Client.<anonymous> (/home/runner/Kitsune-Saiguu-2/app.js:86:17)
at Client.emit (node:events:390:28)
at MessageCreateHandler.handle (/home/runner/Kitsune-Saiguu-2/node_modules/discord.js/src/client/websocket/packets/handlers/MessageCreate.js:9:34)
at WebSocketPacketManager.handle (/home/runner/Kitsune-Saiguu-2/node_modules/discord.js/src/client/websocket/packets/WebSocketPacketManager.js:103:65)
at WebSocketConnection.onPacket (/home/runner/Kitsune-Saiguu-2/node_modules/discord.js/src/client/websocket/WebSocketConnection.js:330:35)
at WebSocketConnection.onMessage (/home/runner/Kitsune-Saiguu-2/node_modules/discord.js/src/client/websocket/WebSocketConnection.js:293:17)
at WebSocket.onMessage (/home/runner/Kitsune-Saiguu-2/node_modules/ws/lib/event-target.js:120:16)
at WebSocket.emit (node:events:390:28)
at Receiver._receiver.onmessage (/home/runner/Kitsune-Saiguu-2/node_modules/ws/li
I didn't really have much of an issue creating embeds before discord.js v13.
Small note: this was the error shown on Repl.it
I'm trying to learn how to create NFTs on the Ethereum block chain.
In terminal (Ubuntu 20.04.3 LTS)
Aki-Zeta:~/my-nft$ node scripts/mint-nft.js
I keep getting
/home/patonn89/my-nft/scripts/mint-nft.js:6
const { createAlchemyWeb3 }
^
Syntax Error Unexpected Token {
see bottom for full error
Here is my code using VScode
require("dotenv").config()
const API_URL = process.env.API_URL;
const PUBLIC_KEY = process.env.PUBLIC_KEY;
const PRIVATE_KEY = process.env.PRIVATE_KEY;
const { createAlchemyWeb3 } = require("#alch/alchemy-web3")
const web3 = createAlchemyWeb3(API_URL)
const contract = require("../artifacts/contracts/MyNFT.sol/MyNFT.json")
const contractAddress = "0xf469355dc12e00d8cda65b3a465bdad65da27e22"
const nftContract = new web3.eth.Contract(contract.abi, contractAddress)
async function mintNFT(tokenURI) {
const nonce = await web3.eth.getTransactionCount(PUBLIC_KEY, 'latest'); //get latest nonce
//the transaction
const tx = {
'from': PUBLIC_KEY,
'to': contractAddress,
'nonce': nonce,
'gas': 500000,
'data': nftContract.methods.mintNFT(PUBLIC_KEY, tokenURI).encodeABI(),
}
const signPromise = web3.eth.accounts.signTransaction(tx, PRIVATE_KEY)
signPromise
.then((signedTx) => {
web3.eth.sendSignedTransaction(
signedTx.rawTransaction,
function (err, hash) {
if (!err) {
console.log(
"The hash of your transaction is: ",
hash,
"\nCheck Alchemy's Mempool to view the status of your transaction!"
)
} else {
console.log(
"Something went wrong when submitting your transaction:",
err
)
}
}
)
})
.catch((err) => {
console.log(" Promise failed:", err)
})
}
mintNFT(
"https://gateway.pinata.cloud/ipfs/QmcRikKfA6xdaNZkojW28xpvZYysQXSJEb52YdeRJP3GGv"
)
Is it something to do with that "{" in line 6, or something else in line 6?
Prior to running this script I ran "npm install #alch/alchemy-web3", and verified the directories exist (both by going there and with cd). Other people with similar issues are missing something, and I have no idea what I'm missing. I have checked for spurious spaces and semicolons but I am not experienced with this language.
I have been using the tutorials off of the Ethereum project site.
full error
/home/patonn89/my-nft/scripts/mint-nft.js:6
const { createAlchemyWeb3 }
^
SyntaxError: Unexpected token {
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:413:25)
at Object.Module._extensions..js (module.js:448:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:471:10)
at startup (node.js:117:18)
at node.js:951:3
I had exactly the same error, and it was just a spurious character in my VScode editor, same example as you from ethereum.org.
As you can see in line 24
change const { createAlchemyWeb3 } to const { createAlchemyWeb3 } = require("#alch/alchemy-web3")
/home/kevind/Downloads/VibeUtils2/node_modules/discord.js/src/client/Client.js:548
throw new TypeError('CLIENT_MISSING_INTENTS');
^
TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client.
at Client._validateOptions (/home/kevind/Downloads/VibeUtils2/node_modules/discord.js/src/client/Client.js:548:13)
at new Client (/home/kevind/Downloads/VibeUtils2/node_modules/discord.js/src/client/Client.js:76:10)
at Object.<anonymous> (/home/kevind/Downloads/VibeUtils2/commands/role.js:3:16)
at Module._compile (node:internal/modules/cjs/loader:1103:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1155:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (/home/kevind/Downloads/VibeUtils2/index.js:13:21) {
[Symbol(code)]: 'CLIENT_MISSING_INTENTS'
This is the error I'm getting, however my code looks like
const fs = require('fs');
const {prefix, reactEmoji, token, clientId, guildId} = require('./config/config.json');
const eventFiles = fs.readdirSync('./events').filter(file => file.endsWith('.js'));
const { Client, Collection, Intents, Discord } = require('discord.js');
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.DIRECT_MESSAGES, Intents.FLAGS.GUILD_EMOJIS_AND_STICKERS, Intents.FLAGS.GUILD_MEMBERS, Intents.FLAGS.GUILD_BANS, Intents.FLAGS.GUILD_PRESENCES, Intents.FLAGS.GUILD_MESSAGES] });
client.commands = new Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`)
client.commands.set(command.name, command);
}
const commands = [];
const slashcommandFiles = fs.readdirSync('./slashcommands').filter(file => file.endsWith('.js'));
for (const file of slashcommandFiles) {
const command = require(`./slashcommands/${file}`);
commands.push(command.data.toJSON());
}
const rest = new REST({ version: '9' }).setToken(token);
rest.put(Routes.applicationGuildCommands(clientId, guildId), { body: commands })
.then(() => console.log('Successfully registered application commands.'))
.catch(console.error);
for (const file of eventFiles) {
const event = require(`./events/${file}`);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args, client));
} else {
client.on(event.name, (...args) => event.execute(...args, client));
}
client.on('message', message => {
if (message.content.toLowerCase().startsWith('welcome')) {
message.react(reactEmoji);
console.log(`Reacted on ${message.author.tag}'s 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;
try {
command.execute(message, args);
}catch (error) {
console.error(error);
message.reply('There was an error while trying to execute that command!');
}
})};
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);
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
});
client.login(token);
I'm still handing normal commands until v12 gets deprecated,and so I can transition. However I'm having issues with intents. Please help me on what intents are valid, because those look valid to me. If I'm doing something critically wrong, then please let me know. This is one of my first times actually delving into v13, however as far as I've seen I've done everything correct, that is going off of documentation. If I missed something please let me know, because I think that should work. Most of my ready is handled in an event file.Is there an easy way to add all intents? The ways I've seen here don't work
Ensure your intents are turned on in your Developer Portal.
Go to https://discord.com/developers/applications
Click on your application
Click on the "Bot" section
Enable the intents you need there; these are only privileged intents so not everything will be there, you will need the Server Members Intent & Message Content Intent (just so you're ready for when it is enforced)
Upon checking,GUILD_EMOJIS_AND_STICKERS and GUILD_BANS are not valid intents in Discord.js V12. You'll either need to switch or remove those intents from your array. (Added from comments, just so it's easier to find)
As for adding every intent at once, that's not really possible. Though you could run this in the repl and paste the results into the intents array (this is done in V13, I highly suggest running this yourself in a node repl so it uses your Discord.js version):
const discord = require("discord.js"); const intents = Object.keys(discord.Intents.FLAGS); let formattedIntents = []; intents.forEach((intent) => {formattedIntents.push(`"${intent}"`)}); formattedIntents;
(I made this as one-line as possible because I tested it in my bot's eval slash command, but what it does is pretty simple, imports d.js, gets the keys of the discord.Intents.FLAGS, makes an empty array to hold them, loops through the intents and pushes it to the array, then outputs the list of intents.)
Which should output
"GUILDS","GUILD_MEMBERS","GUILD_BANS","GUILD_EMOJIS_AND_STICKERS","GUILD_INTEGRATIONS","GUILD_WEBHOOKS","GUILD_INVITES","GUILD_VOICE_STATES","GUILD_PRESENCES","GUILD_MESSAGES","GUILD_MESSAGE_REACTIONS","GUILD_MESSAGE_TYPING","DIRECT_MESSAGES","DIRECT_MESSAGE_REACTIONS","DIRECT_MESSAGE_TYPING","GUILD_SCHEDULED_EVENTS"
though I'm not sure if you really want or need every intent.
I have a code which I'm doing on replit, and I'm pretty new to node.js so I really do need assistance with this. I have a code which is this:
const Discord = require("discord.js")
const fetch = require("node-fetch")
const client = new Discord.Client()
const mySecret = process.env['TOKEN']
function getQuote() {
return fetch('https://zenquotes.io/api/random')
.then(res => {
return res.json
})
.then(data => {
return data[0]["q"] + " —" + data [0]["a"]
})
}
client.on("ready", () => {
console.log('Logged in as ${client.user.tag}' )
})
client.on("message", msg => {
if (msg.author.bot) return
if (msg.content === "$inspire") {
getQuote().then(quote => msg.channel.send(quote))
}
})
client.login(process.env.TOKEN)
However, I'm receiving the error:
npx node .
/home/runner/1Starty/index.js:2
const fetch = require("node-fetch")
^
Error [ERR_REQUIRE_ESM]: require() of ES Module /home/runner/1Starty/node_modules/node-fetch/src/index.js from /home/runner/1Starty/index.js not supported.
Instead change the require of /home/runner/1Starty/node_modules/node-fetch/src/index.js in /home/runner/1Starty/index.js to a dynamic import() which is available in all CommonJS modules.
at Object.<anonymous> (/home/runner/1Starty/index.js:2:15) {
code: 'ERR_REQUIRE_ESM'
}
May someone help me on why this is the case?
Open shell and run this command
npm i node-fetch#2.6.6
I've got all the packages necessary and whatnot but I keep on getting an error. First of all, here's my coding (in a file called main.js.):
const client = new Discord.Client();
require("dotenv").config();
const fs = require('fs');
const mongoose = require('mongoose');
client.commands = new Discord.Collection();
client.events = new Discord.Collection();
["command_handler", "event_handler"].forEach((handler) => {
require(`./handlers/${handler}`)(client, Discord);
});
mongoose
.connect(process.env.MONGODB_SRV, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
})
.then(()=>{
console.log('Connected to the database!');
})
.catch((err) => {
console.log(err);
});
client.login(process.env.DISCORD_TOKEN);
My error is
C:\Users\shann\Desktop\DiscordBot\handlers\event_handler.js:10
client.on(event_name, event.bind(null, Discord, client));
^
TypeError: event.bind is not a function
at load_dir (C:\Users\shann\Desktop\DiscordBot\handlers\event_handler.js:10:41)
at C:\Users\shann\Desktop\DiscordBot\handlers\event_handler.js:14:38
at Array.forEach (<anonymous>)
at module.exports (C:\Users\shann\Desktop\DiscordBot\handlers\event_handler.js:14:25)
at C:\Users\shann\Desktop\DiscordBot\main.js:11:37
at Array.forEach (<anonymous>)
at Object.<anonymous> (C:\Users\shann\Desktop\DiscordBot\main.js:10:38)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47
I honestly don't know what the problem is this time. Should I define event.bind? I thought .bind was a function and event was the variable. I've been following a tutorial. I do have mongoose installed through the command center but I don't know if I should reinstall it. Also, I don't see any errors in my coding but I am pretty new so please point them out and how I can fix it!
The coding for command_handler.js
const fs = require('fs');
module.exports = (client, Discord)=>{
const command_files = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
for(const file of command_files){
const command = require(`../commands/${file}`)
if(command.name){
client.commands.set(command.name, command);
} else {
continue;
}
}
}
The coding for event_handler.js is
const fs = require('fs');
module.exports = (client, Discord)=>{
const load_dir = (dirs)=>{
const event_files = fs.readdirSync(`./events/${dirs}`).filter(file => file.endsWith('.js'));
for(const file of event_files){
const event = require(`../events/${dirs}/${file}`);
const event_name = file.split('.')[0];
client.on(event_name, event.bind(null, Discord, client));
}
}
['client', 'guild'].forEach(e => load_dir(e));
}
There isn't actually much of an answer here but the thing is, you don't even need an advanced event handler. All I did was remove the event handler from my handlers and added an event handler to my main.js. Then I removed client and guild from my events. After that, I made it so that in main.js it would look at all the files in events (the folder with all my events) and run them (using fs)!
Credits to #WorthyAlpaca for the help in introducing this alternate method