So i was making a discord game bot where you collect chracters by opening chests, but the problem is that the characters appear again when you already have them.
I used the method db.push
the code:
if(has === true){
console.log(has)
let embed = new discord.MessageEmbed()
.setTitle('Chest Opening | Clash Chest')
.setDescription("<#"+message.author+"> got:\n"+amount+" :coin:")
.setColor('RANDOM')
.setFooter('Created by Tahmid GS#1867')
message.channel.send(embed)
await db.fetch(`coin_${message.author.id}`)
db.add(`coin_${message.author.id}`, amount)
}
else if(has === false){
console.log(has)
await db.fetch(`troop_${message.author.id}`)
db.push(`troop_${message.author.id}`, nada)
let embed = new discord.MessageEmbed()
.setTitle('Chest Opening | Clash Chest')
.setDescription("<#"+message.author+"> got:\n"+amount+" :coin:\n||Common: "+nada+"||")
.setColor('RANDOM')
.setFooter('Created by Tahmid GS#1867')
message.channel.send(embed)
await db.fetch(`coin_${message.author.id}`)
db.add(`coin_${message.author.id}`, amount)
await db.fetch(`card_${message.author.id}`)
db.add(`card_${message.author.id}`, 1)
}
has is let has = db.has(troop_${message.author.id}, nada)
I used let has = db.has(troop_${message.author.id}.nada)
and let has = db.has(nada,troop_${message.author.id})
But it doesn't seem to work, in the console is "false"
nada is the random chracter
You are checking if the database has a specific key. In the database under the key troop_${message.author.id} there is an array. You want to check if that array includes the character or not.
let has = (db.get(`troop_${message.author.id}`) || []).includes(nada);
Also you might want to check for the possibility that db.get() returns undefined or something like that. In that case we call .includes() on an empty array. Instead of getting an error TypeError: Cannot read property 'includes' of undefined.
Related
I'm trying to validate if I already have add a book of the same name AND grade (course) I'm not 100% sure if && works as AND in REACT but I think it does cause didn't got any complaints in the code anyways moving on to the issue:
const register = (e) => {
e.preventDefault();
const docRef = db.collection('libros').doc();
docRef.get().then((doc) => {
if (doc.id.descripcion == descripcion && doc.id.grado == grado)
{
window.alert("Book exist already")
}
else {
docRef.set({
materia: materia,
descripcion: descripcion,
editorial: editorial,
grado: grado,
precio: precio,
id: docRef.id
}).then((r) => {
window.alert("Book added")
})}
})
}
This is the snip code of where I'm having the issue my idea is to loop through all the documents I have in that collection I'm not sure if i'm writing it correctly (clearly not cause is not working).
The idea is that Documents have a field called Description and course (descripcion and grado) and I want to compare the documents first to check if they have the same description and course, like they can have the same description but not the same grade or the same grade but not the same description
(which I think I have that logic correctly) : doc.id.descripcion == descripcion && doc.id.grado == grado
But it doesn't seem to be even running through that code, any tips are welcome and from what I understand is suppose to loop and check every document.
Edit: Forgot to add how it looks in the firebase and the input
This will never find any duplicates:
const docRef = db.collection('libros').doc();
docRef.get().then((doc) => {
if (doc.id.descripcion == descripcion && doc.id.grado == grado) {
window.alert("Book exist already")
}
...
The reason for this is that the first line creates a reference to the new doc. The next line then tries to load that doc, which will never give you any data.
The doc.id.descripcion anddoc.id.grado are also wrong, and should probably be doc.data().descripcion anddoc.data().grado. But that doesn't matter too much, since you'll never get a document from get() anyway, since you're trying to load a document from a reference you just created and never wrote to.
To ensure something is unique in Firestore, use it as the ID of the documents. So if you want the book name and grade to be unique, create the document ID from the book name and grade, instead of asking Firestore to generate a unique ID for you:"
const docId = descripcion + grado;
const docRef = db.collection('libros').doc(docId);
docRef.get().then((doc) => {
if (doc.exists) {
window.alert("Book exist already")
}
...
I'm trying to make a mod logs, I'm not really good at this, I scripted myself and kinda worked but it didn't worked. So basically my plan is when someone types .modlogs #channel, bot is gonna get the channel id and type it to json file with guild id, i made that it works very well I'm stuck on getting key info from json file, im printing the values and they are same.
#commands.command(aliases=['purge'])
#commands.guild_only()
#commands.has_permissions(manage_messages=True)
async def clear(self,ctx, arg: int = None):
if arg is None:
await ctx.send(':x: You need to state a value!')
else:
with open('./logs.json', 'r') as f:
logsf = json.load(f)
if ctx.guild.id in logsf:
embedv = discord.Embed(color = discord.Colour.random())
embedv.add_field(name='Event Type:', value="Clear")
embedv.add_field(name='Channel:', value= ctx.channel)
embedv.add_field(name='Moderator:', value=ctx.message.author)
embedv.footer(text='Epifiz Logging')
schannel = commands.get_channel(logsf[ctx.guild.id])
await ctx.channel.purge(limit=arg)
await discord.schannel.send(embed=embedv)
await ctx.send('Done')
elif ctx.guild.id not in logsf:
await ctx.channel.purge(limit=arg)
await ctx.send(':white_check_mark: Successfully cleared {} messages.'.format(arg))
also my json file:
{
"838355243817369620": 853297044922564608
}
Also guild id is on json file, its not wrong.
Output
You made multiple mistakes in your code. The reason why you are getting the error is because this line here if ctx.guild.id in logsf: returns False even if the guild's id is in your JSON file. Here is why:
logsf = json.load(f) returns a dictionary. You'll get {"838355243817369620": 853297044922564608} it's unclear whether 838355243817369620 or 853297044922564608 is your guild id but think of it this way:
s = {1:2}
2 in s return False
and the second mistake is inserting "838355243817369620" as a str rather than an int like this 838355243817369620.
The solution is to use list() as follow if ctx.guild.id in list(logsf): and to insert "838355243817369620" as an int in your JSON file so it looks like this:
{
838355243817369620: 853297044922564608
}
#rather than this
{
"838355243817369620": 853297044922564608
}
value in embeds accepts str not discord objects. Use f"{input}" rather than the object as an input.
embedv.add_field(name='Channel:', value= f"{ctx.channel}")
embedv.add_field(name='Moderator:', value=f"{ctx.message.author}")
await schannel.send(embed=embedv) rather than await discord.schannel.send(embed=embedv)
From this line schannel = commands.get_channel(logsf[ctx.guild.id]) I can assume that 838355243817369620 is your server's id. So, I think that you can use:
if ctx.guild.id in logsf.keys(): instead of if ctx.guild.id in list(logsf):
and make sure to convert its keys values into int rather than str to make it work.
I have a bot that needs to send a message with a set message, followed by an integer defined by a variable. When I run this, the bot reacts to the message correctly but then doesn't send any response whatsoever. Why? XD (and yes I'm kinda bad and new at coding but idc I am determined to get this to work!)
EDIT: Ok it's sending the text and variable now, but it always prints as 0. Anyone know why it's always zero?
else:
emoji = '\N{Cross Mark}'
await message.add_reaction(emoji)
await message.channel.send("You messed it up at:")
await message.channel.send(f'{bowl_count}')
bowl_count == int(0)
Are you using on_message?
Also are you checking if bowl_count is equal to 0?
You don't need to provide int() unless you have a variable called 0 that's value is a string (text in quote marks)
else:
emoji = '\N{Cross Mark}'
await message.add_reaction(emoji)
await message.channel.send("YOU MESSED IT UP AT: ", bowl_count)
bowl_count = 0
Other than that it looks fine.
If you are using commands, then do define an await ctx.send("TEXT") as a variable called message
else:
emoji = '\n{Cross Mark}'
await message.add_reaction(emoji)
await message.channel.send("YOU MESSED IT UP AT: " + bowl_count)
bowl_count == int(0)
first, the escaped \N doesn't work, try \n
second, just use + to concatenate the strings
As a starter, you can not add a reaction that way, I would recommend doing this;
await message.add_reaction('👍')
As for using a valuable, you can do it using a f string:
text = "Hello!"
await ctx.send(f'{text}')
I want my bot to leave a discord server by using ;leave <GuildID>.
The code below does not work:
if (message.guild.id.size < 1)
return message.reply("You must supply a Guild ID");
if (!message.author.id == 740603220279164939)
return;
message.guild.leave()
.then(g => console.log(`I left ${g}`))
.catch(console.error);
You're most likely not supposed to be looking at message.guild.id, since that returns the ID of the guild you're sending the message in. If you want to get the guild ID from ;leave (guild id), you'll have to cut out the second part using something like .split().
// When split, the result is [";leave", "guild-id"]. You can access the
// guild ID with [1] (the second item in the array).
var targetGuild = message.content.split(" ")[1];
!message.author.id will convert the author ID (in this case, your bot ID) into a boolean, which results to false (since the ID is set and is not a falsy value). I'm assuming that you mean to have this run only if it the author is not the bot itself, and in that case, you're most likely aiming for this:
// You're supposed to use strings for snowflakes. Don't use numbers.
if (message.author.id == "740603220279164939") return;
And now, you just have to use the guild ID that you got from the message content and use that to leave the guild. To do that, just grab the Guild from your bot cache, and then call .leave(). All in all, your code should now look like this:
// Get the guild ID
var targetGuild = message.content.split(" ")[1];
if (!targetGuild) // targetGuild is undefined if an ID was not supplied
return message.reply("You must supply a Guild ID");
if (message.author.id == "740603220279164939") // Don't listen to self.
return;
client.guilds.cache.get(targetGuild) // Grab the guild
.leave() // Leave
.then(g => console.log(`I left ${g}`)) // Give confirmation after leaving
.catch(console.error);
Command raised an exception: HTTP Exception: 400 Bad Request (error code: 10014): Unknown Emoji and EOL while scanning string literal are the 2 errors I have having while trying to add a reaction to an embed msg with python (discord.py)
Here is the full code, the problem is around the exclamation mark
#client.command()
async def ask(ctx, *, question=None):
try:
page = urllib.request.urlopen(f'http://askdiscord.netlify.app/b/{ctx.message.author.id}.txt')
if page.read():
embed = discord.Embed(color=0xFF5555, title="Error", description="You are banned from using AskDiscord!")
await ctx.send(embed=embed, content=None)
return
except urllib.error.HTTPError:
pass
if question:
channel = client.get_channel(780111762418565121)
embed = discord.Embed(color=0x7289DA, title=question, description=f"""
Question asked by {ctx.message.author} ({ctx.message.author.id}). If you think this question violates our rules, click ❗️ below this message to report it
""")
embed.set_footer(text=f"{ctx.message.author.id}")
message = await channel.send(content=None, embed=embed)
for emoji in ('❗️'):
await message.add_reaction(emoji)
for emoji in ('🗑'):
await message.add_reaction(emoji)
embed = discord.Embed(color=0x55FF55, title="Question asked", description="Your question has been send! You can view in the answer channel in the [AskDiscord server](https://discord.gg/KwUmPHKmwq)")
await ctx.send(content=None, embed=embed)
else:
embed = discord.Embed(title="Error", description=f"Please make sure you ask a question...", color=0xFF5555)
await ctx.send(content=None, embed=embed)
Tuple need to have a , at the end if there is only one element in it else its considered as a string in your case change ('❗️') to ('❗️',)