So im trying to make a command that lists all the members in a discord server but it doesnt seem to be working. I did research, tried different methods and none seem to work. This is the code im working with right now.
const bot = new Discord.Client();
bot.on("message", async msg => {
if (msg.author.id !== config.id) return;
let content = msg.content;
let text = content.toLowerCase();
let author = msg.author;
let member = msg.member;
let args = content.split(" ").slice(1);
let argsLower = text.split(" ");
let command = argsLower[0].replace(prefix, "");
if (!msg.content.startsWith(config.prefix)) return;
if (command === "listmembers"){
msg.delete();
msg.channel.guild.fetchMembers().then(guild =>{
console.log("test");
guild.members.forEach(member => console.log(member.user.username));
} );
}
i tried console logging "test" in the function but that doesnt show up in console so i cant seem to get into the function.
If you want to console.log() all of the members, it's just:
message.guild.members.forEach(member => console.log(member.user.username));
but if you're trying to list them out into chat you need to:
var list = [];
message.guild.members.forEach(member => list.push(member.user.username));
message.reply(`Total members: ${message.guild.memberCount}`);
const embed4 = new Discord.RichEmbed()
.setColor(0x684dad)
.setTitle('Member List:')
.setDescription(list);
message.channel.send(embed4);
You can customize it as you wish but that's just an example.
Related
I used a role color changer peice of code, and it was pretty cool, until I uploaded it to glitch.com, now all I get is the "args is not defined" error again, here is a small chunk of the code I was using
const Discord = require('discord.js');
const client = new Discord.Client();
const TOKEN = process.env.TOKEN
require('events').EventEmitter.defaultMaxListeners = 75;
var red = ['#ff0000']
client.on('message', message => {
if (message.content.startsWith('grimm!change red')) {
message.channel.send('color for changed to Red')
const colorRole = message.mentions.roles.first() || message.guild.roles.cache.find(R => R.name === args.join(" "));
colorRole.edit({
color: red[0]
})
}})
client.login(TOKEN)
could anyone tell me how I could possibly fix this? I have been researching everywhere but I have no clue on how to fix this. Thanks!
Try this
client.on('message', message => {
...
const args = message.content.slice(prefix.length).trim().split(' ');
...
});
Command with user input
Attempting to implement texas hold em poker in discord with a bot using node js.
Currently have a problem try to nest
client.on('message', message => {
calls. The idea behind these is that the first one looks for the !poker command, and subsequent ones listen for joining players, player bets etc.
code:
const Discord = require('discord.js');
const dotenv = require('dotenv').config();
const Game = require("./classes.js").Game
const Player = require("./classes.js").Player
// create a new Discord client
const client = new Discord.Client();
// when the client is ready, run this code
// this event will only trigger one time after logging in
client.once('ready', () => {
console.log('Ready!');
});
let prefix = '!';
client.on('message', message => {
//prevent feedback loops
if (!message.content.startsWith(prefix) || message.author.bot) return;
if (message.content.startsWith(`${prefix}poker`)){
//getting args
const args = message.content.slice(prefix.length).trim().split(' ');
const command = args.shift().toLowerCase();
//converting to relevant data type
let no_players = parseInt(args[0]);
let money = parseInt(args[1])
//initialising game object and card deck
let game = new Game();
game.deck = game.createDeck();
//list to contain players (will be objects from the Player class)
let players = [];
//list to contain player usernames, will be used to identify if someone has already joined
let player_users = [];
// loop until we have enough players, as specified by the first input arguemnt
while (players.length <= no_players){
//now wait for a join message
client.on('message', message => {
//if message == join, and the player has not already joined
if (message.content.startsWith('join')){
if (!players.includes(message.author.username)){
let newPlayer = new Player(message.author.username,money);
players.push(newPlayer);
player_users.push(message.author.username);
}
}
});
}
//debugging purposes
console.log(players)
}
if (message.content.startsWith(`${prefix}hands`)){
message.channel.send("Here are the poker hands", {files: ["poker-hand-rankings-mobile.png"]});
}
});
client.login(process.env.TOKEN);
The command syntax in discord will look like !poker {number of players} {betting money for each player}
Other functionality in create decks etc works fine.
When I run in the debugger it doesnt seem to enter the second client.on code block, and I recieve this error upon running FATAL ERROR: MarkCompactCollector: young object promotion failed Allocation failed - JavaScript heap out of memory
Not sure if my overall approach is flawed here, i.e. discord.js cant have two processes waiting for messages running at the same time. Or if there is variable overlap between defining message.
Considering scrapping and moving to python so any help would be greatly appreciated.
Hi guys I have a problem so when I use the command it should show the number of users but it shows 0. How can i fix it?
Code:
if(command === `${prefix}test`) {
let guild = new Discord.Guild(600811118667235339);
var memberCount = guild.members.filter(member => !member.user.bot).size;
let embed = new Discord.RichEmbed()
.addField("Liczba osob", `${memberCount}`)
message.channel.send(embed)
}
You cannot create a new instance of a Discord.Guild() like this. You need to use something like that:
let guild = message.client.guilds.get("600811118667235339");
It will get the guild which has for ID 600811118667235339.
I'm setting up my first discord bot, which will be able to take data from a Google Spreadsheet, from the official API and bring it as a embed message in discord. The problem is at the level of the .addField(), where I can not enter the value of the cell. How can I do this?
const { Client, RichEmbed } = require('discord.js');
const client= new Client();
const GoogleSpreadsheet = require('google-spreadsheet');
const {promisify} = require('util');
const creds = require('./client_secret.json');
client.on('message', message => {
if (message.content === '!bot'){
async function accessSpreadsheet() {
const doc = new GoogleSpreadsheet('1qA11t460-ceILmwu6RtfiPGb_n9MUD_7z6Ld7I_Z6yc');
await promisify(doc.useServiceAccountAuth)(creds);
const info = await promisify(doc.getInfo)();
var sheet = info.worksheets[0];
var cells = await promisify(sheet.getCells)({
'min-row': 2,
'max-row': 5,
'min-col': 3,
'max-col': 3,
'return-empty': true,
})
for (var cell of cells) {
message.author.send(cell.value)
}
}
accessSpreadsheet();
const embede = new RichEmbed()
.setColor('#0099ff')
.setTitle("My Title")
.addBlankField()
.setDescription('Some description')
.addBlankField()
.addField('Name', '•'+ cell[1].value , true)
.setTimestamp();
message.author.send(embede) }
})
client.login('xxx')
I expect the output "Terrassycup 3", but the actual output is "ReferenceError: cell is not defined" in console.log
A few issues I see with your code:
accessSpreadsheet() doesn't return any values it accesses.
accessSpreadhseet() returns a Promise since it's declared as async, but it's never awaited.
The scope of cell is within the for...of loop inside the accessSpreadsheet() function, yet you try to use it well outside of it.
Instead of sending each individual value to the user, you can add them as fields to the embed (the limit is 25) within the function you declare.
async function accessSpreadsheet(embed) {
// Insert the code already being used up to the for loop.
for (let i = 0; i < 25 && cells[i]; i++) embed.addField('Name', `•${cells[i].value}`, true);
}
var embed = new RichEmbed()
.setColor('#0099ff')
.setTitle('**Spreadsheet Info**')
.setDescription('Showing as many values as possible...');
accessSpreadsheet(embed)
.then(() => message.author.send(embed))
.catch(console.error);
I'm quite a newbie to node.js and I'm currently using discord.js to make a Discord bot. As soon as any bot command gets used the console prints a DeprecationWarning.
for example:
(node:15656) DeprecationWarning: Collection#find: pass a function instead
(node:15656) sometimes is another number, nearly always changing.
This is what my code looks like (only one command, I've got multiple, I get this error with all of them though):
const botconfig = require("./botconfig.json")
const Discord = require("discord.js");
const bot = new Discord.Client();
bot.on("ready", () => {
console.log(`Launched ${bot.user.username}...`);
bot.user.setActivity("Games", { type: "PLAYING" });
});
bot.on("message", async message => {
if (message.author.bot) return;
let prefix = botconfig.prefix;
let messageArray = message.content.split(" ");
let cmd = messageArray[0];
let args = messageArray.slice(1);
let botico = bot.user.displayAvatarURL;
if (cmd == `${prefix}help`) {
let helpEmbed = new Discord.RichEmbed()
.addField(".kick", "kick a user", true)
.addField(".ban", "ban a user", true)
.addField(".unban", "unbans a user", true)
.addField(".mute", "mutes a user over a period of time", true)
.setColor("#005b5f")
.setThumbnail(botico);
message.channel.send(helpEmbed);
console.log(`command used: help`);
};
});
bot.login(botconfig.token)
It is in one of your other commands. You more than likely are using something like #Collection.find('name', 'keyname') in one of the other commands.
This has been updated to #Collection.find(x => x.name === "name").
Like it says in the error. #Collection.find() requires a function instead. So use one and the error goes away.