Problem: I have been trying to add a "Activity" field to my info command, and its not working.
Expected result: Responds with the other stuff, along with the Activity field, showing what the user is doing.
Actual response: Shows everything else correctly, except the Activity field, which says undefined/null.
Code:
if (command == "info") {
const embed = new Discord.MessageEmbed()
let member = message.mentions.members.first() || message.guild.members.cache.get(args[1]) || message.guild.member(message.author)
const Roles = new Array()
message.guild.roles.cache.forEach(role => {
if (member.roles.cache.find(r => r.id == role.id)) {
Roles.push(role)
}
})
console.log(member.presence)
embed.setAuthor(user.tag, member.user.avatarURL())
embed.setTitle(`👋 Welcome to ${user.username}'s Profile!`)
embed.addField('#️⃣ Tag:', member.user.tag)
embed.addField('📡 Joined Guild at:', member.user.joinedAt)
embed.addField('💬 Joined Discord at:', member.user.cretedAt
)
if (!member.presence.activities) {
embed.addField('⚽️ Activity:', 'Not playing anything')
} else {
embed.addField('⚽️ Activity:', `${member.presence.activities.type} ${member.presence.activities.name}\n${member.presence.activities.details}\n${member.presence.activities.state}`)
}
embed.addField('📱 Platform:', member.presence.clientStatus)
embed.addField('🤖 Bot:', user.bot)
embed.addField('📜 Roles:', Roles.join(' | '))
embed.setFooter('Bot made with discord.js')
message.channel.send(embed)
}
Presence.activities is an array of Activity.
// Add check for empty activities array
if (!member.presence.activities || member.presence.activities.length == 0) {
embed.addField('⚽️ Activity:', 'Not playing anything')
} else {
const activity = member.presence.activities[0];
embed.addField('⚽️ Activity:', `${activity.type} ${activity.name}\n${activity.details}\n${activity.state}`);
}
Most of the time you will only need the first item of the array. Because you rarely see users with multiple activities.
Related
I'm pretty new to discord.js and JavaScript in general so apologies if this is something really simple!
I'm working on a Discord bot and I'm trying to make it set a variable to a voice channel specified by the user. Currently, ChosenChannel remains null. It works if I replace args with the channel name directly in the code (line 8) but then it can't be changed by a user.
Thanks in advance for any help!
client.on ('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if (command == 'setchannel') {
//set ChosenChannel to a channel within the current server that matches the name typed by the user (not currently working!)
ChosenChannel = message.guild.channels.cache.find(channel => channel.name === args);
//alert user if ChosenChannel is not an actual channel
if (ChosenChannel == null) {
message.channel.send('Unable to find channel');
//alert user if ChosenChannel is not a voice channel
} else if (ChosenChannel.type !== 'voice') {
message.channel.send('That does not seem to be a voice channel');
//otherwise, confirm that the command worked, and print the name of the channel
} else {
message.channel.send('The chosen channel is: ');
message.channel.send(ChosenChannel.name);
}
}
});
args is an array, the channel's name is a string. So you'll need to convert args to a string by joining it back by a space character.
if (command == 'setchannel') {
//set chosenChannel to a channel within the current server that matches the name typed by the user (not currently working!)
const channelName = args.join(' ')
const chosenChannel = message.guild.channels.cache.find(
(channel) => channel.name === channelName,
);
//alert user if chosenChannel is not an actual channel
if (!chosenChannel) {
message.channel.send('Unable to find channel');
//alert user if chosenChannel is not a voice channel
} else if (chosenChannel.type !== 'voice') {
message.channel.send('That does not seem to be a voice channel');
//otherwise, confirm that the command worked, and print the name of the channel
} else {
message.channel.send('The chosen channel is: ');
message.channel.send(chosenChannel.name);
}
}
Actually, channel names can't have spaces, so it will be always the first element of args, so you could also use it like this:
if (command == 'setchannel') {
//set chosenChannel to a channel within the current server that matches the name typed by the user (not currently working!)
const chosenChannel = message.guild.channels.cache.find(
(channel) => channel.name === args[0],
);
// ...
Sorry for the confusing title, I'll clarify. I'm trying to make the bot check if a user has a certain role in their quick.db inventory, and if they do, it'll equip that role. The problem I'm having is that even with the role in the inventory, it returns the error that the role isn't owned. I have a feeling that the problem is the if (db.has(message.author.id + '.hot rod red')) line, as I'm not too sure how to format checking for a role with quick.db. Sorry for the messy code, if anyone knows how to fix this let me know, thanks!
if (db.has(message.author.id + '.hot rod red')) {
if (message.member.roles.cache.some(role => role.name === 'hot rod red')) {
let embed = new Discord.MessageEmbed().setDescription('You already have this role equipped!');
return message.channel.send(embed);
} else {
await message.guild.members.cache.get(user.id).roles.add('733373020491481219');
let embed = new Discord.MessageEmbed().setDescription(`You now have the ${message.guild.roles.cache.get('733373020491481219')} role!`);
message.channel.send(embed);
user.roles.remove(user.roles.highest);
}
} else {
let embed = new Discord.MessageEmbed().setDescription('You do not own this role!'); // ERROR HERE; GIVES ROLE EVEN WITHOUT OWNING
return message.channel.send(embed);
}
Probably try something like
let check = db.get(message.author.id+'.hot rod red')
and check if it is true/false, I'd say to use string rather then boolean as you can use if(check === 'false/true'){}. You can also do
if(!check || check === 'false'){ return
let embed = new Discord.MessageEmbed().setDescription('You do not own this role!');
return message.channel.send(embed);
}
So the final code would be:
let check = await db.get(message.author.id + '.hot rod red');
let rejectEmbed = new Discord.MessageEmbed()
.setDescription('You do not own this role!');
if(!check){
return message.channel.send(rejectEmbed)
}
if(check === 'true'){
if (message.member.roles.cache.some(role => role.name === 'hot rod red')) {
let embed = new Discord.MessageEmbed().setDescription('You already have this role!');
return message.channel.send(embed);
} else {
await message.guild.members.cache.get(user.id).roles.add('733373020491481219');
let embed = new Discord.MessageEmbed().setDescription(`You now have the ${message.guild.roles.cache.get('733373020491481219')} role!`);
message.channel.send(embed);
user.roles.remove(user.roles.highest); // I'm unsure why this is here, this could be causing a potential error
}
}
If there are any more questions, please comment!! I hope this has helped.
Now, I have my shop and all the items already. I want the user so when they buy the FishingRod, they get put in a new Set();, and once they are in that set they can use the fish command. Here's my code for the 'buy' command:
else if (command === 'buy') {
const args = message.content.slice(PREFIX.length).trim().split(' ');
if (isDead.has(message.author.id)) {
message.channel.send('You\'re dead right now lmao you need to wait 5 more minutes before using any more currency and game related commands');
}
const item = await CurrencyShop.findOne({ where: { name: { [Op.like]: commandArgs } } });
if (!item) return message.channel.send('That item doesn\'t exist.');
if (args === 'FishingRod') {
hasRod.add(message.author.id);
}
if (item.cost > currency.getBalance(message.author.id)) {
return message.channel.send(`You don't have enough currency, ${message.author}`);
}
const user = await Users.findOne({ where: { user_id: message.author.id } });
currency.add(message.author.id, -item.cost);
await user.addItem(item);
message.channel.send(`You've bought a ${item.name}`);
}
As you can see, I've already made it so when the args are 'FishingRod', it puts them in the Set. The problem is that when this happens, and I try running the fish command, it still says I haven't got a FishingRod and need to buy one. Any help would be appreciated.
Okay, you're trying to compare the command arguments (which is an array) to a string. You could just do args[0] to get the first argument. Also, you're making it so that it has to be "FishingRod" and can't be lowercase. Try args[0].toLowerCase() === "fishingrod".
I am trying to close a ticket by reacting to a button. But reaction must be given by "support" role. I couldnt do it. reaction.message.member.roles.has is not helping me at this point. Here is my code ;
client.on("messageReactionAdd", (reaction, user) => {
if(reaction.message.member.roles.has('ROLE')) {
let id = user.id.toString().substr(0, 4) + user.discriminator;
let chan = `ticket-${id}`;
const supchan = reaction.message.guild.channels.find(
(channel) => channel.name === chan
);
const chan_id = supchan ? supchan.id : null;
if (
reaction.emoji.name === "🔒" &&
!user.bot &&
user.id != "ID"
) {
reaction.removeAll();
const channel = client.channels.find("name", chan);
const delMsg = new Discord.RichEmbed()
.setColor("#E74C3C")
.setDescription(`:boom: Ticket will be deleted in 5 seconds.`);
channel.send(delMsg).then(() => {
var counter = 0;
const intervalObj = setInterval(() => {
counter++;
if (counter == 5) {
const message = reaction.message;
message.delete();
Thanks for helps !
All of this wrapped inside the messageReactionAdd event
// Replace "message_id" with the proper message id
// Checks if it's the correct message
if (reaction.message.id == "message_id") {
// Check if author of ticket message is from the same user who reacted
if (reaction.message.author == user) {
// Check correct emoji
if (reaction.emoji.name == "🔒") {
// Code to close ticket
}
}
}
EDIT:
Again, this would be wrapped inside the messageReactionAdd event:
// Try to get the ticket message
// If there's none then the user was never opened a ticket so we simply return the code
const ticketMessage = client.tickets.get(user);
if (!ticketMessage) return;
// Checks if it's the correct message
if (reaction.message.id == ticketMessage.id) {
// Check correct emoji
if (reaction.emoji.name == "🔒") {
// Code to close ticket
}
}
I removed the code that check for the reaction message author because getting ticketMessage already handles that. Do note that this means you can make sure a user can only open one ticket.
I've been trying to get the last message of a channel writing a command in another channel.
I want to do something like this:
Channel 1 : (I write) "Get last message of channel 2
channel 2: Last message is ("Hello");
Channel 1: i receive the last message of channel 2 saying, the last message of channel 2 is . "Hello".
My code is this, but isn't working.
if (message.channel.id === '613573853565681671') {
message.channel.fetchMessages().then(collected => {
const filtered = collected.filter(message => message.author.bot);
const lastMessages = filtered.first(1); //Get the last message of this channel.
const TextMessages = `${lastMessages[0].content}`;
console.log(TextMessages + " is the last message of aviso jobs")
if (TextMessages === "look") { //If the last message of this channel is look then go to the other channel
if (message.channel.id === '613553889433747477') {
message.channel.fetchMessages().then(collected => {
const filtered = collected.filter(message => message.author.bot);
const lastMessages2 = filtered.first(1); //Get the last message of this other channel.
const TextMessages2 = `${lastMessages2[0].content}`;
console.log(TextMessages2 + " is the last message of bot")
});
}
}
});
}
I'm having troubles understanding your code so here's how i would do it, maybe it'll help you:
if (message.content.startsWith("!lastmessage")) {
let args = message.content.split(" "); //find every word of the message
if (args.length > 1) { //make sure that there is at least 1 argument, which should be the target channel's id
let target = message.guild.channels.find(c => c.id == args[1]) || null; // find the targeted channel
if (target) { // make sure that the targeted channel exists, if it exists then fetch its last message
target
.fetchMessages({ limit: 1 })
.then(f =>
message.channel.send(
`Last message from <#${target.id}> is...\n> ${f.first().content}`
) // send the last message to the initial channel
);
} else { //if target doesn't exist, send an error
message.channel.send("Target does not exist!");
}
}
}