#discord-bots

1 messages · Page 688 of 1

brittle ingot
#

not locally hosted either.

slate swan
#

haha, Its probably like 60ms for me, my bot is rn searching from over 10 subreddits * 9 with praw api

brittle ingot
#

are you using asyncpraw?

slate swan
#

Average 3ms

#

Mine

brittle ingot
#

its called praw yeah 😄

slate swan
#

Praw is just an api wrapper with a async version which is asyncpraw

slate swan
#

🚶

leaden jasper
slate swan
#

I like calling it the reddit api

brittle ingot
#

i mean you aren't wrong.

slate swan
#

Even the docs calls itself the reddit api

brittle ingot
#

Just use asyncPRAW its literally the same thing, just asynchronous

leaden jasper
#

how about aiohttp

#

its async

slate swan
#

And not reddit only

brittle ingot
#

why go through the hassle of creating requests when there is a library to do it for you?

slate swan
#

Yeah its just unnecessary

slate swan
brittle ingot
#

i mean its a feesible option, just not always the best. as a library can handle eventualities that you may not consider.

slate swan
pliant gulch
#

You don't need to reinvent the wheel

brittle ingot
#

^

leaden jasper
#

maybe the library is slow

#

so u make the requests on ur own

slate swan
#

I want to make a api wrapper for the reddit api or a asyncpraw fork but idk if i should start yert

slate swan
#

Kinda scared

slate swan
brittle ingot
#

i mean there are an endless amount of libraries that need to be made ||I have a project that needs a Python library|| 🤣

slate swan
slate swan
brittle ingot
#

a meme command.

slate swan
#

Ive made a search command with asyncpraw lol

slate swan
slate swan
brittle ingot
#

same, did a meme command for a bot a while back, had it where it searched a set of subreddits, or you could enter your own to search 😄

slate swan
#

Bad thing about asyncpraw using the multiple reddit instance makes it very slow

brittle ingot
#

why not just make it a background task using ```py
@tasks.loop()

slate swan
#

ah yes 126ms

#

5857.46ms

#

lovely

brittle ingot
#

oooof

#

yeah its taking up tons of resources

slate swan
#

I mean I've got like 3 websites and 1 game server running on the same vds

#

and only 4gb 2cores

#

I think using the multiple reddit instance and when you use a limit of subs it will look for the limit in total for all the subreddits and not the limit per subreddit idk

slate swan
#

Nah

#

Dont want to🚶

#

🕴️

#

the latency is so bad I thought my command didn't work and went back to coding, after realising that it was just taking shit ton of time to work lol

#

Damn

leaden jasper
#

asyncpraw is slow ig

slate swan
#

Not really

leaden jasper
#

I used it before but forgot what performance was like

slate swan
#

Depends on how much subreddits your searching and how many submissions your going through but getting a random sub is very quick

leaden jasper
#

aiohttp can get 100 subs in a second

slate swan
#

Thats nice

#

Still not gonna use aiohttp for that

leaden jasper
#

and

#
reddit = asyncpraw.Reddit( client_id="CLIENT_ID", client_secret="CLIENT_SECRET", password="PASSWORD", user_agent="USERAGENT", username="USERNAME", )
#

it doesn't require any of that

#

no auth

slate swan
#

🤷‍♂️

vocal shoal
#

is there a function that returns thr name of the last command/event that ran?

slate swan
#

At your service

leaden jasper
#

Member not found

#

I read the error

vocal shoal
#

member was not found

slate swan
#

discord.ext.commands.errors.MemberNotFound: Member "deleted-role" not found.

#

is delete_after= in seconds or minutes

#

cuz its taking shit ton of time to delete itself for some reason

slate swan
slate swan
#

I have
await channel.send(content=None, embed=embed, delete_after=1)

#

Or only floats

#

and it takes like 30 sec to delete

#

or 15s

#

Did you actually add the member

#

And do you have intents and is the bot higher than the role the member has

#
    for guild in client.guilds:
        for channel in guild.channels:
            if os.path.exists("/home/bot/adx/channel"+str(guild.id)) == True:
                file = open("channel"+str(guild.id), "r")
                if str(channel.id) == file.read():
                    embed = discord.Embed(title="Channel inactive", description="Send a message to refresh", color=0xFF0000)
                    embed.add_field(name="Reason for inactivity:", value="Restart by developer", inline=False)
                    embed.add_field(name="Note: ", value="Everything should be working now.", inline=False)
                    await channel.send(content=None, embed=embed, delete_after=1)
                    break

I have this in on_ready so whenever my bot crashes(every damn second), it sends that so ppl think im just deving the bot and my servers arent shitty

slate swan
#

What about it

#

Can your bot kick others?

#

And is the bot higher in roles than the users your trying to kick

#

Answer my question

#

why add kick command

#

kinda useless just right click

#

All these questions are related to the problem if not answered i cannot help you out understand?

#

and kick user

slate swan
#

Try printing out all members

#
await ctx.send(ctx.guild.members)
#

No send it in a different command

snow flare
#

To do something apart from replying to the interaction, would I use interaction.response just like for replying to the interaction, or would I have to use something else?

slate swan
slate swan
snow flare
#

by something apart from replying I mean like kicking a user, deleting a channel, creating a channel, deleting a message

slate swan
#

Yes i think so

#

Never done it but probably can

snow flare
#

what would I use tho?

#

would I just use interaction.response?

#

and then something like interaction.response.category.create_channel("channel name")?

snow flare
#

ok

slate swan
#

Response is for responding to a msg

lavish sun
#

Looking for some help please on how to do something.
i want to make a discord bot that sends messages every so many minutes but I want to be able to create multiple messages with different time intervals

I know i can use tasks..loop to send a message every so many minutes, but it's a question of how would i actually store every message, different times and cycle through them and post. Obviously tasks.loop requires a timeframe so e.g tasks.loop(minutes=10)

snow flare
fervent quail
umbral dome
slate swan
#

I think interaction has all the attr ctx has

slate swan
umbral dome
#

!e


@client.command(name = "test")
async def _test(ctx):
    try:

        await ctx.send(f"Random tekst here {ctx.author} ")
        message = {
        "content" : f"Random message {ctx.author} "
}
        requests.post(config['Webhookurl'], data=message)
        

    except(ValueError):
        await ctx.send("***not vallid***")
unkempt canyonBOT
#

@umbral dome :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 'bot' is not defined
tacit horizon
#

how to make

if any(word in message.content for word in list):
```not case sensitive
umbral dome
#

!e


@client.command(name = "test")
async def _test(ctx):
    try:

        await ctx.send(f"Random tekst here {ctx.author} ")
        message = {
        "content" : f"Random message {ctx.author} "
}
        requests.post(config['Webhookurl'], data=message)
        

    except(ValueError):
        await ctx.send("***not vallid***")
snow flare
# slate swan I think interaction has all the attr ctx has

how would I create a channel in a particular category tho, because It wouldn't work if I do something like this:

category = ...
await interaction.category.create_channel()

as it would think that .category is a sub class/program of interaction

unkempt canyonBOT
#

@umbral dome :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 'client' is not defined
umbral dome
#

😭

#

yea it works on my pc

slate swan
#

Not familiar with category an its attrs

fervent quail
snow flare
snow flare
#

the problem is that I needed to do it after the interaction

#

and I just don't really know how to work with interactions

slate swan
#

Just do @tacit horizon

if any(word in message.content.lower() for word in list): 
fervent quail
#

