Making a Server User ID function | Discord.js - javascript

I am trying to get all user's ID and name from a server which I done so by using this:
const list = client.guilds.cache.get("GUILD_ID");
list.members.cache.forEach(member => console.log('Name: ' + member.user.username + ' ID: ' + member.user.id));
But i want to input those member ID's and names into a .json file and I tried doing this via a function:
const Discord = require('discord.js');
const client = new Discord.Client();
const token = 'TOKEN';
const prefix = 'a';
const getuser = require('./GetUserId/getID.json');
const fs = require('fs');
const { readdirSync } = require("fs");
const { join } = require("path");
client.commands = new Discord.Collection();
const commandFiles = readdirSync(join(__dirname, "GetUserId")).filter(file => file.endsWith(".js"));
for (const file of commandFiles) {
const command = require(join(__dirname, "GetUserId", `${file}`));
client.commands.set(command.name, command);
}
client.on('message', message => {
if (message.content === 'getID'){
getuser(message);
function getuser (message) {
const list = client.guilds.cache.get("749337851174322288");
if(!getuser[message.author.id]){
getuser[message.author.id] = {
ID: `${list.members.cache.forEach(member => member.user.id)}`,
Name: `${list.members.cache.forEach(member => member.user.username)}`
}
}
fs.writeFile('./GetUserId/getID.json', JSON.stringify(getuser, null, 2), (err) => {
if (err) console.log(err)
})
}
message.delete()
message.channel.send(`*Done.*`)
}
})
client.login(token);
So I tried this code and this came on the .json file:
{
"709827684888215582": {
"ID": "undefined",
"Name": "undefined"
}
}
How would I make the "ID" display user ID's and display all members username in "Name:" in a server/guild in that .json file?

You're looking for Array.prototype.map(), not Array.prototype.forEach()
forEach() simply executes a function on all elements of an array (or a Collection, in this case). map() creates a new array populated with the results of the function.

Related

Discord.js Snipe

I am trying to make a discord.js snipe command and I keep getting an error message: Cannot read properties of undefined (reading 'get'). I created command handlers and event handlers and everything works fine, even the messageDelete event. I get this message every time I run the command
Snipe command:
module.exports = {
commands: ['snipe','sn','s'],
requiredRoles: ['Members'],
callback : (client, message, args) => {
const msg = client.snipes.get(message.channel.id)
if(!msg) return message.channel.send("There's nothing to snipe!")
message.channel.send(`${msg.author} deleted: ${msg.content}`)
}
}
Index file:
const path = require('path')
const fs = require('fs')
const { Client, Intents, Collection } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
const config = require('./config.json');
require('./util/loadEvents')(client);
client.snipes = new Collection()
Event Handler:
const fs = require('fs');
module.exports = client => {
fs.readdir("events/", (_err, files) => {
files.forEach((file) => {
if (!file.endsWith(".js")) return;
const event = require(`../events/${file}`);
let eventName = file.split(".")[0];
client.on(eventName, event.bind(null, client));
delete require.cache[require.resolve(`../events/${file}`)];
});
});
}
And messageDelete Event:
module.exports = async (client,message) => {
if(message.author.client) return;
client.snipes.set(message.channel.id, {
content: message.content,
author: message.author.tag,
})
}
All other commands work perfectly
Make sure you pass the arguments in the correct order.
If you run the callback like this:
callback(message, arguments, arguments.join(' '), client);
The order should be like this:
module.exports = {
commands: ['snipe', 'sn', 's'],
requiredRoles: ['Members'],
callback: (message, arguments, joinedArguments, client) => {
const msg = client.snipes.get(message.channel.id);
if (!msg) return message.channel.send("There's nothing to snipe!");
message.channel.send(`${msg.author} deleted: ${msg.content}`);
}
};

How to set up a SlashCommand with custom options for discord

