Why python if command doesnt work correctly? - python

#Bot.command()
async def kod(ctx,discordid):
objects = Code.manager(db)
code_list = list(objects.all())
i = 1
while i <= len(code_list):
usercode = objects.get(i)
usercode = usercode.__dict__
id = usercode.get('discord_id')
print(discordid)
print(id)
if discordid == id:
await ctx.send("worked")
i = i + 1
I have problem with if command.you can see the result of the print(id) and print(discordid) code here:
806114153915875378
806114153915875378
You can see that discordid and id are the same.
But
if discordid == id:
await ctx.send("worked")
Code doesnt work correctly and bot doesnt send message.There isnt a error printed at terminal.

Try this program
if str(discordid) == str(id):
await ctx.send("worked")

Related

discord.py adding mentioned users to list

I want to make disposable register system by using list which makes adding the discord user to list when you mentioned it but when i try to get user input from message it fails
#bot.command()
async def gameset(ctx,playernum:int):
if playernum <= 10:
await ctx.send('player 1 "<assign #player" mention yourself like this!')
else:
await ctx.send('maximum 10 player!')
num = 1
while num < playernum:
playerlist = []
#bot.command()
async def assign(user):
if user == discord.User.mentioned_in(message=user):
listadd = user
playerlist.append(listadd)
await user.send(f"player {num + 1} mention yourself!")
elif user != discord.User:
await user.send("not user")
else:
await user.send("go fix it dumb")
if playerlist[num - 1] == discord.User:
num = num + 1
else:
await gameset.send("problem with the listing")
also i think this is not the only problem i tried like this too but then my mention/user percaption logic failed i think
#bot.command()
async def ata(user : discord.User):
if not user:
await user.send("go fix it dumb")
else:
listadd = user
playerlist.append(listadd)
await user.send(f"player {num + 1} mention yourself!")
I've tried with #bot.event but i made more progress with #bot.command so if this is able to do with #bot.event i would be pleased if you guys help me understand how can i do with event but command is sufficient too.
Edit: I tried using wait_for() command like this:
num = 1
while num < playernum:
playerlist = []
def check(msg2 : discord.member):
return msg2 == discord.mentions
msg2 = await bot.wait_for("message", check=check)
# player = await bot.fetch_member(msg2.id)
if msg2 == discord.member:
player = str(msg2.id)
listadd = player
playerlist.append(listadd)
await ctx.send(f"player {num + 1} mention yourself!")
num = num + 1
else:
await msg2.send("go fix it dumb")
and i think it worked but now i have another problem which is
discord.ext.commands.errors.CommandNotFound: Command "#!id>" is not found
i get this when i try to mention someone

Discord.py command that deletes messages doesn't work

I'm trying to make a command that deletes a number of messages I want, but it doesn't work.
I got this error:
'coroutine' object has no attribute 'delete'.
if message.content.startswith("!נקה"):
delete_count = 0
try:
value = message.content.split("!נקה ",1)[1] #gets the value of the messages I want to delete
value = int(value)
flag = 1
except:
flag = 0
msg = await message.channel.send("שכחת לכתוב כמה הודעות למחוק.")
await asyncio.sleep(5)
await msg.delete()
if flag == 1:
for i in range(value-1):
if True:
with open("messagesList.txt", "r") as json_file:
messagesList = json.load(json_file) #loads a list of the id of messages
message_id = messagesList[0]
msg = message.channel.fetch_message(message_id)
await msg.delete()
delete_count += 1
with open("messagesList.txt", "w") as json_file:
json.dump(messagesList, json_file)
else:
print("", end = "")
if delete_count != 0:
message = await message.channel.send(f"{delete_count}הודעות נמחקו בהצלחה.") #prints the messages successfully delete
await asyncio.sleep(3) #wait 3 seconds
await message.delete()
Are you trying to create something like a purge command? If you want to simply delete some amount of messages from the channel (without other operations), then try this:
#client.command()
async def clear(ctx, amount = 5): # you can set the default amount of messages that will be deleted (if you didn't specify the amount while running the command)
deleted = await ctx.channel.purge(limit=amount + 1) # adding one to remove "clear" command too
await ctx.send(f"Deleted {len(deleted)} messages") # sends how many messages were deleted
Commands in docs
The error should be here:
except:
flag = 0
msg = await message.channel.send("שכחת לכתוב כמה הודעות למחוק.")
await asyncio.sleep(5)
await msg.delete() #The problematic line.
msg is a coroutine, not a Message object. It doesn't have a delete attribute.
You can simply use the delete_after=time parameter:
except:
flag = 0
msg = await message.channel.send("שכחת לכתוב כמה הודעות למחוק.", delete_after=5)
Another way is to make the bot delete the message, as you've tried:
except:
flag = 0
msg = await message.channel.send("שכחת לכתוב כמה הודעות למחוק.")
await asyncio.sleep(5)
await bot.delete_message(msg)
It's explained in this post.

