Trying to make a fish command /discord.js - javascript

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".

Related

How do I get the users activity discord.js

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.

Bot assigns user a role, even if user doesn't own role

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.

Code not reading the info from the json file

So I'm trying to set up a command to view the amount of candy you have using the info stored in the json file. It doesn't seem to be reading the information correctly.
Here is the command file
const fs = require('fs');
const candyAmount = JSON.parse(fs.readFileSync('./candyheld.json', {encoding:'utf8'}));
const { prefix } = require('../../config.json');
module.exports = {
name: 'candy',
description: 'Displays the amount of candy the user has.',
execute (message, args) {
if (!candyAmount[message.author.id]) return message.channel.send(`You haven\'t started the event yet! Type ${prefix}trickortreat to start!`);
const { candyStored } = candyAmount[message.author.id].candyStored;
message.channel.send(`You have ${candyStored} pieces of candy!`);
},
};
and here is what the json file looks like when it has the info
{"ID":{"candyStored":5}}
I have removed the actual ID number and replaced it with just the word just for this moment. The actual number is in the code.
trickortreat command file
const fs = require('fs');
const candyAmount = JSON.parse(fs.readFileSync('./candyheld.json', {encoding:'utf8'}));
module.exports = {
name: 'trickortreat',
description: 'Special Halloween command',
execute(message, args) {
if (!candyAmount[message.author.id]) {
candyAmount[message.author.id] = {
candyStored: 5
}
fs.writeFile('./candyheld.json', JSON.stringify(candyAmount), err => {
if (err) console.error(err);
});
return message.channel.send('For starting the event, you have been given 5 pieces of candy!');
}
// Stores a random number of candy from 1-3
let candy = Math.floor(Math.random() * 3 + 1);
// Sets the possible messages to be received
let trickortreatmessage = [
'The scarecrow standing behind you jumps out at you and makes you drop all your candy!',
`${message.guild.members.cache.random()} was nice enough to give you Candy! You got ${candy} pieces of candy!`,
`Oh no you asked ${message.guild.members.cache.random()} for Candy and they decided to egg you instead!`
]
// Store one of the random messages
const trickortreat = trickortreatmessage[Math.floor(Math.random() * trickortreatmessage.length)];
if (trickortreat == trickortreatmessage[0]) {
candyAmount[message.author.id].candyStored = 0;
} else if (trickortreat == trickortreatmessage[1]) {
candyAmount[message.author.id].candyStored = candyAmount[message.author.id].candyStored + candy;
}
fs.writeFile('./candyheld.json', JSON.stringify(candyAmount), err => {
if (err) console.error(err);
});
message.channel.send(trickortreat);
},
};
I've been adding some new things and trying to fix this issue and I got an update that will hopefully help figure this out. I made an "addcandy" command to add candy to specific users mentioned. When I use the command, and then use /candy, it reads it perfectly.
So I'm thinking #ericgio was right in that it has something to do with the "trickortreat" command. It adds the number fine but for some reason "candy" isn't reading that change. But it reads the change when I use "addcandy"
So I managed to figure out for anyone else having the same issue. I changed the "const candyAmount" to just be "require('../../candyheld.json') and did the same for my other files and it seems to read correctly now
old code line
const candyAmount = JSON.parse(fs.readFileSync('./candyheld.json', {encoding:'utf8'}));
new code line
const candyAmount = require('../../candyheld.json');

if else in loop bringing up errors in typescript