I can't give you anymore information, I've told you it's interaction.guild

#

look up guild.create_text_channel

#

for how to do it in a category

lavish sun
#

Looking for some help please on how to do something.
i want to make a discord bot that sends messages every so many minutes but I want to be able to create multiple messages with different time intervals

I know i can use tasks..loop to send a message every so many minutes, but it's a question of how would i actually store every message, different times and cycle through them and post. Obviously tasks.loop requires a timeframe so e.g tasks.loop(minutes=10)

sage otter
#

!d itertools.cycle

unkempt canyonBOT
#

itertools.cycle(iterable)```
Make an iterator returning elements from the iterable and saving a copy of each. When the iterable is exhausted, return elements from the saved copy. Repeats indefinitely. Roughly equivalent to:

```py
def cycle(iterable):
    # cycle('ABCD') --> A B C D A B C D A B C D ...
    saved = []
    for element in iterable:
        yield element
        saved.append(element)
    while saved:
        for element in saved:
              yield element
```...
sage otter
#

and use next every new cycle.

snow flare
#

btw, how would I pass variables into my own View class

slate swan
tacit horizon
#

ya

slate swan
tacit horizon
#
if any(word in message.content for word in wrod1):
        await message.channel.send("No") 

if anyone say that word, then i want to add his name in a list.
and how many time he said that .

#

@slate swan help !! 😅

slate swan
#

Im lurking 🕴️

tacit horizon
#

its OOP

tacit horizon
slate swan
#

Cause im thinkingpithink

#

And youll probably want a dict and not a list

tacit horizon
#

ya

slate swan
#

You can use a db or json

#

Json would be fine since your storing an int key with and int value

tacit horizon
#

Json !!!!

slate swan
tacit horizon
#

javascript ?

slate swan
#

No the json.py module that uses the json format

tacit horizon
#

json is python module

slate swan
#

Yes

#

Use it🕴️

tacit horizon
#

and its look like javascript ?

slate swan
#

I mean its from js

#

🕴️

dire folio
#

how would i add a role to a user if i have their id?

tacit horizon
#

with input()

slate swan
#

Nvm what i said

#

Wdym

tacit horizon
#

huh

slate swan
#

Wdym by using input()

tacit horizon
#

wait

#

nvm

slate swan
dire folio
#

but what about the user?

cloud dawn
unkempt canyonBOT
#

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

Gives the member a number of [`Role`](https://docs.disnake.dev/en/latest/api.html#disnake.Role "disnake.Role")s.

You must have the [`manage_roles`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.manage_roles "disnake.Permissions.manage_roles") permission to use this, and the added [`Role`](https://docs.disnake.dev/en/latest/api.html#disnake.Role "disnake.Role")s must appear lower in the list of roles than the highest role of the member.
snow flare
cloud dawn
#

This will only work on member objects*

snow flare
snow flare
dire folio
slate swan
slate swan
dire folio
#

cause idk what type hinting is

snow flare
#

use get_member

dire folio
snow flare
dire folio
#

i get the same Attribute Error

velvet tinsel
#

?

#

whats wrong

dire folio
#

(with get_member not fetch_member)

dire folio
#

user = await bot.get_member(userid)await user.add_roles(913137354900897792)

velvet tinsel
dire folio
#

i am

velvet tinsel
dire folio
#
userid = user.id
user = await bot.get_member(userid)
await user.add_roles(913137354900897792)
velvet tinsel
#

alright

#

ohhh

#

try ctx.guild.get_member(userid)

#

@dire folio ?

dire folio
#

k

velvet tinsel
#

does it work?

dire folio
#

i got TypeError: object Member can't be used in 'await' expression

velvet tinsel
#

no await

#

just ctx.guild.get_member(userid)

dire folio
#

k lemme try it

dire folio
velvet tinsel
#

hmm

slate swan
#

can I change embed.set_image size somehow?

velvet tinsel
#

try making it a str? that's my best guess

#

wait...

slate swan
velvet tinsel
#

is user ctx.author?

velvet tinsel
dire folio
slate swan
#

ah

dire folio
#

at least i think

dire folio
velvet tinsel
#

then what is it?

#

wait

dire folio
#

its a mentioned person

velvet tinsel
#

who is user.id

velvet tinsel
dire folio
#

the id of the mentioned person

velvet tinsel
#

is user: discord.User?

dire folio
#

ye

velvet tinsel
#

ok

#

ohh

#

because user is already the mentioned person, you dont need a get_member

#

just add it directly, because you did a user: discord.User

#
userid = user.id
await user.add_roles(...)
#

... do you really need the user id?

#

@dire folio

dire folio
#

@velvet tinsel i'm getting AttributeError: 'User' object has no attribute 'add_roles'

velvet tinsel
#

hmm

slate swan
#

Add roles only takes member objs

velvet tinsel
#

try await bot.add_roles(userid, role)...Okimii?

velvet tinsel
#

I can finally go sleep

slate swan
velvet tinsel
#

isn't that what he just did?

#

Okimii?

slate swan
#

Wdym

velvet tinsel
#
await user.add_roles(...)
#

is what he did

slate swan
#

Add roles only takes member objs

#

If it would be like that user is a member obj

velvet tinsel
#

member is discord.Member?

slate swan
velvet tinsel
#

ahhh

#

so it's not discord.User?

slate swan
#

pepe:discord.Member
Pepe is a member obj

slate swan
velvet tinsel
#

ahhhh

#

thank you

slate swan
#

Yw

dire folio
slate swan
#

The member obj takes ids and usernames

tacit horizon
#

😅

unkempt canyonBOT
#
Not in my house!

Package could not be found.

slate swan
#

🕴️

tacit horizon
#
if any(word in message.content for word in wrod1):
``` how do i get the user name who type that word
#

i have to add ctx

#

but how ;-;

slate swan
dire folio
slate swan
#

Iircpithink

tacit horizon
lost wolf
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ValueError: None is not in list

slate swan
dire folio
#
async def accept(ctx, user: discord.Member, role):
    userid = user.id
        await user.add_roles(913137354900897792)
tacit horizon
slate swan
slate swan
#

In message content

tacit horizon
dire folio
slate swan
#
async def accept(ctx, memberr: discord.Member, role):
        await member.add_roles(role) 
#

That should work

dire folio
#

ty

dire folio
slate swan
dire folio
slate swan
#

A member id never changes but a member username could

dire folio
#

no cause its going to be for different users

slate swan
#

Then add a different id

#

How you should call the command
!accept 1234567890 role

#

Dont knoe your prefix so i used ! Lol

dire folio
#

so use the id instead of the mention?

slate swan
#

Yes

dire folio
# slate swan Yes

it doesn't do the intended thing
heres the command:

async def accept(ctx, member: discord.Member, role):
    userid = member
    print(userid)
    for item in waiting:
        if item[0] == userid and item[1] == 'hoster' and role == item[1]:
            role = item[1]
            emb = discord.Embed(title='**Accepted**', description=f'Congratulations you have been accepted for {role}!', color=0x2ecc71)
            await member.send(embed=emb)
            await member.add_roles("Hoster")
            emb = discord.Embed(title='**User has been accepted!**', description='The neccessary roles have been added.')
            await ctx.send(embed=emb)
            str(role)
            waiting.remove([userid, role])
            save_waiting()
            return
        elif item[0] == userid and item[1] == 'staff' and role == item[1]:
            role = item[1]
            emb = discord.Embed(title='**Accepted**', description=f'Congratulations you have been accepted for {role}!', color=0x2ecc71)
            await member.send(embed=emb)
            urole = discord.utils.get(bot.get_guild(ctx.guild.id).roles, id = 763000301467992084)
            await member.add_roles(urole)
            urole = discord.utils.get(bot.get_guild(ctx.guild.id).roles, id = 760101679877849089)
            await member.add_roles(urole)
            emb = discord.Embed(title='**User has been accepted!**', description='The neccessary roles have been added.')
            await ctx.send(embed=emb)
            str(role)
            waiting.remove([userid, role])
            save_waiting()
            return
    else:
        await ctx.send('No user found!')
