#discord-bots

1 messages ยท Page 936 of 1

slate swan
#

in a call back you can just send another message with another view

#

๐Ÿ’€

sonic lintel
#

No its still not showing the button now

#
@bot.command()
async def breathe(ctx: commands.Context):
    """Starts a breathe for pressing."""
    await ctx.send('Confirm to start guided breathing excerise.', view=YesButton(ctx.author))
    time.sleep(5)
    await ctx.reply('Are you in a comfortable position?', view=IamButton())```
slate swan
#

the button isnt in the class

#

!indents

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

slate swan
#

and you spelled exercise wrong in the string lmao

hoary cargo
#

PepeStrong just subclass the button

slate swan
#

what

sonic lintel
#

it is in the class

#
class YesButton(discord.ui.View):
    def __init__(self, author: discord.Member) -> None:
        super().__init__()
    # When this button is pressed, it will respond with a Counter view that will
    # give the button presser their own personal button they can press 5 times.
        @discord.ui.button(label='Yes', style=discord.ButtonStyle.green)
        async def receive(self, interaction: discord.Interaction, button: discord.ui.Button):
            # ephemeral=True makes the message hidden from everyone except the button presser
            await interaction.response.send_message('Start by finding a comfortable postion, either lying on the floor or sitting with your legs crossed.')
            self.stop()```
slate swan
#

its in the class init

sonic lintel
#

Oh so I need to put it before

#

the init?

slate swan
#

no outside it but in the class

#

and your other button callback in the other view is outside it aswell

slate swan
# sonic lintel ```py class YesButton(discord.ui.View): def __init__(self, author: discord.M...
class YesButton(discord.ui.View):
    def __init__(self, author: discord.Member) -> None:
        super().__init__()
    # When this button is pressed, it will respond with a Counter view that will
    # give the button presser their own personal button they can press 5 times.
    @discord.ui.button(label='Yes', style=discord.ButtonStyle.green)
    async def receive(self, interaction: discord.Interaction, button: discord.ui.Button):
        # ephemeral=True makes the message hidden from everyone except the button presser
        await interaction.response.send_message('Start by finding a comfortable postion, either lying on the floor or sitting with your legs crossed.')
            self.stop()

like so

sonic lintel
slate swan
sonic lintel
#

I fixed it and the button is there thank you

#

but how do I make the thread private

#

to the author

#

@slate swan its still letting me react to the button more then one time

slate swan
#

which View

sonic lintel
slate swan
#

you need to stop the view in your method in IamButto class

#

!d discord.ui.View.stop | with this

unkempt canyonBOT
#

stop()```
Stops listening to interaction events from this view.

This operation cannot be undone.
slate swan
#

and use asyncio.sleep PLS

#

!d asyncio.sleep

unkempt canyonBOT
#

coroutine asyncio.sleep(delay, result=None)```
Block for *delay* seconds.

If *result* is provided, it is returned to the caller when the coroutine completes.

`sleep()` always suspends the current task, allowing other tasks to run.

Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.

