#discord-bots

1 messages · Page 600 of 1

brittle ingot
#

the pycache is fine. are you loading the cog in your main file?

regal shell
#

This?

brittle ingot
#

yup.

#

you did add the bot.add_cog() at the end of your cog file?

#

Also you may have an issue which is why the cog isn't showing. I would recommend adding a try/except statement in there to handle errors.

regal shell
#

Just like the video

fair panther
#

RePlIt

regal shell
#

Yes I can’t use vsc cuz chromebook

fair panther
brittle ingot
#

just visit their site and download the tar file or .deb file and run it in the terminal

fair panther
#

Well you can run it using chromebook crostini

regal shell
#

Ahh ok

brittle ingot
#

or whatever linux distro you have.

fair panther
#

Or use wine

regal shell
#

Ima stick to repl for now lol

fair panther
#

Yes

#

I like replit

brittle ingot
#

not sure that you can do cogs on repl.it iirc. however to continue.

fair panther
boreal ravine
brittle ingot
#
try: 
  await client.load_extension(f"cogs.{filename[:-3]}")
  print(f"{filename[:-3]} has loaded.")
except Exception as e:
   print(f"Failed to load {filename[:-3]} : {e}")

regal shell
#

On why there’s no error

boreal ravine
#

functions inside classes must be on the same line the init dunder is called

brittle ingot
#

yes and like Kayle said make sure you are indented in your cog. ^^

boreal ravine
#

!e

class a:
    def __init__(self, bot):
        self.bot=bot
def ping(self):
    print(1)
a=a("j")
a.ping()
``` this is what ur tryna do lol
unkempt canyonBOT
#

@boreal ravine :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 7, in <module>
003 | AttributeError: 'a' object has no attribute 'ping'
brittle ingot
agile shadow
#

does any one have a method of getting the guild in on_user_update(before: discord.User, after: discord.User)

slate swan
#

ok so i add the role with Guild.get_role() first

#
  File "C:\Users\damie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 300, in static_login
    data = await self.request(Route('GET', '/users/@me'))
  File "C:\Users\damie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 254, in request
    raise HTTPException(r, data)
discord.errors.HTTPException: 401 Unauthorized (error code: 0): 401: Unauthorized

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "D:\gg$\Cloner + Nitro claimer\Zzz.py", line 319, in <module>
    client.run(token, bot=False)
  File "C:\Users\damie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 723, in run
    return future.result()
  File "C:\Users\damie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 702, in runner    await self.start(*args, **kwargs)
  File "C:\Users\damie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 665, in start
    await self.login(*args, bot=bot)
  File "C:\Users\damie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 511, in login
    await self.http.static_login(token.strip(), bot=bot)
  File "C:\Users\damie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 304, in static_login
    raise LoginFailure('Improper token has been passed.') from exc
discord.errors.LoginFailure: Improper token has been passed.
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000001D28A4B81F0>
Traceback (most recent call last):
  File "C:\Users\damie\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 116, in __del__
    self.close()
  File "C:\Users\damie\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 108, in close
```...
#
  File "C:\Users\damie\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 745, in call_soon
    self._check_closed()
  File "C:\Users\damie\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 510, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed```
#

why?

agile shadow
brittle ingot
#
data = await self.request(Route('GET', '/users/@me'))
  File "C:\Users\damie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 254, in request
    raise HTTPException(r, data)
discord.errors.HTTPException: 401 Unauthorized (error code: 0): 401: Unauthorized

is this a selfbot?

slate swan
#

Yes, don't worry, there's no nuke thing or anything

agile shadow
#

...

brittle ingot
#

Selfbotting is against discord's terms of service, regardless of your intentions.

agile shadow
#

you do know self bots arent allowed right

slate swan
#

Yes, don't worry, there's no nuke thing or anything

slate swan
#

tell me when your done so you can help me

brittle ingot
#

we're done.

slate swan
#

ok

slate swan
#

well imma need some help

brittle ingot
#

ok

slate swan
#

i kind of have not use python in like a year so i pretty much remember nothing

#

            while True:
                try:
                    reaction, user = await self.bot.wait_for("reaction_add", timeout=10, check=check)

                    if str(reaction.emoji) == "▶️" and cur_page != pages:
                        cur_page += 1
                        await message.edit(embed=embed1)
                        await message.remove_reaction(reaction, user)

                    elif str(reaction.emoji) == "◀️" and cur_page > 1:
                        cur_page -= 1
                        await message.edit(embed=emb)
                        await message.remove_reaction(reaction, user)

                    else:
                        await message.remove_reaction(reaction, user)

                except:
                    pass``` no errors, problems in the video
slate swan
slate swan
#

so imma trying to make my discord dm people with a certin roles

#

and i forgot how to start

#

i also forgot how to do loops

#

so imma need some help

brittle ingot
slate swan
#

@brittle ingot do you have any idea why he doesn't want to? :c

slate swan
brittle ingot
brittle ingot
slate swan
#

ok

slate swan
slate swan
#

@slate swan skidling leave the server u wont get help breaking tos

brittle ingot
#

no its against the rules of this server and discord's terms of service. make a legitimate bot.

slate swan
#

🙄

brittle ingot
slate swan
#

-.-

brittle ingot
#

damn hold up

#
def check(reaction, user):
    return reaction.message == message and user == ctx.author
slate swan
#

so then id be doing

  check()```
#

for example

brittle ingot
#

no your check goes in the check kwarg of the wait_for

#

check = check

slate swan
#

oh alright

#

ok so i trying to make this discord bot im makeing dm people with a specific role a certain question like if i do !quest it will ask the people with the hero role if they would like to start a quest

#

i can figure out out to code my bot to do that

brittle ingot
#

ahh gotcha. and they reply with something? or they just come into the server?

slate swan
# brittle ingot no your check goes in the check kwarg of the wait_for

currently have this

            def check(reaction, user):
                return user == ctx.author and str(reaction.emoji) in ["◀️", "▶️"]
                return reaction.message == message and user == ctx.author
            while True:
                try:
                    reaction, user = await self.bot.wait_for("reaction_add", timeout=10, check=check)

                    if str(reaction.emoji) == "▶️" and cur_page != pages:
                        cur_page += 1
                        await message.edit(embed=embed1)
                        await message.remove_reaction(reaction, user)

                    elif str(reaction.emoji) == "◀️" and cur_page > 1:
                        cur_page -= 1
                        await message.edit(embed=emb)
                        await message.remove_reaction(reaction, user)

                    else:
                        await message.remove_reaction(reaction, user)

                except:
                    pass
``` and it does the same thing 😭
slate swan
brittle ingot
#

the second return is unreachable code... just add it to the first return

brittle ingot
slate swan
#
            def check(reaction, user):
                return user == ctx.author and str(reaction.emoji) in ["◀️", "▶️"] and reaction.message == message and user == ctx.author```
#

like that?

brittle ingot
#

yes

slate swan
#

long line lol

brittle ingot
#

yeah 😂