#

i haven't changed the elif part

#

the list looks like [[1212341231, 'hoster']]

brittle ingot
#

you should be able to just mention a member and pull their ID from the mention as long as you type hinted it properly.

lost wolf
#

how do i get the user id that used the command?

brittle ingot
#

user_id = ctx.author.id

lost wolf
#

alright thanks

brittle ingot
#
async def accept(self, ctx, memberr: discord.Member, role: discord.Role): 
    member_id = memberr.id 
    role_name = role.name

Type hinting like i did above for both memberr and role allows you to mention the role or memberr by @, ID, or its exact name and receive the entire object for it. Note: any exact names that have spaces need to be incased in quotation marks so your command knows its one arg.

lost wolf
#

how to check if someone mentions my bot. and if they do the bot will send a message

slate swan
#

how would i make a reminder command i was thinking using asyncio.sleep() because its a private bot but im not because its kinda bad practice so how would i?

#

my while loop doesn't go thru completely for some reason it just stays at the start and restarts itself

slate swan
#

its kinda nsfw but aigh

#
                while autoporn:
                    if message.channel.is_nsfw():
                        if os.path.exists("/home/bot/adx/channel"+str(message.guild.id)) == True:
                            file = open("channel"+str(message.guild.id), "r")
                            if str(message.channel.id) in file.read():
                                post = reddit.subreddit("legalteens").random()
                                while post.url == None or "redgif" in post.url:
                                    print("skip")
                                    post = reddit.subreddit("legalteens").random()
                                embed = discord.Embed(title="r/legalteens")
                                embed.set_image(url=post.url)
                                await message.channel.send(content=None, embed=embed)

                                post = reddit.subreddit("hentai").random()
                                while post.url == None or "redgif" in post.url:
                                    print("skip")
                                    post = reddit.subreddit("hentai").random()
                                embed = discord.Embed(title="r/hentai")
                                embed.set_image(url=post.url)
                                await message.channel.send(content=None, embed=embed)
                                #
                                post = reddit.subreddit("zerotwohentai").random()
                                while post.url == None or "redgif" in post.url:
                                    print("skip")
                                    post = reddit.subreddit("zerotwohentai").random()
                                embed = discord.Embed(title="r/zerotwohentai")
                                embed.set_image(url=post.url)
                                await message.channel.send(content=None, embed=embed)
                                # ```
#

would await asyncio.sleep() work as fix for
aiohttp.client_exceptions.ClientOSError: [Errno 104] Connection reset by peer

or does it need to be time.sleep()

dire folio
# brittle ingot ```py async def accept(self, ctx, memberr: discord.Member, role: discord.Role): ...

could u check this pls.

async def accept(ctx, memberr: discord.Member, role: discord.Role):
    userid = memberr.id
    for item in waiting:
        if item[0] == userid and item[1] == 'Hoster' and role == item[1]:
            emb = discord.Embed(title='**Accepted**', description=f'Congratulations you have been accepted for {item[1]}!', color=0x2ecc71)
            await memberr.send(embed=emb)
            await memberr.add_roles("Hoster")
            emb = discord.Embed(title='**User has been accepted!**', description='The neccessary roles have been added.')
            await ctx.send(embed=emb)
            str(role)
            waiting.remove([userid, role])
            save_waiting()
            return
#

cause it doesn't seem to be working

brittle ingot
#

Hoster ?

dire folio
#

ye thats the role name

#

and it is what i am inputting

brittle ingot
#

so you get a role object to use then. so instead of:

await member.add_roles("Hoster") 

Which wouldn't work anyways as it takes a role object.

do:

await member.add_roles(role)
#

also your if statement looks a bit wonky.

#
if item[0] == userid and item[1] == 'Hoster' and role == item[1]:

has you checking the same thing twice essentially.

try:

if item[0] == memberr.id and item[1] == role.name: 
    ... do stuff
#

Also have you considered a database by chance? i don't mean to put you down, but your code looks a bit inefficient with the for loop. May be better to store anyone waiting for a role in a database where you can store the userId as the primary key, the role id as the role they are waiting for and their status as "waiting", "accepted", or "denied". This could easily be done using SQLite or PostgreSQL

slate swan
#

how can i make a check that checks if the interaction author is the context author?

brittle ingot
#

what is the code? is there a callback? like res or something? you could do:

if res.author.id === ctx.author.id:
    ...some stuff
slate swan
#

trying to do a button that only is valid when the context author interacts with it

#

dont have a tb since i havent started

brittle ingot
#

you should get a return of essentially context with the interaction and you can check that as it should return who interacted if the person who interacted isn't the author of the command then pass else execute code.

slate swan
brittle ingot
#

oh gosh its been a bit since i've used buttons in python 😂

brittle ingot
#

#1


def filter(res): 
   return res.author.id = ctx.author.id

try:
  while True:
      res = await self.bot.wait_for('Button_click', check=check, timeout = 500)
     
      if clause == true:
            ...execute code
    
except asyncio.timeoutError as e:
    ...handle it
#

remember its all psuedo. depends on the lib and everything.

slate swan
#

im using disnake lol

brittle ingot
#

oh then i have no clue. brb.

slate swan
#

damn😭

brittle ingot
#

what type of interaction.

slate swan
#

wdym what type

pliant gulch
pliant gulch
#

!d discord.ui.View.interaction_check

unkempt canyonBOT
#

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

A callback that is called when an interaction happens within the view that checks whether the view should process item callbacks for the interaction.

This is useful to override if, for example, you want to ensure that the interaction author is a given user.

The default implementation of this returns `True`.

Note

If an exception occurs within the body then the check is considered a failure and [`on_error()`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.View.on_error "discord.ui.View.on_error") is called.
slate swan
#

🚶

pliant gulch
#

This works the same way as the cog check you get inside of Cogs

#

Just store a ctx instance variable to your view class

#

Then use it inside of the interaction_check

#

