DM Specific User ID on Discord.js Bot - discord

i'm new to coding bots and i need help on how to add a command on messaging a certain person a customized message. this is what i have so far. what should i do?
const Discord = require('discord.js');
const config = require("./Data/config.json")
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] })
client.once('ready', () => {
console.log('Ready!');
});
client.login('TOKEN');
client.on('message', async message => {
if (message.author.bot) return;
let prefix = '??'
if (!message.content.startsWith(prefix)) return;
let args = message.content.slice(prefix.length).trim().split("/ +/g");
let msg = message.content.toLowerCase();
let cmd = args.shift().toLowerCase();
if (msg.startsWith(prefix + 'ping')) {
message.channel.send('pong');
}
if (msg.startsWith(prefix + 'hello')) {
message.channel.send('hewwo uwu');
}
});

To fetch a user by id, you can use bot.users.fetch()
To direct message a user, you can use User.send():
const user = await client.users.fetch(userId);
user.send("This is a DM!");

This simple function will easily resolve the user (you can provide a user object or user ID so it’s very helpful)
async function DMUser(resolvable, content, client) {
const user = client.users.resolve(resolvable)
return user.send(content)
}
//returns: message sent, or error
//usage: DMUser(UserResolvable, "content", client)
Related links:
UserManager.resolve
User.send
UserResolvable

Related

Discord js, Bot can only find itself until someone else send a message

I was trying to get all the members of a role but i can only get the bot until someone else send a message then i can see them too
here is my code
const matches = require("../differents-matches")
module.exports = (client) => {
setInterval(async () => {
/*const allmatch = await matches.
where('_notified').exists(false).
where('_startDate').lt(Date.now()).
where('_endDate').gt(Date.now())
allmatch.forEach(element => {
})*/
console.log(client.guilds.cache.get('1050150840813498401').roles.cache.get('1050889003110506516').members.map(m => m.user.id))
//
}, 5000)
}
i tried the solution proposed in this post but the problem is still here
i have all the intents needed :
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, GatewayIntentBits.GuildMembers], fetchAllMembers: true });
and i did activate the server member intent in the bot options, i can't find any other thing to try. If you have an idea of what is the problem please leave a message.
It is expected, actually the fetchAllMembers client option disappeared with Discord.js v13.
You should now fetch the guild members manually:
const matches = require("../differents-matches")
module.exports = (client) => {
setInterval(async () => {
/*const allmatch = await matches.
where('_notified').exists(false).
where('_startDate').lt(Date.now()).
where('_endDate').gt(Date.now())
allmatch.forEach(element => {
})*/
const guild = client.guilds.cache.get('1050150840813498401');
await guild.members.fetch(); // do what fetchAllMembers previously did
console.log(guild.roles.cache.get('1050889003110506516').members.map(m => m.user.id))
//
}, 5000)
}

Discord.js v13 bot cannot send message