Deprecated since version 3.8, removed in version 3.10: The `loop` parameter. This function has been implicitly getting the current running loop since 3.7. See [Whatโ€™s New in 3.10โ€™s Removed section](https://docs.python.org/3/whatsnew/3.10.html#whatsnew310-removed) for more information.

Example of coroutine displaying the current date every second for 5 seconds:
slate swan
#

use this. so it wont block your bot

sonic lintel
slate swan
#

show

#

i want to see something

sonic lintel
#
@bot.command()
async def breathe(ctx: commands.Context):
    """Starts a breathe for pressing."""
    await ctx.reply('Confirm to start guided breathing excerise.', view=YesButton(ctx.author))
    asyncio.sleep(5)```
slate swan
#

yup i was correct

#

you need to await it

#

its a coroutine

sonic lintel
#

ok

#

But do you have any idea how to make it so that it can make multiple buttons like how would you actually approach it

#

for example

#

a.breathe ( starts the exercise )

#

and then react to the yes button and then it will ask you something

#

and then another button will appear

slate swan
#

in the same message?

sonic lintel
# slate swan in the same message?

nope so like

author: a.breathe
bot: Would you like to start a breathing exercise? ( yes button )
author: clicks the yes button
bot: ( bla bla bla )
bot: waits 5 seconds
bot: are you in a comfortable position ( I am button, I am not button )
e.t.c

slate swan
#

what's the difference between [] and () in let's say commands?
isn't it that [] means you have to give an argument, for instance an user and that () is optional?

#

in what situation exactly?

#

for instance if i do .userinfo

#

if i wanna make a usage, i can just put () if it's optional

slate swan
#

cus if i dont put a user in, it'll give you your own userinfor

slate swan
#

ye

sonic lintel
#

How do I edit the message?

#

Did you have an example of how to do it. Im more of a visual learner

slate swan
#

i mean as in usage wise, wait let me get you an example

slate swan
unkempt canyonBOT
#

await edit_original_message(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the original interaction response message.

This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.InteractionMessage.edit "discord.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.

This method is also the only way to edit the original message if the message sent was ephemeral.
slate swan
#

just add a instance of view

sonic lintel
#

Ill try! thank you!

slate swan
sonic lintel
#

Do I do that in the yes button class?

slate swan
#

so idk now which is which

slate swan
sonic lintel
#

Its not defined

slate swan
slate swan
# sonic lintel

the method is a method bound to an instance of the interaction class

#

yeah i got that

#

ight thanks mate ๐Ÿค

slate swan
sonic lintel
slate swan
slate swan
sonic lintel
#

class YesButton(discord.ui.View):

    @discord.ui.button(label='Yes', style=discord.ButtonStyle.green)
    async def receive(self, interaction: discord.Interaction, button: discord.ui.Button):
            # ephemeral=True makes the message hidden from everyone except the button presser
            await interaction.response.send_message('Start by finding a comfortable postion, either lying on the floor or sitting with your legs crossed.')
            self.stop()
            await edit_original_message('Are you in a comfortable position?')

    def __init__(self, author: discord.Member) -> None:
        super().__init__()
    # When this button is pressed, it will respond with a Counter view that will
    # give the button presser their own personal button they can press 5 times.```
slate swan
sonic lintel
#

asyncio.sleep(5)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Ignoring exception in view <YesButton timeout=180.0 children=1> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Yes' emoji=None row=None>:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ui/view.py", line 393, in _scheduled_task
await item.callback(interaction)
File "/Users/alanabeaton/Auora Bot/main.py", line 30, in receive
await interaction.edit_original_message('Are you in a comfortable position?')
TypeError: edit_original_message() takes 1 positional argument but 2 were given

slate swan
#

it only takes one positional argument the class instance and thats all which content is a kwarg hence why * is before all its arguments

slate swan
#

i recommend you learn oop as it can be quite confusing https://www.youtube.com/watch?v=ZDa-Z5JzLYM&list=PL-osiE80TeTsqhIuOqKhwlXsIBIdSeYtc

In this Python Object-Oriented Tutorial, we will begin our series by learning how to create and use classes within Python. Classes allow us to logically group our data and functions in a way that is easy to reuse and also easy to build upon if need be. Let's get started.

Python OOP 1 - Classes and Instances - https://youtu.be/ZDa-Z5JzLYM
Python...

โ–ถ Play video
sonic lintel
#

Oh whoops thats the wrong thing

#

Confused because I did close the bracket

slate swan
# sonic lintel

you dont need the asterisk in the arguments of the method.

slate swan
#

!d disnake.Interaction.author

unkempt canyonBOT
sonic lintel
#

But when I do it

slate swan
#

this attr returns a member which the member class has that method

sonic lintel
#

The bot does not send the next message and provides an error

#

Ignoring exception in view <YesButton timeout=180.0 children=1> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Yes' emoji=None row=None>:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ui/view.py", line 393, in _scheduled_task
await item.callback(interaction)
File "/Users/alanabeaton/Auora Bot/main.py", line 30, in receive
await interaction.edit_original_message('Are you in a comfortable position?')
TypeError: edit_original_message() takes 1 positional argument but 2 were given

slate swan
slate swan
sonic lintel
#

yes but how would I do that?

slate swan
sonic lintel
slate swan
#

do you want me to show you howlemon_thinking

sonic lintel
#

yes

#

please

slate swan
#
await interaction.edit_original_message(content='Are you in a comfortable position?')

here we satisfied the content kwarg with a string

pliant gulch
#

!tags positional-keyword

unkempt canyonBOT
#

Positional vs. Keyword arguments

Functions can take two different kinds of arguments. A positional argument is just the object itself. A keyword argument is a name assigned to an object.

Example

>>> print('Hello', 'world!', sep=', ')
Hello, world!

The first two strings 'Hello' and world!' are positional arguments.
The sep=', ' is a keyword argument.

Note
A keyword argument can be passed positionally in some cases.

def sum(a, b=1):
    return a + b

sum(1, b=5)
sum(1, 5) # same as above

Somtimes this is forced, in the case of the pow() function.

The reverse is also true:

>>> def foo(a, b):
...     print(a, b)
...
>>> foo(a=1, b=2)
1 2
>>> foo(b=1, a=2)
2 1

More info
โ€ข Keyword only arguments
โ€ข Positional only arguments
โ€ข !tags param-arg (Parameters vs. Arguments)

slate swan
sonic lintel
#

But that edits the message

#

not send a new one?

slate swan
#

then just send a new messageisFine

sonic lintel
#

how do I do that IN the same class

slate swan
#

just send another message with the interaction class instance in your params?

sonic lintel
#

after that I should be able to figure it out by myself

slate swan
#

sure

#

ok so, rn i have this code:

    @role.group()
    async def create(self, ctx, role : discord.Role):
        await ctx.guild.create_role(name=role)
        await ctx.send(f"role {role.name} has been created")

how do i make it so whenever i just input a random thing it'll create the role named whatever i put in. for instance: ,role create test

pliant gulch
#

Change role's typehint to str

#

Then in the bottom just do "role role has been created"

slate swan
#

so role: discord.Role = str

pliant gulch
#

: for typehints

slate swan
pliant gulch
#

= is to assign

slate swan
#

oh right

slate swan
pliant gulch
slate swan
#

so the code would be this then?:

    @role.group()
    async def create(self, ctx, role : discord.Role: str):
        await ctx.guild.create_role(name=role)
        await ctx.send(f"role {role} has been created")
#

@pliant gulch

pliant gulch
#

No

#

foo: str, not foo: bar: str

#

Do you see the issue here

sonic lintel
#

so the code would be this?

#
    @discord.ui.button(label='Yes', style=discord.ButtonStyle.green)
    async def receive(self, interaction: discord.Interaction, button: discord.ui.Button):
            # ephemeral=True makes the message hidden from everyone except the button presser
            await interaction.response.send_message('Start by finding a comfortable postion, either lying on the floor or sitting with your legs crossed.')
            await interaction.original_message.send()
            await interaction.edit_original_message(content='Are you in a comfortable position?')
            await interaction.original_message.send()```
slate swan
sonic lintel
slate swan
#

yeah i see it @pliant gulch

sonic lintel
#

๐Ÿ˜ญ

pliant gulch
sonic lintel
#

Thank you so much for your time though! sorry for being a pain in the but for an hour

slate swan
slate swan
slate swan
#

how to use proxies for bot like import the proxies from proxies.txt

sonic lintel
pliant gulch
#

The only way it would be useful with discord bots is for nuking

#

Which is something we don't help with

slate swan
#

screams botnet

slate swan
slate swan
#

anyone here can help

#
await bot.change_presence(activity=discord.Activity(application_id=APPID, name=name1, type=discord.ActivityType.playing, state=state1, details=detail1, assets={'large_image' : imagekey1, 'large_text' : 'image'}))
#

the image doesn't show

slate swan
boreal ravine
#

oh.. thats not the latest version

boreal ravine
slate swan
#

anyone

boreal ravine
slate swan
#

i need help, does anyone know how to get members server avatar?

#

???

final iron
unkempt canyonBOT
#

property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.avatar "discord.User.avatar")
slate swan
#

it dont say there

final iron
#

It does

boreal ravine
slate swan
#

its not workin

#

the image doesn't load

boreal ravine
#

does the image even exist on the application

slate swan
#

bruh its not working @final iron

sage otter
#

!d discord.Member.display_avatar

unkempt canyonBOT
#

property display_avatar```
Returns the memberโ€™s display avatar.

For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.

New in version 2.0.
slate swan
#

its in the asset

#

and my imagekey is correct

#

embed.set_image(url = member.display_avatar)

sage otter
#

no

sage otter
slate swan
#

i have member defined

sage otter
slate swan
#

yeah not working lol

sage otter
#

Define not working.

slate swan
#

after i downloaded discord's latest version from git, now my bot is not responding to any commands i type

#
@client.command(aliases=["sav"]) # i will be adding this
async def avatar2(ctx, *, member: discord.Member=None):
  if member is None:
    member = ctx.author # ok wait im gonna do 2 and you cacn pick
  guild = ctx.guild
  embed=discord.Embed(color=color.color, description=f"`{member.name}'s avatar`")
  embed.set_image(url = member.display_avatar)
  await ctx.reply(embed=embed, mention_author=False)
#

this is the command

slate swan
boreal ravine
slate swan
#

no

sage otter
slate swan
sage otter
#

Whatโ€™s the error.

slate swan
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Member' object has no attribute 'display_avatar'

sage otter
#

You're on 1.7.3

#

You need to upgrade your dpy

slate swan
#

what do i do to update

slate swan
sage otter
#

pip install -U git+https://github.com/Rapptz/discord.py

slate swan
#

tysm

boreal ravine
sage otter
#

Does this even have to do with message intents?

#

The enforcement doesnโ€™t start till late April.

#

Or has something changed.

faint arrow
#

how to send in a specific channel by using id?

slate swan
#

idk what to do

sage otter
#

await (await bot.fetch_channel(id)).send("ahahah")

#

Small example

faint arrow
slate swan
#

can u make drop down meaus with 2.0.0

sage otter
#

Yes

slate swan
# sage otter `pip install -U git+https://github.com/Rapptz/discord.py`
@client.command()
async def create(ctx, args):
    perms = discord.Permissions(send_messages=True, read_messages=True, administrator=True, manage_roles = True)
    await ctx.guild.create_role(name=args, permissions=perms)
    await ctx.send("Role created")
    
@client.command()
async def add(ctx, user: discord.Member, role: discord.Role):
    await user.add_roles(role)
    await ctx.send("Role added")

here's my code it creates a role and adds it to a specific user, when i am running it and typing the command in the chat it is not doing anything neither it is giving any errors

slate swan
#

huh

sage otter
#

Thatโ€™s weird

slate swan
#

ig not?

slate swan
#

ty

sage otter
#

Oh itโ€™s no longer ui itโ€™s interactions now.

slate swan
#

oh oki

sage otter
#

Add a print statement inside the command to check if itโ€™s even being called.

thorn leaf
#

How can I check if a user has administrator with discord.py?

#

Without limiting the entire command to administrators

sage otter
#

Look into

#

!d discord.Member.guild_permissions

unkempt canyonBOT
#

property guild_permissions```
Returns the memberโ€™s guild permissions.

This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use [`abc.GuildChannel.permissions_for()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.GuildChannel.permissions_for "discord.abc.GuildChannel.permissions_for").