E.g ```py
return self.context.author == interaction.author

brittle ingot
#

thank god andy was here 😂 i got docs open trying to bash my way through it to try and find an answer 😂

pliant gulch
#

This will cause all children of the view to only run if the ctx author is the one pressing the button/interaction

pliant gulch
slate swan
slate swan
pliant gulch
#

You'd subclass View and give it a ctx parameter inside of the class constructor

slate swan
#

alr thx

solid falcon
pliant gulch
#

You'd probably want to use an async driver for OpenAI engines

#

If there is one, otherwise run it inside of executor

#

As this would block your bot for the amount of time it takes to compute results

slate swan
#

oh and @brittle ingot thx for effort

dire folio
brittle ingot
#

!d discord.Member.add_roles

unkempt canyonBOT
#

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

Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s.

You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
brittle ingot
#

you can give it a list of roles to add.

slate swan
#

you can only add roles as a list and not a single role

pliant gulch
#

*roles means you can add any amount of roles

slate swan
#

like their isnt something like add_role

slate swan
dire folio
#

how would i separate the role names

slate swan
snow flare
#

I have made my own View class, and I'm trying to pass variables into it, but for some reason I get this error: discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'View' object has no attribute 'children'
This is how it looks. Did I do it the wrong way? and how can I fix it?

class View(View):

    def __init__(self, ctx, category):
        self.ctx = ctx
        self.category = category

view = View(ctx, category)
slate swan
#

as any string

snow flare
slate swan
#

welp dont know

snow flare
#

what lib do you use?

solid falcon
pliant gulch
snow flare
slate swan
#

thats to subclass a class

snow flare
#

oh, ok, so would I just write something like super().__init__(ctx, category)?

#

under def init

pliant gulch
#

No, because the superclass doesn't take ctx nor category

#

Those are your custom stuff so you don't pass it to the superclass

slate swan
#
class View(View):
    def __init__(self, ctx, category):
    self.ctx = ctx
    self.category = category
    def super().__init__(timeout=None):
snow flare
#

what is the point of it then?

snow flare
slate swan
#

it wont work

pliant gulch
#

Not def super

#

Just super().__init__()

slate swan
#

how did i mess that up

#

when im working with it rn

snow flare
#

ok, it worked, thank you guys

slate swan
#

yw

#

how can i get an author of an error handler?

dire folio
# brittle ingot you can give it a list of roles to add.

i did await memberr.add_roles('Trial Mod', 'Staff') and got the error

Ignoring exception in command accept:
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 976, in accept
    await memberr.add_roles('Trial Mod', 'Staff')
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/member.py", line 777, in add_roles
    await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'str' object has no attribute 'id'

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

Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'id'
snow flare
#

also, if I wanted to make a private command, that can only be used by a user with a certain role, would I just add a @has_role() decorator into the command?

snow flare
#

ok, thanks

slate swan
#

yw

snow flare
pliant gulch
slate swan
pliant gulch
dire folio
pliant gulch
snow flare
pliant gulch
#

Since you get that in on_command_error

snow flare
#

if you pass in ctx into the event

pliant gulch
#

You can do so via get_role

#

!d discord.Guild.get_role

unkempt canyonBOT
slate swan
#

i tried but i got no response from the error handler

pliant gulch
#

Take the return of this method and save it as the role

#

Pass it to add_roles

pliant gulch
slate swan
# pliant gulch Can you show the code?
@bot.event 
async def on_command_error(ctx,error):
    view = buttons.tb(ctx.author)
    if isinstance(error, commands.CommandNotFound): 
        embed8 = disnake.Embed(title="Error!!!",
        description=f"Could not continue",
        color=0xe74c3c,
        timestamp=datetime.datetime.utcnow()) 
        await ctx.send(embed=embed8,view=view)
        await view.wait()
        if view.value is True:
            embed9 = disnake.Embed(title="Terminal",
            description=error,
            color=0xe74c3c,
            timestamp=datetime.datetime.utcnow())
            await ctx.send(embed=embed9)
slate swan
pliant gulch
pliant gulch
#

Somethings happening inside of the buttons.tb then

#

What is that doing exactly?

slate swan
#
class Tb(disnake.ui.View):
    def __init__(self,author: disnake.Member):
        self.author = author
        super().__init__(timeout=10.0)
        self.value = None

    async def on_timeout(self):
        self.children[0].disabled = True
        self.stop()

    @disnake.ui.button(label="Traceback",style=disnake.ButtonStyle.red)
    async def traceb(self,button:disnake.ui.Button,intr: disnake.MessageInteraction):
        await intr.send("Loading Traceback...",ephemeral=True)
        self.value = True
        self.children[0].disabled = True
        self.stop()
#

thats the class

pliant gulch
#

Where exactly are you using the author though

#

And I don't see anything here that would cause an error

#

Is there no error raised and it just hangs?

slate swan
#

nope

snow flare
#

how can I tag a channel in a message?

#

if I have the channel object

slate swan
#

nvm lol

pliant gulch
#

!d discord.TextChannel.mention

unkempt canyonBOT
pliant gulch
# slate swan nope

Got no clue then, maybe try putting the class construction inside of a try-except to see if you maybe get an error out

snow flare
snow flare
#

or would it just be: channel.send("message " + discord.the_channel_that_I_want_to_mention.mention)?

pliant gulch
#

Just channel.mention

snow flare
pliant gulch
#

channel here being a discord.TextChannel instance

snow flare
#

shit, wrong mention

snow flare
pliant gulch
slate swan
slate swan
pliant gulch
#

I got no clue then

slate swan
#

damn

slate swan
kindred epoch
#

@slate swan is that a slash command or a normal command?

#

Cuz slash commands has a diff global command handler

slate swan
#

how can i make a util which returns X based on what i input eg:

content = "--do ban --do kick"
util.args(content, "--do")```
i want to make it return **ban** anyone know how i can do this
slate swan
#

normal command

kindred epoch
#

Oh ok

slate swan
#

yeah

rare saddle
#

version discord.py == 2.0

wicked atlas
wicked atlas
#

Honestly, I'd suggest moving to a fork instead of using d.py anymore

rare saddle
slate swan
rare saddle
slate swan
slate swan
rare saddle
slate swan
#

because if your doing buttons the kwarg is style

rare saddle
slate swan
#

yw

brittle ingot
#

idk who pinged me but i was afk sorry.

harsh abyss
#

how do i fix that i just downloaded requests and it says that

slate swan
#

iirc

harsh abyss
#

ik i downloaded it

wicked atlas
harsh abyss
#

thanks

slate swan
#

and use aiohttp request isnt async

brittle ingot
#

plus im in this server and they are beta testing a bot, They want people to add the bot to their servers to test it. The bot requests Administrator permissions, but has only Help, info, bot info, support and thats it. Its supposed to be a raid prevention bot. Am i the only one who thinks it sounds fishy?

slate swan
#

!pypi aiohttp

unkempt canyonBOT
wicked atlas
#

It's either their doing something not good, or they could just not be educated on why not to give bots admin

brittle ingot
#

i think they're trying to get the bot in 75 servers to get the verification process going. but #1 never give a bot admin perms. #2 why beta test with none of the needed commands for the bot to actually function...

brittle ingot
wicked atlas
#

😐

slate swan
brittle ingot
#

oh i know lol

slate swan
#

all of my bots need admin perms

brittle ingot
#

mhmm bet

slate swan
brittle ingot
#

no offense if it actually needs it then great, but like i see so many people using it as a way to bypass actually giving their bot the permissions they should need at a minimum. you know? Like one of the first things i do is sit down and say. What will my bot do? What permissions does it need to do that?

slate swan
pliant gulch
brittle ingot
#

really?

slate swan
wicked atlas
slate swan
wicked atlas
#

😐

pliant gulch
slate swan
pliant gulch
#

I've made auto permissions calculators before just so I don't need to think that much

brittle ingot
#

wait is there an invite generator in python libs?

#

i don't see why not.

harsh abyss
slate swan
#

not coma

harsh abyss
#

thanks

#

i cant see that well

slate swan
#

yw

#

lol

harsh abyss
#

what does that mean

brittle ingot
#

should be requests.get() right?

harsh abyss
#

i got it

slate swan
#

how can i make a util which returns X based on what i input eg:

