Discord does not respond to commands - javascript

It is a simple command but my bot is not responding when I ask it. It has administrator priviledges so it should respond. What am I doing wrong?
const {
Client,
Intents,
Message
} = require('discord.js');
const client = new Client({
intents: [Intents.FLAGS.GUILDS]
});
const config = require("./config.json");
client.on('ready', () => {
console.log(`Bot ${client.user.tag} foi carregado em ${client.user.size} e esta online!`);
client.user.setGame(`Eu estou em ${client.guilds.size} servidores`)
});
client.on("guildCreate", guild => {
console.log(`O bot entrou nos Servidor: ${guild.me} (ID: ${guild.id}). QTD mebros: ${guild.memberCount} `);
client.user.setActivity('YouTube', {
type: 'WATCHING'
});
});
client.on("guildDelete", guild => {
console.log(`O bot foi removido do serivdor: ${guild.name} (ID: ${guild.id})`);
client.user.setActivity(`Serving ${client.guilds.size} servers`)
})
client.on("menssage", async message => {
if (message.author.bot) return;
if (menssage.channel.type === "dm") return;
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const comando = args.shift().toLowerCase();
if (comando === "ping") {
const m = await message.channel.send("Ping?");
m.edit(`Pong a latencia e ${m.createdTimesTamp - message.createdTimesTamp}ms. `)
}
});
client.login(config.token);

The function setGame doesn't exists, you need to change it to
client.user.setActivity(`Serving ${client.guilds.size} servers`, { type: 'PLAYING' })

Related

DM a specific user with discord.js with options in a slash command

today i was trying to make a /warn command that DM the warned user, but when i do that i see an error saying : "Expected token to be set for this request, but none was present"
could anyone help me ?
there is my code :
const { SlashCommandBuilder, PermissionFlagsBits, messageLink, Client } = require('discord.js');
const { GatewayIntentBits } = require('discord.js');
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
module.exports = {
data: new SlashCommandBuilder()
.setName('warn')
.setDescription('Choisi une qqun à warn.')
.addUserOption(option =>
option
.setName('cible')
.setDescription('Le membre à warn')
.setRequired(true))
.addStringOption(option =>
option
.setName('raison')
.setDescription('La raison du warn'))
.setDefaultMemberPermissions(PermissionFlagsBits.BanMembers)
.setDMPermission(false),
async execute(interaction) {
const target = interaction.options.getUser('cible');
await client.users.send(target.id, 'vous avez été warn.')
await interaction.reply(`${target.username} warn`);
},
};
you just need to do
let raison = interaction.options.getString('raison');
if (!raison) raison = "No raison provided.";
try {
target.send(`vous avez été warn. \n> Raison: ${raison}`)
} catch (e) { interaction.reply({content: 'couldn\'t dm user his DMs are closed', ephemeral: true}) }

How to fix "Cannot send messages to this user"

I tried sending messages to a user through their DMs and got the error Cannot send messages to this user.
Here is my code:
const Discord = require("discord.js")
const config = require("./config.json");
const client = new Discord.Client();
const fs = require('fs');
client.on('ready', () => {
console.log('ca marche!!!!')
setInterval(() => {
const guild = client.guilds.cache.get("758345919350964254");
if (!guild) return; // pour évité toute erreur
guild.members.fetch();
guild.members.cache.random().createDM().then(dm =>{
dm.send(".")})
console.log("ENFIIIIIIINNN")
}, 3000);
console.log('ca marche')
})
client.login(config.token);
I tried to catch the error but didn't succeed:
client.on('ready', () => {
console.log('ca marche!!!!')
setInterval(() => {
const guild = client.guilds.cache.get("758345919350964254");
if (!guild) return; // pour évité toute erreur
guild.members.fetch();
guild.members.cache.random().createDM().then(dm =>{
dm.send(".")}).catch(error => console.log('message impossible '))
console.log("ENFIIIIIIINNN")
}, 3000000);
console.log('ca marche')
})
client.login(config.token);
Info:
discord.js version: 14.6.0
node version: v19.0.0
Error:
Uncaught DiscordAPIError DiscordAPIError: Cannot send messages to this user

Discord Reaction Role doesn't attribute roles

I'm trying to create a Discord Reaction Role and I would like to assign a role when a user clicks on the message emoji in the channel. Here is my code, it doesn't work from messageReactionAdd :
const Discord = require('discord.js');
const client = new Discord.Client();
const { token } = require('./config.json');
client.on("ready", () => {
console.log("Bot opérationnel");
});
// Permet d'ajouter une réaction à un message
client.on('messageCreate', message => {
if (message.content === '!roles') {
const reactionEmoji = message.guild.emojis.cache.find(emoji => emoji.name === 'FR');
message.react(reactionEmoji);
// console.log(reactionEmoji)
}
});
client.on("messageReactionAdd", (reaction, user) => {
if (user.bot) return;
console.log("Réaction ajoutée");
if (reaction.message.id === "1036663050276704346") { //ID du message
console.log(reaction.message.id);
if (reaction.emoji.name === message.guild.emojis.cache.find(emoji => emoji.name === 'FR')) {
var member = reaction.message.guild.members.cache.find(member => member.id === user.id); // Va récuperer le membre du serveur
member.roles.add("1036583426620399647").then(mbr => { // Assigne le role avec ID France
console.log("Role attribué avec succès pour" + mbr.displayName);
}).catch(err => {
console.log("Le role n'a pas pu etre attribué :" + err);
});
}
}
});
client.login(token);
Thank you in advance.
Activate the SERVER MEMBERS INTENT and the MESSAGE CONTENT INTENT from the Discord Developer Portal