I've been at this for 4h now... I'm making a discord bot that should take a user's input and define the word using an API call. I have an index.js that should call my urban.js file and define a word a user inputs. For example, if a user inputs "/urban cow," the bot should put the definition of a cow. However, right now it cannot read the option after "/urban" no matter what I try.
// THIS IS MY urban.js FILE
const {
SlashCommandBuilder,
SlashCommandStringOption
} = require('#discordjs/builders');
const {
request
} = require('undici');
const {
MessageEmbed
} = require('discord.js');
const wait = require('node:timers/promises').setTimeout;
const trim = (str, max) => (str.length > max ? `${str.slice(0, max - 3)}...` : str);
async function getJSONResponse(body) {
let fullBody = '';
for await (const data of body) {
fullBody += data.toString();
}
return JSON.parse(fullBody);
}
module.exports = {
data: new SlashCommandBuilder()
.setName('urban')
.setDescription('Replies with definition!')
.addStringOption(option =>
option.setName('input')
.setDescription('word to define')
.setRequired(true)),
async execute(interaction) {
const term = interaction.options.getString('input')
console.log(term);
const query = new URLSearchParams({
term
});
const dictResult = await request(`https://api.urbandictionary.com/v0/define?${query}`);
const {
list
} = await getJSONResponse(dictResult.body);
if (!list.length) {
return interaction.editReply(`No results found for **${term}**.`);
}
const [answer] = list;
const embed = new MessageEmbed()
.setColor('#EFFF00')
.setTitle(answer.word)
.setURL(answer.permalink)
.addFields({
name: 'Definition',
value: trim(answer.definition, 1024)
}, {
name: 'Example',
value: trim(answer.example, 1024)
}, {
name: 'Rating',
value: `${answer.thumbs_up} thumbs up. ${answer.thumbs_down} thumbs down.`,
}, );
interaction.editReply({
embeds: [embed]
});
},
};
// THIS IS THE INDEX JS FILE. It's not a filepath issue.
const {
token
} = require('./config.json');
const fs = require('node:fs');
const path = require('node:path');
const {
Client,
Collection,
Intents,
MessageEmbed,
DiscordAPIError
} = require('discord.js');
const wait = require('node:timers/promises').setTimeout;
const client = new Client({
intents: [Intents.FLAGS.GUILDS]
});
client.commands = new Collection();
const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
const eventsPath = path.join(__dirname, 'events');
const eventFiles = fs.readdirSync(eventsPath).filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const filePath = path.join(eventsPath, file);
const event = require(filePath);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args));
} else {
client.on(event.name, (...args) => event.execute(...args));
}
}
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
// Set a new item in the Collection
// With the key as the command name and the value as the exported module
client.commands.set(command.data.name, command);
}
client.once('ready', () => {
console.log('Ready!');
});
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
await interaction.deferReply({
ephemeral: true
});
await wait(4000);
if (!command) return;
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
}
});
console.log(token)
client.login(token)
When I console.log(interaction.options.getString('input'))
it just gives me null.
when I console.log interaction it gives me a detailed account of the command and everything else like the user that sent it. But none of the information from the SlashCommand data. Please help.

creating a help command for my discord bot

I am trying to create a help page that lists all the commands for my discord bot...
currently everything is coming through as Undefined within the discord and I am confused as to why.
Here is my help.js
const fs = require('fs');
const { SlashCommandBuilder } = require('#discordjs/builders');
module.exports = {
data: new SlashCommandBuilder()
.setName('help')
.setDescription('Lists all available commands'),
async execute(interaction) {
let str = '';
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./${file}`);
str += `Name: ${command.name}, Description: ${command.description} \n`;
}
return void interaction.reply({
content: str,
ephemeral: true,
});
},
};
I could try to do the v12 way, but I am trying to make a bot that is completely up to date with v13...
Assuming all of your commands are structured like the code you presented, you were only missing a couple things. First was that the command name and description would be under command.data not just command. Also with let you can leave it empty (as I have) and fill it with anything.
const fs = require('fs');
const { SlashCommandBuilder } = require('#discordjs/builders');
module.exports = {
data: new SlashCommandBuilder()
.setName('help')
.setDescription('Lists all available commands'),
async execute(interaction) {
let str
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./${file}`);
str += `Name: ${command.data.name}, Description: ${command.data.description} \n`;
}
return interaction.reply({
content: str,
ephemeral: true,
});
},
};

Cannot read properties of null (reading 'id') [Discord Slash Commands]