Here is my code
I tried to run it and when i run the command nothing shows up
can someone pls help me with this
const Discord = require("discord.js");
const bot = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });
const token =
"MTAxNzgyMjQ1MjU1MTc5NDgxOA.GjO8F-.VWCMsDKV5_YdP1w6gnEME6Jucd7BN9OADesM4s";
const prefix = "lb!";
bot.on("ready", () => {
console.log("Your bot is now online");
});
bot.on("messagecreate", (message) => {
if (message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLocaleLowerCase();
if (command === "hello") {
message.reply("Hi ${message.author}");
}
});
bot.login(token);
Message content is now a privileged intent. You may have to enable it for your bot in the Discord Developer Portal. You could (or should) also use interaction commands instead, so that you don't need that intent, as its purpose is to provide user privacy.
Hello Syed Faizan Ali Kazmi, Done Fix Your Code
// © Ahmed1Dev
const Discord = require("discord.js");
const bot = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });
const token =
"MTAxNzgyMjQ1MjU1MTc5NDgxOA.GjO8F-.VWCMsDKV5_YdP1w6gnEME6Jucd7BN9OADesM4s";
const prefix = "lb!";
bot.on("ready", () => {
console.log("Your bot is now online");
});
bot.on("messagecreate", (message) => {
if (message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLocaleLowerCase();
if (command === prefix + "hello") {
message.reply("Hi ${message.author}");
}
});
bot.login(token);
// © Ahmed1Dev
With Regards,
Ahmed1Dev
I rewrite the code. Hope this will work
const Discord = require("discord.js");
const bot = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });
const token = "never post your bot token online";
const prefix = "lb!";
bot.on("ready", () => {
console.log("Your bot is now online");
});
bot.on("messageCreate", (message) => {
if (message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if (command === "hello") {
message.reply(`Hi ${message.author}`);
}
});
bot.login(token);
Also, if you didn't tick Message Content Intent, then go tick it in Discord Developer Portal

message event listener not working properly

I currently have the following code:
const Discord = require('discord.js');
const client = new Discord.Client({
partials: ['MESSAGE', 'CHANNEL', 'REACTION']
});
const db = require('quick.db')
client.on('message', async message => {
const DmLogger = require('./MainServer/dmRecieving.js');
DmLogger(client, message, Discord);
const levels = require('./MainServer/levels/main.js');
levels(client, message)
if (message.channel.id === configFile.LoggingChannel) return;
if (message.author.bot) return;
if (!message.guild) return;
let prefix = db.get(message.guild.id + '.prefix') || '~'
if (!message.content.startsWith(prefix)) return;
let args = message.content
.slice(prefix.length)
.trim()
.split(/ +/g);
if (message.content.toLowerCase() == prefix + 'info') {
const commandFile = require(`./Embeds/info.js`);
return commandFile(client, message);
}
if (message.content.toLowerCase() == prefix + 'help') {
const commandFile = require(`./Embeds/help.js`);
return commandFile(client, prefix, message);
}
if (message.content.toLowerCase() == prefix + 'fonts') {
const commandFile = require(`./Commands/font.js`);
return commandFile(client, msg, args, prefix, message);
}
if (message.content.toLowerCase().startsWith(prefix + 'setup')) {
const commandFile = require(`./Commands/setup/main.js`);
return commandFile(client, message, db);
}
});
Whenever I send a message that includes a command the event listener is firing however it is not detecting the message content.
This module has been working fine for the passed few months its just suddenly erroring after I reinstalled the discord.js module.
In discord.js v13, it is necessary to specify an intent in new discord.Client(). Events other than the specified intent will not be received.
ClientOptions
Intents#FLAGS
To receive the message event, you will need the GUILDS and GUILD_MESSAGES intents.
You mean...
const client = new Discord.Client({
partials: ['MESSAGE', 'CHANNEL', 'REACTION'],
intents: [Discord.Intents.FLAGS.GUILDS, Discord.Intents.FLAGS.GUILD_MESSAGES]
});
Or to receive all (including privileged intent) events...
const client = new Discord.Client({
partials: ['MESSAGE', 'CHANNEL', 'REACTION'],
intents: Object.keys(Discord.Intents.FLAGS)
});
Also, in discord.js v13, the message event has been deprecated, so it is recommended to replace it with messageCreate.
- client.on('message', async message => {
+ client.on('messageCreate', async message => {
Since discord.js v13, you need to declare what your bot is doing with Intents
Here's how you declare them :
const client = new Discord.Client({
partials: ['MESSAGE', 'CHANNEL', 'REACTION'],
intents: ['GUILD_MESSAGES']
})
The GUILD_MESSAGES Intent is essential because it allows your bot to read and reply to messages in guilds.
However, you should check the documentation to see if your bot needs some more Intents

Giving roles on discord

I'm making a discord murder mystery bot.
const Discord = require('discord.js');
const client = new Discord.Client();
client.on("message", (message) => {
msg = message.content.toLowerCase();
if (message.author.bot) {
return;
}
mention = message.mentions.users.first();
if (msg.startsWith("kill")) {
if (mention == null) {
return;
}
message.delete();
mention.send('you are dead');
message.channel.send("now done");
}
});
client.login('my token');
What would I add to the code so after the person who was tagged got there role changed from alive to dead?
// First, make sure that you're in a guild
if (!message.guild) return;
// Get the guild member from the user
// You can also use message.mentions.members.first() (make sure that you check that
// the message was sent in a guild beforehand if you do so)
const member = message.guild.members.cache.get(mention.id);
// You can use the ID of the roles, or get the role by name. Example:
// const aliveRole = message.guild.roles.cache.find(r => r.name === 'Alive');
const aliveRole = 'alive role ID here';
const deadRole = 'dead role ID here';
// You can also use try/catch with await if you make the listener and async
// function:
/*
client.on("message", async (message) => {
// ...
try {
await Promise.all([
member.roles.remove(aliveRole),
member.roles.add(deadRole)
]);
} catch (error) {
console.error(error);
}
})
*/
Promise.all([
member.roles.remove(aliveRole),
member.roles.add(deadRole)
]).catch(console.error);
The Promise.all means that the promises for adding and removing the roles are started at the same time. A promise is an object that can resolve to a value or reject with an error, so the .catch(console.error) logs all errors. I recommend that you handle errors for message.delete(), mention.send('you are dead'), and message.channel.send("now done") as well.
For more information on member.roles.remove() and member.roles.add(), see the documentation for GuildMemberRoleManager.

Trying to display JSON data from API as an array

So I've been trying to make a Discord Bot in Node.js, Im fetching data from an external api and using the BOT to display the data, problem is that when I call the function, its showing one by one instead of everything in one message.
I want to display everything in one message.
const token = 'my discord token is here';
const Discord = require('discord.js');
const axios = require('axios');
const client = new Discord.Client();
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`)
})
client.on('message', async msg => {
if (msg.content === '!inventario') {
let getInv = async () => {
let response = await axios.get('my api link where im getting the info is here')
let inventario = response.data
return inventario
}
let inventarioValue = await getInv ()
var inv = inventarioValue.total_inventory_count
msg.channel.send(`Total de Itens no inventário: ${inventarioValue.total_inventory_count} \nSkins:\n`);
for (var i=0;i<inv;i++)
{
var itens = inventarioValue.descriptions[i].market_name
msg.channel.send(itens);
}
}
});
client.login(token);
I want to execute this inventarioValue.descriptions[i].market_name, then after executing showing the full result instead of showing one by one.
Thanks
You can map object array element and add to message. For a better visual reflection, you can add them to embed.
const token = 'my discord token is here';
const Discord = require('discord.js');
const axios = require('axios');
const client = new Discord.Client();
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`)
})
client.on('message', async msg => {
if (msg.content === '!inventario') {
let getInv = async () => {
let response = await axios.get('my api link where im getting the info is here')
let inventario = response.data
return inventario
}
let inventarioValue = await getInv()
var inv = inventarioValue.total_inventory_count
let embed = new Discord.MessageEmbed()
embed.setDescription(`${inventarioValue.descriptions.map(val => val.market_name).join('\n')}`)
msg.channel.send(`Total de Itens no inventário: ${inventarioValue.total_inventory_count} \nSkins:\n`, embed);
}
});
client.login(token);

Resources