Discord.js v12 code breaks when upgrading to v13 - javascript

When updating my discord.js to v13 there are many errors I get:
//member.hasPermission is not a function
member.hasPermission("SEND_MESSAGES")
//Cannot send an empty message
channel.send(someEmbed)
//Cannot send an empty message
channel.send({embed: someEmbed})
//Warning: The 'message' event was deprecated, use 'messageCreate' instead
client.on("message", msg => {})
//Cannot send an empty message
channel.send(user)
//[CLIENT_MISSING_INTENTS] Valid intents must be provided for the client
const client = new Client()
//channel.join is not a function
await channel.join()
These don't happen in v12, so how do I fix them in v13?

Discord.js v13 has a lot of changes, and those are only a few. Before updating to v13, you should change the following things
//member.hasPermission("SEND_MESSAGES")
member.permissions.has("SEND_MESSAGES")
//channel.send(someEmbed) / channel.send({embed: someEmbed})
channel.send({ embeds: [someEmbed] }) //make sure it's an array!
//client.on("message", msg => {})
client.on("messageCreate", msg => {})
//channel.send(user)
channel.send(user.toString())
//const client = new Client()
const { Intents, Client } = require("discord.js")
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES]}) //more intents may be provided
//await channel.join()
const { joinVoiceChannel } = require("#discordjs/voice") //requires installation
joinVoiceChannel({
channelId: channel.id,
guildId: guild.id,
adapterCreator: guild.voiceAdapterCreator
})
There are some more changes. You can see them in the guide

Related

Discord bot not giving reply [duplicate]

This question already has an answer here:
message.content doesn't have any value in Discord.js
(1 answer)
Closed last month.
Can someone help me out? I'm actually stuck. This the the source code for a bot I made to send GIFs when requesed by a user in a server. The bot is online and connecting to the Discord API.
Discord bot getting online image
The bot should be activated when typed !gif , in keyword the user can type any categorie or emotion they want and the bot would get the gif.
There are no errors shown yet but the bot is still not replying.
No reply image
Bot online image
I am also getting valid reply when used the giphy api url.
const Discord = require('discord.js');
require('dotenv').config();
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on("messageCreate", async (message) => {
const tokens = message.content.split(" ");
if (tokens[0] == "!gif") {
const keywords = tokens.slice(1, tokens.length).join(" ");
const url = `http://api.giphy.com/v1/gifs/search?q=tag&api_key=token&limit=5`;
const response = await fetch(url);
const result = await response.json();
const index = Math.floor(Math.random() * result.results.length);
message.channel.send(result.results[index].url);
}
});
client.login(process.env.DISCORD_BOT_TOKEN);
I tried many online fixes none worked I also tried changing version of Discord.js, node-fetch as well as dotenv but none worked.
Discord.js v14
const { Client, GatewayIntentBits, Events } = require('discord.js')
require('dotenv').config()
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildMessages,
],
})
client.on(Events.MessageCreate, async (message) => {
if (message.author.id === client.user.id) return
const token = message.content.split(' ')
if (token[0] === '!gif')
message.channel.send({
content: `<#${message.author.id}>`,
files: ['https://media.tenor.com/fTTVgygGDh8AAAAM/kitty-cat-sandwich.gif'],
})
})
client.on(Events.ShardReady, () => {
console.log(`Logged in as ${client.user.tag}!`)
})
client.login(process.env.TOKEN)

Bot isn't replying to any message