content = "--do ban --do kick"
util.args(content, "--do")```
i want to make it return **ban** anyone know how i can do this
rare saddle
#

???

visual island
#

dpy v2.0 or external lib?

#

if dpy, use view kwarg

slate swan
#

likely an external lib

#

its 2.0

rare saddle
slate swan
#

lol

slate swan
#

u need to use view=

#

and then u need to make a class for ur button view

#

not me lol

#

what

slate swan
slate swan
rare saddle
slate swan
slate swan
#

i replied to the wrong person

#

lol

harsh abyss
#

it dosent say hello when i join

#

or goodbye when i leave

slate swan
#

brah

harsh abyss
#

what

slate swan
#

u have so many problems in that code

harsh abyss
#

how it works perfectly so far

#

except the goodbye and hello prat

#

part

slate swan
#

just saying you should use aiottp

harsh abyss
#

im just watching a video on how to create my first bot

slate swan
#

and not request

#

yeah because requests isnt async

#

yep

slate swan
harsh abyss
#

so switch requests with aiottp

slate swan
unkempt canyonBOT
slate swan
harsh abyss
#

can i still just do the aiottp.aiottp

#

or is it diffrent

slate swan
#

its a bit different

harsh abyss
#

okay

slate swan
#

check the docs

harsh abyss
#

so instead of request.request it would be aiohttp.ClientSession()

slate swan
#

yep

harsh abyss
#

will that fix my problem

#

with the hello and goodbye

slate swan
#

prob not but it will help ur bot run better

harsh abyss
#

okay

slate swan
rare jolt
#

My discord bot controls a UI, so on my main thread I start a tk window and then fork off a thread to run the bot. I pass to that thread a reference to an object with methods that the bot can call to trigger things on the UI. I'm getting a really confusing error from the bot's thread.

Exception in thread TheClicker:
Traceback (most recent call last):
  File "C:\Users\m\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner
    self.run()
  File "C:\Users\m\AppData\Local\Programs\Python\Python39\lib\threading.py", line 910, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\m\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1652, in cget
    return self.tk.call(self._w, 'cget', '-' + key)
TypeError: can only concatenate str (not "int") to str

the place my bot thread starts is here:

    root = tk.Tk()
    player = ChannelSurfTk(root, rng, playlist)
    def OnClose():
        global exit_code
        player.OnClose()
        exit_code=EXIT_USER
    import threading
    from time import sleep
    threading.Thread(
        group=None,
        target=discord.main,
        name='TheClicker',
        args=(player), kwargs={},
        daemon=True
    ).start()

and discord.main is

def main(ui_hooks):
    print("here0")
    return DiscordChannelsurf(ui_hooks, cfg.TOKEN)

but not even "here0" is being printed. I can't figure out what is causing cget to be called with an incorrect parameter. The bot doesn't even call any tk methods, I commented out the few places it uses ui_hooks while trying to debug this.

rare saddle
#

Why am I getting an error if I reinstalled the library with version 1.7.3?

#

After all, 1.7.3 components should work

heavy folio
#

how do i get the bot's role

slate swan
#

how can i get a commands required permissions?

boreal ravine
rare saddle
slate swan
#

how to make the buttons line up?

@bot.command(aliases = [])
@commands.cooldown(1, 1, commands.BucketType.user)
async def emb(ctx, **kwargs):
    await ctx.message.delete()

    msg = await ctx.send(
        embed = discord.Embed(title = 'Русский / Enlish', timestamp = ctx.message.created_at),
        components = [
            Button(style = ButtonStyle.green, label = 'Русский'),
            Button(style = ButtonStyle.red, label = 'English')
        ])

    responce = await bot.wait_for('button_click', check = lambda message: message.author == ctx.author)
rare saddle
visual island
#

or use ActionRow

boreal ravine
rare saddle
rare saddle
visual island
rare saddle
#

What if I use a different library with buttons?

slate swan
#

disnake has good buttons lol

jolly shore
#

import discord
from discord.ext import commands, tasks
from datetime import datetime
import random
from itertools import cycle

client = discord.Client()
status = cycle(['Minecraft', 'Roblox', 'Pie', 'Fortnite'])
@client.event

async def on_message(message):
change_status.start()
if message.author == client.user:
return
if message.content.startswith('hi'):
await message.channel.send('hi')
if message.content.startswith('time'):
datem = datetime.today().strftime("%m/%d/%y")
await message.channel.send(datem)
if message.content.startswith('user'):
await message.channel.send(message.author)
if message.content.startswith('daball'):
r = ['Yes', 'No', 'Fifty percent']
await message.channel.send(random.choice(r))

@tasks.loop(seconds=10)
async def change_status():
await client.change_presence(activity=discord.Game(next(status)))
client.run(token)

visual island
#

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

round robin
jolly shore
slate swan
#

does interaction have all the attrs that ctx has?

boreal ravine
slate swan
slate swan
#

how can I edit Embed from msg in msg2?

    msg = await ctx.send(
        embed = discord.Embed(title = 'Выбирите язык\nSelect language', timestamp = ctx.message.created_at),
        components = [
                    [Button(style = ButtonStyle.blue, label = 'Русский'),
                    Button(style = ButtonStyle.blue, label = 'English')]
                ])
    responce = await bot.wait_for('button_click', check = lambda message: message.author == ctx.author)
    if responce.component.label == 'Русский':
      msg2 = await ctx.send(
          embed = discord.Embed(title = '', timestamp = ctx.message.created_at),
          components = [
                      [Button(style = ButtonStyle.blue, label = 'Русский'),
                      Button(style = ButtonStyle.blue, label = 'English')]
                  ])

i tried with msg.edit() but it not work

cloud dawn
#

You did so it will be msg2 not msg

odd walrus
#

getting 400 client error when sending webhooks

#

means that my ip is prolly flagged for sending too much i assume?

vague grove
#

yo guys, how can my bot fetch when someone joins vc, and liek their id or name

manic wing
#

!d discord.on_voice_state_update || member = member. Where member is an instance of discord.Member. name, id = member.name, member.id

unkempt canyonBOT
#

discord.on_voice_state_update(member, before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") changes their [`VoiceState`](https://discordpy.readthedocs.io/en/master/api.html#discord.VoiceState "discord.VoiceState").

The following, but not limited to, examples illustrate when this event is called...
vague grove
#

gotcha

vague grove
unborn steppe
#

I just finished making a bot that checks for Steam sales. I wanted to make it public on GitHub but I don’t know how to hide my token. Can someone help?

manic wing
vague grove
#

alr

slate swan
unborn steppe
#

I just started using it

manic wing
#

you can make a file just called hidden.py, put token in it and import the token into main file from it. before pushing, make a file called .gitignore and just put hidden.py in it

unborn steppe
#

Alright, thanks.

manic wing
#

this will stop the hidden.py from being pushed to the repository - but code will still work fine

unborn steppe
manic wing
#

nope that should be all

#

just from hidden import TOKEN where TOKEN is a variable in hidden.py

#

client/bot.run(token)

visual island
#

utils.get

vague grove
#

how can I move members into a different vc w/ the bot?

heavy folio
unkempt canyonBOT
#

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

Moves a member to a new voice channel (they must be connected first).

You must have the [`move_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.move_members "discord.Permissions.move_members") permission to use this.

This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member.edit "discord.Member.edit").

Changed in version 1.1: Can now pass `None` to kick a member from voice.
slate swan
#