slate swan
#
        pages = 5
        cur_page = 1

        gsperms = discord.Embed(color=0x2f3136, title="", description=f"**General Server Permissions**\nView Channels:{vich}\nManage Channels:{mach}\nManage Roles:{marl}\nManage Emojis and Stickers:{meas}\nView Audit Log:{val}\nManage Webhooks:{mw}\nManage Server:{ms}")
        gsperms.set_thumbnail(url=member.display_avatar)
        
        mperms = discord.Embed(color=0x2f3136, title="", description=f"**Membership Permissions**\nCreate Invite:{ci}\nChange Nickname:{cn}\nManage Nicknames:{mn}\nKick Members:{km}\nBan Members:{bm}\n")
        mperms.set_thumbnail(url=member.display_avatar)

        tcperms = discord.Embed(color=0x2f3136, title="", description=f"**Text Channel Permissions**\nSend Messages:{sm}\nSend Messages In Threads:{it}\nCreate Public Threads:{cm}\nCreate Private Threads:{cpm}\nEmbed Links:{el}\nAttach Files:{af}\nAdd Reactions:{ar}\nUse External Emojis:{uee}\nUse External Stickers:{ues}\nMention Everyone:{me}\nManage Messages:{mm}\nManage Threads:{mt}\nRead Message History:{rmh}\nSend TTS Messages:{tts}\nUse Slash Commands:{usc}")
        tcperms.set_thumbnail(url=member.display_avatar)

        vcperms = discord.Embed(color=0x2f3136, title="", description=f"**Voice Channel Permissions**\nConnect:{con}\nSpeak:{sp}\nPriority Speaker:{ps}\nMute Members:{mute}\nDeafen Members:{dfm}\nMove Members:{move}")
        vcperms.set_thumbnail(url=member.display_avatar)

        aperms = discord.Embed(color=0x2f3136, title="", description=f"**Advanced Permissions**\nAdministrator:{adm}")
        aperms.set_thumbnail(url=member.display_avatar)```
#

originally it was all in 1 description

#

before i paged it

brittle ingot
# slate swan they they respond with something

alright so we want to do a couple of things. we wanna fetch the role, either by ID or name. we can use get_role(role-id) if you wanna do id. otherwise we can use utils.get(ctx.guild.roles, name="role-name") if you wanna get by name. then we can check the guild's members for that role and if they have the role dm them, if not pass. However depending on the member count of the server this might be abusive. so we could use a database store the IDs of members who have the role. and just use a for loop to go through that list of member get_member(stored-id) and then send the DM to the member we got.

slate swan
brittle ingot
#

you have ctx.author == user in there twice, although i don't think that has anything to do with it.

slate swan
#
return user == ctx.author and str(reaction.emoji) in [":arrow_backward:", ":arrow_forward:"] and reaction.message == message```
#

there

slate swan
#

like under @bot. commands()

brittle ingot
#

yeah you want it to be a command right?

slate swan
#

yea

brittle ingot
#

then yes under the command decorator.

slate swan
#

is there a way I can get all the reactors of a message with discord ,oy

brittle ingot
#

!d discord.Reaction.users

unkempt canyonBOT
#

async for ... in users(*, limit=None, after=None)```
Returns an [`AsyncIterator`](https://discordpy.readthedocs.io/en/master/api.html#discord.AsyncIterator "discord.AsyncIterator") representing the users that have reacted to the message.

The `after` parameter must represent a member and meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.

Examples

Usage

```py
# I do not actually recommend doing this.
async for user in reaction.users():
    await channel.send(f'{user} has reacted with {reaction.emoji}!')
```...
brittle ingot
#

or

#

!d discord.Reaction.count

unkempt canyonBOT
brittle ingot
#

second is only one reaction though.

slate swan
#

like this

brittle ingot
regal shell
#

This cog is still broken fml 🤦‍♂️

slate swan
#

damn

#

im really bad at this thx for helping me tho

#

how do I do it with a specific channel Id though

does reaction.users take any params for channel id?
await reaction.users().flatten()

brittle ingot
#

so you will need to define a function which will act as the command.

@bot.command()
async def startQuest(ctx):
    role = ctx.guild.get_role(role-id)

from there you can loop through the servers members (you can get a guild instance from ctx) and check if the role is in each members roles.

brittle ingot
slate swan
#

ok ill set this up

#

ill get back to you

#

sorry i meant message id

#

how do i make a server lock command, that locks all channels instead of just one?

brittle ingot
#

ahh okay, you want to get the message from the channel instance. or just

message = await client.fetch_message(message-id) #not recommended if using alot as its an API call.

from there you can get the messages reactions. with message.reactions and go from there.

slate swan
#

like this

forest vortex
brittle ingot
pliant gulch
#

At that point wouldn't it be better to just make a new role that has no send messages perm

brittle ingot
#

You would still need to assign it to everyone though, wouldn't you? which is the same but just another way?

pliant gulch
#

Ah yea I totatlly over looked that aspect

#

But either way discord.py should be handling the ratelimits so this is "safe" ish to do

brittle ingot
# slate swan api abuse?

quickly changing settings or better known as using the API for a use its not intended for. Discord servers aren't set up to be locked like that even though its possible.

slate swan
brittle ingot
pliant gulch
#

If you really want to be in the clear, I'd just read the response headers grab the X-Ratelimit- headers and look for reset after

#

Sleep that amount and do it again

slate swan
#

hmm

pliant gulch
#

But, then again that's why discord.py does internally

brittle ingot
#

oh that's smart.

brittle ingot
#

is it an error?

pliant gulch
slate swan
#

no

#

it mean that code is not being used

slate swan
brittle ingot
#

ah

slate swan
#

or has never been used

brittle ingot
# slate swan but what about raids happening?

I imagine discord didn't plan for that eventuality until it happened which is why its part of their guidelines and not part of their platform as far as safety measures. I'm not saying don't do it, im just saying beware of ratelimits and code accordingly to handle them like Andy was saying.

brittle ingot
slate swan
#

to dm every member with that role

brittle ingot
#

that will be a bit further along. So firstly we know that ctx.guild has a members attribute and according to what we know about for loops we can do something like:

for member in ctx.guild.members:
    ... #check if role in member.roles
slate swan
#

ok where do i set this up

brittle ingot
#

right under getting the role. since it will be a part of the command

slate swan
#

ok

#

yup there is no red error line so its good

brittle ingot
#

great, so now inside that for loop we want to check if role in member.roles

pliant gulch
#

What

#

That's gonna be super slow

#

Just use Role.members

#

!d discord.Role.members

unkempt canyonBOT
brittle ingot
#

wow completely forgot that

#

forget what i was saying.

slate swan
#

ok so discord.Role.members

brittle ingot
#

role.members

#

so you would do:
members = role.members

#

we would still need to loop through them though andy.

slate swan
#

so i have to put that in the same command line

brittle ingot
#

below where you get the role but above the for loop, and we will modify that for loop to incorporate this.

wicked atlas
#

Pretty sure you can just... ```py
if member in role.members:

slate swan
#

ok ill set that up

brittle ingot
#

we want to send a DM to every member that has that role

slate swan
#

yes

wicked atlas
#

Ah ok, that's understandabe

pliant gulch
brittle ingot
#