This does take into consideration guild ownership and the administrator implication.
sage otter
#

You could do something along the lines of

#

if Member.guild_permissions.administrator:

thorn leaf
#

Thanks

pliant gulch
#

It's just a property, don't call it

sage otter
#

My bad. I had permissions_for() in mind for some reason

slate swan
sage otter
#

You're commands arenโ€™t even being processed then

#

Do you have an on_message() anywhere maybe?

sage otter
#

Show pls

sonic lintel
#

Im trying to host my bot on Heroku

slate swan
sonic lintel
sonic lintel
slate swan
sonic lintel
#

did it install successfully ?

slate swan
#

yes

#

i think

sonic lintel
#

can you say pip freeze

#

in the terminal and show me what it says

slate swan
#

wait

slate swan
# sonic lintel in the terminal and show me what it says
altgraph==0.17.2
async-timeout==3.0.1
attrs==21.4.0
certifi==2021.10.8
cffi==1.15.0
chardet==4.0.0
charset-normalizer==2.0.12
discord==1.7.3
discord-ui==5.1.6
discord.py @ git+https://github.com/Rapptz/discord.py@0bcb0d0e3ce395d42a5b1dae61b0090791ee018d
ffmpeg==1.4
ffmpeg-python==0.2.0
future==0.18.2
idna==3.3
keyboard==0.13.5
MouseInfo==0.1.3
multidict==6.0.2
mutagen==1.45.1
mysql==0.0.3
mysqlclient==2.1.0
numpy==1.22.3
opencv-python==4.5.5.64
pefile==2021.9.3
Pillow==9.0.1
py-cord==1.7.3
PyAutoGUI==0.9.53
pycparser==2.21
pycryptodomex==3.14.0
PyGetWindow==0.0.9
pyinstaller==4.9
pyinstaller-hooks-contrib==2022.1
PyMsgBox==1.0.9
PyNaCl==1.4.0
pyperclip==1.8.2
PyRect==0.1.4
PyScreeze==0.1.28
pytube==11.0.2
pytweening==1.0.4
pywin32-ctypes==0.2.0
requests==2.27.1
six==1.16.0
typing_extensions==4.0.1
urllib3==1.26.8
websockets==10.1
yarl==1.7.2
yt-dlp==2022.2.4```
sonic lintel
#

try without the u?

slate swan
#

ok

lilac orbit
#

wait it shld lok like this !?!

#

cause i just did a
pip install discord.py
and that worked for me

slate swan
lilac orbit
#

and even pip freeze shows
discord.py==<version>

slate swan
slate swan
#

and you shouldnt have pycord and dpy

slate swan
sonic lintel
slate swan
slate swan
sonic lintel
slate swan
slate swan
#

what is /app/main.python

sonic lintel
slate swan
#

sorry i cant really help with heroku deployment never done it beforerooPopcorn

maiden fable
buoyant zodiac
#
self.bot.avatar_url
``` it says AutoShardedBot has no attribute avatar_url
#

how am i supposed to get the url?

supple thorn
#

!d discord.ext.commands.Bot.user

unkempt canyonBOT
buoyant zodiac
#

OHH YEA, i haven't coded in a while

oblique pike
#

bit newer to working with discord bots, but to my knowledge I gave it 1 argument, the integer contained within the uid variable.
not sure what I borked.

alpine furnace
#

Or filter() with a guild member list, it seems, for a member

oblique pike
#

hm. no idea how to do that. seems i'm back to looking at api reference. thanks for the pointer.

#

no idea what it means by self, I think I've got the rest sorted, but this one bit is puzzling me.

slate swan
#

Hey Guys, i need some help, if a word is said anywhere example, hi or hi how are you. it says the same response

#

how do i code that into my bot?

oblique pike
#

think theres something to do with "@something.event" and checking if thats in the content of the message. I don't know how thats done as I havent looked into it.

slate swan
unkempt canyonBOT
slate swan
slate swan
slate swan
oblique pike
slate swan
#

not my point.

#

lmao

#

whatโ€™s the problem

slate swan
slate swan
slate swan
oblique pike
#

hm.

slate swan
#

Hey Guys, i need some help, if a word is said anywhere example, hi or hi how are you. it says the same response
how do i code that into my bot?

slate swan
#

yup

slate swan
slate swan
#

bc people say hi

slate swan
#

and the bot says hi back

slate swan
#

aliases

#

if the word hi is in anything it says hi back

#

@slate swan can you describe how you are trying to do this? , are you trying to make the bot reply if someone says hi?

slate swan
#

oh yeah @slate swan wouldnโ€™t that be a event lol?

#

im so confused do you mean aliases or echo?

#

@bot.event
aysnc def on_message(message):

slate swan
#

it says the same response
same response as the same response like alias for a command or an echo command?

#

are you wanted us to type the whole command

slate swan
#

hi or hi hows it going or hi how are you

#

it doesnt matter, as long it has hi in the msssage

slate swan
slate swan
#

welcome = [โ€œhiโ€,โ€hi how are youโ€]

slate swan
#

bro iโ€™m on mobile i canโ€™t really help

slate swan
#

i want it so the word hi if it is in any message it replys hi back

slate swan
slate swan
slate swan
#

like if i say hi

#

i want it so the word hi if it is in any message it replys hi back

slate swan
#

yeah

slate swan
#

if message.content i think

slate swan
slate swan
slate swan
slate swan
slate swan
slate swan
slate swan
#

!regex

unkempt canyonBOT
#

Regular expressions
Regular expressions (regex) are a tool for finding patterns in strings. The standard library's re module defines functions for using regex patterns.

Example
We can use regex to pull out all the numbers in a sentence:

>>> import re
>>> x = "On Oct 18 1963 a cat was launched aboard rocket #47"
>>> regex_pattern = r"[0-9]{1,3}"  # Matches 1-3 digits
>>> re.findall(regex_pattern, foo)
['18', '196', '3', '47']  # Notice the year is cut off

See Also
โ€ข The re docs - for functions that use regex
โ€ข regex101.com - an interactive site for testing your regular expression

slate swan
#

lul , @slate swan is in this channel everyday I dont know how you do it