How to monitor both reactions and removal of reactions in the same function using Discord.py

I currently have a function which is polling a message for reactions and adding users to a list based on that using Discord.py. Here is the code below:
#commands.Cog.listener()
async def on_message(self, message):
editMessage = message
tankBoosters = []
healBoosters = []
dpsBooster = []
boosters = []
# we do not want the bot to reply to itself
if message.author != self.bot.user:
return
if len(message.embeds) > 0:
for embed in message.embeds:
if "Boost is Ready" in embed.fields:
return
else:
pass
for x in message.embeds:
if '<:tank:801416324306829312>' and '<:healer:801416334243921971>' and '<:dps:801416343848615947>' in x.description:
await message.add_reaction('<:tank:801416324306829312>')
await message.add_reaction('<:healer:801416334243921971>')
await message.add_reaction('<:dps:801416343848615947>')
embedToEdit = x
def check(reaction, user):
return str(reaction.emoji) in ['<:tank:801416324306829312>', '<:healer:801416334243921971>', '<:dps:801416343848615947>'] and user != self.bot.user
boosters = tankBoosters + healBoosters + dpsBooster
while len(boosters) != 4:
if len(boosters) != 4:
reaction, user = await self.bot.wait_for('reaction_add', check=check)
print(message.reactions)
if reaction.emoji.name == 'tank' and len(tankBoosters) == 0:
tankBoosters.append(user)
if reaction.emoji.name == 'healer' and len(healBoosters) == 0:
healBoosters.append(user)
if reaction.emoji.name == 'dps' and len(dpsBooster) < 2:
dpsBooster.append(user)
if len(tankBoosters) == 1 and len(healBoosters) == 1 and len(dpsBooster) == 2:
message = f"<:tank:801416324306829312> {tankBoosters[0].mention} \n <:healer:801416334243921971> {healBoosters[0].mention} \n <:dps:801416343848615947> {dpsBooster[0].mention} \n <:dps:801416343848615947> {dpsBooster[1].mention}"
embedToEdit.add_field(name="Boost is Ready", value=message, inline=False)
await editMessage.edit(embed=embed)
This is working fine, but what I need to do be able to do is remove users from the respective lists (tank, heal and dps) when a reaction is removed from the message.
I.e. a message is posted and 3 tanks, 2 healers and 6 DPS "sign up" to the message by posting reactions to the message and they are appended to their respective lists. Then 1 tank and 2 DPS "unsign" by removing their reaction to the message. I need to remove those users from the list when they remove their reaction. I have looked into using message.reactions[0].users() but according to the VS Code debug terminal, message.reactions[0].users() is <discord.iterators.ReactionIterator object at 0x011B5DF0>
, which I unfortunately don't know enough about python or discord to understand!
I think you can try this:
#bot.event
async def on_raw_reaction_remove(payload):
reaction = str(payload.emoji)
msg_id = payload.message_id
user_id = payload.user_id
guild_id = payload.guild_id
exists = db.exists(msg_id)
When someone remove his reaction, you know what reaction, the user ID...
For those interested, or frustratedly searching for answers on how to do this, I ended up changing my approach slightly. Instead of doing all the logic inside the on_message function, I removed that and used on_raw_reaction_add and on_raw_reaction_remove instead, and I am tracking users by storing them in global arrays which are emptied once certain conditions are met.
This does mean that the code can only handle looking at one post at a time, but thats all I need it to do for now :)