so now we will change that for loop to ```py
for member in members:
... # send message to member with member.send()

brittle ingot
slate swan
brittle ingot
#

now member objects have a send attribute you can use to send them a DM. You will want to put it in a try/except though as some members may have DM's for a server turned off.

slate swan
#

ok wait my mind went blake say that again

brittle ingot
#

you can send a DM to a member using the .send() method on the member object. so inside the for loop we can do something like:

try: 
    message = await member.send("my-message")
    ... other code waiting a reply

except discord.Forbidden:
    pass
slate swan
#

ok i think i get it

#

so i put this under the for member in members:

brittle ingot
#

correct and make sure its indented.

#

so its inside the for loop

slate swan
brittle ingot
#

try: should be its own line with the message on the next line inside the try block

slate swan
brittle ingot
#

should look like:

try: 
    message = await member.send("Would you like to start the battle?")

except discord.Forbidden:
    pass
slate swan
#

ok ill fix it

brittle ingot
#

what happened to the for loop? we need that

slate swan
#

oh wait it got cut off while i way typeing ill fix it

#

there i fix it

#

i press enter and moved it up

#

my bad

patent surge
#

How to invoke another command in a Command

valid perch
#

Ctx.invoke iirc

cloud dawn
unkempt canyonBOT
#

await invoke(command, /, *args, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Calls a command with the arguments given.

This is useful if you want to just call the callback that a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") holds internally.

Note

This does not handle converters, checks, cooldowns, pre-invoke, or after-invoke hooks in any matter. It calls the internal callback directly as-if it was a regular function.

You must take care in passing the proper arguments when using this function.
brittle ingot
#

alright so we've sent the message, we've handled if the member has DM's turned off for the server with a try/except. Now in the try portion of the try/except right below where we send the message we want to make a check so it will be something like this:

def check(m):
    m.author != m.author.bot and m.channel == message.channel

next we will use that check in a wait for which will tell the bot to wait for a response from the member we sent the message to.

try:
  msg = await bot.wait_for('message', check = check, timeout = 60) 

  if msg.content,lower() == "yes": 
      await ctx.send(f"{member.display_name} is ready to start")
  elif msg.content.lower() === 'no': 
      await ctx.send(f"{member.display_name} is not ready to start")
  else:
      pass
except asyncio.timeoutError:
    await ctx.send(f"No response from {member.display_name}")

What we are doing is creating the code that will handle the response. if you have any questions let me know and i can walk you through it.

slate swan
#

ok

#

first thing first i have to put /def check(m):
m.author != m.author.bot and m.channel = message.channel
/ under the first tryand except

brittle ingot
#

inside the try portion of the try / except right under where you send the message to the member. (right under member.send line)

slate swan
#

ok got it

brittle ingot
#

You may need to import asyncio if you haven't already.

slate swan
#

think i all ready have

brittle ingot
# slate swan

add a return right before m.author != m.author.bot (sorry complete fudged that)

#

so should be:

def check(m):
    return m.author != m.author.bot and m.channel == message.channel
#

sorry

queen summit
#

how can i get a user object from an abc.Snowflake

brittle ingot
#

!d discord.Client.get_user

unkempt canyonBOT
slate swan
pliant gulch
brittle ingot
#

could also do !m.author.bot too right? or im i confusing that with js

pliant gulch
#

Author.bot is a bool

slate swan
#

oh yea it is

brittle ingot
#

thats js nevermind (haven't actually touched python in months :/ )

slate swan
brittle ingot
#

great blind leading the blind 😂

obsidian kayak
#

guys how do i get a webhook from another server the tommy innit discord is being hacked by a web hook and i need to delete it

brittle ingot
#

you can only get a webhook from a server the bot is in.

obsidian kayak
#

oh yeah i know the bot is in that server

brittle ingot
#

!d discord.Guild.webhooks

unkempt canyonBOT
#

await webhooks()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Gets the list of webhooks from this guild.

Requires [`manage_webhooks`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_webhooks "discord.Permissions.manage_webhooks") permissions.
obsidian kayak
#

how do i get the webhook

#

ill send a pic of whats happening

brittle ingot
#

ok

slate swan
brittle ingot
slate swan
#

take your time i have time

brittle ingot
#

m.author not m.author.bot i think?

obsidian kayak
#

yeah people are going crazy lol

brittle ingot
#

that doesn't look like a webhook

slate swan
#

instead of making a separate role for my verification command, how do edit the everyone role so when a user does the comand it gives them access to the rest of the server?

@commands.Cog.listener()
    async def on_message(self, message):
        if message.channel.id == 909671265864933406:
            await message.delete()
        if message.channel.id == 909671265864933406 and message.content.lower() == '*verify':
            fullaccessrole = get(message.guild.roles, id=909670961115201537)
            await message.author.add_roles(fullaccessrole)
obsidian kayak
#

oh well thats what admins were saying

brittle ingot
#

you can't change channel names through a webhook, just go in the audit logs figure out which bot is doing it and ban them.

slate swan
#

@brittle ingot i tried what we did earlier

obsidian kayak
#

but the hacker has full controll

slate swan
#
            def check(reaction, user):
                return user == ctx.author and str(reaction.emoji) in ["◀️", "▶️"] and reaction.message == message
            while True:
                try:
                    reaction, user = await self.bot.wait_for("reaction_add", timeout=10, check=check)

                    if str(reaction.emoji) == "▶️" and cur_page != pages:
                        cur_page += 1
                        await message.edit(embed=embed1)
                        await message.remove_reaction(reaction, user)

                    elif str(reaction.emoji) == "◀️" and cur_page > 1:
                        cur_page -= 1
                        await message.edit(embed=emb)
                        await message.remove_reaction(reaction, user)

                    else:
                        await message.remove_reaction(reaction, user)

                except:
                    pass```
#

this didnt work, the reactions didnt even change the page

brittle ingot
#

or server owner?

obsidian kayak
#

they all say in the picture they cant do anything

brittle ingot
#

otherwise its sounds like the owners account was hacked.

brittle ingot
wicked atlas
#

Dang token grabbers

obsidian kayak
#

all im asking for is a way to get in and get the id of the bot or webhook and delete it

#

im a member btw

brittle ingot
#

yeah, which would mean the owner needs to figure who it is an ban them since they have absolute permissions. And as a member you can't access that unless your bot has admin permissions in that case i would say configure the bot to access the audit log yourself and find out who edited the channels or created channels that way.

obsidian kayak
#

kinda like im hacking in but in a good way

pliant gulch
#

Webhooks don't have the power to change channel names lol, this is a selfbot

wicked atlas
pliant gulch
#

You are gonna have to check the audit logs and remove that person manually

slate swan
#

hmmmmm

obsidian kayak
#

oh

#

it seems to be a bot or a webhook

wicked atlas
#

Yeah, the nuker probably created that with their script as well

brittle ingot
#

if its their bot they will want to regenerate their bots token on the developer portal

obsidian kayak
#

no its a new bot from the hacker

brittle ingot
#

so ban the bot?

slate swan
#

Check the profile of the bot , if it has a tag #0000 it's a webhook simpl

pliant gulch
#

Unless you have admin powers, you cannot do anything

brittle ingot
#

oh true.

pliant gulch
#

Just sit back and wait

#

Or until discord API blacklists the bot

#

Although I'd doubt that would happen quickly

obsidian kayak
#

yeah

brittle ingot
#

we can't react to messages anymore 😦

wicked atlas
#

Webhooks won't have tags or anything else on them

brittle ingot
#

wow what a unique name 😂

slate swan
#

Looks more like a token lol

#
    if c == "toggle":
        anti = db.find_one({ "guild_id": ctx.guild.id })['toggled']
        if anti == True:
            await ctx.send("turned antinuke off since it was on")
        db.update_one({
            'toggled': False,
        })
        if anti == False:
            db.update_one({
            'toggled': True,
        })
            await ctx.send(f"toggled antinuke :thumbsup:")```

trying to toggle it off but but it only stays on true idek
#

giving me

 Command raised an exception: TypeError: update_one() missing 1 required positional argument: 'update'```
obsidian kayak
#

just read some of the mods messages and they cant ban or kick anyone or do anything

regal shell
#

Can anyone help me on why it’s not registering my cog?

obsidian kayak
slate swan
#

ok what next

heavy folio
#
pymongo error: filter must be an instance of dict, bson.son.SON, or other type that inherits from collections.Mapping
```whats this error
brittle ingot
#

bson.son.SON 😂 sorry idk why but that killed me

heavy folio
#

do you know why tho

brittle ingot
#

its a type error, your filter isnt of type dict. what does your filter look like?

slate swan
heavy folio
#

idk what that filter thing is, i just did ```py
userid = member.id
myCollection.find_one_and_delete({"userid", userid})

#

member is an arg btw

brittle ingot
slate swan
#

ok

#

lay it on me

brittle ingot
heavy folio
#

oh

#

so how should a filter be like

#

i just wanna find and delete

brittle ingot
#

so keep your current code and change the , to a :

heavy folio
#

and also in the db theres this thing py _id: ObjectId("someid") userid: someid reason: reasonbut reason is an arg and can be different at times so idk how i can delete it

heavy folio
brittle ingot
brittle ingot
# slate swan lay it on me

alright, so underneath the check we want to add:

try:
  msg = await bot.wait_for('message', check = check, timeout = 60) 

  if msg.content.lower() == "yes": 
      await ctx.send(f"{member.display_name} is ready to start")
  elif msg.content.lower() === 'no': 
      await ctx.send(f"{member.display_name} is not ready to start")
  else:
      pass
except asyncio.timeoutError:
    await ctx.send(f"No response from {member.display_name}")

This portion of code is telling the bot to wait for a message and checking the contents of the message for the acceptable responses. In this case acceptable responses are: yes or no

obsidian kayak
#

we chill now we have a discord staff

heavy folio
#

alr

brittle ingot
#

oh good

pliant gulch
slate swan
#

ignore the KeyError thats a seperate cmd

brittle ingot
slate swan
#

just noticed this

#

it keeps printing it for some reason, i think ive got a loop somewhere

#

could it be the timeout=10?

brittle ingot
#

no, the timeout tells the bot to stop waiting after 10 seconds.

slate swan
#

well, it keeps giving that 'working5' message