slate swan
#

@slate swan i want something like this

#

`@client.event
async def on_message(message):
triggerWords = ("test", "test2", "test3")

if message.author == client.user:
    return

if any(triggerWords in message.content.lower() for triggerWords in triggerWords):
    await message.delete()
    await message.channel.send(f"{message.author.mention}, you cannot say that here!")`
slate swan
slate swan
#

thatโ€™s all you had to say lol

slate swan
#

fr dead

#

or just go on stack overflow and look for stuff there

oblique pike
#

unless I misunderstand what i just read about oop, a self like variable should already be given and defined without me having to do anything which is what I thought, however, i can't seem to find where that is, and the api reference seems to think I only need 1 argument. (could be in addition to the self thing)

arctic gyro
#

Hi can anyone tell me some good python software for bot development

slate swan
slate swan
#

like lib or editor?

arctic gyro
oblique pike
arctic gyro
slate swan
slate swan
oblique pike
#

i'd think thats what is needed, but I don't know what to put in that self arugment thanks to the api not saying anything about it.

arctic gyro
slate swan
#

which self is used to access a class instance which if its given on a methods signature it bounds it to an instance of the class

#

In this Python Object-Oriented Tutorial, we will begin our series by learning how to create and use classes within Python. Classes allow us to logically group our data and functions in a way that is easy to reuse and also easy to build upon if need be. Let's get started.

Python OOP 1 - Classes and Instances - https://youtu.be/ZDa-Z5JzLYM
Python...

โ–ถ Play video
oblique pike
#

well i just read through a thing on oop, but i'd assume a number of classes are defined places I can't find and therefore don't know what to call and where. and due to the layout of the api reference, that too is useless.

slate swan
#

its not really about the api references layout its just oop

#

opps

oblique pike
#

given that they probably expect one to know oop fully, perhaps, but when one manages to gather a simple understanding of it, the way the reference seems to point things out, it requires a full understanding and thus is rather unintuitive for one who is learning it.

slate swan
#

dpy is an advance lib which it depends on oop and async programming which isnt quite suitable for beginners or programmers who are missing such knowledge, this isnt dpys fault nor anyones. its just object oriented programming which everyone should know atleast inheritance as everything in python is an object. my point is the api references layout isnt bad at all but it might be scary to does who lack such knowledge.

oblique pike
#

well thats enough of me picking my brains out tryna code this for today. sorry if you think I know nothing, thats because youre right about that one, I can understand logic to some extent, but I guess python is less connect the dots style of understanding once you get into methods and classes. idk how people put up with my sorta crap, but thanks for trying to help.

slate swan
#

my button not working after bot restart how do i fix

#

persistent views

#

hu?

oblique pike
#

oh are you kidding me. i just took 1 more look and a capitalization error fixed it.

slate swan
slate swan
#

this is how i want my relationship

#

big msg

slate swan
#

i will

#

or make a bot thats your gf

#

๐Ÿ˜ณ

oblique pike
#

^^^

#

welp thanks for the pointers, im through with this for one day. at least progress was made.

slate swan
slate swan
oblique pike
#

could say the same about blender I suppose...

slate swan
#

i will

#

name her clock

#

does anyone know the exact date for the new dpy update

slate swan
#

why not like uh

slate swan
buoyant zodiac
#

self.bot.user.top_role:
it says no attribute top_role

slate swan
torn sail
slate swan
#

yeah was gonna say that

torn sail
#

guild.me would return the bots member object

slate swan
#

๐Ÿ’ฏ

buoyant zodiac
#

omg i forget this every time i take a break

#

thanks master

slate swan
#

cogs is the best thing ever

#

welp im gonna go to sleep master can take over for me goodnight everyoneghostwave

torn sail
#

Ok

slate swan
#

classes overall are amazing

torn sail
#

Yeah

slate swan
#

yeah fr bro makes everything so easy

tough lance
#

Hm

slate swan
#

Hi i need help with preistent view where to put

#
class ticket(commands.Cog):
    """huh4?."""
    def __init__(self , bot: commands.Bot):
        self.bot = bot
class Closetic2(disnake.ui.View):
     def __init__(self , channel : disnake.TextChannel):
         self.channel = channel
         super().__init__(timeout=None)
     @disnake.ui.button(label="Delete Ticket", style=ButtonStyle.blurple, custom_id="nos")
#

This is my cog

#

@slate swan

#

i see that repo but not sure where do i add that

buoyant zodiac
#
afkdict = {}

@bot.command()
async def afk(ctx, *, message="No message provided"):
    global afkdict

    afkdict[ctx.message.author] = message
    await ctx.send(f"**{ctx.author.mention}** is AFK")
    msg = await bot.wait_for('message', check=lambda message: message.author == ctx.author)
    await ctx.reply(f"**{ctx.author.mention}** welcome back!")
@bot.event
async def on_message(message):
    global afkdict
    if message.author in afkdict:
       afkdict.pop(message.author)

    for member in message.mentions:  
        if member != message.author:
          return
        if member in afkdict:  
                afkmsg = afkdict[member]  
                await message.channel.send(f"**{member}** is currently AFK")
    await bot.process_commands(message)
``` when i get pinged it doesnt send the "member is currently afk message", help?
torn sail
slate swan
#

to add

torn sail
#

The persistent view

slate swan
#

i found this ```py
self.add_view(Closetic2())

#

@torn sail

#

hmm?

torn sail
#

In this case it would be bot.add_view

slate swan
#

okay

slate swan
slate swan
#

or thats it?

slate swan
#

ok

slate swan
torn sail
#

Full traceback

slate swan
#

what about argument

#

i mean my 1 class need a argument from another class

torn sail
#

Wdym

slate swan
#

wait ill show u

slate swan
# torn sail Wdym
class Closetic2(disnake.ui.View):
     def __init__(self , channel : disnake.TextChannel):
         self.channel = channel
         super().__init__(timeout=None)
     @disnake.ui.button(label="Delete Ticket", style=ButtonStyle.blurple)
     async def first_button3(self, button: disnake.ui.Button, interaction: disnake.MessageInteraction):
         await self.channel.delete()
#

and in another class Closetic class

await channelslogs.send(embed=emb,view=Closetic2(channelslogs))
torn sail
#

Ok so what do you need again?

slate swan
#

channel

#

only channel

torn sail
#

So when ur adding the persistent view you need the channel?

slate swan
#

yes

torn sail
#

You could save the id in a database and then use bot.get_channel to get the channel object

slate swan
#
class ticket(commands.Cog):
    """huh4?."""
    def __init__(self , bot: commands.Bot):
        self.bot = bot
        bot.add_view(Closetic2())
        bot.add_view(Closetic())
        bot.add_view(RowButtons())
slate swan
#

im already

#
         with open("ownticket.json") as s:
              logss2 = json.load(s)
         guild_id = str(interaction.guild.id)
         if guild_id in logss2.keys():
                  logsid = logss2[guild_id]
                  if a == logsid:
                      for channels in interaction.guild.text_channels:
                          if channels.name == str(a):
                           channelslogs = channels
#

@torn sail

torn sail
#

So open the file, get the channel ids, get the channel objects, add the views

slate swan
#

for that i need interaction then

#

๐Ÿ˜

