#discord-bots

1 messages · Page 1121 of 1

slate swan
#

i does doesnt it?

#

!e ```py
l = [1,2,3,4]
print(( a % 1 for a in l ))

unkempt canyonBOT
#

@slate swan :white_check_mark: Your eval job has completed with return code 0.

<generator object <genexpr> at 0x7ff29ef3fca0>
slate swan
#

it does

maiden fable
cunning finch
#

Excuse me

slate swan
#
    @commands.command(aliases = ["панель", "Панель", "профиль", "Профиль", "prof", "Prof", "p", "P", "п", "П", "g", "G", " g"])
    async def command_control_panel(self, ctx):

        img = requests.get("URL", stream = True) 
        img = Image.open(io.BytesIO(img.content))
        img = img.convert('RGBA') 

        img1 = requests.get("URL", stream = True) 
        img1 = Image.open(io.BytesIO(img1.content))
        img1 = img1.convert('RGBA') 

        img1M = requests.get("URL", stream = True) 
        img1M = Image.open(io.BytesIO(img1M.content))
        img1M = img1M.convert('L') 

        idrawImg = ImageDraw.Draw(img)
        font =  ImageFont.truetype('./Шрифты/picsel.ttf', size = 60)
        font1 =  ImageFont.truetype('./Шрифты/picsel.ttf', size = 50)
        author = ctx.author.name
        tag = ctx.author.discriminator

        text = f'{author}#{tag}'


        counter = 555 - len(text) * 23
        counter1 = 555 - len(text1) * 21

        idrawImg.text( (counter, 40), text= text, font=font, fill = (91,141,199,25))
        idrawImg.text((counter1, 530), "123", font=font1, fill = (91,141,199,255))


        url = ctx.author.display_avatar

        url1 = requests.get(url, stream = True) 
        url1 = Image.open(io.BytesIO(url1.content))
        url1 = url1.convert('RGBA') # конфертировал аву в РГБА
        url1 = url1.resize((300, 300), Image.ANTIALIAS)

        url1M = Image.new('L', url1.size, 0 )
        idrawM = ImageDraw.Draw(url1M) 
        idrawM.ellipse((0, 0, 300, 300), fill=255) 

        img.paste(url1, (406, 170), url1M)
        img.paste(img1, (0, 0), img1M)
        img2 = img
        idrawImg2 = ImageDraw.Draw(img2)
        idrawImg2.arc((400, 168, 706, 469),start=0, end=0, width=10)
        img2.save('./ImageS/profile.png')

        file = discord.File("./ImageS/profile.png")

        await ctx.send(file=file, view=class_control_panel(ctx.author.id))

Dear forgive me, tell me what is wrong. he gives it out, then he doesn't.

slate swan
slate swan
cunning finch
slate swan
cunning finch
#

Amm

dusky pine
cunning finch
#

This @slate swan

dusky pine
#

you mean user.mention?

#

!d discord.User.mention

unkempt canyonBOT
maiden fable
dusky pine
#

if you put the water up your nose bruh you will probably die

slate swan
#

💀 thats not drowning in the water, its the water getting in your body

dusky pine
#

how about directly injecting water into your lungs

swift pumice
#

does someone know an nsfw(real) api?

slate swan
#

(real)

swift pumice
#

i already have an nsfw(anime) api

dusky pine
swift pumice
swift pumice
dusky pine
#

it probably does

swift pumice
#

i couldnt find any on google

dusky pine
#

what about xv

slate swan
#

I'm probably gonna get muted if I run the pypi command for an async nsfw api wrapper

#

😭

dusky pine
#

no it's for good cause

unkempt canyonBOT
slate swan
#

😭

#

Dear tell me what is the problem? this happens randomly with commands.

dusky pine
#

LX no ban pls

slate swan
#

I'm gonna get warned for sure

visual yarrow
#

Not really server-appropriate @slate swan @swift pumice

slate swan
#

oop thanks 😭

swift pumice
visual yarrow
#

👍

slate swan
#

that's a server banner

#

and only unlocks after 2 boosts iirc

#

it uses image manipulation and a task to see how many members are online and offline

#

and creates images and edits them

#

use the PIL module with a task to see the number of online members and create images

#

and set the server banner

maiden fable
#

I can't even imagine changing the server banner every x min

dusky pine
#

ah yes, ratelimit

slate swan
#

Dear tell me what is the problem? this happens randomly with commands. i.e. error or not

regal pulsar
severe bone
#

guys with discord.py if u send a command with an txt file attachment how can i make it so the bot reads it and writes it in another txt file

dusky pine
#

!d discord.Message.attachments

unkempt canyonBOT
dusky pine
#

^ use that @severe bone

severe bone
#

alr ty

maiden fable
#

Can u share some code?

limber pollen
#

Hello bro. Is there any bot which will autokick in 24 hours if you don't get that role etc..?

maiden fable
#

This isn't the correct channel to ask this type of question. We can help u code that type of bot though

slate swan
# maiden fable Lemme try figuring that out
    @commands.command(aliases = ["панель", "Панель", "профиль", "Профиль", "prof", "Prof", "p", "P", "п", "П", "g", "G", " g"])
    async def command_control_panel(self, ctx):
        lvl = cursor.execute(f"SELECT юзер_уровень_чат FROM users WHERE id = {ctx.author.id}").fetchone()[0]

        img = requests.get("URL", stream = True) 
        img = Image.open(io.BytesIO(img.content))
        img = img.convert('RGBA') 

        img1 = requests.get("URL", stream = True) 
        img1 = Image.open(io.BytesIO(img1.content))
        img1 = img1.convert('RGBA') 

        img1M = requests.get("URL", stream = True) 
        img1M = Image.open(io.BytesIO(img1M.content))
        img1M = img1M.convert('L') 

        idrawImg = ImageDraw.Draw(img)
        font =  ImageFont.truetype('./Шрифты/picsel.ttf', size = 60)
        font1 =  ImageFont.truetype('./Шрифты/picsel.ttf', size = 50)
        author = ctx.author.name
        tag = ctx.author.discriminator

        text = f'{author}#{tag}'
        text1= f'LVL {lvl}'

        counter = 555 - len(text) * 23
        counter1 = 555 - len(text1) * 21

        idrawImg.text( (counter, 40), text= text, font=font, fill = (91,141,199,255))
        idrawImg.text((counter1, 530), text= text1, font=font1, fill = (91,141,199,255))

        url = ctx.author.display_avatar

        url1 = requests.get(url, stream = True) 
        url1 = Image.open(io.BytesIO(url1.content))
        url1 = url1.convert('RGBA') # конфертировал аву в РГБА
        url1 = url1.resize((300, 300), Image.ANTIALIAS)

        url1M = Image.new('L', url1.size, 0 ) 
        idrawM = ImageDraw.Draw(url1M) 
        idrawM.ellipse((0, 0, 300, 300), fill=255) 

        img.paste(url1, (406, 170), url1M)
        img.paste(img1, (0, 0), img1M)
        idrawImg.arc((405, 168, 706, 470),start=0, end=359, width=5)
        img.save('profile.png')

        file = discord.File("profile.png")

        await ctx.send(file=file, view=class_control_panel(ctx.author.id)) 
#

where URL there are direct links from google drive

heady sluice
#

that's a lot of unnecessary variables

#

a lot lot

slate swan
maiden fable
#

Uh, can u send me the url to which u r sending a GET request?

slate swan
cold sonnet
#

meh

heady sluice
#

meh

maiden fable
#

So the URL is https://drive.google.com/uc?export=download&confirm=no_antivirus&id=137EzkeyUKAIYSxnWSEP3ulsQpYfISnUJ?

maiden fable
#

@slate swan can u afford to save the image and then use the Pillow module?

slate swan
#

should I upload images from the disk? it's slow so I didn't do it(

maiden fable
slate swan
#

Okay I'll try

slate swan
#

Hunter's so smart

slim heart
#

whats the best place to host a discord bot(free)?

slate swan
#

😔

slate swan
slim heart
#

hmmmm

#

(online 24/7)?

slate swan
slim heart
#

not really helpful

slim heart
slate swan
# slim heart other?

you can't really find good services to host your bot for free, you have to BUY a vps

#

or use AWS for 12 months free 😔

#

if you got a credit card you can get a vps free for 3 years

#

ew which one?

#

one year from aws, one from google cloud and another one from oracle

#

lmao

alpine cove
#

loool

slate swan
#
  File "main.py", line 71, in task
    if member.activities and 'discordoofi' in member.activities[0].name:
TypeError: argument of type 'NoneType' is not iterable
#

member activity does not have a name

#

how do i fix that

slate swan
uncut jacinth
#

Wait

slate swan
slate swan
uncut jacinth
#

member.activities[0].name

#

Thats right

slate swan
#

.name returns None.

uncut jacinth
slate swan
#

!e "a" in None

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 | TypeError: argument of type 'NoneType' is not iterable
slate swan
#

see the error

slate swan
uncut jacinth
#

I use it in my bot, It returns user activity

uncut jacinth
#

For the info command

#

And it outputs the user activity

slate swan
unkempt canyonBOT
uncut jacinth
slate swan
#

maybe the library designer was high when he wrote Optional[str] here.

heady sluice
#

oh wait I'm dumb

#

sorry

slate swan
#
    for member in guild.members:
        role = discord.utils.find(lambda r: r.name == 'Supporter', member.guild.roles)
        if member.activities and 'discofi' in member.activities[0].name:
            print(f"{member} ✅")
            if role in member.roles:
                continue
            else:
                await member.add_roles(discord.Object(id=921720262217568268))
                await fluf.send(f'gave supporter role to {member}')
        elif member.activities and 'discoroofi' not in member.activities[0].name:
            print(f"{member} ❌")
            if role not in member.roles:
                continue
            else:
                await member.remove_roles(discord.Object(id=921720262217568268))
                await fluf.send(f'removed supporter role from {member}')
#

where do i put try except

slate swan
#

i never used try and except

heady sluice
#

instant realisation of my mistake

slate swan
slate swan
slate swan
heady sluice
slate swan
#

dpy?

slate swan
#

Better to just do an "if None" check before using it

uncut jacinth
#
if "ActivityType.playing" in str(member.activities):
                memberactivity = "**Playing** "+member.activities[0].name
slate swan
#

Its a game after all

uncut jacinth
#

Yes

slate swan
#

anyways don't overthink and just use an if check it makes ur life easier

slate swan
#

or after both if statement'es

slate swan
#

yes

#

what's your python version?

#

idk im using replit

slate swan
slate swan
#

Oh got it

slate swan
#

oh

#

💀 i was thinking of using a walrus operator but dont really think its needed here

#

see if that code works

#

works nice

#

no errors

#

does it do what its' meant to

#

yesss

robust fulcrum
#

Finally me done with my custom prefix thing

slate swan
#

buttttttttttttttbut it keeps dming me "gave role to' same person again and again

#

show your updated code

#

looped until guild.members gets completed

#

add a "break" or "return"

#
@tasks.loop(seconds=40)
async def task():
    await bot.wait_until_ready()
    guild = bot.get_guild(921366728016011324)
    fluf = bot.get_user(716707479005823036)
    for member in guild.members:
        if member.activity and member.activity.name:
        role = discord.utils.find(lambda r: r.name == 'Supporter', member.guild.roles)
        if member.activities and 'discoroofi' in member.activities[0].name:
                  print(f"{member} ✅")
                  if role in member.roles:
                      continue
                  else:
                      await member.add_roles(discord.Object(id=921720262217568268))
                      await fluf.send(f'gave supporter role to {member}')
        elif member.activities and 'discorloofi' not in member.activities[0].name:
                  print(f"{member} ❌")
                  if role not in member.roles:
                      continue
                  else:
                      await member.remove_roles(discord.Object(id=921720262217568268))
                      await fluf.send(f'removed supporter role from {member}')
slate swan
#

everything else is same

#

show the updated one because a single indent can change a lot of results

slate swan
#

if member.activities and 'discoroofi' in member.activities[0].name: dont need this line anylonger

#

replace with if 'discoroofi' in member.activity.name

#

cause you're already checking the activities

#

okayy

proud apex
#

Why does the bot send nothing when you mention a user?

@bot.command()
async def card(ctx, user: discord.Member = None):
    if user == None:
        user = ctx.author
         
        image = Image.open("fons/user_card.png")
        font = ImageFont.truetype("fons/font/GOTHIC.TTF", size = 80)
        print(1)
        name = user.name
        tag = user.discriminator
        date_format = "%d %B %Y"
        print(2)
        draw = ImageDraw.Draw(image)
        draw.text((725,279), f"{name}#{tag}", font = font, fill="#ffffff")
        draw.text((600,400), f"{user.created_at.strftime(date_format)} года", font = font, fill="#ffffff")
        print(3)
        
        avatar = user.avatar_url_as(size = 128)
        avt = BytesIO(await avatar.read())
        img = Image.open(avt)
        img = img.resize((479, 478)) # 
        image.paste(img, (120, 359)) # 
        print(4)
        image.save("user_card.png")
        await ctx.send(file = discord.File("user_card.png"))
        print(5)
slim heart
#

is it possible to make something like siri with py-cord(discord.py fork that can detect sounds)?

proud apex
#

well, if you do not mention the participant, then it will take the form of the one who entered the team, right?

slate swan
#

you indented your code wrong

#

and that's why it doesn't work

robust fulcrum
#
async def my_hook():
    bot.conn = await aiosqlite.connect("name.db")
    bot.cur = await bot.conn.cursor() 

Is it important to make this for a db?

slate swan
#

yes, it is I just meant that how can bot.conn and bot.cur be accessed within the get_prefix function

#

and connecting to the db every time a message is sent....seems a bit off

robust fulcrum
#

Let me ask a pro guy

slate swan
#

hm, it should be possible to do something like

async def my_hook():
    bot.conn = await aiosqlite.connect("name.db")
    bot.cur = await bot.conn.cursor() 

bot.setup_hook = my_hook

def get_prefix(...):  
  ...

bot.command_prefix = get_prefix
#

that is if I'm not being dumb

robust fulcrum
slate swan
#

...?

robust fulcrum
slate swan
#

I uhhh told you to learn sqlite

#

you basically make a connection the my_hook function

robust fulcrum
slate swan
#

and use the same connection

#

oh god

robust fulcrum
#

Oh

#

I understand

robust fulcrum
slate swan
#

...? template?

robust fulcrum
slate swan
robust fulcrum
#

What botvar

proud apex
robust fulcrum
paper sluice
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

robust fulcrum
slate swan
#

ahem ahem

robust fulcrum
slate swan
unkempt canyonBOT
#

Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:

bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"

@bot.command()
async def get(ctx: commands.Context):
    """A command to get the current value of `test`."""
    # Send what the test attribute is currently set to
    await ctx.send(ctx.bot.test)

@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
    """A command to set a new value of `test`."""
    # Here we change the attribute to what was specified in new_text
    bot.test = new_text

This all applies to cogs as well! You can set attributes to self as you wish.

Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!

robust fulcrum
slate swan
#

maybe

#

anyways, in your case, bot.conn and bot.cur are botvars

paper sluice
robust fulcrum
robust fulcrum
paper sluice
robust fulcrum
#

@slate swan in get_prefix
What arguments i need to take?

slate swan
#

||I|| ||don't|| ||know||

robust fulcrum
#

I also don't know

proud apex
robust fulcrum
#

Just guiding if not know indentation

paper sluice
slate swan
proud apex
#

Ahhahaahah

robust fulcrum
slate swan
#

the message object of the context message

robust fulcrum
#

Like i type >help
It goes in the message

paper sluice
#

yes

robust fulcrum
#

And bot guild I'd?

slate swan
#

?

#

bot is the Bot obj

paper sluice
#

bot means bot, if it was guild id, it would named guild_id xD

robust fulcrum
#

My brain out cause of sql

slate swan
#

¯_(ツ)_/¯

robust fulcrum
#

My brain need some oil

#

Like cars need

slate swan
#

guild_id = message.guild.id is what

paper sluice
slate swan
robust fulcrum
#

(☉。☉)!→

paper sluice
#

ya ur brain really needs oil

robust fulcrum
#

Yes me mad that i started discord.py without learning python fully

slate swan
#

but nvm am not gonna give english lessons here so uhh

slate swan
#

I will never believe this!

slate swan
robust fulcrum
slate swan
paper sluice
robust fulcrum
#

Anyway me start sqlite code bye!
If i would need help I'll ask

slate swan
robust fulcrum
paper sluice
#

then u related it with a car, when u personify, u use something that a human would do which is equivalent to oil and car in this case

robust fulcrum
#

ᕙ( ͡◉ ͜ ʖ ͡◉)ᕗ

slate swan
#

okay we are way off topic now

#

and my brain has probably reduced to half due to the dpy server

slate swan
#

save the effort for another time if one does

paper sluice
slate swan
#

🙁

robust fulcrum
#

I want to become doctor idk why me learning coding

paper sluice
#

i dont even know how to code lemon_angrysad

slate swan
#

brain does need oil the problem is how many types of it you would need to keep it as productive as it used to be

robust fulcrum
slate swan
#

long term goods require some effort..

paper sluice
robust fulcrum
slate swan
#

unfortunate to know

robust fulcrum
slate swan
#

Woo

paper sluice
robust fulcrum
slate swan
robust fulcrum
#

(。•́︿•̀。)

dusky pine
slate swan
dusky pine
#

what

slate swan
slate swan
#

change that everywhere

slate swan
slate swan
# slate swan

I didn't understand what's wrong ,can you explain to me?

#

cool

slate swan
limber pollen
#

Bro why my welcomer bot got rate limit from discord?

slate swan
slate swan
regal pulsar
# slate swan

you need an instance of disnake.User not the class itself

slate swan
#

not even an instance, an actual user object

regal pulsar
#

yeah yeah ;/

slate swan
#

I have already been given 3 different answers on 3 servers

#

I will do the command again

slate swan
#

you have to accept in an argument which takes the actual user object, and uses that to access the ID

#

not the class for the User object

regal pulsar
#

user = ctx.author

#

if you want the guy who ran the command

slate swan
#

just have it passed into the func

def open_acccount(user):
  ...
  users[str(user.id)] = {}

''' and call the command using '''

open_account(ctc.author.id) #if in a prefix command

and I see no point in making that function asynchronous

slate swan
#

and the error is?

robust fulcrum
#

@slate swan can we use json as a storage?

#

I saw many use it

slate swan
#

or if changed manually

slate swan
unkempt canyonBOT
slate swan
#

your code is faulty, really faulty

#

!code format it like this

unkempt canyonBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

slate swan
#

it's harder to view it otherwise

robust fulcrum
#
async def my_hook():
    bot.conn = await aiosqlite.connect("name.db")
    bot.cur = await bot.conn.cursor()

Ashley do i need to use the create table in the my_hook function?

slate swan
#

sure, why not?

robust fulcrum
#

But i am getting one problem

slate swan
#

where else did you plan to use it anyways

heady sluice
slate swan
#

problem is?

bold sun
#

I want help to standardize all these job titles. There are different titles here in a file. I want to do it using python. for eg , There is (vice president - engineering, vice president- technical) so it should be (vp eng, vp tech) and so on. So please if anyone can help me or provide easy method to do it. I will pay if anyone is willing to do it.

slate swan
#

!rule 9

unkempt canyonBOT
#

9. Do not offer or ask for paid work of any kind.

slate swan
#

and that doesnt seem too long, you can manually edit that

paper sluice
#

and its not related to discord bot

slate swan
#

that too

vocal snow
slate swan
#

!rule 7

unkempt canyonBOT
#

7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.

slate swan
#

still too much work

#

or am just too lazy

heady sluice
slate swan
#

wasnt referring to you

heady sluice
#

why not

paper sluice
#

cuz meh

heady sluice
#

you're meh

dusky pine
#

ash feeling kinda rude today

paper sluice
slate swan
thin raft
#

Use a real db pls

slate swan
thin raft
#

Why?

#

Is disnake sync?

slate swan
#

there isn't anything asynchronous being done in there

paper sluice
dusky pine
#

swas: "ah yes put async here it will make it asynchronous"

paper sluice
#

the only thing async is get_bank_data which i think it also sync code inside async function

thin raft
#

Yeah that yes but if disnake is async then I'll use async funcs

dusky pine
#

also json as db 🤮

thin raft
#

He uploaded a vid making that with postgre

dusky pine
#

GOOOD

slate swan
#
async def get_data(): return __import__("json").loads(await (await __import__("aiofiles").open("uwu.json")).read())

is what I can think of

dusky pine
#

now swas... your last task is to write tests

slate swan
dusky pine
slate swan
#

imagine not ✨ return ✨ ing the data

dusky pine
#

mmaybe i should change my pydis nickname

slate swan
#

😩it triggers me somehow, i write worse examples anyways

zenith mural
#

But uwu.json>>

slate swan
paper sluice
slate swan
#

ryuga, the way you said that...it hurts

#

😭

zenith mural
#

uwu.json

dusky pine
#

still ignoring the fact that json

slate swan
#

Why u name var same 😑

maiden fable
slate swan
#

and no lambda, I hate lambda

#

await f.read() will not parse the json data by itself, you'll have to use the loads function to parse it

maiden fable
#

u r not using read....?

maiden fable
slate swan
#

my bad, fixed it

slate swan
#

help anyone?

slate swan
#

iohhh

#

and stop using globals.

#

lol i was only testing stupid misake

slate swan
#

from_url is an awaitable

slate swan
#

why isnt this printing?

#

anyone?

slate swan
#

bot(

sick birch
#

I doubt that’s it

slate swan
wanton chasm
#

is on ready called once? because you load the cog after the bot is ready.

slate swan
#

frick me lmfao my cog file was called Events.p and not .py

paper sluice
#

why were u still getting syntax highlighting for python pithink

slate swan
#

im not sure

pliant gulch
paper sluice
#

hey andy 👋

pliant gulch
pliant gulch
sick birch
pliant gulch
# sick birch Is that why they’re async now?

I have no clue as to what the reason was behind the change. I can assume that there was no BAD reason to switch to async as, discord.py is in an async context anyways. But most often than not, cog loading will still be before connecting to the gateway as I'll assume you connect in setup_hook and not on_ready

slate swan
still swan
#

is that correct?

class _Command(Command):
    def __init__(
        self: "_Command", 
        func: Callable[..., Any], 
        **kw: Any
    ) -> None:
        setup(func, **kw)
        super().__init__(func, **kw)

bot.command = partial(bot.command, cls=_Command)
bot.group = partial(bot.group, cls=_Command)
#

how to set cls for all bot.command without doing bot.command(cls=_Command) multi times? may someone help me please?

slate swan
#

anyone know about sqlite?

still swan
slate swan
#

ty

still swan
#

np

torn sail
maiden fable
unkempt canyonBOT
#

@command(*args, **kwargs)```
A shortcut decorator that invokes [`command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.command "discord.ext.commands.command") and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin.add_command "discord.ext.commands.GroupMixin.add_command").
maiden fable
#

Or what TheMaster said

pliant gulch
#

Self is missing

still swan
# torn sail you could subclass ```py class Bot: def command(name=discord.utils.MISSING, ...

i already did that is it okay?

class Command(commands.Command):
    def __init__(self: "Command", func: Callable[..., Any], **kw: Any) -> None:
        setup(self, func, **kw)
        super().__init__(func, **kw)

commands.command = partial(commands.command, cls=Command)
commands.GroupMixin.command = partialmethod(commands.GroupMixin.command, cls=Command)

class Group(commands.Group):
    def __init__(self: "Group", *args: Any, **attrs: Any) -> None:
        setup(self, *args, **kw)
        super().__init__(*args, **attrs)

commands.group = partial(commands.group, cls=Group)
commands.GroupMixin.group = partialmethod(commands.GroupMixin.group, cls=Group)
torn sail
slate swan
#

anyone?

torn sail
slate swan
#
@client.command(aliases=["log", "logs", "audit", "audit-logs", "audit-log", "auditlogs"])
@commands.has_permissions(view_audit_log=True)
async def auditlog(ctx, lmt:int):
  idk = []
  str = ""
  async for entry in ctx.guild.audit_logs(limit=lmt):
    idk.append(f'''User: `{entry.user}`
Action: `{entry.action}`
Target: `{entry.target}`
Reason: `{entry.reason}`\n\n''')
  for n in idk:
       str += n
  str = str.replace("AuditLogAction.", "")
  embed = discord.Embed(title=f"{ctx.guild_name}", description=f">>> {str}", color=0x2f3136)
  await ctx.reply(embed=embed)
torn sail
#

🤔

slate swan
#

Hunter is so smart

potent spear
#

so we're not gonna talk about str = ?

maiden fable
#

Thanks for the sarcasm

maiden fable
potent spear
#

Ok, I've seen enough

maiden fable
#

I hope you liked the first episode of Everyday Python Practices. See you tomorrow!

potent spear
#

I'm definitely unsubscribing

slate swan
#

Hunter's humour is even more broken than I expected

maiden fable
#

til I have humor

idle laurel
#

if payload.emoji == ":envelope_with_arrow:"

im running this with a reaction message, but when i click the reaction its returning false almost like im reaction to a different mesage, but im using the actual emoji not text

slate swan
maiden fable
#

Might also wanna send the code

idle laurel
maiden fable
#

sure

idle laurel
#

basically this is what ive got so far, everything but the emoji works fine

potent spear
slate swan
idle laurel
maiden fable
#

That seems like u r shouting on him

slate swan
idle laurel
#

no ideas what typecasting is

maiden fable
#

they just mean str(payload.emoji)

slate swan
#

hunter is so kind ❤️

idle laurel
#

oooh,

maiden fable
#

That is known as typecasting since str is a type and u r converting payload.emoji to string, so u r "casting" it to a string

idle laurel
#

pains me i didnt try that before, but cheers

idle laurel
maiden fable
#

Same

slate swan
shrewd apex
#

would scare the shit out for breakfast

slate swan
shrewd apex
shrewd apex
slate swan
shrewd apex
#

weird pplpithink

maiden fable
#

See, even Asher agrees but nvm

slate swan
#

I hate you hunter

maiden fable
#

it is what it is

slate swan
#

snakes are cute 😩 yellow albinos ❤️

shrewd apex
#

...

#

whats wrong with this world

slate swan
#

lmao

#

variety

maiden fable
shrewd apex
#

people have their own uniques tastes ig

slate swan
#

you guys dont have a sense of humour, that's it

shrewd apex
#

¯_(ツ)_/¯

shrewd apex
slate swan
#

im ded||snakes|| serious tho

shrewd apex
maiden fable
#

lmao what the

slate swan
#

deadsnakes~

shrewd apex
slate swan
shrewd apex
#

thats innovativepithink

paper sluice
#

*hd

shrewd apex
#

f hd quality

slate swan
#

everybody has a broken humour here

maiden fable
#

Ya'll might wanna take this to an ot channel

slate swan
#

waiting for mods

brave ravine
#

how would i automatically have my bot create a new line once a certain amount of characters are typed out

idle laurel
#

im trying to remove the reaction after the if statement

    async def on_raw_reaction_add(self, payload: nextcord.RawReactionActionEvent):
        find = utils.SERVERS.find({"_id": str(payload.guild_id)})
        user = self.bot.get_user(payload.user_id)
        for data in find:
            ticket = data['Ticket ID']
            channel = data['Channels']['Ticket']
        if str(payload.emoji) == "📩" and user != self.bot.user and int(payload.message_id) == int(ticket):

How am i best doing it, my previous methods i've had nothing but error, my head taken a beating on this one

brave ravine
#

for example, i do not like how this looks and would prefer the mentions to go onto a new line one they take up a certain amount of space

brave ravine
#

thats not automatically

#

thats hard coding it for the mentions to go onto a new line

#

which would have the name issues

idle laurel
#

you wanted mentions to go onto a new line?

brave ravine
#

automatically based on how much space the characters take up

#
desc = f"{data} \nMap: {mapLink}\nParticipants: {participants}"```
unkempt canyonBOT
#

Source code: Lib/textwrap.py

The textwrap module provides some convenience functions, as well as TextWrapper, the class that does all the work. If you’re just wrapping or filling one or two text strings, the convenience functions should be good enough; otherwise, you should use an instance of TextWrapper for efficiency.

brave ravine
#

thats my code, but i want to modify it so that once a line becomes too long, it creates a new line

brave ravine
tacit token
#

how can i solve it, if message deleted and the message is a picture the bot on_message_update send the picture?

paper sluice
unkempt canyonBOT
tacit token
#

ty

idle laurel
#
message = await self.bot.get_channel(int(channel)).fetch_message(int(ticket))
await message.remove_reaction("📩", user)

returning:

    if member.id == self._state.self_id:
AttributeError: 'NoneType' object has no attribute 'id'
brave ravine
#

is there also a way to automate pagination based on much data is being read?

for example, im using pandas to log some biking data and want to recall it in discord in groups of 10.

the way i have my code now, i have to manually create new pages and pull information manually in groups of 10, which although does what i want, is inconvenient

brave ravine
paper sluice
idle laurel
paper sluice
#

show the whole traceback

#

!traceback

unkempt canyonBOT
#

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

idle laurel
# paper sluice show the whole traceback
Traceback (most recent call last):
  File "D:\Documents\Programming\Python\Hyplex Bot\venv\lib\site-packages\nextcord\client.py", line 445, in _run_event
    await coro(*args, **kwargs)
  File "D:\Documents\Programming\Python\Hyplex Bot\discord\cogs\ticket.py", line 53, in on_raw_reaction_add
    await message.remove_reaction("📩", user)  # remove the reaction
  File "D:\Documents\Programming\Python\Hyplex Bot\venv\lib\site-packages\nextcord\message.py", line 1592, in remove_reaction
    if member.id == self._state.self_id:
AttributeError: 'NoneType' object has no attribute 'id'
brave ravine
#

that just means that member has no "id" parameter thing

paper sluice
#

no it means member is None

brave ravine
idle laurel
#

ive changed to pull from payload.user_id but then i get a

File "D:\Documents\Programming\Python\Hyplex Bot\venv\lib\site-packages\nextcord\client.py", line 445, in _run_event
    await coro(*args, **kwargs)
  File "D:\Documents\Programming\Python\Hyplex Bot\discord\cogs\ticket.py", line 51, in on_raw_reaction_add
    await payload.message_id.remove_reaction("📩", payload.user_id)  # remove the reaction
AttributeError: 'int' object has no attribute 'remove_reaction'
slate swan
idle laurel
# slate swan change it to discord.Object(id=payload.user_id)

same issue:

Traceback (most recent call last):
  File "D:\Documents\Programming\Python\Hyplex Bot\venv\lib\site-packages\nextcord\client.py", line 445, in _run_event
    await coro(*args, **kwargs)
  File "D:\Documents\Programming\Python\Hyplex Bot\discord\cogs\ticket.py", line 51, in on_raw_reaction_add
    await payload.message_id.remove_reaction("📩", nextcord.Object(id=payload.user_id))
AttributeError: 'int' object has no attribute 'remove_reaction'
brave ravine
#

different issue

#

the attribute error tells you whats wrong

slate swan
brave ravine
idle laurel
idle laurel
slate swan
#

so your issue is solved now ig?

brave ravine
slate swan
#
@bot.command()
@commands.has_permissions(kick_members=True)
async def timeout(ctx, user: discord.Member = None, time: str = None):
    time = humanfriendly.parse_timespan(time)

    if user == None:
      await ctx.reply(f"Please add a user to timeout!")

    if time == None:
      await ctx.reply("Please add a duration for the timeout!")

    await user.timeout(until = discord.utils.utcnow() + datetime.timedelta(minutes = time))

    embed=discord.Embed(description="", color=discord.Colour.red())
    embed.set_author(name=f"Successfully timed out {user} for {time}", icon_url="https://cdn.discordapp.com/emojis/934179741425090590.webp?size=96&quality=lossless")

    await ctx.reply(embed=embed)```
Error:
 ```discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: type object 'datetime.datetime' has no attribute 'timedelta'```
#

its datetime.timedelta

#

you probably imported datetime from datetime

idle laurel
slate swan
#

great

slate swan
sick birch
#
from datetime import timedelta, datetime

datetime.now() # ✅
timedelta(seconds = 5) # ✅
slate swan
#

alright thanks

sick birch
#

OR:

import datetime
datetime.datetime.now() # ✅
datetime.timedelta(seconds = 5) # ✅

you pick which you like

#

sorry sarth

slate swan
#

😩 its oki, you got it this time

brave ravine
#
async def bikeDatalogBook(ctx, df, buttons, current):
    page1 = discord.Embed(title = "logged Dates:", 
                        description="\n".join(df["Date:"].iloc[0 : 10]), color=discord.Color.blurple())
    page1.set_footer(text=f"Page 1")

    page2 = discord.Embed(title = "logged Dates:", 
                        description="\n".join(df["Date:"].iloc[11 : 20]),color=discord.Color.blurple())
    page2.set_footer(text=f"Page 2")

    page3 = discord.Embed(title = "logged Dates:", 
                        description="\n".join(df["Date:"].iloc[21 : 30]),color=discord.Color.blurple())
    page3.set_footer(text=f"Page 3")``` is there a way to automatically make new pages every 10 data inputs?
#

or do you have to manually add new pages in the code the way im doing it now

slate swan
#

how do i delete the bots message

#

my own bots message

#

after certain timr

#

?

#

!d discord.ext.commands.Context.send @slate swan

unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

This works similarly to [`send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for non-interaction contexts.

For interaction based contexts this does one of the following...
slate swan
#

see the delete_after kwarg

#

Ooohhhhh

#

you ca basically ```py
await ctx.send("message", delete_after = seconds)

#

same for any send methods

#

okay (:

idle laurel
#

stumbled onto my next error, had this working before with the same code

            message = await self.bot.get_channel(int(channel)).fetch_message(int(ticket))
            await message.remove_reaction("📩", nextcord.Object(id=payload.user_id))

            channel_name = f"ticket-{str(user)}"

            guild = message.channel.guild
            author = user
            transcript = user
            support = get(guild.roles, name="Staff")

            overwrites = {
                guild.default_role: nextcord.PermissionOverwrite(read_messages=False),
                guild.me: nextcord.PermissionOverwrite(read_messages=True),
                author: nextcord.PermissionOverwrite(read_messages=True),
                support: nextcord.PermissionOverwrite(read_messages=True)
            }

            new_channel = await guild.create_text_channel(channel_name, overwrites=overwrites)
#

returns this:

Traceback (most recent call last):
  File "D:\Documents\Programming\Python\Hyplex Bot\venv\lib\site-packages\nextcord\client.py", line 445, in _run_event
    await coro(*args, **kwargs)
  File "D:\Documents\Programming\Python\Hyplex Bot\discord\cogs\ticket.py", line 68, in on_raw_reaction_add
    new_channel = await guild.create_text_channel(channel_name, overwrites=overwrites)
  File "D:\Documents\Programming\Python\Hyplex Bot\venv\lib\site-packages\nextcord\guild.py", line 1192, in create_text_channel
    data = await self._create_channel(
  File "D:\Documents\Programming\Python\Hyplex Bot\venv\lib\site-packages\nextcord\guild.py", line 1070, in _create_channel
    payload = {"allow": allow.value, "deny": deny.value, "id": target.id}
AttributeError: 'NoneType' object has no attribute 'id'
jovial urchin
#

What do I need to know before I can start making discord bots?

paper sluice
#

how do i get the bot loop in lightbulb to run_in_executor

scarlet aurora
#
    @commands.Cog.listener()
    async def on_reaction_add(reaction, user):
        channel = discord.utils.get_channel(762287224796348446)
        if reaction.message.channel.id != channel.id:
            return
        if reaction.emoji == ":Brawlhalla:":
            role = discord.utils.get(user.server.roles, name="Brawlhalla")
            await user.add_roles(role)``` How do I enter the emoji into rection.emoji ?
idle laurel
paper sluice
jovial urchin
scarlet aurora
jovial urchin
sick birch
jovial urchin
scarlet aurora
#

no

jovial urchin
scarlet aurora
#

nope

sick birch
#

Generally speaking, it's a library

#

Though people have different definitions for "library" vs "module" vs "framework"

jovial urchin
slate swan
unkempt canyonBOT
#

asyncio.get_event_loop()```
Get the current event loop.

If there is no current event loop set in the current OS thread, the OS thread is main, and [`set_event_loop()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.set_event_loop "asyncio.set_event_loop") has not yet been called, asyncio will create a new event loop and set it as the current one.

Because this function has rather complex behavior (especially when custom event loop policies are in use), using the [`get_running_loop()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_running_loop "asyncio.get_running_loop") function is preferred to [`get_event_loop()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_event_loop "asyncio.get_event_loop") in coroutines and callbacks.

Consider also using the [`asyncio.run()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.run "asyncio.run") function instead of using lower level functions to manually create and close an event loop.

Deprecated since version 3.10: Deprecation warning is emitted if there is no running event loop. In future Python releases, this function will be an alias of [`get_running_loop()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_running_loop "asyncio.get_running_loop").
paper sluice
scarlet aurora
#

how's it a library

paper sluice
sick birch
paper sluice
#

users[str(user.id)] this dict has no key called "bank"

tacit token
#

guys, the on_message_edit log the links, why?

#

and every message

#
@client.event
async def on_message_edit(before,after):
    channel=client.get_channel(980392593781309480)
    now = datetime.datetime.now()
    current_time=now.strftime("%H:%M:%S")
    current_date=now.strftime("%d/%m/%Y")
    embed=discord.Embed(color=0x66ff66,description=f"Üzenet megváltoztatva itt: {after.channel.mention}",timestamp=datetime.datetime.utcnow())
    embed.set_author(name=f"{before.author}", icon_url=before.author.avatar_url)
    embed.add_field(name=f"Előtte",value=f"{before.content}", inline=True)
    embed.add_field(name=f"Utána",value=f"{after.content}", inline=True)
    embed.set_footer(text=f"Üzenet ID: {after.id}\nDátum: {current_date} • Idő: {current_time}")
    await channel.send(embed=embed)
unique bronze
#

So hello, I need some help. I am trying to make a bot, and I'm trying to use the bot subclass thingy, and trying to use on_message to send a message every time a message that has some...thing(?). (as an example, if an user sends a message saying only "rule 1" the bot sends a message saying "Rule 1, follow Discord TOS")

(code is here)

  1 #bot.py
  2 import os
  3 import discord
  4 import random
  5 import time
  6
  7 from dotenv import load_dotenv
  8 from discord.ext import commands
  9
 10
 11 load_dotenv()
 12 TOKEN = os.getenv('DISCORD_TOKEN')
 13 GUILD = os.getenv('DISCORD_GUILD')
 14 bot = commands.Bot(command_prefix='€')
 15 client = discord.Client()
 16
 17 #@client.event
 18 #async def on_ready():
 19 #    print(f'{client.user.name} has connected to Discord :)')
 20
 21
 22 @bot.event
 23 async def on_ready():
 24         print(f'{bot.user.name} has connected to Discord!')
 25
 26 #@bot.event
 27 #async def on_message(message):
 28 #    if message.author == client.user:
 29 #        await bot.process_commands(message)
 30 #        return
 31
 32
 33 @bot.command(name='ping', help='| Ping Pong, tells you the bot\'s latency :)')
 34 async def ping(ctx):
 35     #wait ctx.channel.send = 'pong'
 36     await ctx.reply(f'pong!    {round(bot.latency * 1000)}ms')
 37
 38 random_message = 'Random message :D'
...
(the messages I want to print, and a bunch of if statements that make it print stuff, I know this is inefficient and should be optimized)
....
 71 if message.content == 'random message':
 72         response = random.choice(random_message)
 73         await message.channel.send(response)
 74         await bot.process_commands(message)
...
bot.run(TOKEN)```
#

if the

 26 @bot.event
 27 async def on_message(message):
 28     if message.author == client.user:
 29         await bot.process_commands(message)
 30         return```
block is uncommented, the commands stop working
sick birch
#

Obviously, commands are only processed if your bot is the one to send said command

#

One way to accomplish this is to have a dict of keywords to messages, and the bot will send that message based on that dict

unique bronze
#

hm

unique bronze
#

because that's what I'm doing

#

the whole bot worked before I made it use the bot subclass

#

I could just convert it back to using discord.Client

idle laurel
#

why do i get this error when i run my slash command, but it returns no error in the log and it does as i was coded?

slate swan
unique bronze
slate swan
slate swan
unique bronze
#

I figured I need to replace the client thingies but idk what to replace them with lol

slate swan
idle laurel
slate swan
idle laurel
slate swan
unique bronze
slate swan
slate swan
paper sluice
unique bronze
idle laurel
slate swan
#

interaction.channel access the TextChannel object and sends a normal message

idle laurel
slate swan
slate swan
unique bronze
slate swan
tacit token
#

hi, i have a "small" problem. my on_message_edit work, but

@client.event
async def on_message_edit(before,after):
    channel=client.get_channel(vizsgalati)
    now = datetime.datetime.now()
    current_time=now.strftime("%H:%M:%S")
    current_date=now.strftime("%d/%m/%Y")
    embed=discord.Embed(color=0x66ff66,description=f"Üzenet megváltoztatva itt: {after.channel.mention}",timestamp=datetime.datetime.utcnow())
    embed.set_author(name=f"{before.author}", icon_url=before.author.avatar_url)
    embed.add_field(name=f"Előtte",value=f"{before.content}", inline=True)
    embed.add_field(name=f"Utána",value=f"{after.content}", inline=True)
    embed.set_footer(text=f"Üzenet ID: {after.id}\nDátum: {current_date} • Idő: {current_time}")
    await channel.send(embed=embed)
slate swan
slate swan
unique bronze
#

and the ones that aren't, are commented

unique bronze
sick birch
unique bronze
#

yo @sick birch, is there an issue with using client.user in a bot that uses Bot

#

and if there is, how can I replace it?

#

so how do I replace it?

tacit token
#

yes, i see

#

but why

heady sluice
#

you named your Bot client?

unique bronze
heady sluice
#

well if you have bot, you should use bot

#

if you have client, use client

full lily
#

this ^^

unique bronze
#

I also just realized that the reason the block of code was there, was to stop recursion so

heady sluice
#

Idk what the issue is, I'm more used to people who come here knowing python
commands.Bot inherits from discord.Client, which means that everything that client has, bot also has it

#

if you used Client before, then you should have no problem changing everything to a Bot instance and it's going to work

unique bronze
#
 71     if message.content == 'random message':
 72         response = random.choice(random_message)
 73         await message.channel.send(response)
 74         await bot.process_commands(message)
#

does that have an issue?

heady sluice
#

yeah, processing commands doesn't do anything there

unique bronze
#

welp

sick birch
#

or something like this:

unique bronze
sick birch
# sick birch _ _ _ _

point is, there are a million different reasons for why it could be empty before and after

heady sluice
#

what I just realised is that random_message is a single string

#

what do you wanna take out of a string

unique bronze
#

it's tied to a string

heady sluice
#

!e

import random

random_message = "I'm a simple string"
response = random.choice(random_message)
print(response)
unkempt canyonBOT
#

@heady sluice :white_check_mark: Your eval job has completed with return code 0.

s
unique bronze
#

random_message = 'random_message'

#

idk how to help u :/

#

!e

import random

random_message = [
  'this',
  'is',
  'a random',
  'group of strings'
]

response = random.choice(random_message)
print(response)
unkempt canyonBOT
#

@unique bronze :white_check_mark: Your eval job has completed with return code 0.

is
unique bronze
#

yea it works

#

yup

#

but like, the whole thing doesn't work anymore

potent spear
#

you basically don't want to use YT tutorials

#

since that's mostly crappy implementations and outdated lib use

candid cliff
#

!d discord.ext.commands.Command

unkempt canyonBOT
#

class discord.ext.commands.Command(*args, **kwargs)```
A class that implements the protocol for a bot text command.

These are not created manually, instead they are created via the decorator or functional interface.
unique bronze
#

apparently the name random_message isn't "defined", although it is

slate swan
unique bronze
frigid raft
#

Are you asking for help ?

unique bronze
#

yes

frigid raft
#

Can you send the code pls

potent spear
#

yeah, you want to use a database instead of json

unique bronze
#
import random

random_message = [
  'this',
  'is',
  'a random',
  'group of strings'
]

@bot.event
async def on_message(message):
  response = random.choice(random_message)
  await message.channel.send(response)
#

that's basically what it does

#

if u want the full thing, I can send it

frigid raft
#

and it says that random_message is not defined ?

unique bronze
#

yes

#

File "/home/iravii/python-stuff/CommandBot/Commanbot.py", line 78, in on_message
response = (first_message)
NameError: name 'first_message' is not defined

#

that's the error

frigid raft
#

first_message is not random_message

unique bronze
#

yea ik

#

I have random_message AND first_message

#

that's just to demonstrate

frigid raft
#

Ehh send the whole command

unique bronze
#

the whole code?

#
 71 @bot.event 
 72 async def on_message(message):
 73     if message.content == 'random message':
 74         response = random.choice(random_message)
 75         await message.channel.send(response)```
#

this is what's relevant ig

frigid raft
#

ok and where is first_message ?

unique bronze
#

above it

#
first_message = 'this is a demonstration message'
frigid raft
#

wait your codes are not the same, can you please just send the command with lines wich are problematic pls

unique bronze
#

wdym

frigid raft
#

send a screenshot

#

with the error

unique bronze
#

they're basically the same

frigid raft
#

in any case you don't use your first_message in your event, so why not remove it?

unique bronze
#

I do use it

frigid raft
#

where so ?

unique bronze
#

...

frigid raft
#

I'm sorry but in those two event that you sent you don't use first_message

unique bronze
#
 75     if message.content == 'random message':
 76         response = random.choice(random_message)
 77         await message.channel.send(response)
 78
 79     if message.content == 'first message':
 80         response = (first_message)
 81         await message.channel.send(response)
 82
 83     if message.content == 'second message':
 84         response = (second_message)
 85         await message.channel.send(response)
 86
 87     if message.content == 'third message':
 88         response = (third_message)
 89         await message.channel.send(response)
 90
 91     if message.content == 'fourth message':
 92         response = (fourth_message)
 93         await message.channel.send(response)
 94
 95     if message.content == 'fifth message':
 96         response = (fifth_message)
 97         await message.channel.send(response)
 98
 99     if message.content == 'sixth message':
100         response = (sixth_message)
101         await message.channel.send(response)
102
103     if message.content == 'seventh message':
104         response = (seventh_message)
105         await message.channel.send(response)
106
107     if message.content == 'eighth message':
108         response = (eighth_message)
109         await message.channel.send(response)
110
111     if message.content == 'ninth message':
112         response = (ninth_message)
113         await message.channel.send(response)
114
115     if message.content == 'tenth message':
116         response = (tenth_message)
117         await message.channel.send(response)
118```
unique bronze
#

that's horrible code, I know it is

frigid raft
#

ok i see

unique bronze
#

so don't say anything about that

frigid raft
#

dw

full lily
#

haha

unique bronze
potent spear
#

commands be like

full lily
unique bronze
#

ah

frigid raft
#

so first_message is above your bot_event ? @unique bronze

unique bronze
full lily
#

random_message isn't defined?

unique bronze
full lily
#

yeah weird

unique bronze
#

indeed

frigid raft
#
@bot.event
async def on_message(message):
   first_message = '...'
   if message.content == 'random...':
     response = random.choice(random_message)
     await message.channel.send(response)
...```Is your code like this @unique bronze ?
full lily
#

what if you define it inside of the function

unique bronze
#

it worked when I used Client instead of Bot btw

frigid raft
#

that's why it doesn't work... You have to define a variable inside your function if it's outside the event it'll be not defined

frigid raft
#

np

idle laurel
#

is there a specific decorator for the "has_any_role" for slash commands? or do they work on both commands and slash?

unique bronze
#

oh wait no

#

I commented out the wrong thing

potent spear
#

very common question you can ctrl+f that in this channel

unique bronze
#

IT WORKS

paper sluice
#

bruh

#

press ctrl+f and search that question

jovial urchin
#

What is a token?

sick birch
jovial urchin
#

Idk how to log into my bot, less so how to create it. Im guessing I have to do some stuff on Discords website? Is there a tutorial for that?

sick birch
frigid raft
#

you should learn more about Python i think

vital bloom
#

Hey can somoene help me please

heady sluice
jovial urchin
sick birch
#

For testing, just go for admin

sick birch
vital bloom
jovial urchin
sick birch
sick birch
frigid raft
#

@jovial urchin You have to create an url for invite your bot, but this is in the doc

jovial urchin
#

Which doc?

frigid raft
#

wait a sec

#

Here you got everything you need for create your bot.

jovial urchin
#

If I understand correctly: I need a url to where my code is and then add it to the Interactions Endpoint URL?

frigid raft
#

is only the url for the bot access to your account and then join the server

jovial urchin
#

I don't understand. How do I give the bot the code?

frigid raft
#

in your text editor

#

at the end of your code you'll add py bot.run('Your token that you get from the website')

sick birch
#

To log in: py bot.run("token")

#

Examples of sending API requests to control your bot:

await ctx.send("Hello, world!")

which sends a message in discord

jovial urchin
#

ah I see. And to keep the bot alive I need to stay logged in and have the script continue to run?

frigid raft
#

yeah or pay for hosting

vale wing
# jovial urchin What is a token?

Generally token is an encrypted string that contains some data about person who is authorising with it, and only server side knows how to decrypt it

vale wing
pliant gulch
#

iirc, the first two halves of a discord token will be the user's snowflake, then it'll be the epoch for when the user was registered

#

The last half will be the actual auth stuff, the HMAC

#

Probably wrong I haven't looked at that in a long time

potent spear
pliant gulch
#

I could see the first part being somewhat useful

jovial urchin
vale wing
frigid raft
#

Notice that you have to refresh it sometimes otherwise the bot will disconnect by itself

#

@jovial urchin

jovial urchin
frigid raft
#

Yeah

#

for exemple you'll use your command prompt, and for run your file you'll have to do File\path\main.py, this will execute your code but at some point you'll have to run it again from a new window

frigid raft
jovial urchin
#

Inactivity from who?

frigid raft
#

users who don't use the bot

jovial urchin
#

Can't I just have my bot make some random API calls every now and then to make it seem alive?

frigid raft
#

Everything is possible 🤷🏻‍♂️

low badger
#

Wondering if anyone has another approach to doing timed events with Discord bots. I've been poking around and many places suggest the tasks extension, but what if the bot is rebooted for whatever reason? All the queued tasks would be gone, right? I plan to make some features that allow users to go on "quests" that might take a few hours to complete. When complete, the bot will send a message on discord that the event has concluded. Any thoughts?

frigid raft
#

What sort of quests

#

And yes if the bot is not always connected, the qeued would be gone

#

@low badger

muted lark
#

has anybody made a discord bot that allows you to see what number a player was to join a server (so like you could do /joinnum player, and it'll show if they were the 23rd person to join the server for example)?

low badger
# frigid raft What sort of quests

Best way I can think to describe it is Farmville like. If you plant a crop it takes 30 minutes, 2 hours, 6 hours, etc. The user doesn't have to keep the window open, the server handles it all. But I need a system that works even if the server is disrupted, so I figure I'd store each event in a database with a time of when it should be completed. The only thing I'm missing is how the server will check the database for when events are complete. Hope that makes sense. Do people even play Farmville anymore? haha

#

I guess most mobile games work off mechanics like this as well.

frigid raft
#

I don't know Farmville 🤣

#

But it's a really good discord bot project fr

low badger
#

I thought it would be cool lol. Right now they can do dailies that give them exp and gold. But questing would give you more gold to send gifts to friends, stuff like that.

#

So far the users have enjoyed it.

#

I could have the bot check on regular intervals. Maybe ever 60 seconds or so, but that would not be accurate. I also thought of having the bot check at startup and set it's check again time to whatever the lowest remaining time was within the task list itself.

#

But that has issues too. If the oldest one is 1 hour, but someone submits a new one that takes 10 minutes, then it's off again. So maybe it sets it's time to the lowest remaining timer every time someone starts a timed event.

vocal plover
# low badger Best way I can think to describe it is Farmville like. If you plant a crop it ta...

The way you want to do this is actually quite different; instead of doing background events what you want is to make it appear as if they happen in the background, but actually just calculate them on the fly. If a user gains X coins every hour, for example, then you only need to update the actual number of coins the use has when they next interact with the bot, using a last_updated field or similar to calculate the interval

low badger
vocal plover
#

Schrodinger's coins, so to speak kek

low badger
#

Haha

vocal plover
low badger
sick birch
#

How can I use the discord.ext.tasks extension to create a task that's run at a certain time on a certain interval? For example, at 0000 UTC, every 2 days? From the docs it seems the time attribute and the hours, seconds, minutes attribute are mutually exclusive

vocal plover
sick birch
#

Ah okay, that's unfortunate. I'll see if we can change up how the feature works, and if not I'll go with your idea. Thanks!

vocal plover
#

np

pliant gulch
#

!d discord.utils.sleep_until maybe this will help as well?

unkempt canyonBOT
#

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

Sleep until a specified time.

If the time supplied is in the past this function will yield instantly.

New in version 1.3.
sick birch
#

Mmmm.. another good one

#

Would that go inside or outside the task?

pliant gulch
#

Yes

slate swan
#

no new message, but messige notification. Help?

candid cliff
jovial urchin
#
import discord

client = discord.Client()

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if message.content.startswith('$hello'):
        await message.channel.send('Hello!')

client.run('your token here')

In this script, why is on_message passed an argument and where does it get it from?

turbid knoll
#

It gets called whenever there is a message and the parameter is the message that activated the function

sick birch
jovial urchin
sick birch
#

on_ready actually happens after discord.py's internal cache and everything else is ready to go

jovial urchin
#

So discords servers tells me when anything at all happens?

sick birch
#

Exactly

jovial urchin
#

Whats the decorator for?

sick birch
#

It's to let discord.py know that the following function is an event, and you should call it when it happens

#

Without the decorator it's just a plain old function that does nothing

#

You seem interested in how things work under the hood, I suggest you try to connect to discord's gateway without using a library like discord.py to get a much deeper understanding of how things work under the hood. I found it that way when I made a bot without using discord.py or any other wrapper

austere dune
#

yooo making a discord bot, i can send hard coded embed messages but how can i send a user input embed message?

#

its for a stock/option bot im making

#

like to send alerts to a server

sick birch
#

User input how? An argument in a command?

austere dune
#

right in a way

#

lemme write an example

#

yall know how you can make your own discord bots, well i made a very simple bot. need to figure out how i can send custom embed messages. now for context, i know i can hard code the message using
embed = discord.embed (title="title", description="some crazy ass description", color=0x00ff4)
but what if i want to say like
!embed today we are going to talk about video games
and it sends that as an embedded message. for context the bots prefix is "!"

sick birch
#

Well however you get it, if you can get it into a variable (which it should already be in one), you can just use that in the embed however you want

austere dune
#

i have an idea but idk if its valid -> title = userinput(input = " ")

#

same for description

jovial urchin
austere dune
#

and then just doembed = discord.embed (title=input, description=input, color=0x00ff4)

sick birch
austere dune
#

lemme go try that

#

thank you robin for the help

sick birch
sick birch
austere dune
#

whats deleted channel?

sick birch
#

Not sure why it's showing up as #deleted-channel for you

#

If you want to access it click on the threads button at the top right, and go to discord-api-and-gateway

austere dune
#

ah okay is it a thread to this channel?

sick birch
#

Yes, it is

austere dune
#

dont have access to it lol

sick birch
#

It's more focused than this channel, more advanced you could say

austere dune
#

no worries

still swan
#

is it possible to change the discord.ui.Select width and height? may someone help me please?

austere dune
#

hmm doesnt seem to work, but ima figure it out, just needed a start

sick birch
sick birch
still swan
austere dune
#

Had a typo first lol

sick birch
#

And can I see the code/any errors you have?

austere dune
#

wait i fixed it lmao

#

im dumb

#

@sick birch what am i doing wrong, theres no errors, and when i type the command theres no response

#

code doesnt break tierh

#

either*

sick birch
#

Mmm, did you do client.run(...)?

torn sail
sick birch
#

Ah good catch, didn't see that

austere dune
austere dune
sick birch
#

Yeah it's an event, not a command

#

@client.command(), yes

frozen patio
#

How can I group commands together in cogs?

austere dune
sick birch
torn sail
#

Also use the function that is currently in the string. It has the correct parameters for a command

austere dune
#
AttributeError: 'Client' object has no attribute 'command'```
frozen patio
sick birch
#

Also commands all take commands.Context instance as the first parameter

frozen patio
#

Like this:

@bot.group()
async def setup(ctx):
    if ctx.invoked_subcommand is None:
        return await ctx.send("Doesn't exist :rolling_eyes:.")

But like in cogs

sick birch
#

Ahh okay, group commands

austere dune
sick birch
#

it should be the same, but instead of @bot.group() it's @commands.group()

frozen patio
#

Oh

sick birch
frozen patio
#

Then to call it in the group command it would be

sick birch
#

Just regular, nothing special about calling it

frozen patio
#

@commands.setup()

#

To call the group yes?

sick birch
#

You don't call the group, discord.py calls it for you when you call the command in discord

frozen patio
#

I am using nextcord

sick birch
#

Yes, my point still stands

frozen patio
#

Do I not do that in cogs

frozen patio
#

Hmm ok

austere dune
#

okay ive tried like every possible way, even adding "context.message.send" but still doesnt work

sick birch
#

Are you using commands.Bot instead of discord.Client?

frozen patio
sick birch
#

You've passed in the proper intents, enabled in the dashboard as well?

sick birch
frozen patio
#

Lemme see

#

I gotta finish adding some things in here

austere dune
frozen patio
#

commands.Bot()

#

Capitalize the bot

#

And you cannot have 2

austere dune
#

so i gotta remove one?

frozen patio
#

Use commands

austere dune
#

or ig comment it out

frozen patio
#

that one

austere dune
#

okay

sick birch
#

You need to have either discord.Client or commands.Bot, but not both

frozen patio
#

You can always do an on_message then can still do commands

austere dune
#

so instead of "client.event" id just have to replace "bot.event"

frozen patio
#

@sick birch Yup it worked

#

The grouping worked

#

Thank you, I am trying to get a verified bot

austere dune
#

okay okay we're getting somewhere

sick birch
frozen patio
#

Bot development is not easy

sick birch
#

No indeed, not without the right tools and a well structured bot

austere dune
#

ahhh you guys are goats

frozen patio
#

Using a database can really get you somewhere tho

sick birch
#

I saw you were using aiosqlite, maybe you'd like to look into an ORM to make it even easier/better?

frozen patio
#

Yea

#

I am using it for now

#

Making a dashboard in python is just hell nah

#

TS tho is Yes, I made a dashboard in TS actually

#

Works nice

sick birch
#

Did you use a framework? If so, which?

frozen patio
#

nestJS for the backend

austere dune
#

okay kings another question, if i want to add a gif into the embedded message, how would i go about doing that?

frozen patio
#

then the dashboard was react

frozen patio
sick birch
#

React + TS, a time and tried combo. Good for you! 🎉

frozen patio
#

Pulling ban analytics

#

timeout and kick anlytics

austere dune
frozen patio
#

You could do

#

embed.set_image(url="") or embed.set_thumbnail(url="")

austere dune
#

gotcha

austere vale
#
@commands.Cog.listener()
  async def on_user_update(self, before, after):
    #name
    if before.name != after.name:
      embed=nextcord.Embed(title="Name Change",description=f"{after.mention}",color=0xfd9fa1, timestamp=datetime.utcnow())
      fields=[("Before",before.name,False),("After", after.name,False)]
      for name, value, inline in fields:
        embed.add_field(name=name,value=value,inline=inline)
      await self.bot.get_channel(933978399280599080).send(embed=embed)
```can someone help me please?
torn sail
#

datetime.datetime.utcnow()

austere vale
#

oh

torn sail
#

datetime is part of a module also called datetime

austere vale
#

tysm!

jovial urchin
#
import discord
client = discord.Client()


for i in client.guilds:
    print(i)
@client.event
async def on_message(message):
    if message.author == client.user:
        pass
    elif message.content[0] == "!":
        await message.channel.send('Hello!')

with open("token.txt", "r") as f:
    token = f.read()

client.run(token)

Why doesn't this print the guilds the bot is in? It is in 1 server currently

sick birch
#
for i in client.guilds:
    print(i)

is called before the bot is even ready

jovial urchin
#

Ah, I need to wait for the on_ready call?

frozen patio
#

Why is the commands going twice

#

It just says the same thing twice

#

I am not running it anywhere else

slate swan
#

!d discord.ext.commands.Bot.wait_until_ready