why when the bot switches to 2 if it gives such an error?

    msg_1 = await ctx.send(
        embed = discord.Embed(title = 'Выбирите язык\nSelect language', timestamp = ctx.message.created_at),
        components = [
                    [Button(style = ButtonStyle.blue, label = 'Русский'),
                    Button(style = ButtonStyle.blue, label = 'English')]
                ])
    responce = await bot.wait_for('button_click', check = lambda message: message.author == ctx.author)
    if responce.component.label == 'Русский':
      msg2 = await msg_1.edit(
          embed = discord.Embed(title = '2', timestamp = ctx.message.created_at),
          components = [
                      [Button(style = ButtonStyle.blue, label = 'Русский'),
                      Button(style = ButtonStyle.blue, label = 'English')]
                  ])
weary gale
#
async def on_member_join(member: discord.Member):
    role = member.guild.get_role(893297001897295942), (example123123123123)
    await member.add_roles(role)```
#

how could i make it so that it gives a user two roles when they join?

#

i dont think i've done it correctly

weary gale
#

how lol

boreal ravine
#

the same way you gave/got the first role

weary gale
#

do i just clone the role - member line

#

=*

boreal ravine
#

yes

weary gale
#

ok thx

slate swan
#

is there a way i can make this only call once because it seems its getting called for as many mutual servers as the user like im in 3 servers with the bot and its getting called 3 times any way i can make it only get called once?

    @commands.Cog.listener()
    async def on_presence_update(self, before, after):
      return print(f"User: {before} > before: {before.status} - after: {after.status}")```
https://cdn.discordapp.com/attachments/921522898773114922/921599904332275732/unknown.png **im using Pycord**
jade tartan
#
  File "c:\Users\thoma\Desktop\discord.py\python\bot.py", line 320, in <module>
    client.load_extension(f'Cogs.{filename[:-3]}')
  File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 674, in load_extension
    spec = importlib.util.find_spec(name)
  File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\importlib\util.py", line 94, in find_spec
    parent = __import__(parent_name, fromlist=['__path__'])
ModuleNotFoundError: No module named 'Cogs'```
#

Anyone

#

?

#

Hello

slate swan
#

shut the fuck up

#

is there a way i can make this only call once because it seems its getting called for as many mutual servers as the user like im in 3 servers with the bot and its getting called 3 times any way i can make it only get called once?

    @commands.Cog.listener()
    async def on_presence_update(self, before, after):
      return print(f"User: {before} > before: {before.status} - after: {after.status}")```
https://cdn.discordapp.com/attachments/921522898773114922/921599904332275732/unknown.png **im using Pycord**
jade tartan
#
  File "c:\Users\thoma\Desktop\discord.py\python\bot.py", line 320, in <module>
    client.load_extension(f'Cogs.{filename[:-3]}')
  File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 674, in load_extension
    spec = importlib.util.find_spec(name)
  File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\importlib\util.py", line 94, in find_spec
    parent = __import__(parent_name, fromlist=['__path__'])
ModuleNotFoundError: No module named 'Cogs'```
slate swan
#

shut up brah
is there a way i can make this only call once because it seems its getting called for as many mutual servers as the user like im in 3 servers with the bot and its getting called 3 times any way i can make it only get called once?

    @commands.Cog.listener()
    async def on_presence_update(self, before, after):
      return print(f"User: {before} > before: {before.status} - after: {after.status}")```
https://cdn.discordapp.com/attachments/921522898773114922/921599904332275732/unknown.png **im using Pycord**
manic wing
slate swan
#

shut the fuck up lil boy

#

luh brah named caeden 😛

jade tartan
#

he's abusing me

manic wing
#

you just ping mods and theyll mute him

slate swan
#

no kizzap ur so cringe "abusing me!!" like shut up brah

jade tartan
#

<@&831776746206265384>

slate swan
#

<@&831776746206265384> this guy hacking me

manic wing
#

hm maybe even a temp ban

jade tartan
#

<@&831776746206265384>

glacial sail
#

What's going on here?

hot cobalt
#

!mute 913724640021594142 Investigating

manic wing
#

that would be nice

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied mute to @slate swan until <t:1639802647:f> (59 minutes and 59 seconds).

jade tartan
#

can i message mods?

#

thanks u

jade tartan
glacial sail
scarlet spear
#

pls search

jade tartan
#

Its all good now hes muted

scarlet spear
#

pls beg

jade tartan
#

now

scarlet spear
#

dank memer isn't here?

#

@slate swan memer

#

how

jade tartan
#

Can you help me with my code tho?

scarlet spear
jade tartan
#
  File "c:\Users\thoma\Desktop\discord.py\python\bot.py", line 320, in <module>
    client.load_extension(f'Cogs.{filename[:-3]}')
  File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 674, in load_extension
    spec = importlib.util.find_spec(name)
  File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\importlib\util.py", line 94, in find_spec
    parent = __import__(parent_name, fromlist=['__path__'])
ModuleNotFoundError: No module named 'Cogs'```
scarlet spear
#

srsly

#

I'm 13

jade tartan
#
    if filename.endswith("Cogs1.py"):
        client.load_extension(f"Cogs.{filename[:-3]}")
scarlet spear
#

oh wow

jade tartan
scarlet spear
#

report

slate swan
#

woah whatd i miss

jade tartan
slate swan
#

😳

slate swan
scarlet spear
#

@jade tartan

jade tartan
#

@scarlet spear yes

scarlet spear
slate swan
jade tartan
#
  File "c:\Users\thoma\Desktop\discord.py\python\bot.py", line 328, in <module>
    for filename in os.dir(".\Cogs"):
AttributeError: module 'os' has no attribute 'dir'```
#
    if filename.endswith("Cogs1.py"):
        client.load_extension(f"Cogs.{filename[:-3]}")
manic wing
#

!d os.listdir

unkempt canyonBOT
#

os.listdir(path='.')```
Return a list containing the names of the entries in the directory given by *path*. The list is in arbitrary order, and does not include the special entries `'.'` and `'..'` even if they are present in the directory. If a file is removed from or added to the directory during the call of this function, whether a name for that file be included is unspecified.

*path* may be a [path-like object](https://docs.python.org/3/glossary.html#term-path-like-object). If *path* is of type `bytes` (directly or indirectly through the [`PathLike`](https://docs.python.org/3/library/os.html#os.PathLike "os.PathLike") interface), the filenames returned will also be of type `bytes`; in all other circumstances, they will be of type `str`.

This function can also support [specifying a file descriptor](https://docs.python.org/3/library/os.html#path-fd); the file descriptor must refer to a directory.

Raises an [auditing event](https://docs.python.org/3/library/sys.html#auditing) `os.listdir` with argument `path`.
jade tartan
manic wing
#

no you can leave it ambiguous

#

and it will be local dir

jade tartan
#

ok

slate swan
#

#unban bubba

#

he aint do shit

#

all of you are just soft

#

who are you?

jade tartan
#
from discord.ext import commands
import os

class TestCog(commands.Cog):
    def __init__(self, client):
        self.client = client


@commands.command()
@commands.is_owner()
async def reload(self, ctx, cog: str):
    try:
        self.bot.unload_extention(cog)
        self.bot.load_extention(cog)
    except Exception as e:
        await ctx.send("Could not reload cog")
        return
    await ctx.send("Cog reloaded")
    
    def setup(client):
        client.add_cog(TestCog(client))
        print(f"Background is loaded")```
#

Is this right?

waxen zodiac
#

#unban bubba he did nothing at all

slate swan
#

<@&831776746206265384> bubbas friends are here now

daring olive
#