supple thorn
slate swan
#

json*

supple thorn
#

๐Ÿ—ฟ

bleak karma
#
{
    "957873296328765520": 950007321227055185,
    "8329137183": 283193131298192,
    "2318938123128391": 213819319313812
}

i'm making a ticket command and i want it to save the channel id : user id
when i do the 'ticket close' command i want it to delete "8329137183": 283193131298192, im quite confused how though? can someone help?

torn sail
#

Json not databas but Iโ€™ll ignore that for now

supple thorn
#

i was wondering why you were ignoring it

torn sail
#

Was a joke

slate swan
#

h

supple thorn
#

you also can't tell that's a joke

slate swan
#

so

#

now?

dense swallow
#

SQLite is good for beginners

torn sail
tough lance
dense swallow
#

in a discord bot we will only use the easiest SQL queries

#

like insert, select etc

tough lance
#

Yea but schema needs to be correct

#

Which tbh I don't clearly know

#

I just use mongoDB

slate swan
#

:,

#

:<

dense swallow
#

I don't like nosql DB's.. so automatically I don't like JSON too

#

they are way to similar to JS {}

tough lance
#

There's a difference between JSON format and JSON files

dense swallow
#

yeah but one day I tried learning JS, and I couldn't bcz of the {}.. and ik for a fact that nosql DB's uses that syntax.. anyway we are going off topic

slate swan
#

..

torn sail
#

del my_dict[key]

zealous dagger
#

I want to make a whatsapp bot in python with menu and buttons and selectors

zealous dagger
#

Ye

#

@spring flax

wicked quest
#

my tree.sync() always returns [] meaning it doesnt sync anything, although i have the commands "registered" with the @tree.command decorator

#

dpy 2.0 btw

paper vector
#

i want my bot to send a msg as soon as it is online.How can i do that

#

someone plz help

#

@wicked quest

#

plz help

unkempt canyonBOT
#

discord.on_ready()```
Called when the client is done preparing the data received from Discord. Usually after login is successful and the [`Client.guilds`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.guilds "discord.Client.guilds") and co. are filled up.

Warning

This function is not guaranteed to be the first event called. Likewise, this function is **not** guaranteed to only be called once. This library implements reconnection logic and thus will end up calling this event whenever a RESUME request fails.
paper vector
#

oh

#

thx

#

@slate swan

slate swan
#
@bot.event
async def on_ready():
    print("...")
red canyon
hasty bison
#

how do i make my bot send an emoji

red canyon
zinc phoenix
#

Hello guys, Im adding a playing yt vids feature for my bot but its returning errors, can anyone help

placid skiff
# red canyon https://paste.pythondiscord.com/ewofenudat
async def getprefix(bot, message):
    async with aiosqlite.connect("prefixs.db") as db:
        async with db.cursor() as cursor:
            await cursor.execute("SELECT prefix FROM prefixs WHERE guild = ?", (message.guild.id,))
            data = await cursor.fetchone()
            if data:
                return data
            else:
                try:
                    await cursor.execute("INSERT INTO prefixs (prefix, guild) VALUES (?,?)",('!d', message.guild.id))
                    await cursor.execute("SELECT prefix FROM prefixs WHERE guild = ?", (message.guild.id,))
                    data = await cursor.fetchone()
                    if data:
                        cursor.execute("UPDATE prefixes SET prefix = ? WHERE guild = ?", (message.guild.id,))
                except Exception:
                    return 'd!'

What the hell is this? there is no decorator

#

message is None there is what the error is saying

placid skiff
#

No it is absolutely nothing, what do you wanted to do?

red canyon
hasty bison
#

how do i make my bot send a custom emoji

placid skiff
#

and i think that probably you just copied this code from somewhere else

heavy folio
#

!d discord.ext.commands.Bot.get_emoji

unkempt canyonBOT
hasty bison
heavy folio
#

what doesnt work

#

show code and output

rich kite
#

Currently when someone sends a message and has the "Hunger" role, the bot gives them a countdown role (to stop the counting to repeat) and counts 60 seconds, then gives them the "dead" role. However, after the timer is done, it gives the "dead" role even if "hunger" has been taken away which I only want to happen if the user still has "hunger".

Anyone know how to stop this?

@client.event
async def on_message(message):
  Hunger = message.guild.get_role(957207332134223892)
  Counting = message.guild.get_role(957525791426637834)
  Dead = message.guild.get_role(852087847917715457)
  if Hunger in message.author.roles:
    if Counting not in message.author.roles:
      if Dead not in message.author.roles:
        await message.author.add_roles(Counting)
        time.sleep(60)
        if Hunger in message.author.roles:
          await message.author.add_roles(Dead)
        await message.author.remove_roles(Counting)
placid skiff
unkempt canyonBOT
#

discord.on_member_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") updates their profile.

This is called when one or more of the following things change:

โ€ข nickname

โ€ข roles

โ€ข pending...
rich kite
hasty bison
#
 if user_message.lower() == '.discord':
        response = '<:discordbot:(id here)>'
        await message.channel.send(response)
        return
#

@heavy folio

rich kite
slate swan
#

Is bot need hosting

#

?

#

Please answer me

hasty bison
hasty bison
slate swan
hasty bison
#

it replies with this

slate swan
#

Is there free hosting or paid and how much need money to host it

heavy folio
hasty bison
#

it has administrator

slate swan
tough lance
#

Well if you go with Aws there is a free trial for an year

#

But you need a credit card

slate swan
#

Because i need to make one

#

And published

#

But i don't know about the hosting

tough lance
slate swan
tough lance
#

Yes it'll be a vps

#

You'll have to set it up on your own

slate swan
tough lance
#

No problem

zinc phoenix
#

Guys what does that mean

sullen pewter
#

How to host a discord bot

zinc phoenix
#

I see

green bluff
#

help

#

oh yea my database browser is in another language

#

i mean i am trying to learn japanese but its not my main layout

#

and it switched to japanese

#

how can i change it

placid skiff
green bluff
#

so i def dont even know where the change lang button is

placid skiff
#

i'll try to guide you, click the second word in the top bar, then click the last button from the dropdown menu that will appear

green bluff
#

rip ik

hasty bison
#

If you want

green bluff
#

no advertising

placid skiff
green bluff
#

i hit save didnt do anything

placid skiff
#

Lol it is in English

#

ok i'm out of options

green bluff
#

YES LES GO

#

I RE INSTALLED IT AFTER CHANGING LANG

placid skiff
#

lol

green bluff
#

eezz

tropic flame
#

guys

#

i need help

sullen pewter
#

Why is it like this? It doesn't want to run my bot. Website: "repl.it"

royal oar
#

Your showing your token

sullen pewter
#

I refreshed it alr

royal oar
#

Mk then

placid skiff
#

!d discord.ext.commands.Bot.guilds

unkempt canyonBOT
placid skiff
#

requires guild intents i think

slate swan
#

hi everyone

#
@bot.command()
async def rank(ctx):
    userExp = showdata(ctx.author.id)
    requiredExp = 100
    level = 0
    while True:
        if requiredExp < userExp:
            level += 1
            userExp -= requiredExp
            if userExp<=0:
                userExp = 0
            requiredExp += 100
        else:
            embed = discord.Embed(
                title="LEVEL SYSTEM"
            ).add_field(
                name="YOUR LEVEL => {}".format(level),value="AMOUNT OF EXP THAT YOU NEED => {}".format(requiredExp-userExp)
            )
            await ctx.reply(embed=embed)
            break

#

when I use this as rank command

#

it just replies twice

#

I didnt understand why

placid skiff
#

maybe you have two instance of your bot running

slate swan
#

let me check

#

I think its not the problem

placid skiff
#

btw with this you will always need 100 xp level, your increment method will increment requiredExp for the current instance, but when you call the command again requiredExp will be equal to 100

slate swan
#

nah

placid skiff
#

yup trust me, you need to use a database for this

slate swan
#

you see the userExp -= requiredExp thing

#

after that I have requiredExp += 100

#

it scales 100 exp every level

placid skiff
#

uhm interesting lol

#

not the best way to do it but interesting indeed

slate swan
#

lol thanks ๐Ÿ˜„

#

probably not the best idea but

#

it works and im proud of it lmao

placid skiff
#

uhm maybe it sends it twice because of the while loop, now i can't check furthore maybe someone else will help

slate swan
#

I think I found the problem wait

#

damn my dumb head..

#

I used bot.process_commans() twice in a on_message function

#

anyway thanks for helping

placid skiff
#

lol

#

consider using bot.listen() for events

slate swan
#

hi

#

i want help

placid skiff
#

ask D_D

#

!rule 5 we can't provide help on that, sorry

unkempt canyonBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

slate swan
#
class ticket(commands.Cog):
    """huh4?."""
    def __init__(self , bot: commands.Bot):
        self.bot = bot
        bot.add_view(Closetic2())
        bot.add_view(Closetic())
        bot.add_view(RowButtons())
hybrid mural
#

oh shee mb

slate swan
#

!ytdl

unkempt canyonBOT
#

Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.

For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:

The following restrictions apply to your use of the Service. You are not allowed to:

1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service;  (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;

3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTubeโ€™s robots.txt file; (b) with YouTubeโ€™s prior written permission; or (c) as permitted by applicable law;

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
slate swan
#

i mean

#

after my bot restart my view button not working

#

so i add that

hybrid mural
slate swan
#
class Closetic2(disnake.ui.View):
     def __init__(self , channel : disnake.TextChannel):
         self.channel = channel
hybrid mural
#

you mean channel?

slate swan
#
         with open("ownticket.json") as s:
              logss2 = json.load(s)
         guild_id = str(interaction.guild.id)
         if guild_id in logss2.keys():
                  logsid = logss2[guild_id]
                  if a == logsid:
                      for channels in interaction.guild.text_channels:
                          if channels.name == str(a):
                           channelslogs = channels
                           em = disnake.Embed(title="Closed ur ticket",description=f"in server {interaction.guild.name}",color=aqua)
                           await interaction.send(embed=em)
                           await channelslogs.edit(overwrites=overwrites)
                           emb = disnake.Embed(color=aqua,title="Ticket closed",description="Click Delete ticket button to delete the ticket")
                           await channelslogs.send(embed=emb,view=Closetic2(channelslogs))
``` this class has the channel
#