#
            def check(reaction, user):
                return user == ctx.author and str(reaction.emoji) in ["◀️", "▶️"] and reaction.message == message
                print(f'working1')
            while True:
                try:
                    reaction, user = await self.bot.wait_for("reaction_add", timeout=10, check=check)
                    print(f'working2')
                    if str(reaction.emoji) == "▶️" and cur_page != pages:
                        cur_page += 1
                        await message.edit(embed=embed1)
                        await message.remove_reaction(reaction, user)
                        print(f'working3')
                    elif str(reaction.emoji) == "◀️" and cur_page > 1:
                        cur_page -= 1
                        await message.edit(embed=emb)
                        await message.remove_reaction(reaction, user)
                        print(f'working4')
                    else:
                        await message.remove_reaction(reaction, user)

                except:
                    print(f'working5')
                    pass```
pliant gulch
#

Theres literally a while true loop

slate swan
#

true

pliant gulch
#

ANd working5 is in the except

heavy folio
pliant gulch
#

Meaning theres an error

#

But you are supressing the errors with your try except

heavy folio
#

also @brittle ingot do you know how to delete all documents in a collection?

pliant gulch
#

You need to catch the exception

slate swan
#

so how would i print the error

slate swan
#

except exception as e?

pliant gulch
#

Yes and print it or raise it

#

And its Exception

brittle ingot
pliant gulch
#

Not the lowercased

slate swan
#
                except exception as e:
                    print(f'error: {e}')
                    pass```
#

ima try this

brittle ingot
#

Exception

slate swan
#

yeah misspelled

#

incredible 🤣

brittle ingot
#

i have noticed checking the current pages in the same if statement as the str(reaction.emoji) as always cause me issues. but we all know im a certified dumbo 😂

pliant gulch
#

Raise the error instead of printing it

slate swan
#

how do u raise errors? raise.error()?

#

i have truly no clue lol i never did those basics

pliant gulch
#

No you use the raise statement

brittle ingot
#

oh i did reply. im fried.

slate swan
#
raise CommandInvokeError```?
brittle ingot
#

raise e

#

i believe

slate swan
#

@pliant gulch @brittle ingot did that, nothing happened

#

literally nothing

#

reactions were added, but the functions didnt work

brittle ingot
#

do you have asyncio imported?

slate swan
#

mhm

#

of course

brittle ingot
#

try doing:

except asyncio.timeoutError:
    print("timed out")

and see if that triggers? Could be that the timeout is too low? at this point idk, just throwing ideas

slate swan
#

idk why the === is not working

brittle ingot
#

i should just be two ==

slate swan
#

k

slate swan
brittle ingot
#

also make sure you indentations match. remember pep8 recommends one tab or 4 spaces for an indentation and they should be consistent througout

slate swan
#

i use 4 spaces

brittle ingot
#

not you sorry was speaking to forgot python person

slate swan
#

oh lol no worries

brittle ingot
#

member being none? or user?

slate swan
#

sec ill send the rest

brittle ingot
#

kk

slate swan
#

well, what is needed

#

ok i fix it

brittle ingot
#

the error and the portion of code it refers to

heavy folio
slate swan
#
    @commands.command(name="userinfo", aliases=['ui', 'uinfo', 'whois'])
    async def userinfo(self, ctx, member: Union[discord.Member, discord.User] = None):
        try:
            if member == None:
                member = ctx.author
#200 lines of stuff that works
#stuff that doesnt work VV
            br = " ![bug_reporter](https://cdn.discordapp.com/emojis/910283568608075898.webp?size=128 "bug_reporter")"
            bot_owner = " ![bot_owner](https://cdn.discordapp.com/emojis/910284400049135616.webp?size=128 "bot_owner")"
            bot_staff = "![bot_staff](https://cdn.discordapp.com/emojis/910285117585490002.webp?size=128 "bot_staff")"
            supporter = "![supporter](https://cdn.discordapp.com/emojis/910307203636940860.webp?size=128 "supporter")"
            bot_badges = 'None'
            if member.id == 813989866236149770:
                bot_badges = f'{bot_owner}{bot_staff}{br}{supporter}'
            elif member.id == 689005922550284318:
                bot_badges = f'{supporter}'

            pages = 2
            cur_page = 1
#embed stuff
            await message.add_reaction("◀️")
            await message.add_reaction("▶️")

            def check(reaction, user):
                return user == ctx.author and str(reaction.emoji) in ["◀️", "▶️"] and reaction.message == message
                print(f'working1')
            while True:
                try:
                    reaction, user = await self.bot.wait_for("reaction_add", timeout=10, check=check)
                    print(f'working2')
                    if str(reaction.emoji) == "▶️" and cur_page != pages:
                        cur_page += 1
                        await message.edit(embed=embed1)
                        await message.remove_reaction(reaction, user)
                        print(f'working3')
                    elif str(reaction.emoji) == "◀️" and cur_page > 1:
                        cur_page -= 1
                        await message.edit(embed=emb)
                        await message.remove_reaction(reaction, user)
                        print(f'working4')
                    else:
                        await message.remove_reaction(reaction, user)

                except asyncio.timeoutError:
                    print("timed out")
#stuff that doesnt work^^
        except:
            fetchmember = await self.bot.fetch_user(member.id)
#100 lines of other stuff that works``` @brittle ingot there
brittle ingot
heavy folio
#

oh alr

unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

brittle ingot
slate swan
heavy folio
#

oh okay

brittle ingot
slate swan
#

so its only the pages bit that isnt working properly

brittle ingot
slate swan
#

i shortened it a ton

#

removed the embed prints so its legible

#

ok ill try it

brittle ingot
brittle ingot
#

Andy you still lurking? any ideas for Terrors issue?

slate swan
#

how do i set it to work when i do ! startbattle

#

I'm having trouble gathering messages that my bot has sent in the past and even tested the runtime by having it send "a" but the bot doesn't send anything.

#

becuase this is not working

#

how can i use requests to delete a message

brittle ingot
slate swan
#

ok

slate swan
brittle ingot
#

i was trying to avoid pinging him incase he was busy 😂 lol but yeah

slate swan
#

well if hes busy then he just wont reply lol

regal shell
#

I’m still struck to find out why it’s not recognizing my cog I’ve rewrote it twice copying the video just to be sure

slate swan
#

o change it now this wont work

#

bot = client ( if you dont wanna change it )

brittle ingot
regal shell
#

Am I missing something?

brittle ingot
brittle ingot
# slate swan ?

make a DELETE request to the proper endpoint. you can find the info in the documentation in the developer portal

slate swan
pliant gulch
brittle ingot
#

Its not private so discord definitely has it in their documentation. Otherwise libs like discord.py wouldn't be a thing 😄

slate swan
#

...

#

Question

slate swan
#

Is it possible to retrieve all messages that a user sent by using messages = await ctx.guild.history(limit = 100, check = check).flatten() ?

#
requests.delete(f"https://discord.com/api/v9/channels/{message.channel.id}/messages/{message.id}")
``` this doesnt work, any ideas?
#

Check is defined as def check(message): return message.author.id == 899002742989791273

pliant gulch
# slate swan nope

For each try-except block can you catch the error and print print(repr(error))

slate swan
#

Is it possible to retrieve all messages that a user sent by using
```messages = await ctx.guild.history(limit = 100, check = check).flatten()``
?

pliant gulch
#

You need to catch the error

slate swan
#

except Exception as e?

pliant gulch
#

Yes

#

Then do what I said earlier but instead of error do e

slate swan
pliant gulch
#

As your putting it in e

brave flint
#

hello i had a problem so i made a giveaway cmd
so i made def convert for convert like H is hour to seconds so my asyncio.sleep can work, but it doesnt convert it

slate swan
#

nothing else happened, even when i tried using the reactions

pliant gulch
#

Ok, so the error happening is the timeout is running out

slate swan
#

but the reactions wont work either

unkempt canyonBOT
#

@slate swan :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | NameError: name 'requests' is not defined
pliant gulch
slate swan
#

duh

#
    @commands.command(name="userinfo", aliases=['ui', 'uinfo', 'whois'])
    async def userinfo(self, ctx, member: Union[discord.Member, discord.User] = None):
        try:
            if member == None:
                member = ctx.author
#200 lines of stuff that works
#stuff that doesnt work VV
            pages = 2
            cur_page = 1