I can not launch my js Discord bot, error message

So I tried to follow a tutorial to make my own music discord bot but when I try to launch it I got some problems
I correctly installed the modules, and I've also made a json file that contain my token to make the bot,
There is the command prompt
and there is my code
const Discord = require('discord.js');
const client = new Discord.Client();
const DisTube = require('distube');
const distube = new DisTube(client, { searchSongs: false, emitNewSongs: true });
const { token } = require('./info.json');
const prefix = '!';
client.on("ready", () => {
console.log('${client.user.tag} va venir faire mousser tout ça!');
});
client.on("message", async(message) => {
if (message.author.bot) return;
if (!message.content.startsWith(prefix)) return;
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift();
const status = (queue) => `Volume: \`${queue.volume}%\` | Filter: \`${queue.filter || "Off"}\` | Loop: \`${queue.repeatMode ? queue.repeatMode == 2 ? "All Queue" : "This Song" : "Off"}\` | Autoplay: \`${queue.autoplay ? "On" : "Off"}\``;
distube
.on("playSong", (message, queue, song) => message.channel.send(
`Joue :musical_note: et nique Brian \`${song.name}\` - \`${song.formattedDuration}\`\nDemandé par: ${song.user}\n${status(queue)}`
))
.on("addSong", (message, queue, song) => message.channel.send(
`Ajoutée! ${song.name} - \`${song.formattedDuration}\` to the queue by ${song.user}`
))
.on("playList", (message, queue, playlist, song) => message.channel.send(
`Joue :musical_note: \`${playlist.name}\` playlist (${playlist.songs.length} songs).\nDemandé par: ${song.user}\nJoue mtn \`${song.name}\` - \`${song.formattedDuration}\`\n${status(queue)}`
))
.on("addList", (message, queue, playlist) => message.channel.send(
`Ajouté \`${playlist.name}\` playlist (${playlist.songs.length} songs) to queue\n${status(queue)}`
))
.on("searchResult", (message, result) => {
let i = 0;
message.channel.send(`**Choisi en dessous**\n${result.map(song => `**${++i}**. ${song.name} - \`${song.formattedDuration}\``).join("\n")}\n*Tu as 60s pour choisir*`);
})
.on("searchCancel", (message) => message.channel.send(`Annulé batard`))
.on("error", (message, e) => {
console.error(e)
message.channel.send("Call Souf ça bug: " + e);
});
if (command =="play") {
if (!message.member.voice.channel) return message.channel.send('Tu ne peux pas entendre la douce mélodie.');
if (!args[0]) return message.channel.send('Décide toi frère!');
distube.play(message, args.join(" "));
}
if (command =="stop") {
const bot = message.guild.members.cache.get(client.user.id);
if (!message.member.voice.channel) return message.channel.send('Tu ne peux pas entendre la douce mélodie.');
if (bot.voice.channel !== message.member.voice.channel) return message.channel.send('Tu est pas dans le même channel que moi');
distube.stop(message);
message.channel.send('Tu as arreté la musique');
}
});
client.login(token);
In discord.js v13 all bots are required to define their intents in the Client constructor.
Example:
change your
const Discord = require('discord.js');
const client = new Discord.Client();
to
const {Client, Intents} = require('discord.js');
const client = new Client({intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES]});
You would obviously change the intents to what your bot would use.
More info can be found here

i'm trying to put a manipulated image to welcome people on my dicrod bo using jimp

I'm using this but it's not working. I don't know why please help me.
const Discord = require("discord.js");
const jimp = require("jimp");
const client = new Discord.Client();
const config = require("./config.json");
client.on("ready", () => {
console.log(`Bot foi iniciado`)
});
client.on("guildMemberAdd", async member => {
let canal = client.channels.get("750795877089804309")
let fonte = await jimp.loadFont(jimp.FONT_SANS_32_BLACK)
let mask = await jimp.read('mascara.png')
let fundo = await jimp.read('fundo.png')
jimp.read(member.user.defaultAvatarURL).then(avatar => {
avatar.resize(400, 400)
mask.resize(400, 400)
fundo.resize(270, 190)
avatar.mask(mask)
fundo.print(fonte, 05, 120, member.user.username)
avatar.composite(fundo, 80, 170).write('resultado.png')
canal.send(``, {
files: ["resultado.png"]
})
console.log('imagem enviada')
})
.catch(err => {
console.log('Deu erro aqui porra')
});
});
client.on("message", async message => {
if (message.author.bot) return;
if (message.channel.type === "dm") return;
if (!message.content.startsWith(config.prefix)) return;
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const comando = args.shift().toLowerCase();
if (comando === "ping") {
const m = await message.channel.send("Sifude");
m.edit(`A Latência é ${m.createdTimestamp - message.createdTimestamp}ms. A Latencia da API é ${Math.round(client.ping)}ms`);
}
});
client.login(config.token);
You need to use:
let canal = client.channels.cache.get("750795877089804309")
As client.channels return a ChannelManager object and not a collection.

Categories

Resources