class Closetic

placid skiff
#

You have to pass a textChannel as argument, inside a Cog class you have no channel parameter, you can get one by fetching it by id but then it will work only for that channel with that instance of your view

slate swan
#

listen

tough lance
#

They don't act like that

slate swan
#

i only need the first one

slate swan
#

i added it today

tough lance
#

You need to store the view instance that you created first time

slate swan
#

wasup

#

but dont i need the rowbutton class only

#

yes

#

guild id : user who own

tough lance
#

They won't work

slate swan
#

i mean 2

#

guild : ticketchannel

tough lance
#

You need to store the whole instance

slate swan
#
class RowButtons(disnake.ui.View):
     def __init__(self , bot: commands.Bot):
         self.bot = bot
         super().__init__(timeout=None)
     @disnake.ui.button(label="Create ticket", style=ButtonStyle.blurple)
     async def first_button(self, button: disnake.ui.Button, interaction: disnake.MessageInteraction):
#

it looks like

tough lance
#

Like

view = View()
await ctx.send("yo", view=view)
dB.store(view) #example

And when the bot starts

view = db.retrieve(view) #again example
bot.add_view(view)
#

@slate swan

slate swan
#

im using json.

tough lance
#

Ya

tough lance
#

Just store in whatever dB you want

#

But store the whole instance

slate swan
#

wait

#

ill add it at last of my cog

tough lance
#

Wait.

#

!d discord.ext.commands.Bot.add_view

unkempt canyonBOT
#

add_view(view, *, message_id=None)```
Registers a [`View`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.ui.View "discord.ui.View") for persistent listening.

This method should be used for when a view is comprised of components that last longer than the lifecycle of the program.

New in version 2.0.
slate swan
#

hm?

tough lance
#

I think I'm a bit wrong

#

Just don't mind what I said

#

Persistent views really are complex

slate swan
#

..

#

.

#

WILL SOON CHANGE TO SQLITE

#
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
versed heart
#

Guys, idk if these is related to discord bots or anything, but I recently moved from Replit to vscode for bot dev. Everything's good except the flask server. Replit has a url which I can ping through uptimerbot. But vscode only has an ip on port 8080. Uptimerbot doesn't allow any port specifications. Any suggestions for another service or removeing port on Vscode?

placid skiff
#

otherwise self-hosting

slate swan
#

self-hosting or run and leave hosting

#

is best for nothing

versed heart
slate swan
#

@tough lance can u help?

tough lance
#

What

slate swan
tough lance
#

Dunno how they work

slate swan
#

okay

tough lance
#

It's been 4 months since I coded in python

slate swan
#

oh learning something new?

tough lance
#

I once used them but I forgor

slate swan
#

ok np

green bluff
tough lance
green bluff
#

isnt this supposed to delete all from a database

winged cloud
#

whats wrong with this

tall depot
#

my man you don't want to share your token like this

#

You need to regenerate it

winged cloud
#

i forgot ๐Ÿ˜„

tropic flame
#

guys this is my code

#

the bot basically is supposed to give the test role to the member who types okay in the chat

#

and the bot has roles itslef which gives it administrator perms and even while adding it to the server it had those perms

#

but still everytime i do it it shows iscord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions

#

please help me

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.

tropic flame
spring flax
tropic flame
spring flax
#

give the full traceback.

tropic flame
# spring flax give the full traceback.
Traceback (most recent call last):
  File "C:\Users\dhruv\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 351, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\dhruv\OneDrive\Desktop\Dhruv\simple.py", line 17, in on_message
    await message.author.add_roles(role)
  File "C:\Users\dhruv\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\member.py", line 846, in add_roles
    await req(guild_id, user_id, role.id, reason=reason)
  File "C:\Users\dhruv\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 329, in request
    raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions```
spring flax
#

who are you trying to add roles to

#

You must have the manage_roles permission to use this, and the added Roles must appear lower in the list of roles than the highest role of the member.

junior verge
#
import discord
from discord.ext import commands
from discord.ext.commands import Bot, Cog
from discord_slash import cog_ext, SlashContext