Python/Discord When I try to make python get the userID of a discord user it just does nothing, no error message and no output

This is the code using the userID:
if message.content == "MMO start":
dir = r'C:\\Users\\User\Desktop\MMOProfiles'
MessageAuthor = str(userID)
newpath = os.path.join(dir,MessageAuthor)
doesExist = os.path.exists(newpath)
if doesExist == False:
await message.channel.send("Creating profile")
os.makedirs(newpath)
if doesExist == True:
await message.channel.send("You already have a profile")
And this is the function which is defining the userID:
async def UserID(ctx):
userID = ctx.author.id
The userID is already inside the userID you can type print(userID) to see it in terminal.

How can I make top 10 command work, where it grabs the top 10 in the JSON?

Here's my current code:
import discord
from discord.ext import commands
class Fun:
def __init__(self, client):
self.client = client
#commands.command(aliases=["lb"], pass_context=True)
async def leaderboard(self, ctx):
experience = self.getexperience()
with open('users.json') as f:
data = json.load(f)
lines = sorted(data.items(), key=operator.itemgetter(1), reverse=True) # sorts lines by balance
lb = [] # leaderboard
for line in lines: # each line in file
user = self.bot.get_user(id=int(line[0])) # grab user object from ID
if not user:
user = await self.bot.fetch_user(int(line[0]))
lb.append(f"{user.name} | {format(line[1], ',d')} {experience}\n") # add username and balance to leaderboard
limitedMsgs = [] # array for each page
pageCount = math.ceil(len(lb) / 10) # pageCount = number of users / 10 users per page
for x in range(0, pageCount): # for every page
limitedMsgs.append("".join(lb[x*10:x*10+10])) # add those 10 users to 1 page
currPage = 0
embed = discord.Embed(color=0xdfe324, description=limitedMsgs[0])
embed.set_footer(text=f"Page: {currPage + 1} of {pageCount}")
msg = await self.client.say(embed=embed)
def check(reaction, user):
return (user == ctx.message.author) and (str(reaction.emoji) == '⬅' or str(reaction.emoji) == '➡')
while(True):
if pageCount > 1:
if currPage == 0: # if first page
await msg.add_reaction("➡")
print(pageCount)
elif (currPage + 1) == pageCount: # if last page
await msg.add_reaction("⬅")
else: # if not first nor last
await msg.add_reaction("➡")
await msg.add_reaction("⬅")
try:
reaction, user = await self.bot.wait_for('reaction_add', timeout=60, check=check) # wait for user reaction
except asyncio.TimeoutError:
break # end while loop if no user reaction
if str(reaction.emoji) == '⬅':
currPage = currPage - 1
if str(reaction.emoji) == '➡':
currPage = currPage + 1
embed = discord.Embed(color=0xdfe324, description=limitedMsgs[currPage])
embed.set_footer(text=f"Page: {currPage + 1} of {pageCount}")
await msg.clear_reactions()
await msg.edit(embed=embed)
await msg.clear_reactions() # clear reactions after while loop
def setup(client):
client.add_cog(Fun(client))
heres the error:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Fun' object has no attribute 'getexperience'
Like I said before, I want it to grab the top 10 in the JSON, then order it into first to last but I'm stuck on this part. Most of this code is done; it's just the grabbing of the xp from the JSON. Any help would be appreciated. Thanks.
The error seems to be because of the line experience = self.getexperience(), as the full traceback should have pointed out. Your class/cog doesn't have the method, getexperience.

Categories

Resources