#embed stuff
            await message.add_reaction("◀️")
            await message.add_reaction("▶️")

            def check(reaction, user):
                return user == ctx.author and str(reaction.emoji) in ["◀️", "▶️"] and reaction.message == message
                
            while True:
                try:
                    reaction, user = await self.bot.wait_for("reaction_add", timeout=10, check=check)
                    
                    if str(reaction.emoji) == "▶️" and cur_page != pages:
                        cur_page += 1
                        await message.edit(embed=embed1)
                        await message.remove_reaction(reaction, user)
                        
                    elif str(reaction.emoji) == "◀️" and cur_page > 1:
                        cur_page -= 1
                        await message.edit(embed=emb)
                        await message.remove_reaction(reaction, user)
                        
                    else:
                        await message.remove_reaction(reaction, user)

                except Exception as e:
                    print(repr(e))
#stuff that doesnt work^^
        except:
            fetchmember = await self.bot.fetch_user(member.id)
#100 lines of other stuff that works```
#

so do i remove timeout=10?

slate swan
#

whoops moros sorry for ping i copied my last message

pliant gulch
#

Believe it or not, you need to actually authorise to delete messages

#

Crazy isn't it

brittle ingot
#

its all good. Sorry im in and out as im trying to do some courses, clean house and work on projects :E

brittle ingot
slate swan
#

ok explain how to do that

brittle ingot
#

change @bot.command() to @client.command()

or

where you define:

client = commands.Bot(command_prefix = "!", case_insensitive=True, intents = discord.Intents.all())

change client to bot.

If you do one of these you don't need to do the other. The second is recommended for consistency and ease of interpretation. If you come to get help and use client as your bot variable we may assume you are using discord.Client which wouldn't be accurate since you are actually using commands.Bot

slate swan
#

ok ill test it

heavy folio
#

better to use bot btw, nothing will happen if you use client but bot is recommended

brittle ingot
#

^

slate swan
#

yea i change it to bot and i do !startbattle and nothing still happens

slate swan
#

i farted

slate swan
#

@slate swan what is ur command

#

nope just nothing

#

send ur command

#

@slate swan i finally got antinuke to work 🤣

brittle ingot
#

!paste it here and then save it and send the link in chat here so we can see it in its entirety.

unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

slate swan
#

^^

heavy folio
brave flint
#

from swastik 🙂

slate swan
#

!tutorials

#

nvm this isnt dpy

#

!tag

unkempt canyonBOT
#
**Current tags**

» args-kwargs
» async-await
» blocking
» botvar
» class
» classmethod
» codeblock
» comparison
» contribute
» customchecks
» customcooldown
» customhelp
» decorators
» defaultdict
» dict-get

slate swan
#

!tag tutorials

heavy folio
slate swan
#

do not use tutorials, outdated and dogshit

brittle ingot
slate swan
#

me and @slate swan got banned from dpy because we were annoying people in general

slate swan
slate swan
#

ok

#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

slate swan
#

the first part

heavy folio
#

that isnt relevant...

slate swan
#

first of all why would you define intents, but then define it again in commands.Bot

brittle ingot
#

that was from before just wasn't removed yet

slate swan
#

ah

slate swan
# slate swan

possibly the timeouterror messing up? don't you have to define the timeout?

brittle ingot
#

it is defined in the wait_for

slate swan
#

didn't see that

#

Whats the command to delete a message after a command is invoked

brittle ingot
#

await ctx.message.delete() ?

slate swan
heavy folio
heavy folio
# slate swan

i can see that your indents are messed up, maybe thats why

slate swan
#

or role = ctx.guild.get_role(id) since you arent using that for anything

slate swan
heavy folio
#

@slate swan does your bot have any global error handlers, if no are there any errors printed

brittle ingot
slate swan
#

omfg

#

im dumb

brittle ingot
#

lol

slate swan
#

i didnt see that

heavy folio
#

msg isnt in line with if

brittle ingot
#

the only thing i can think of is indentation.

heavy folio
#

if not the line should be shown, is it just me?

#

also dont use replit, use some proper code editor/IDE

slate swan
#

pretty sure

#

vsc in browser

#

@brittle ingot @slate swan thx for the help

heavy folio
#

you cant run the code in there tho

heavy folio
#

just use the vsc app

slate swan
brittle ingot
slate swan
#

might be on a chrome book or something, cant tell

slate swan
heavy folio
brittle ingot
#

they are, we covered it already

slate swan
#

ok

#

og

brittle ingot
#

yes, didn't know they could install VSC on cb

brittle ingot
#

can

slate swan
#

wait what im so confused what are we saying

#

ill line them up

heavy folio
#

replit's indentations are screwed up, just use vsc/some other IDE

pliant gulch
#

Why wouldn't you be able to install VSC On a chromebook? Not doing any research here but chromebook is using google os, which is just linux with changes

heavy folio
pliant gulch
#

VSC has binaries for linux

#

Or an appimage I can't remember

brittle ingot
heavy folio
#

most schools dont allow linux (third party stuff) for security reasons

brittle ingot
#

wow im slow at typing

slate swan
#

i've never used a chromebook but for school so i don't know, i had goguardian on that bitch and couldnt do anything

heavy folio
slate swan
#

the green line means its not being used

brittle ingot
#

which is weird because its definitely being used.

slate swan
#

wouldn't def be under try or am i being dumb

#

yea

#

wait

brittle ingot
#

dumb

slate swan
#

nvm

brittle ingot
#

😂

slate swan
#
@bot.event
    async def on_message(message):
        if "discord.gg/" in message.content:
            if message.author.id in anti.find_one({"_id": message.guild.id})["whitelisted"]:
                return
            else:
                chan = anti.find_one({"_id": message.guild.id})["modlogs-id"]
                channel = bot.get_channel(chan)
                if channel is None:
                    return
                else:
                    embed = discord.Embed(title="Mod-Logs | Invite Deleted", timestamp = message.created_at, color=discord.Color.from_rgb(255,250,250), description="Invite Message Deleted!")
                    embed.add_field(name=f"Author", value=message.author)
                    embed.add_field(name=f"Content", value=message.content)
                    await channel.send(embed=embed)
                    requests.delete(f"https://discord.com/api/v9/channels/{message.channel.id}/messages/{message.id}",headers=headers)
                    await message.channel.send(f"{message.author.mention} please don't send discord server invites",delete_after=5)

        await bot.process_commands(message)
``` i have a feeling the error is the `timestamp`
brittle ingot
#

what are the headers? are they defined?

slate swan
#

mhm

#

the deleting message worked, untill i added the embed

#

why would you do a request to delete

#

thats why

#

the channel didnt set

#

cant you just do await message.delete()

#

@brittle ingot am i right or dumb again

#

hmmm

brittle ingot
#

are you sure you are getting the channel? if there is no channel it returns without executing th rest of the code.

brittle ingot
brittle ingot
#

@slate swan why are you doing a request to delete if you have the message object you can just call await message.delete()

brittle ingot
slate swan
#

ok

brittle ingot
# slate swan wdym

im going to copy the code we worked on and put in . infront of the lines so you can see what we mean by indentation.

slate swan
#

!d discord.Message.delete

unkempt canyonBOT
#

await delete(*, delay=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Deletes the message.

Your own messages could be deleted without any proper permissions. However to delete other people’s messages, you need the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission.

Changed in version 1.1: Added the new `delay` keyword-only parameter.
slate swan
#

why do people think that is funny

brittle ingot
#

idk but that is not discord-bots.

slate swan
#

WRONG CHAT

brittle ingot
#

no. can use the code snippets we worked on earlier.

#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

slate swan
#

hmmm

#

dont mine all the client event

#

@brittle ingot

brittle ingot
unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied mute to @slate swan until <t:1637116096:f> (9 minutes and 59 seconds) (reason: discord_emojis rule: sent 27 emojis in 10s).

brittle ingot
#

bruh, wtf

slate swan
#

idk

#

so you want me to space it like that

brittle ingot
#

lines 9, 14, 19, 24 and 25 you can get rid of.

#

referring to the link you sent

brittle ingot
#

Also on line 26 from your link you can change bot = to client = (that will be easier as you will only need to change one other thing to make its consistent.)

regal shell
#

I can’t figure out what’s wrong with the syntax

brittle ingot
regal shell
#

… thanks lmfao

#

Still not registering the cog might just say f it and not organize it lol

brittle ingot
#

also you can't just call send you need to send it somewhere. ctx has a channel attribute messages can be sent to, so the reply will be in the channel the command invokes from so instead do:

await ctx.send('pong')
regal shell
#

Thanks

brittle ingot
#

np

regal shell
#

Fixed it

opaque plinth
brittle ingot
#

yeah we grabbed that 😄

regal shell
#

Now just gotta figure out why it won’t register the cog

brittle ingot
#

all of your indents should be inline with the def __init__

#

well lemme explain that better

regal shell
#

But def innit is so far in do i need to just scoot them all inwards?

brittle ingot
#
class Moderation(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_ready(self):
        print(f'{self.__class__.__name__} is alive!!')
    
    @commands.command()
    async def ping(self, ctx):
        await ctx.send('Pong!')

def setup(client):
    client.add_cog(Moderation(client))
regal shell
#

Oh ok so move my commands in line with def

brittle ingot
#

correct commands, listeners, etc

regal shell
#

So just the @command part not the rest?

brittle ingot
#

exactly as it appears in my example.

brittle ingot
brittle ingot
#

it should look like:

return not m.author.bot and m.channel == message.channel
regal shell
#

It’s saying Indention error on line 11 bruh

brittle ingot
slate swan
#

m

brittle ingot
regal shell
#

I fixed line 11 and it’s now 13 here’s pic

slate swan
#

see now that is wrong

regal shell
brittle ingot
slate swan
slate swan
#

the lines guide you , it must be parallel with the 2nd line

brittle ingot
#

that almost just lead me down a road of 15 minutes of confusion 😂

slate swan
brittle ingot
#

client.wait_for sorry forgot to have you change that bit

#

instead of bot.wait_for

slate swan
#

ok

#

it still dose nothing when i !startbattle

kindred epoch
#

Check indent for the check

#

Yep

#

It's the indents

#

Check indents

slate swan
#

plus it still say this is not being used

brittle ingot
slate swan
#

How do you get a list of all roles?

brittle ingot
#

ctx.guild.roles

#

!d discord.Guild.roles

unkempt canyonBOT
#

property roles: List[discord.role.Role]```
Returns a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of the guild’s roles in hierarchy order.