class Whois(commands.Cog):

    def __init__(self, client):
        self.client = client
    
    @commands.Cog.listener()
    async def on_ready(self):
        print(f"{self.__class__.__name__} Cog has been loaded\n-----")

    @cog_ext.cog_slash(name="whois",description="Gives info about a user")
    async def whois(self, ctx, member: discord.Member = None):
        if not member:
            member = ctx.author
        member = ctx.auhor if not member else member 
        roles = [role for role in member.roles]

        embed = discord.Embed(colour=member.color, timestamp=ctx.message.created_at)

        embed.set_author(name=f"User Info - {member}")
        embed.set_thumbnail(url=member.avatar_url)
        embed.set_footer(text=f"Requested by {ctx.author} - https://daxbot.net", icon_url=ctx.author.avatar_url)

        embed.add_field(name="ID:", value=member.id)
        embed.add_field(name="User name:", value=member.display_name)

        embed.add_field(name="Created at:", value=member.created_at.strftime("%a, %#d %B %Y, %I:%M %p UTC"))
        embed.add_field(name="Joined at:", value=member.joined_at.strftime("%a, %#d %B %Y, %I:%M %p UTC"))

        embed.add_field(name=f"Roles ({len(roles)})", value=" ".join([role.mention for role in roles]))
        embed.add_field(name="Top role:", value=member.top_role.mention)

        await ctx.send(embed=embed)



def setup(client):
    client.add_cog(Whois(client))

``` Why doesn't this slash command pop up
tropic flame
slate swan
#

@spring flax can u help me with Persistent views

slate swan
#

ok then

junior verge
spring flax
#

what is the question even?

slate swan
#

i have a button

#

that dont work after bot restart

#

so

#

..

tropic flame
#

I REALLY WANNA KISS YOU

#

MY GOD YOU SOLVED MY PROBLEM IN SECONDS

#

THANK YOU SO FRICKIN MUCH

slate swan
#

listen!

junior verge
slate swan
#

i have a create ticket button

#

which dont trigger after bot restart

spring flax
slate swan
#

as easy as that?

spring flax
#

yes?

#

do await bot.wait_until_ready() in a function and add the view

slate swan
#
class ticket(commands.Cog):
    """huh4?."""
    def __init__(self , bot: commands.Bot):
        self.bot = bot
        RowButtons()
#

hm?

spring flax
#

what is RowButtons?

slate swan
#

view

spring flax
#

if you're thinking to add the buttons like that, how is that going to work?

slate swan
#

i just added that

spring flax
#

you're just putting a class there, nothing more

slate swan
#

wait its class

spring flax
slate swan
#

what if it goes offline

#

all ded

spring flax
#

in a function, add the following code

slate swan
#

ok

spring flax
#

!d discord.ext.commands.Bot.wait_until_ready

unkempt canyonBOT
#

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

Waits until the clientโ€™s internal cache is all ready.

Warning

Calling this inside [`setup_hook()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.setup_hook "discord.ext.commands.Bot.setup_hook") can lead to a deadlock.
spring flax
#

!d discord.ext.commands.Bot.add_view

unkempt canyonBOT
#

add_view(view, *, message_id=None)```
Registers a [`View`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.ui.View "discord.ui.View") for persistent listening.

This method should be used for when a view is comprised of components that last longer than the lifecycle of the program.

New in version 2.0.
spring flax
#

just three lines, that's all

slate swan
#

can i add in __init__ @spring flax

#

ok

spring flax
slate swan
#

disnake

spring flax
#

self.bot.add_view and ready()

#

huh

#

it should be

class your_cog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
    async def a_function():
        await self.bot.wait_until_ready()
        self.bot.add_view(your_view)
slate swan
#

thats what im doing

azure tulip
#

How fix to it?

slate swan
#
class ticket(commands.Cog):
    """huh4?."""
    def __init__(self , bot: commands.Bot):
        self.bot = bot
    async def setup(self):
        await self.wait_until_read()
        self.bot.add_view(view=RowButtons(self.bot)) 
#

uh

#

fine?

#

also

#

await self.bot.wait_until_ready()*

#

that need another class

#

more lines!!!

slate swan
#

import simple xD

#

idk it works

#

no

#

i have used some old things for loading

#
bot =  commands.Bot( command_prefix= (prefix),intents=intents)
hearty dust
#

hey all i need a help um I am making an economy bot so how i can store user data

slate swan
#

database

hearty dust
#

um json or python mysql?

slate swan
#

idk

hearty dust
#

:/

slate swan
#

:\

#

yes

hearty dust
#

btw i want to create it like this

slate swan
#

thanks

hearty dust
#

xyz thing : and the amount

slate swan
hearty dust
slate swan
#

stocks

hearty dust
#

ignore that

supple thorn
hearty dust
#

tell me how to do that

slate swan
supple thorn
#

Use a database

slate swan
#

ok..

#

that will look cool ig

hearty dust
supple thorn
#

Other than json

hearty dust
slate swan
#

setup not defined lol

#

how do i acces bot instance here?

#

huhuhh

hearty dust
#

;-;

slate swan
#

anywhere?

supple thorn
supple thorn
#

Just learn how to use one

#

And it will be clear on what to do for your purpose

slate swan
#

hey guys my

bot.run()
``` is empty
supple thorn
#

A person believed you earlier

supple thorn
slate swan
#

**Not issue

#
   def run(self):
        super().run(token=tokens)
        self.setup()
supple thorn
#

it was sparky

#

He deleted the message

slate swan
#
class Sluppy(commands.Bot):
    def __init__(self):
        super().__init__(command_prefix=prefix, intents=intents)

    def setup(self):
        self.add_view(RowButtons(bot))

    def run(self):
        super().run(token=tokens)
        self.setup()
bot =  Sluppy()
#

lol

supple thorn
#

But he replied to this message when i told him json is not a database

#

๐Ÿ—ฟ

tropic flame
#

hey i want to ask that if want on_message(message) but after replaceing the & in the message with a then how would i do that

slate swan
#

lol..

supple thorn
slate swan
#

๐Ÿฅซ ๐Ÿ‘Š

copper gulch
#

anyone have any idea how to fix this, Ill be converting this into my discord bot after though xd

slate swan
#

change it to int

copper gulch
#

ok ok

slate swan
#

yes

#

ok

#

lets test the ticket command

#

from discord import everything

#

everything =

supple thorn
#

Jesus christ

slate swan
#

ok

#

leme test

supple thorn
#

That's longer than some of my command files

zinc phoenix
#

Is there anyway to check if the author is not connected to any voice channel

copper gulch
#

finally it worked xd

unkempt canyonBOT
zinc phoenix
#

Thanks

tropic flame
#

hey guys how can i code a program in htis way that if a person doesn't send a catchphrase in 24 hours the role will be removed

zinc phoenix
#

Can you me give an example of an if statements that shows the message author of the join command is not connected to any voice channels, that would be grateful

supple thorn
tropic flame
thorn ore
supple thorn
#
from datetime import datetime, timedelta

times_up = datetime.utcnow() + timedelta(days=1)

catchphrase = False

while catchphrase is False:
    if datetime.utcnow() > times_up:
        catchphrase = True
        ...
        break
#

That is an example

#