I'm trying to get a little familiar with the slash command handler, but I get an error when trying to grab the member id, this happens with just about everything I try to grab.
Here at the top is directly my command, where I try to send a message with the content "user.id".
this is my command:
const { SlashCommandBuilder } = require("#discordjs/builders");
module.exports = {
data: new SlashCommandBuilder()
.setName("avatar")
.setDescription("SERVUSSS")
.addUserOption(option => option.setName("member").setDescription("memberdings").setRequired(true)),
async execute(interaction) {
const user = interaction.options.getUser('target');
await interaction.reply(`${user.id}`);
}
}
this is my deploy file:
require("dotenv").config();
const fs = require("fs");
const { REST } = require("#discordjs/rest");
const { Routes } = require("discord-api-types/v9");
const commands = [];
const commandFiles = fs.readdirSync("./src/commands").filter(file => file.endsWith(".js"));
commandFiles.forEach(commandFile => {
const command = require(`./commands/${commandFile}`);
commands.push(command.data.toJSON());
});
const restClient = new REST({version: "9"}).setToken(process.env.TOKEN);
restClient.put(Routes.applicationGuildCommands(process.env.APPLICATION_ID, process.env.GUILD_ID),
{body: commands }).then(() => console.log("success")).catch(console.error);
my index file:
require("dotenv").config();
const { Client, Collection } = require("discord.js");
const fs = require("fs");
const client = new Client({intents: []});
client.commands = new Collection();
const commandFiles = fs.readdirSync("./src/commands").filter(file => file.endsWith(".js"));
commandFiles.forEach(commandFile => {
const command = require(`./commands/${commandFile}`);
client.commands.set(command.data.name, command);
});
client.once("ready", () => {
console.log("ready!!");
});
client.on("interactionCreate", async (interaction) => {
if(!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName)
if(command) {
try {
await command.execute(interaction)
} catch(error) {
console.log(error)
if(interaction.deferred || interaction.replied) {
interaction.editReply("error")
} else {
interaction.reply("error")
}
}
}
})
client.login(process.env.TOKEN)
I actually stick to it pretty much all the time
https://discordjs.guide/ just do not understand what I'm doing wrong
Since option name is member then it's going to be
const user = interaction.options.getUser('member');
In your command file, the name for the option is given as member, but when you are using interaction.options.getUser(), you are passing the name as 'target'. So all you have to do is change the line where you are declaring the user to: const user = interaction.options.getUser('member')

Discord.js Join and Leave Events not working

i am trying to make a bot with some new tricks i figured out but the events arent working.
When someone Joins or Leaves, it doesn't event log it in the console.
index.js:
const config = require('./config.js');
const {Client} = require('discord.js');
const client = new Client();
const utils = require('./utils.js');
let prefix = config.prefix;
client.on('ready', () => {
utils.ready(client);
utils.registerEvents(client);
});
client.on("message", message => {
utils.onMessage(client, message, prefix);
})
client.login(config.token);
utils.js:
const fs = require("fs");
const eventHandler = require('./eventHandler.js');
module.exports.ready = async (client) => {
console.log("--------------------");
console.log("Name: " + client.user.username);
console.log("ID: " + client.user.id)
console.log("--------------------");
client.user.setActivity("Team INSTINCT BETA", {"type": "STREAMING", "url": "https://twitch.tv/hanyaku"});
}
module.exports.onMessage = async (client, message, prefix) => {
let raw = message.content.slice(prefix.length).split(" ");
let cmd = raw[0];
let rawArgs = raw.join(" ");
let args = rawArgs.slice(cmd.length).split(" ");
if(message.content.startsWith(prefix))
{
fs.exists(`./commands/${cmd}.js`,function(exists){
let cmdFile = require(`./commands/${cmd}.js`);
cmdFile.run(client, message, args);
});
}
}
module.exports.registerEvents = async (client) => {
eventHandler.register(client,'guildMemberAdd');
eventHandler.register(client,'guildMemberRemove');
}
eventHandler.js:
module.exports.register = async (client, eventName) => {
eval(`${eventName}(client);`);
}
function guildMemberAdd(client)
{
client.on('guildMemberAdd', member => {
let eventFile = require(`./commands/guildMemberAdd.js`);
eventFile.run(client, member);
});
console.log("Event guildMemberAdd Registriert");
}
function guildMemberRemove(client)
{
client.on('guildMemberRemove', member => {
let eventFile = require(`./commands/guildMemberRemove.js`);
eventFile.run(client, member);
});
console.log("Event guildMemberRemove Registriert");
}
guildMemberAdd.js:
const { Client, Collection, MessageEmbed, MessageAttachment } = require('discord.js');
const fs = require("fs");
const Canvas = require('canvas');
const fetch = require("node-fetch");
module.exports.run = async (client, member) => {
console.log('Member Joined');
let channel = client.channels.cache.get('776942211798532106');
let { user } = member;
var name = user.tag;
let embed = new MessageEmbed()
.setTitle('Welcome')
.setDescription('Have a nice time, ' + name)
channel.send(embed);
}
I guess the error is in the eventHandler.js or in the guildMember.js
I hope to get help.
Greetings
-Hanyaku
I think you need to enable SERVER MEMBERS INTENT.
Go to discord dev portal and in bot section there will be SERVER MEMBERS INTENT option, enable it.

Categories

Resources