I have this function that is supposed to get referral codes from users. User gives a code and the referral code checked if it exists in the database then evaluated if
it does not match the current user, so that one should not refer himself and
it is a match with one of the codes in the database
This code however just does not find a match even if the code given is in the database. If the referral code matches the one of the current user, it works correctly and points that out i.e one cannot refer themselves.
But if the referral code is a match to that of another user which is how a referral system should work, it still says no match.
How can I remove this error
export const getID = functions.https.onCall(async(data, context) => {
const db = admin.firestore();
const usersSnapshot = await db.collection("user").get();
const allUIDs = usersSnapshot.docs.map(doc => doc.data().userID);
const userID = context.auth.uid;
const providedID = "cNx7IuY6rZlR9mYSfb1hY7ROFY2";
//db.collection("user").doc(providedID).collection("referrals").doc(userID);
await check();
function check() {
let result;
allUIDs.forEach(idFromDb => {
if (providedID === idFromDb && (idFromDb === userID)) {
result = "ownmatch";
} else if (providedID === idFromDb && (idFromDb !== userID)) {
result = "match";
} else {
result = "nomatch";
}
});
return result;
}
if (check() === "match") {
return {
message: `Match Found`,
};
} else if (check() === "ownmatch") {
return {
message: `Sorry, you can't use your own invite code`,
};
} else {
return {
message: `No User with that ID`
};
}
});
(This is not an answer, but a simple refactoring.)
This is what your code is currently doing (roughly, I didn't run it):
const resultMsgs = {
nomatch: 'No User With That ID',
ownmatch: 'Sorry, you can\'t use your own invite code',
match: 'Match Found',
}
function check(uids, providedId, userId) {
let result
uids.forEach(idFromDb => {
if (providedId !== idFromDb) {
result = 'nomatch'
return
}
if (userID === idFromDb) {
result = 'ownmatch'
return
}
result = 'match'
})
return result
}
export const getID = functions
.https
.onCall(async (data, context) => {
const userId = context.auth.uid
const providedId = 'cNx7IuY6rZlR9mYSfb1hY7ROFY2'
const db = admin.firestore()
const user = await db.collection('user').get()
const uids = user.docs.map(doc => doc.data().userId)
const checkResult = check(uids, providedId, userId)
return { message: resultMsgs[checkResult] }
})
(I removed the seemingly-spurious db collection operation.)
Your forEach is iterating over all of the uuids, but result will be set to whatever the last comparison was. Perhaps this is correct, but:
If you're looking for any match, this is not what you want.
If you're looking for all matches, this is not what you want.
If you're looking to match the last UUID, it's what you want, but an odd way to go about it.
So:
If you want any matches, use... ahem any form of an any function.
If you want all matches, use any form of an all function.
If you want the first match, then just check the first element.
If you want the complete set of comparisons then you'll need to use map instead of forEach, and handle each result appropriately, whatever that means in your case.
In any event, I'd recommend breaking up your code more cleanly. It'll be much easier to reason about, and fix.

Why doesn't kicking people work using discord.js

const Discord = require("discord.js"),
bot = new Discord.Client();
let pre = "?"
bot.on("message", async msg => {
var msgArray = msg.content.split(" ");
var args = msgArray.slice(1);
var prisonerRole = msg.guild.roles.find("name", "Prisoner");
let command = msgArray[0];
if (command == `${pre}roll`) {
if (!msg.member.roles.has(prisonerRole.id)) {
roll = Math.floor(Math.random()*6)+1;
msg.reply(`You rolled a ${roll}`)
} else {
msg.reply(`HaHa NOOB, you're in prison you don't get priveleges!`)
}
}
if (command == `${pre}kick`) {
var leaderRole = msg.guild.roles.find("name", "LEADER");
var co_leaderRole = msg.guild.roles.find("name", "CO-LEADER");
if (msg.member.roles.has(leaderRole.id) ||
msg.member.roles.has(co_leaderRole.id)) {
var kickUser = msg.guild.member(msg.mentions.users.first());
var kickReason = args.join(" ").slice(22);
msg.guild.member(kickUser).kick();
msg.channel.send(`${msg.author} has kicked ${kickUser}\nReason: ${kickReason}`);
} else {
return msg.reply("Ya pleb, you can't kick people!");
}
}
})
bot.login("token").then(function() {
console.log('Good!')
}, function(err) {
console.log('Still good, as long as the process now exits.')
bot.destroy()
})
Everything works except actually kicking the person. The message sends nut it doesn't kick people. For example, when I type in ?kick #BobNuggets#4576 inactive, it says
#rishabhase has kicked #BobNuggets
Reason: inactive
But it doesn't actually kick the user, which is weird, can you help me?
Change
msg.guild.member(kickUser).kick();
to
kickUser.kick();
also, make sure the bot is elevated in hierarchy
Use kickUser.kick();
I recommend using a command handler to neaten up your code. You don't want all your commands in one .js file.
Try something like this for the Ban command itself. I use this for my Bot:
client.on("message", (message) => {
if (message.content.startsWith("!ban")) {
if(!message.member.roles.find("name", "Role that can use this bot"))
return;
// Easy way to get member object though mentions.
var member= message.mentions.members.first();
// ban
member.ban().then((member) => {
// Successmessage
message.channel.send(":wave: " + member.displayName + " has been successfully banned :point_right: ");
}).catch(() => {
// Failmessage
message.channel.send("Access Denied");
});
}
});
That should work, set the role you want to use it (cAsE sEnSiTiVe) and change !ban to whatever you feel like using. If you change all "ban"s in this to kick, it will have the same effect. If this helped you, mark this as the answer so others can find it, if not, keep looking :)

Categories