The first element of this list will be the lowest role in the hierarchy.
slate swan
#

Thank you

brittle ingot
#

np

slate swan
#

damn

#

this is just not gonna work

brittle ingot
#

it will. im sure. just i decided to help you and haven't touched python in forever. so yeah. we will figure it out.

regal shell
#

@brittle ingot I got the cog to work how do I go about adding more commands to it?

slate swan
#

kk

brittle ingot
brittle ingot
# slate swan kk

i just noticed something. you have an on_message event. You didn't process comands afterwards.

regal shell
brittle ingot
#

failed

slate swan
#

!d discord.ext.commands.Bot.process_commands

unkempt canyonBOT
#

await process_commands(message)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.

By default, this coroutine is called inside the [`on_message()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message "discord.on_message") event. If you choose to override the [`on_message()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message "discord.on_message") event, then you should invoke this coroutine as well.

This is built using other low level tools, and is equivalent to a call to [`get_context()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") followed by a call to [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").

This also checks if the message’s author is a bot and doesn’t call [`get_context()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") or [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke") if so.
brittle ingot
#

thank you

regal shell
#

Is there a place where I can like vouch for you? Moros

brittle ingot
#

@slate swan on line 70 add in:

await client.process_commands(message)

make sure that its in line with the if statements above it. essentially so its not a part of any of the if statements.

regal shell
brittle ingot
brittle ingot
slate swan
#
    logs = logs[0]
IndexError: list index out of range```

 if self.db.find_one({ "guild_id": guild.id })['toggled'] == True:
    logs = await guild.audit_logs(limit=1, action=discord.AuditLogAction.ban).flatten()
    logs = logs[0]
    reason = "culprit • triggered antinuke event • ban member"```
#

DUDE WHAT

brittle ingot
#

Welcome bad _ObjectID don't do anything stupid again 😛

slate swan
brittle ingot
#

print logs

#

im assume its an issue with your fetching of the audit logs ban.

slate swan
#
    @commands.Cog.listener() 
    async def on_member_ban(self, guild, member):
     if self.db.find_one({ "guild_id": guild.id })['toggled'] == True:
        logs = await guild.audit_logs(limit=1, action=discord.AuditLogAction.ban).flatten()
        logs = logs[0]
        reason = "culprit • triggered antinuke event • ban member"
        whitelisted = self.db.find_one({ "guild_id": guild.id })['whitelisted']
        if logs.user.id in whitelisted:
            return
        punishment = self.db.find_one({ "guild_id": guild.id })['punishment']
        if punishment == 'ban':
            try:
                await logs.user.ban(reason=f"{reason}")
                return
            except:
              pass
        if punishment == 'kick':
            try:
                await logs.user.kick(reason=f"{reason}")
                return
            except:
              pass
#

Ignoring exception in on_member_remove
Traceback (most recent call last): File "C:\Users\misery\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\misery\Desktop\alone\bot\cogs\anti.py", line 85, in on_member_remove
logs = logs[0]
IndexError: list index out of range

#

ohh u want me to print logs

regal shell
brittle ingot
slate swan
brittle ingot
brittle ingot
slate swan
#

i do not have anyone to test ban to get that error again

#

what 2 do

brittle ingot
#

invite me and ban me 😂

slate swan
#

k got it

brittle ingot
#

no need to index it

slate swan
#

so just get rid of logs = logs[0]?

brittle ingot
#

yup

slate swan
#

ahhhh

brittle ingot
#

and you can change your logs variable to log. or even name it entry for ease of reading later on

slate swan
#

join back rq lets see if that fixed

#
Ignoring exception in on_member_join
Traceback (most recent call last):
  File "C:\Users\misery\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\misery\Desktop\alone\bot\cogs\anti.py", line 228, in on_member_join
    if logs.user.id in whitelisted:
AttributeError: 'list' object has no attribute 'user'
Ignoring exception in on_member_remove
Traceback (most recent call last):
  File "C:\Users\misery\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event    await coro(*args, **kwargs)
  File "C:\Users\misery\Desktop\alone\bot\cogs\anti.py", line 87, in on_member_remove
    if logs.user.id in whitelisted:
AttributeError: 'list' object has no attribute 'user```
#

getting that on startup

#
Ignoring exception in on_member_remove
Traceback (most recent call last):  File "C:\Users\misery\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)  File "C:\Users\misery\Desktop\alone\bot\cogs\anti.py", line 87, in on_member_remove
    if logs.user.id in whitelisted:
AttributeError: 'list' object has no attribute 'user'[<AuditLogEntry id=910365716211974185 action=AuditLogAction.ban user=<Member id=898420656725704705 name='1fc1fdf69a7f089aff28f65f0ab37984' discriminator='0001' bot=False nick=None guild=<Guild id=910278334263484416 name="1fc1fdf69a7f089aff28f65f0ab37984's server" shard_id=None chunked=True member_count=2>>>]
Ignoring exception in on_member_ban
Traceback (most recent call last):
  File "C:\Users\misery\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)  File "C:\Users\misery\Desktop\alone\bot\cogs\anti.py", line 38, in on_member_ban    if logs.user.id in whitelisted:
AttributeError: 'list' object has no attribute 'user'```
when i banned u
brittle ingot
#

so it is a list? it wasn't before...

slate swan
#

dude i have no clue what i made i just ran with it

#

first time trying to make a anti-nuke

brittle ingot
#

for some reason its returning you as the banned one...

slate swan
#

strange

brittle ingot
#

going by whats printed out, you should be able to do log = logs[0] and do log.user.id to access the information.

slate swan
#
        logs = await guild.audit_logs(limit=1, action=discord.AuditLogAction.ban).flatten()
        log = logs[0]
        reason = "culprit • triggered antinuke event • ban member"
        whitelisted = self.db.find_one({ "guild_id": guild.id })['whitelisted']
        if log.user.id in whitelisted:
            return
        punishment = self.db.find_one({ "guild_id": guild.id })['punishment']
        if punishment == 'ban':
            try:
                await log.user.ban(reason=f"{reason}")
                return
            except:
              pass
        if punishment == 'kick':
            try:
                await log.user.kick(reason=f"{reason}")
                return
            except:
              pass
#

so like that?

heavy folio
#

@brittle ingot do you know in a db how do i get the var "modid" in the document py _id: ObjectId("someid") userid: someid reason: "reason" modid: modidbut the mod (ctx.author) can blacklist many users so idk how to find that for the specific user's document

brittle ingot
#

once you find the doc by its userid as long as you assign it a variable you should be able to do varName.modid to access the modid

heavy folio
#

idk how to find the doc by its id

#

all i do is py myCollection.find_one({"userid": userid})

#

so idk how to get the object id

brittle ingot
heavy folio
#

ohh

brittle ingot
#

not sure if you have to await it in python, its required to await it in JS which is where i use mongo the most.

heavy folio
#

no need to await, ty i'll try it now

brittle ingot
brittle ingot
slate swan
#
            def check(reaction, user):
                return user == ctx.author and str(reaction.emoji) in ["◀️", "▶️"] 
            def check2(reaction, user):
                return reaction.message == message
            while True:
                try:
                    reaction, user = await self.bot.wait_for("reaction_add", checks=[check, check2])```