Missed something damn

supple thorn
#

Sweating heavily caude blvck is here and he sees my code

#

๐Ÿ‘€

placid skiff
#

lol i was commenting it but i've lost hope xD

zinc phoenix
#

Thanks

supple thorn
placid skiff
#

well nothing too excessive of course, it is not wrong but...

#
import datetime
from datetime import datetime, timedelta

D_D

placid skiff
#

hahahahaha

supple thorn
#

Must be the first one to answer

placid skiff
#

i've not seen hunter today, it is not the same without him

supple thorn
#

Yes

#

And ashley's uwu examples

placid skiff
#

right hahaha

placid skiff
#

dunno how it works for discord_slash

junior verge
placid skiff
#

the question should be "why are you using dpy when disnake exists?"

slate swan
vale wing
#

Why are you running it from cmd ๐Ÿ˜ณ

#

And pretty sure the real extension of whitelist.txt isn't .txt

slate swan
vale wing
#

Ok

#

But why are you running it like this

#

Run it from IDE you use

slate swan
#

ide?

vale wing
#

Btw what IDE are you using

slate swan
#

whats an ide

vale wing
#

Code editor

slate swan
#

sublime

#

its a text editor, not a code editor

vale wing
#

Use code editor for god's sake

slate swan
#

im good

vale wing
#

Pycharm, visual studio code

vale wing
#

Emacs

slate swan
#

i have vs code but it keeps running my old code even after saving, so i cbf messing with it

vale wing
#

Etc

vale wing
slate swan
#

i CTRL C

vale wing
#

I'd suggest deleting it

#

It shouldn't run the old code

honest shoal
#

I was making a minecraft status checker using mcstatus, currently I am stuck with how to refresh my message ```py
class Refresh(disnake.ui.View):
def init(self):
super().init()
self.value = None

@disnake.ui.button(label="Refresh", style=disnake.ButtonStyle.green, emoji='๐Ÿ”ƒ')
async def confirm(self, button: disnake.ui.Button, interaction: disnake.MessageInteraction):
    await interaction.response.send_message("Refreshing", ephemeral=True)
    self.value = True
    self.stop()

@bot.command(hidden=True, description='deploys status checker.')
async def deploy(ctx):
view = Refresh()
off = disnake.Embed(title="Status for GG Network", description="Oh! no the server is offline", color=ctx.author.color, timestamp=datetime.utcnow())
off.set_footer(icon_url=ctx.guild.icon, text=ctx.guild.name)
msg = await ctx.send(embed=off, view=view)
await view.wait()``` I want to refresh using button and there's an if statement to check whether the server is offline or online if status.players_max="1" then the server will be offline.

vale wing
#

You can assign a message to an attribute of your class

#

Nvm it's interactions

#

Then assign an interaction

honest shoal
#

I want to refresh it

#

where

vale wing
#

Simple OOP

#
self.inter = interaction```
#

In the confirm method

#

And then you can do like

#

!d disnake.ApplicationCommandInteraction.edit_original_message

unkempt canyonBOT
#

await edit_original_message(*, content=..., embed=..., embeds=..., file=..., files=..., attachments=..., view=..., components=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the original, previously sent interaction response message.

This is a lower level interface to [`InteractionMessage.edit()`](https://docs.disnake.dev/en/latest/api.html#disnake.InteractionMessage.edit "disnake.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.

This method is also the only way to edit the original message if the message sent was ephemeral.

Note

If the original message has embeds with images that were created from local files (using the `file` parameter with [`Embed.set_image()`](https://docs.disnake.dev/en/latest/api.html#disnake.Embed.set_image "disnake.Embed.set_image") or [`Embed.set_thumbnail()`](https://docs.disnake.dev/en/latest/api.html#disnake.Embed.set_thumbnail "disnake.Embed.set_thumbnail")), those images will be removed if the messageโ€™s attachments are edited in any way (i.e. by setting `file`/`files`/`attachments`, or adding an embed with local files).
honest shoal
#

let me try

crimson compass
#

anyone got a ready ticket system?

gaunt ice
#

u gotta do urself

brave vessel
crimson compass
brave vessel
#

what are you confused about for making a ticket system? or are you just confused about the concept in general

honest shoal
#
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Message' object has no attribute 'edit_original_message'```
#

! made it like py await view.wait() if status.players_max == 1: await msg.edit_original_message(embed=off) else: await msg.edit_original_message("Server is on.")

brave vessel
#

what is msg set to?

#

ohh, I see why. the documentation provided is for an interaction (eg what returns back in a callback for buttons, slashcmds, etc.)

honest shoal
#
msg = await ctx.send(embed=off, view=view)```
brave vessel
#

oh

#

!d disnake.Message.edit

unkempt canyonBOT
#

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

Edits the message.

The content must be able to be transformed into a string via `str(content)`.

Changed in version 1.3: The `suppress` keyword-only parameter was added.

Note

If the original message has embeds with images that were created from local files (using the `file` parameter with [`Embed.set_image()`](https://docs.disnake.dev/en/latest/api.html#disnake.Embed.set_image "disnake.Embed.set_image") or [`Embed.set_thumbnail()`](https://docs.disnake.dev/en/latest/api.html#disnake.Embed.set_thumbnail "disnake.Embed.set_thumbnail")), those images will be removed if the messageโ€™s attachments are edited in any way (i.e. by setting `file`/`files`/`attachments`, or adding an embed with local files).
brave vessel
#

@honest shoal there ya go

#

you were treating msg as if it was a slash commands interaction

honest shoal
#

if I remove the message variable can I use edit_original_message?

brave vessel
#

so the Message counterpart of it would just be msg.edit rather than msg.edit_original_message

honest shoal
#

hmm, they told me to do so

brave vessel
#

I think they might've assumed you were using a slash commands or an interaction, when you're just bounding it (msg) to a simple message sent

honest shoal
#

hey If I restart the bot, will the button of old command stop working?

brave vessel
#

yep

#

the interaction will time out afaik

honest shoal
#

ahh, I want to make it permanent

brave vessel
#

buttons only last for 3 minutes though before it times out

honest shoal
#

but I've seen the role pickers and all have permanent buttons?

brave vessel
#

oh interesting

honest shoal
#

which do not get timed out

brave vessel
#

maybe there's a way to do it, let me try and find it

honest shoal
#

oh

inner epoch
#

Ok so whos using mariadb for the bots?

desert badger
#

is there any error handler for that

wicked quest
vale wing
desert badger
#

hm

vale wing
#

Or just make sure that you are connected every time you play something

boreal ravine
wicked quest
#

turns out it just matters where you put the asyncio.run()

vale wing
boreal ravine
#

No

vale wing
#

Bots can't stream videos

junior verge
#

What's the easiest way to get slash commands without changing a lot of your code

vale wing
#

Search+replace

junior verge
#

Yeah but whats the easiest way

vale wing
#

I dunno any other ways

boreal ravine
junior verge
#

Like what library etc

vale wing
#

Just replace the decorators, ctx's, some typehints, do some linting and find if anything was replaced in a wrong way

boreal ravine
zinc phoenix
#

How do I make a list global, I have tried using global queue but when I use it in a command, the program brokes unless I declare that variable in the command part

boreal ravine