!mute 921053014981234759 inv

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied mute to @waxen zodiac until <t:1639803477:f> (59 minutes and 59 seconds).

slate swan
#

Aw, call for the mods

#

yep

#

soft asf

#

ok?

jade tartan
#

Ayeeee less gooo for the mods

slate swan
#

ikr

hot cobalt
#

!mute 544202101522432012

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied mute to @slate swan until <t:1639803508:f> (59 minutes and 59 seconds).

jade tartan
#

Wait whats inv?

glacial sail
#

"investigating"

daring olive
#

invoice

jade tartan
#

ohh ok

daring olive
#

i charge $1,000 per mute

jade tartan
#
from discord.ext import commands
import os

class TestCog(commands.Cog):
    def __init__(self, client):
        self.client = client


@commands.command()
@commands.is_owner()
async def reload(self, ctx, cog: str):
    try:
        self.bot.unload_extention(cog)
        self.bot.load_extention(cog)
    except Exception as e:
        await ctx.send("Could not reload cog")
        return
    await ctx.send("Cog reloaded")
    
    def setup(client):
        client.add_cog(TestCog(client))
        print(f"Background is loaded")``` is this right?
#

tho

slate swan
daring olive
#

12.5% APR

slate swan
#

im sorry

#

!ot

unkempt canyonBOT
slate swan
#

🧍‍♂️

daring olive
#

dogekek good one. i'll leave you guys to it

slate swan
#

i think it was self.bot.reload_extention(cog)

#

it unloads and loads a cog if irrc

jade tartan
slate swan
#

!d discord.ext.commands.Bot.reload_extension

unkempt canyonBOT
#

reload_extension(name, *, package=None)```
Atomically reloads an extension.

This replaces the extension with the same extension, only refreshed. This is equivalent to a [`unload_extension()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.unload_extension "discord.ext.commands.Bot.unload_extension") followed by a [`load_extension()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.load_extension "discord.ext.commands.Bot.load_extension") except done in an atomic way. That is, if an operation fails mid-reload then the bot will roll-back to the prior working state.
heavy folio
#

how do i get the bot's integration role

jade tartan
#

Nvm

#

the bot isnt responding to my command

#
@commands.is_owner()
async def reload(self, ctx, cog: str):
    try:
        self.bot.reload_extention(cog)
    except Exception as e:
        await ctx.send("Could not reload cog")
        return
    await ctx.send("Cog reloaded")```
heavy folio
jade tartan
#
discord.ext.commands.errors.CommandNotFound: Command "reload" is not found```
#
from discord.ext import commands
import os

class TestCog(commands.Cog):
    def __init__(self, client):
        self.client = client


@commands.command()
@commands.is_owner()
async def reload(self, ctx, cog: str):
    try:
        self.bot.reload_extention(cog)
    except Exception as e:
        await ctx.send("Could not reload cog")
        return
    await ctx.send("Cog reloaded")
    
    def setup(client):
        client.add_cog(TestCog(client))
        print(f"Background is loaded")```
slate swan
#

its not indented well

pliant gulch
unkempt canyonBOT
#

property self_role: Optional[discord.role.Role]```
Gets the role associated with this client’s user, if any.

New in version 1.6.
slate swan
heavy folio
#

also

#
embed.add_field(name="Description", value=[cog.description if cog.description else "No description provided."], inline=False)
```im using this for so it takes the cog's description if there is one, else it'll be "No description provided", for some reason this is the output:
jade tartan
#

All?

slate swan
west escarp
#

Or use an or expression

#

!e ```py

description = "test"
print(description or "default")
description = None
print(description or "default")

unkempt canyonBOT
#

@west escarp :white_check_mark: Your eval job has completed with return code 0.

001 | test
002 | default
slate swan
# slate swan yes

should look like this

class TestCog(commands.Cog):
    def __init__(self, client):
        self.client = client


    @commands.command()
    @commands.is_owner()
    async def reload(self, ctx, cog: str):
        try:
            self.client.reload_extention(cog)
        except Exception as e:
            await ctx.send("Could not reload cog")
            return
        await ctx.send("Cog reloaded")

    def setup(client):    
        client.add_cog(TestCog(client))
        print(f"Background is loaded")
slate swan
#

And the setup outside the class

#

well yes but im to lazy🧍‍♂️

#

done happy?

#

yert not yet

slate swan
woven flint
#

how'd i convert the member.created_at datatime value to how long ago it was?

slate swan
#

subtract it from datetime.now() to get a timedelta object , it will tell how long ago it was

woven flint
#

okay ill try it

heavy folio
woven flint
heavy folio
#

also is it possible for me to override the global command error handler

woven flint
#

just like i thought lol

heavy folio
#

cuz for commands.MissingRequiredArgument, in the global handler it'll do ctx.send_help(ctx.command) but for a specific command i dont want that to happen

pliant gulch
#

Decorate a method which you use to handle it

#

Can just pass to ignore

heavy folio
#

thanks

slate swan
#

Or just use a Unix timestamp tbh

unkempt canyonBOT
#

kakashi/cogs/info.py line 107

'Joined Server' : f"{member.joined_at.strftime('%d %B %Y')}`​ <t:{int(member.joined_at.timestamp())}:R> `​{position+1}/{ctx.guild.member_count}",```
jade tartan
#

Yeah my code aint working

#

the cog file aint working

slate swan
#

Problem?

heavy folio
maiden fable
#

With time.time() returning the current unix time

jade tartan
cerulean osprey
#

So Im trying to make a simple thing that makes the bot greet you when you say "hello" and its name. As of right now.. I have this

if msgl.startswith('hello chimera') or msgl.startswith('hi chimera'):
        channel = message.channel
        await channel.send('Hello! What is your name?')
        print('Check 1')

        def check(m):
            return m.content == 'hello' and m.channel == channel
        print('Nice')
        msg = await client.wait_for('message', check=check)
        await channel.send(f'Hello {msg}!')
        print('Check 2')
``` Naturally the prints are to see exactly where its going wrong. It printed both "Check 1" and "Nice" but not "Check 2".. what am I doing wrong?
slate swan
slate swan
maiden fable
#

!d discord.utils.format_dt

unkempt canyonBOT
#

discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.9)") for presentation within Discord.

This allows for a locale-independent way of presenting data using Discord specific Markdown...
maiden fable
#

Tho it takes a datetime object, in disnake, we modified it to take in an int too

slate swan
#

oh I see , I'll update it later yert

jade tartan
#

yeah cogs aint working

slate swan
#

I asked for code.....

maiden fable
#

Not a code problem

jade tartan
#
from discord.ext import commands

class TestCog(commands.Cog):
    def __init__(self, client):
        self.client = client


    @commands.command()
    @commands.is_owner()
    async def reload(self, ctx, cog: str):
        try:
            self.client.reload_extention(cog)
        except Exception as e:
            await ctx.send("Could not reload cog")
            return
        await ctx.send("Cog reloaded")
        print(f"Reloaded")

    def setup(client):    
        client.add_cog(TestCog(client))
        print(f"Background is loaded")```
#

this is my cogs file

slate swan
maiden fable
#

He selected the option Run as Python Module

slate swan
jade tartan
#
for filename in os.listdir(path='.'):
    if filename.endswith("Cogs1.py"):
        client.load_extension(f"Cogs.{filename[:-3]}")
slate swan
#

Move it outside

cerulean osprey
jade tartan
slate swan
cerulean osprey
#

I hope so, I feel like it could be useful in the future

slate swan
slate swan
cerulean osprey
#

Except Im already failing bc it aint working omg

visual island
#

yes

slate swan
#

Okjam_cavedude

slate swan
slate swan
maiden fable
#

He was just asking if u await it or not

slate swan
#

view.wait() isnt a coroyert

slate swan
#

Right😨

#

Jk ik it isnt

visual island
#

it isn't?

slate swan
#

Nojam_cavedude

maiden fable
#

!d discord.ui.View.wait

unkempt canyonBOT
#

await wait()```
Waits until the view has finished interacting.