I'm trying to make a simple Discord bot, but I haven't been able to get it to respond to any of my messages.
const Discord = require("discord.js");
const { GatewayIntentBits } = require('discord.js');
const client = new Discord.Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent
]
});
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`)
})
client.on("messageCreate", msg => {
if(msg.content === "ping") {
msg.reply("pong");
}
})
const token = process.env['TOKEN']
client.login(token)
The bot is logging into discord, I'm not getting any errors in the console, and I've toggled on all the privileged gateway intents.
Edit
So, my previous answer was wrong, but is most definitely a better way to send messages.
There's not anything else that I can see is wrong with the code -- so I guess I'll try to debunk?
const { Client, GatewayIntentBits } = require("discord.js");
const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent ]});
client.on("ready", async() => {
console.log(`${client.user.tag} logged in.`);
});
client.on("messageCreate", async(message) => {
if(message.content.toLowerCase() === "ping") {
message.reply({ content: "pong!" }); // or message.reply("pong!");
}
});
client.login(process.env.TOKEN);
This should be a runnable instance of your code. What you should do is see if you're even getting the messageCreate event at all, by running it like this:
client.on("messageCreate", (message) => {
console.log(`Received message!`);
});
If you do get something, then it is unable to correctly parse the message content. Are you ensuring it's the same capitalization wise? Is it spelt correctly?
If you don't get something, it's an issue with your Intents, or the way your event is structured.
Try adding parenthesis around your msg, though that shouldn't affect anything. Just a thought.
Incorrect Answer
In discord.js#13.x.x, the way to send messages has changed.
Formerly, you could do the following:
message.reply("Hello world!");
But now, to make formatting what provided property is what, it goes as follows:
message.reply({
content: "Hello world!",
});
You can also add things such as Embeds by using embeds: [], or Components by: components: [] (which requires Action Rows, not base Components).
Hope this helps.

DiscordJS V13 doesnt react to dms

I have this very basic code for a very basic discord bot
since the new discord.js version 13 you need to declare intents.
I tried doing that using the bitmap 32767 (basically declaring all intents), however the bot doesnt trigger the "messageCreate" event when a message is send
in the dms it only works in servers.
All privileged gateway intents on the developer site have been set to true.
What am I missing?
const Discord = require("discord.js");
const allIntents = new Discord.Intents(32767);
const client = new Discord.Client({ intents: allIntents });
require("dotenv").config();
const botName = "Miku";
client.once("ready", () => {
//gets executed once at the start of the bot
console.log(botName + " is online!");
});
client.on("messageCreate", (message) => {
console.log("got a message");
});
(async() => {
//bot connects with Discord api
client.login(process.env.TOKEN);
})();
You cannot listen for events in the Direct Messages unless they are direct responses/replies/reactions to the initial message.
For example, you can send a message to new members and wait for a response:
client.on('guildMemberAdd', member =>{
member.send("Welcome to the server!");
message.awaitReactions(filter, { max: 1, time: 60000, errors: ['time'] })
.then((collected) => {
//Now, write your code here that handles the reactions.
});
but there is no way to listen for events within the Direct Messages. As in, client.on... will never fire because of a DM event.

Unable to fetch all guild members through Discordjs v13

I have been trying to fetch the list of all members in my guild using the syntax as mentioned in the docs here. But am not receiving any output. Below is the code that I am using.
const { Client, Intents, Guild } = require("discord.js");
require("dotenv").config();
const commandHandler = require("./commands");
const fetch = require("node-fetch");
const client = new Client({
intents: ["GUILDS", "GUILD_MESSAGES", "GUILD_PRESENCES"],
});
client.once("ready", async (data) => {
console.log("Ready!");
console.log(`Logged in as ${client.user.tag}!`);
const Guilds = client.guilds.cache.map((guild) => guild);
console.log(Guilds[0]);
await Guilds[0].members.fetch().then(console.log).catch(console.error);
});
client.on("interactionCreate", async (interaction) => {
if (!interaction.isCommand()) return;
if (interaction.commandName === "ping") {
await interaction.reply(client.user + "💖");
}
});
client.on("messageCreate", commandHandler);
client.login(process.env.BOT_TOKEN); // Kushagra's bot
I am getting the information on Guild instance through the console.log on line 13. But do am not getting any output for line 15.
However, I noticed that I was getting some output if I add options to fetch() command on line 14. I received some output when I added {query: 'random text'}.
Just wanted to understand why I am unable to get a list of all members.
Thanks!🙂
I found that I had missed out on the Intent.
It seems that in order to fetch members you need to add an intent GUILD_MEMBERS while creating a client instance.
So replacing the client creation with the one below will work.
const client = new Client({
intents: ["GUILDS", "GUILD_MESSAGES", "GUILD_PRESENCES", "GUILD_MEMBERS"]
});

Discord.js 'presenceUpdate' not being called

I have a "Special User" which is equal to 'Client.users.fetch(Special User's ID)'.
Then the user has two event listeners attached to the it, 'message' and 'presenceUpdate',
The message event listener works perfects, although the presenceUpdate does not work at all,
All help is greatly appreciated!
require("dotenv").config();
const Discord = require(`discord.js`);
const Client = new Discord.Client();
Client.on("ready", () => {
console.log(`\tClient Ready`);
});
var SpecialUser = Client.users
.fetch(process.env.ID)
.then((User) => {
console.log(User.username);
// Working
User.client.addListener("message", (message) => {
console.log("message");
});
// Not Working
User.client.addListener("presenceUpdate", (Old, New) => {
console.log(`Presence Updated`);
});
})
.catch(console.error);
Client.on("message", (message) => {});
Client.login(process.env.TOKEN);
If the presenceUpdate event doesn't trigger, chances are you'll need to add the GUILD_PRESENCES intent either using the client options:
const Discord = require(`discord.js`);
const client = new Discord.Client({
intents: ['GUILDS', 'GUILD_MESSAGES', 'GUILD_PRESENCES'],
});
// rest of your code...
In your Discord dashboard; by choosing your bot then by clicking on the Bot settings:

Categories