slate swan
#

ok

#

can that work? with multiple checks

#

rip

slate swan
brittle ingot
#

no not that i know of.

slate swan
#

how can i check for multiple checks

brave flint
#

self.loop.create_task(check())
NameError: name 'self' is not defined
did anyone know what i need to change? i use cogs

slate swan
#

self = self.bot

brittle ingot
#

just add another and in the first def check or you can add an nested check in your wait for essentially an if statement that checks if msg.id == message.id

brittle ingot
slate swan
#
def __init__(self, bot):
        self.bot = bot```
brave flint
slate swan
#

swear thats right

brittle ingot
brave flint
slate swan
#

yeah lol

#

i had it wrong

brittle ingot
#

show code? im sure i can't help but showing your code may help someone else understand whats wrong and ensure they're able to help you.

brave flint
valid perch
#

Thats the exact indentation?

#

I feel like its not

brave flint
#

nope

valid perch
#

Send your code as it actually is please

brave flint
#
async def check(self, ctx):
        voice_channel = ctx.voice_client.channel
        member_count = len(voice_channel.members)
        if member_count == 1:
            await asyncio.sleep(90)
            ctx.voice_state.stop()
            del self.voice_states[ctx.guild.id]
        if member_count == 2:
            return member_count
    self.bot.loop.create_task(check())```
brittle ingot
#

oop

slate swan
#

no code block 🤧

heavy folio
# brittle ingot assign this to a variable and you should be able to do for instance: ```py user...
Ignoring exception in command blacklist status:
Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 167, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:\Users\user\Desktop\theBot\cogs\botmods.py", line 187, in _status_blacklist
    mod = await self.bot.fetch_user(find_userid.modid)
AttributeError: 'dict' object has no attribute 'modid'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 994, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 1448, in invoke
    await ctx.invoked_subcommand.invoke(ctx)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 894, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 176, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'dict' object has no attribute 'modid'```
brave flint
heavy folio
valid perch
#

I'll help when you show us the right code for your error. Your current code has indentation issues

valid perch
#

yea

slate swan
valid perch
brittle ingot
valid perch
#

@ me when its right

slate swan
#
            def check(reaction, user):
                return user == ctx.author and str(reaction.emoji) in ["◀️", "▶️"] 
            def check2(reaction, user):
                return reaction.message == message
            while True:
                try:
                    reaction, user = await self.bot.wait_for("reaction_add", checks=[check, check2])```how can i make this work? not sure how i can add the 2 checks to the same one
heavy folio
#

ohh

valid perch
#

return user == ctx.author and str(reaction.emoji) in [":arrow_backward:", ":arrow_forward:"] and reaction.message == message

heavy folio
regal shell
#

@brittle ingot you free to help me rq?

brittle ingot
#

yeah

full valley
#
games = {}
set_aid = set()

#!r command -> Randomly sorts players into teams
@bot.command()
async def r(ctx):
    if ctx.channel.id in allowed_channels: #and ctx.author.id in games.values():
        ggid = settings.find_one({"guild_id": ctx.guild.id})
        qsize = ggid["qsize"]
        game_id = ggid["game_id"]
        tally = ggid["tally"]
        set_aid.add(ctx.author.id)
        for x in set_aid:
            if x in games[game_id-1]:
                settings.update_one({"guild_id": ctx.guild.id}, {"$inc": {'tally': 1}})
                if tally >= (qsize/2):
                    settings.update_one({"guild_id": ctx.guild.id}, {"$set": {'tally': 0}})

Hi guys anyone know how I can fix this? I'm trying to make it so when 3 people use the command !r, who's id's are also stored as values in a dictionary named games, something will happen.

regal shell
#

I can’t figure out how to fix the indention error

slate swan
valid perch
brave flint
#

how bout that?

full valley
slate swan
# valid perch screenshot it? Although Ill guess for you. Your only gonna have `self` in metho...
    @commands.command(name="userinfo", aliases=['ui', 'uinfo', 'whois'])
    async def userinfo(self, ctx, member: Union[discord.Member, discord.User] = None):
        try:
            if member == None:
                member = ctx.author
#200 lines of stuff that works
#stuff that doesnt work VV
            pages = 2
            cur_page = 1
#embed stuff
            await message.add_reaction("◀️")
            await message.add_reaction("▶️")

            def check(reaction, user):
                return user == ctx.author and str(reaction.emoji) in ["◀️", "▶️"] and reaction.message == message
                
            while True:
                try:
                    reaction, user = await self.bot.wait_for("reaction_add", timeout=10, check=check)
                    
                    if str(reaction.emoji) == "▶️" and cur_page != pages:
                        cur_page += 1
                        await message.edit(embed=embed1)
                        await message.remove_reaction(reaction, user)
                        
                    elif str(reaction.emoji) == "◀️" and cur_page > 1:
                        cur_page -= 1
                        await message.edit(embed=emb)
                        await message.remove_reaction(reaction, user)
                        
                    else:
                        await message.remove_reaction(reaction, user)

                except Exception as e:
                    print(repr(e))
#stuff that doesnt work^^
        except:
            fetchmember = await self.bot.fetch_user(member.id)
#100 lines of other stuff that works```
#

the center bit is what matters

valid perch
brittle ingot
regal shell
#

Did that now syntax error on ‘await’

slate swan
#

between pages and print(repr(e))

valid perch
slate swan
#

and when it used to, it would change the embeds for the messages that previously sent

brave flint
slate swan
#

heres a vid of what i mean

#

no bully 🤧

regal shell
#

Taking a pic through laptop rq

slate swan
regal shell
slate swan
#

considering youre on a phone rn

#

nvm then

brave flint
slate swan
regal shell
#

I’m trying I don’t know what to indent

#

Wel I know what

#

But when I indent it leads to more problems lol

brittle ingot
#

we are gonna need to work on teaching proper indentation 😄

valid perch
unkempt canyonBOT
#

Indentation

Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.

Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.

Example

def foo():
    bar = 'baz'  # indented one level
    if bar == 'baz':
        print('ham')  # indented two levels
    return bar  # indented one level

The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.

Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines

More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation

valid perch
#

xx

slate swan
#
try:
  #stuff
    if stuff is stuff:
      #stuff
    else:
      #stuff
except:
  #stuff``` @regal shell indent example
brittle ingot
#

OH MY WORD! THAT IS A THING? i've been trying to explain it all day 😂

brave flint
valid perch
#

Your cog already has an init method 🤷

#

But each to there own I guess

#

And another class wouldn't have access to your classes instance. But meh

slate swan
brave flint
slate swan
#

yup still nothing

valid perch
regal shell
#

Ok I fixed one part

brave flint
valid perch
#

huh

heavy folio
pliant gulch
#

Doesn't replit default a tab to 2 spaces instead of 4