A view is considered finished when [`stop()`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.View.stop "discord.ui.View.stop") is called or it times out.
maiden fable
#

There (:

visual island
#

yea it makes no sense if it isn't a coro

slate swan
#

Wait it is

await​ ​view​.​wait​()
```![yert](https://cdn.discordapp.com/emojis/832277526809149461.webp?size=128 "yert")
#

😭

#

I should go to sleep smh

boreal ravine
#

nice

slate swan
#

Had a massive brain fart so i should go to sleep

shadow wraith
#

hi 🕴️

#

what's going on

slate swan
#

And don't take my emoji mr🕴️

#

\🕴️

jade tartan
shadow wraith
#

🚶 dude

slate swan
shadow wraith
#

your brain farded

slate swan
#

Yes

brittle ingot
#

👀

shadow wraith
#

scroll up..

slate swan
#

Mini🕴️

#

Why you exposing me🕴️ 🚶

shadow wraith
#

🕴️ wdym im not

slate swan
#

Yes you are you imposter 🕴️

shadow wraith
#

🕴️ i only told him to uhh like uhhhh like uhh

#

scroll up

slate swan
#

🕴️

#

Why you stealing my emojis smh🕴️

#

🚓

shadow wraith
#

😃 don't know 🕴️

slate swan
#

🕴️

shadow wraith
#

🕴️ best emoji

jade tartan
#

C:\Users\thoma\AppData\Local\Programs\Python\Python310\python.exe: No module named enter-your-module-name

#

it keeps saying this

slate swan
shadow wraith
#

is enter-your-module-name defined?

shadow wraith
slate swan
jade tartan
slate swan
#

Was a typo

maiden fable
#

I told Gangster his problem but okay

shadow wraith
#

☠️

slate swan
#

🕴️

shadow wraith
#

🕴️

jade tartan
#

Whatever am not doing cogs

#

this is too complicated

shadow wraith
#

ok then give code

#

bru

#

☠️

maiden fable
#

@jade tartan just do python main.py or whatever your bot file name id

slate swan
#

🕴️

shadow wraith
slate swan
#

🕴️

shadow wraith
#

i once got a ssl certificate error for calling commands.Bot() twice 🕴️ ☠️

slate swan
#

Im always lurking

shadow wraith
#

never showed the issue itself

slate swan
#

🕴️

shadow wraith
#

the traceback, was the ssl certificate

#

but i fixed it

maiden fable
jade tartan
#

thats what the file directory writes at like that

shadow wraith
jade tartan
#

nothing

shadow wraith
#

☠️

jade tartan
#

ama just uninstall python

shadow wraith
jade tartan
#

and vs

shadow wraith
#

wait you didn't know basic python from the start 🕴️

jade tartan
#

no i know

shadow wraith
#

then why uninstall python

slate swan
#

I was born knowing py

shadow wraith
slate swan
shadow wraith
#

if there was a extension in vscode where if you had an error it would give you a stack overflow link that'd be awesome

quick gust
#

peak level of laziness

shadow wraith
#

your right

#

peak level of laziness

slate swan
shadow wraith
#

lie of the day

slate swan
#

Yep

shadow wraith
#

i'd use it tho ☠️

slate swan
#

I wouldn't cuz im to good🕴️

shadow wraith
#

i wouldn't use stack overflow for forgetting a bracket 💀

tough lance
#

Lol

frail mesa
#

Hello, could anyone take a look at this and tell me what I'm doing wrong?

import discord,os
from keep_alive import keep_alive
from discord.ext import tasks

client = discord.Client()

@client.event
async def on_ready():
  print('We have logged in as {0.user}'.format(client))
  global members
  guild = client.get_guild(757463397683036200)
  role = guild.get_role(793942123627282452)
  members = [member for member in guild.members if role in member.roles]

@tasks.loop(seconds=120)
async def check_role():
  global members
  guild = client.get_guild(757463397683036200)
  role = guild.get_role(793942123627282452)
  members = [member for member in guild.members if role in member.roles]

@client.event
async def on_message(message):
  if message.author == client.user:
    return
  
  if message.content.startswith('!scosa'):
      try:
        await message.channel.send(os.getenv('VerifiedBMHour') + ' +9 in 30 minutes hosted by ' + os.getenv('scosa') + '!')
      except:
        await message.channel.send('Only Admins have permission to use this command.')
        return
#

The command works, but it's not locked behind the role it should be, and I have no idea why

shadow wraith
#

import os

slate swan
#

they did

shadow wraith
#

true

slate swan
shadow wraith
#

use commands.Bot()

slate swan
#

!d discord.ext.commands.has_role you can use this to check if member has role

unkempt canyonBOT
#

@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.

If a string is specified, you must give the exact name of the role, including caps and spelling.

If an integer is specified, you must give the exact snowflake ID of the role.

If the message is invoked in a private message context then the check will return `False`.

This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").

Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
slate swan
#

if you use the Bot commands constructor

tough lance
#

Also start the task with task.start()

boreal ravine
tough lance
#

Sometimes?

quick gust
#

doing what sarthak said would still be better and cleaner

slate swan
#

why when the bot switches to 2 if it gives such an error?

    msg_1 = await ctx.send(
        embed = discord.Embed(title = 'Выбирите язык\nSelect language', timestamp = ctx.message.created_at),
        components = [
                    [Button(style = ButtonStyle.blue, label = 'Русский'),
                    Button(style = ButtonStyle.blue, label = 'English')]
                ])
    responce = await bot.wait_for('button_click', check = lambda message: message.author == ctx.author)
    if responce.component.label == 'Русский':
      msg2 = await msg_1.edit(
          embed = discord.Embed(title = '2', timestamp = ctx.message.created_at),
          components = [
                      [Button(style = ButtonStyle.blue, label = 'Русский'),
                      Button(style = ButtonStyle.blue, label = 'English')]
                  ])
slate swan
#

Yes

upbeat otter
slate swan
slate swan
#

it happens because interaction is not responded when you click the button

#

you can just make an ephermeal response sayin button is clicked or something to avoid it

slate swan
#

I didn't understand how.

sullen shoal
slate swan
#

Myxi you havent been here in a while hows it goingpithink

sullen shoal
#

i used to get that kind of error later when i deferred it, it workef fine

slate swan
#

Thats nicepithink

sullen shoal
#

how bout you

slate swan
#

Better yert

sullen shoal
#

i made some crap api wrapper

slate swan
sullen shoal
slate swan
#

Never heard of it

sullen shoal
#

maybe they're handling it wrong

#

or outdated

#

we use defer when it will take more than 3 seconds to respond

#

however in your case it doesn't seem to take more than 3 seconds

slate swan
#

why do you write with riddles?

sullen shoal
#

if all you want are ui elements except application commands, use discord.py 2.0

timber crescent
#

Can someone confirm what happens when I tryna use the same bot token twice?

#

Like simultaneously