heavy folio
slate swan
# valid perch Care to add some print statements and see what runs, what doesnt, etc. Kinda at ...
            pages = 2
            cur_page = 1
            await message.add_reaction("◀️")
            await message.add_reaction("▶️")
            print("reactions got added")
            def check(reaction, user):
                return user == ctx.author and str(reaction.emoji) in ["◀️", "▶️"]  and reaction.message == message
            print("check worked")
            while True:
                try:
                    reaction, user = await self.bot.wait_for("reaction_add", check=check)
                    print('try statement worked')
                    if str(reaction.emoji) == "▶️" and cur_page != pages:
                        cur_page += 1
                        await message.edit(embed=embed1)
                        await message.remove_reaction(reaction, user)
                        print('page up worked')
                    elif str(reaction.emoji) == "◀️" and cur_page > 1:
                        cur_page -= 1
                        await message.edit(embed=emb)
                        await message.remove_reaction(reaction, user)
                        print('page down worked')
                    else:
                        await message.remove_reaction(reaction, user)

                except:
                    pass```ima test this
brittle ingot
#

like discord and pastebin

heavy folio
#

4 spaces is recommended right?

brittle ingot
#

yeah

heavy folio
#

idk i feel 4 spaces makes the code look more organized

brittle ingot
#

idek where you would only use two spaces. tbh

slate swan
#

@valid perch nothing, literally nothing

heavy folio
slate swan
#

the reactions were added and nothing was printed whateven

valid perch
#

Sure your running the latest code?

slate swan
#

mhm

#

reloaded the cog

#

ill do it once more

valid perch
#

restart your bot

slate swan
#

already doing it lol

#

command was done twice^

#

but it fails at the try statement

brittle ingot
#

alright, im out. have a good one.

regal shell
#

Ugh I hate this

brittle ingot
slate swan
#

no lol

valid perch
#

More print statements, and its likely the check isn't returning true so print those checks

regal shell
#

I am lmfao

heavy folio
#

nah thats not replit

slate swan
#

id rather localhost lmao

heavy folio
#

anyways

heavy folio
#

you shouldnt use it to develop your bot as well

regal shell
#

What should I use then?

#

I’m this far in lmfao

#

Is there a way to transfer everything

slate swan
#

@valid perch here

regal shell
#

What should I use to code then

valid perch
valid perch
regal shell
#

I have vsc but don’t know how to use it

slate swan
#

if check is true:

#

/false?

valid perch
valid perch
#

Its a nice editor yea

slate swan
regal shell
#

I have the mobile version

slate swan
#

ive never done things like that

valid perch
#

Do you return print statements...

regal shell
#

I’m trying to download actual version

valid perch
#

Think
Or do you put a print on there own line

regal shell
#

Can’t it’s not supported will mobile version work?

valid perch
#

Dunno, I try avoiding coding on phones

regal shell
#

It’s not on phone it’s on a chrome book

valid perch
#

Ah, pain

#

Can you install anything?

regal shell
#

I’ll send pic in dms can you tell me good ones?

slate swan
valid perch
#

This is fairly basic stuff, so I might recommend a python refresher to make future bot development easier on ya

valid perch
#

Do you. Thats great to hear

slate swan
#
            def check(reaction, user):
                user == ctx.author and str(reaction.emoji) in ["◀️", "▶️"]
                print('this worked')
                reaction.message == message 
                print('that worked')
                return
            print('all worked')```
#

WAIT

#

ok there

valid perch
#

Code after return isn't run. Fun fact, return returns

#

Print the result of the check...

#

There always gonna 'work'

slate swan
#

that good?

valid perch
#

What

#

You also now don't return anything from your check so gl with that

#

Your second == isn't assigned to anything

#

..

slate swan
#

message = await ctx.send(embed=emb)

#

its already in the source

valid perch
#

🤦‍♂️

slate swan
#
            message = await ctx.send(embed=emb)

            await message.add_reaction("◀️")
            await message.add_reaction("▶️")
            print("reactions got added")

            def check(reaction, user):
                user == ctx.author and str(reaction.emoji) in ["◀️", "▶️"]
                print('this worked')
                reaction.message == message 
                print('that worked')
                return
            print('all worked')```
valid perch
#

I'm gonna get back to work. But you've got this

Try actually printing the results of your conditions and then return the result. Hint you can print variables by doing print(variable)

#

Your check will always retuyrn None but whatever

slate swan
#

yup still say its unused

#

How would I kick the user if they didn’t do this command after 24 hours of joining?

@client.event
async def on_message(message):
   if message.channel.id == 909671265864933406: 
       await message.delete()
   if message.channel.id == 909671265864933406 and message.content.lower() == '*verify':
       fullaccessrole = get(message.guild.roles, id=909670961115201537)
       await message.author.add_roles(fullaccessrole)```
dusk pumice
#

How to use button without dpy 2.0?

dusk pumice
maiden fable
#

Like dislash or discord_components

full valley
#

Hey does anyone know how I can see if a command is used 3 times, by only by people that their id’s are stored in a certain key in a dictionary

#

e.g.
!q (player id as value in dict)
!q (player id as value in dict)
!q (player id not in dict)
!q (player id as value in dict)

Then command goes through

dusk pumice
#
hunter = True
def thankyou():
  print("Thank you hunter")

if hunter:
  thankyou()
unkempt canyonBOT
#

@dusk pumice :white_check_mark: Your eval job has completed with return code 0.

Thank you hunter
naive parcel
#

hello

#

i have a doubt

#

i wanna display the users using my bot

#

and i use the code len(self.client.users) and the intents are enabled

#

and with 21 servers it shows 13k users

#

so is that the accurate amount of users using the bots or its showing the total number of members in each server where the bot is present

#

if u have a solution pls ping me and reply

naive parcel
#

that means the bot is being used by that amount of members on a regular basis

boreal ravine
#

I mean that its the amount of users that the amount of guilds ur bot is in

naive parcel
#

oh well

#

aight tnx

boreal ravine
#

np

naive parcel
#

so thats basically not the amount of users using the bot

boreal ravine
#

yes

#

just the amount of people ur bot can see

naive parcel
#

so is there a way to get the users using the bot

naive parcel
#

im using this rn and as u said its showing the number of members in the guilds the bot is in

#

maybe there is no way

slate swan
#

!d discord.ext.commands.Bot.get_all_members

unkempt canyonBOT
#

for ... in get_all_members()```
Returns a generator with every [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") the client can see.

This is equivalent to:

```py
for guild in client.guilds:
    for member in guild.members:
        yield member
slate swan
#

There

#

Get len(set(that_thing))

slate swan
naive parcel
slate swan
#

a bit lower down u can see a video on what happens

naive parcel
#

its gonna show all the members the bot will see

slate swan
#

Well that's the point isn't it

#

essentially i need it to only edit the new message and not the old ones

naive parcel
slate swan
#

can someone help me?

class music(commands.Cog)
   def_init_(self, client):
     self.client=client
``` it says the cog is invalid syntax
boreal ravine
slate swan
boreal ravine
boreal ravine
maiden fable
#

I an init with a single underscore 🤤
I am init with a double underscore 🤤

slate swan
slate swan
#

Makes sense

#

what link

#

Pretty accurate

slate swan
slate swan
maiden fable
#

Sooo?

slate swan
#

Pretty accurate for you

#

09

boreal ravine
#

dunder methods with 1 underscore 😏

slate swan
#

ik, just ironic

maiden fable
#

Don't y'all think it's OT....?

maiden fable
slate swan
#

thats not something to be proud of but u do u 🤧

#

Wouldn't say 'thanks' without knowing what it means but sure

full valley
#

Hey does anyone know how I can see if a command is used 3 times, by only by people that their id’s are stored in a certain key in a dictionary

e.g.
!q (player id as value in dict)
!q (player id as value in dict)
!q (player id not in dict)
!q (player id as value in dict)

Then command goes through

slate swan
#
      await message.channel.send(embed=embed)
      await message.add_reaction("👍") #adding reaction
      await message.add_reaction("👎") #adding reaction```
#

How come this doesn't work?

boreal ravine
slate swan
full valley
#

I’ve hit a brick wall 😩

boreal ravine
slate swan
#

wdum

#

Can you show an example

boreal ravine
#

No need to

slate swan
#

why

#

I don't understand

boreal ravine
#

set a variable

#

when sending the message

slate swan
#

message = await ctx.send(embed=embed)
message.add_reaction("emoji")

#

this?

boreal ravine
#

adding a reaction is a coroutine

slate swan
#

hm

boreal ravine
#

dont forget that

slate swan
#

ty

boreal ravine
#

👍

full valley
#

Alright I think i’ve found a solution to my answer

#

first run a check for my command to see if players issuing the command are in the dictionary

#

if they are add them to a new list, then check if the length of the list is == 3

#

This better work YEP

dusk pumice
#

How can my bot know what roles the user have?

#

ping to awnser plz

full valley
#

has_any_role @dusk pumice

#

iirc

dusk pumice
#

Urr

#

I didn't ment that