#discord-bots

1 messages Β· Page 149 of 1

vale wing
#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

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

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

upbeat basalt
#

this is it @vale wing

uncut flume
#

Can someone help me with this
ClientConnectorCertificateError?

Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, β€˜[SSL: Certificate_Verify_Failed] certificate verify failed: unable to get local issuer certificate (_ssl.c:1131)’]

vale wing
#

@uncut flume

upbeat basalt
#

Do i have to use @tasks.loop?

uncut flume
vale wing
# upbeat basalt https://paste.pythondiscord.com/ozisenusoj

1st and main issue: you must not use blocking requests library in async app. Use aiohttp, check client quickstart on their docs

2nd issue is unoptimized code with tons of weird if-elif-else constructions. For example you could use a better construction instead of this

if "a" in text or "b" in text or "c" in text:```
You need to do
```py
if any(letter in text for letter in ("a", "b", "c")):```

I couldn't understand the logic of all those conditional operators but I am sure after a bit of thinking and restructuring it can be simplified a lot
vale wing
uncut flume
#

Linux Mint

vale wing
#

Ok I'll try to look it up

upbeat basalt
vale wing
#

What country are you running the script from @uncut flume

uncut flume
#

United States

vale wing
#

Ok

upbeat basalt
#

and do i still have to do tasks if i did this?

vale wing
#

!blocking

unkempt canyonBOT
#

Why do we need asynchronous programming?
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.

What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:

import discord

# Bunch of bot code

async def ping(ctx):
    await ctx.send("Pong!")

What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.

async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!

upbeat basalt
vale wing
#

You have background loop, make it proper looking

upbeat basalt
#

Lol now you say so, i do have to wait when i use a different function while its performing the requests

upbeat basalt
timid spade
#

i can use @commands.has_role with role id right?

slate swan
#

indeed

timid spade
vale wing
slate swan
#

you just mention the role ids and names there

#

this works different from the has_permissions deco :p

timid spade
#

oh make soo much sense

#

i read docs for has_permissions

#

lel

vale wing
#

Happens

uncut flume
vale wing
#

Could you give me terminal's output after you executed those commands?

uncut flume
slate swan
#

Yo

vale wing
#

@uncut flume you made a typo I think

slate swan
#

Anybody wants to help me with ChEmIsTrY?

naive briar
#

What is that

vale wing
#

It's update-ca-certificates, plural

slate swan
#

Chemistry πŸ§ͺ

uncut flume
#

You can see me type the command correctly under that line

slate swan
uncut flume
#

I’d suggest finding a homework help discord

upbeat basalt
#
async with session.get(url, headers=headers) as req:
                                                          s = BeautifulSoup(req.text, 'lxml')
``` gives ```File "/home/pi/bot.py", line 367, in testfunc
    s = BeautifulSoup(req.text, 'lxml')
  File "/usr/lib/python3/dist-packages/bs4/__init__.py", line 310, in __init__
    elif len(markup) <= 256 and (
TypeError: object of type 'method' has no len()
slate swan
uncut flume
#

ok

tropic estuary
#

hello does anyone know how to make a inventory in nextcord/discord.py?

naive briar
unkempt canyonBOT
#

coroutine text(encoding=None)```
Read response’s body and return decoded [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") using specified *encoding* parameter.

If *encoding* is `None` content encoding is autocalculated using `Content-Type` HTTP header and *charset-normalizer* tool if the header is not provided by server.

[cchardet](https://aiohttp.readthedocs.io/en/stable/glossary.html#term-cchardet) is used with fallback to [charset-normalizer](https://aiohttp.readthedocs.io/en/stable/glossary.html#term-charset-normalizer) if *cchardet* is not available.

Close underlying connection if data reading gets an error, release connection otherwise.
naive briar
#

Await it

upbeat basalt
#

yeah i already found it but thanks :))

naive briar
#

🐈

vale wing
#

@uncut flume and the export gave no output right?

slate swan
uncut flume
vale wing
upbeat basalt
#

oh

#

yeah i did everything with bs4 now

#

that would be a whole lot of rewriting for an old project lol

vale wing
#

That thing in real() func if I highly oversimplify makes the blocking function async and you can run it without affecting event loop

#

I forgor

naive briar
#

lol

vale wing
#

πŸ’€

slate swan
#

Xd

vale wing
#

Gotta google

#

The heck happened to discord send button

slate swan
#

πŸ˜‚πŸ˜‚

naive briar
#

πŸˆβ€β¬›

#

Bad luck

slate swan
vale wing
#

!d asyncio.loop.run_in_executor

unkempt canyonBOT
#

awaitable loop.run_in_executor(executor, func, *args)```
Arrange for *func* to be called in the specified executor.

The *executor* argument should be an [`concurrent.futures.Executor`](https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor "concurrent.futures.Executor") instance. The default executor is used if *executor* is `None`.

Example:
vale wing
#

πŸ€“

upbeat basalt
#

so i should just place that function in my code like that?

slate swan
slate swan
#

Finally worked

vale wing
#

Please don't "place smth in your code"

#

That sounds unprofessional

upbeat basalt
#

Oh okey, i will implement it in my code

#

like that? XD

vale wing
#

Ye but I didn't mean that

slate swan
#

Copy paste code

upbeat basalt
#

Oh

vale wing
slate swan
#

EZ PZ

upbeat basalt
#

okey

slate swan
vale wing
#

I wonder if anyone collaborated on my ai bot (probably nobody)

slate swan
#

Copy paste always doesn't work 🀷

slate swan
vale wing
#

Yeah, as expected, at least it got +1 star πŸ€—

slate swan
#

Nice

#

🐸

#

So how to use hax

#

!d discord.Interaction

unkempt canyonBOT
#

class discord.Interaction```
Represents a Discord interaction.

An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.

New in version 2.0.
slate swan
#

🀷

vale wing
#

Bro I drank weird coffee now I am farting with rate of 6 fpm

slate swan
vale wing
#

Yeah that's IT schizophrenia

slate swan
#

Hard word to understand with my lil brain

#

;-;

vale wing
#

Psychological disorder

slate swan
#

Ohk πŸ—Ώ

slate swan
vale wing
#

With

slate swan
#

What logging uses for in discord logger

crimson girder
#

can somebody help me with this error

vale wing
#

!d logging

slate swan
#

Idk lol

unkempt canyonBOT
#

Source code: Lib/logging/__init__.py...

uncut flume
#

@vale wing Did you find any solutions?

vale wing
slate swan
#

Cul

reef shell
vale wing
crimson girder
slate swan
vale wing
#

What

slate swan
#

Like session has been resumed or like

#

Ye something like dat

#

Also warning: cant give up error

#

Like this.

vale wing
#

The only payloads you send via ws is heartbeat and the connection establishment/closure payloads

slate swan
#

Any examples? I am bad at understanding xd

vale wing
#

Like Identify, Resume

slate swan
vale wing
uncut flume
slate swan
#

Like listen
Any event when random session resumes pop up in console and bot sends a message or do some specific action on it

#

Any gateway event*

#

!d discordpy.logging

spring needle
#

What’s the logic of modal class

slate swan
#

Be more specific at least for me xd

vale wing
#

@uncut flume do you have openssl installed

uncut flume
#

No

#

Can you send the link?

spring needle
slate swan
#

ahhhhhhhh

#

Like doing more stuff after sending modak

#

hello, can i ask for help in here

#

Modal*, why iam so bad at understanding bruh

brittle ocean
#

I have an image i want to give an x and y axis using matplotlib, however i don't know how to then send the image (with the x & y axes) as a message (nextcord)

#

any ideas as to how to achieve that?

slate swan
vale wing
#

@uncut flume try running openssl version -a

slate swan
#
            while True:
                await channel.send(embed=discord.Embed(title="How much should we expect to receive in USD?", description="eg. $100", color=0x000000))
                usd_amount = await client.wait_for("message", check=lambda x: x.channel==channel and x.author==sender)
                amount = usd_amount.content
                sendt = await channel.send(embed=discord.Embed(title="", description=f"Should we expect to receive $**{amount}** worth of {coin}?", color=0xa3a3a3), components=[Button("Correct"), Button("Incorrect")])
                wtfsent = await sendt.wait_for("button", client)
                if str(wtfsent.component)=="Incorrect":
                    continue
                elif str(wtfsent.component)=="Correct":
                    if sendconfirm==False or receiveconfirm==False:  
                        if str(wtfsent.component)=="Correct":
                            if wtfsent.author==sender:
                                sendconfirm = True
                                await wtfsent.respond(embed=discord.Embed(title="", description=f"{sender.mention} has responded to 'Correct'", color=0x1eff00))
                            elif wtfsent.author==receiver:
                                receiveconfirm = True
                                await wtfsent.respond(embed=discord.Embed(title="", description=f"{receiver.mention} has responded to 'Correct'", color=0x1eff00))
                            elif wtfsent.author==receiver and receiveconfirm==True:
                                await channel.send("ALREADY DONE")
                            elif wtfsent.author==sender and sendconfirm==True:
                                await channel.send("ALREADY DONE")
                            elif receiveconfirm==True and sendconfirm==True:
                                break
                            print(sendconfirm)
                            print(receiveconfirm)
            await channel.send("pro fr")
spring needle
slate swan
vale wing
#

is True better than == True

slate swan
#

i want it to ask the question once, once both people clicks correct it sends "pro fr", if one of the people clicks incorrect, it asks the question again, but the bot is not really doing what i want it to do

vale wing
#

Or if var can only be of bool type like

is_good = True  # can only be True or False
if is_good```
slate swan
spring needle
vale wing
slate swan
#

Yea yea

#

so um if anyone wants to help me, feel free to tell me some Solution

slate swan
#

Where u want it to execute after clicking submit

vale wing
#

I am pretty sure the confusion happens because of them

slate swan
#

Agreeeedd

#

okay.

upbeat basalt
#

@vale wing

vale wing
#

Yes?

upbeat basalt
#

@tasks.loop(seconds=120.0) does this mean 120 seconds after the function inside it has started or 120 seconds after it has finished?

vale wing
#

Every 120 seconds after start() was called

upbeat basalt
#

wait so if i have ```py
@tasks.loop(seconds=120.0)
async def restock():

vale wing
#

That's a question for me too actually πŸ˜‚

upbeat basalt
#

oh, but tasks.loop is infinite right?

vale wing
#

Yeah as long as you don't stop() it or limit the amount of times it needs to be run

upbeat basalt
upbeat basalt
vale wing
#

Correct

upbeat basalt
#

And if i want to run it i don't do restock() but i do restock.start() right?

slate swan
#

@vale wing is this right, does the continue make the code go back to the start of the loop?

vale wing
#

That's right but I am pretty sure wait_for("button") isn't. Iirc discord.py only has on_interaction event

#

!d discord.on_interaction

unkempt canyonBOT
#

discord.on_interaction(interaction)```
Called when an interaction happened.

This currently happens due to slash command invocations or components being used.

Warning

This is a low level function that is not generally meant to be used. If you are working with components, consider using the callbacks associated with the [`View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View") instead as it provides a nicer user experience.

New in version 2.0.
vale wing
#

See

slate swan
vale wing
#

But you shouldn't use event waiting for buttons, views are recommended

vale wing
slate swan
#

or atleast i hope so..? because im using discord==1.7.3

#
@bot.command()
async def removeword(ctx, *, word):
  await ctx.message.delete()
  with open(f"{ctx.guild.id}.json", "r") as f:
    guilds = json.load(f)
  form = f'{word}, '
  form2 = ''
  await removeworld(guilds, ctx.guild, word)
  with open(f"{ctx.guild.id}.json", "w") as f:
    json.dump(guilds, f, indent=4)
  await ctx.send(f"Added the word <> **{word}**.")
async def removeworld(guilds, guild, word):
  form = f'{word}, '
  re.sub(f'{form}', '', '').strip()
#

why wont this remove the words?

vale wing
slate swan
timid spade
#

my drop down menu stops working when i restart my bot
is there any way to fix it?

slate swan
#

no code no answer

brittle ocean
#

ok that was a little harsh dont ya think

slate swan
#

does break exit the loop?

slate swan
#

!d discord.Client.add_view

unkempt canyonBOT
#

add_view(view, *, message_id=None)```
Registers a [`View`](https://discordpy.readthedocs.io/en/latest/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
brittle ocean
#

ok not so simple question.
using matplotlib, i want to give an image x & y axes and then save the result as a png and send it as a message. How do I do that? Im using nextcord btw

slate swan
unkempt canyonBOT
#

class nextcord.File(fp, filename=None, *, description=None, spoiler=False, force_close=False)```
A parameter object used for [`abc.Messageable.send()`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.abc.Messageable.send "nextcord.abc.Messageable.send") for sending file objects.

Note

File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.abc.Messageable.send "nextcord.abc.Messageable.send")s.
slate swan
#

also, matplotlib is blocking so just in case you already don't, throw it into an asyncio executor

brittle ocean
#

ah, okay thx

brittle ocean
vale wing
#

You specifically need whole 1st func and 4 last lines of the 2nd in highlighted lines

#

If they didn't get highlighted, those are 2 last functions in module

brittle ocean
#

oh

#

that's a little bigger than what i expected the solution to be :D

vale wing
#

Not really big

#

Non-async function draws the plot itself, saves it to BytesIO, seeks to 0 to make it readable and returns it, async one runs the blocking in executor so it doesn't affect event loop

slate swan
ember nest
#

Can help to know how can I make bot send message to everyone in the server?

primal token
#

Like in a dm?

ember nest
primal token
#

You shouldn't mass dm members in a server, it's against TOS

ember nest
#

I mean I have a discord bot

#

I want it to dm people if there is event or update etc

#

Dm everyone

primal token
#

Just ping everyone or have an announcement channel or have a special notification role

slate swan
#

ping them in the server πŸ€·β€β™‚οΈ

ember nest
#

Idk but the server owner said he was that dm all feature lol

#

But it's my bot

primal token
#

Tell him it's againsts TOS

ember nest
#

So my bot would get banned or me?

primal token
#

Yes, discord has the right to refuse service by disabling or banning your account

ember nest
#

Oof

#

Nah nevermind then lol

#

I just got my active developer badge don't wanna lose it that fast lol

primal token
#

πŸ¦›

ember nest
#

Sadly I can't view it on mobile tho

primal token
#

why not? The update has already been released

ember nest
#

Hmm really

primal token
#

yep

ember nest
#

Oh yea discord need update lol

#

Lemme update it brb

#

Oh yeah now I can view it

#

Lmao

primal token
ember nest
#

Lmao

#

I'll flex on my girl friend

primal token
ember nest
#

πŸ˜‚

timid spade
silk yacht
#

is there a way to create a background task without a loop? literally everything that comes up when I look for background tasks in discord bots is: @tasks.loop(), but that's not what I'm looking for - I want to be able to run code in the background, while keeping the bot running. I've tried:

task = asyncio.create_task(background_function())
await task

But when the task is awaited, the bot freezes and you can't send any commands to it (it seems the main thread is being blocked by the code being run). Is there a way to put that in the background, have it reply to the user when it's done, and not block the main thread?

naive briar
timid spade
fading marlin
ember nest
#

Is it to make a good looking giveaway slash command hard?

silk yacht
timid spade
fading marlin
#

what're you doing in background_function?

#

it means it's positional only

naive briar
silk yacht
naive briar
unkempt canyonBOT
#

awaitable loop.run_in_executor(executor, func, *args)```
Arrange for *func* to be called in the specified executor.

The *executor* argument should be an [`concurrent.futures.Executor`](https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor "concurrent.futures.Executor") instance. The default executor is used if *executor* is `None`.

Example:
silk yacht
fading marlin
#
await bot.loop.run_in_executor(None, func, ...)
#

that is, assuming func isn't a coroutine

#

otherwise you'd use create_task

silk yacht
# fading marlin otherwise you'd use create_task

in my original message:

But when the task is awaited, the bot freezes and you can't send any commands to it (it seems the main thread is being blocked by the code being run). Is there a way to put that in the background, have it reply to the user when it's done, and not block the main thread?

#

I'll try the run_in_executor though

fading marlin
#

depending on what you're doing, you'd use either run in executor, or create_task. Looping 100,000,000 times is blocking, so you'd use run in executor

silk yacht
fading marlin
#

it doesn't matter what the actual function is. What matters is what the function does

silk yacht
#

ok so two problems then:
the actual code is an exec() function, it's sort of meant to do different things depending on the situation
bot.loop.run_in_executor doesn't do anything at all, I'm wondering if that's because i'm using an extension, and therefore bot doesn't seem to be defined

#

I say that because I ran into a problem with bot not being defined earlier (instead of using bot.command I had to use commands.command)

fading marlin
#

in the example I gave, bot is supposed to be your commands.Bot instance

silk yacht
#

which is not defined in that file, because it's an extension... at least I think

fading marlin
#

if you're in a cog, you've probably defined an attribute called bot

silk yacht
slate swan
#

hm it is, so just use ctx.bot to access the bot

#

you don;t need the bot there actually, you can just ```py
import asyncio

asyncio.get_event_loop()``` to get the event loop

silk yacht
# slate swan you don;t need the bot there actually, you can just ```py import asyncio asynci...

I just tried:```py
loop = asyncio.get_event_loop()
loop.run_in_executor(None, background_run, ctx, code_input, language)

and it says:
```py
/usr/local/Cellar/python@3.11/3.11.0/Frameworks/Python.framework/Versions/3.11/lib/python3.11/asyncio/base_events.py:1910: RuntimeWarning: coroutine 'background_run' was never awaited
  handle = None  # Needed to break cycles when an exception occurs.
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
ember nest
#

Can someone help me to make a slash giveaway command?

fading marlin
#

background_run can't be a coroutine, and you gotta await run_in_executor

silk yacht
#

ah

silk yacht
fading marlin
#

yes, background_run should be a coroutine because of that

silk yacht
#

and using create_task() causes the bot to freeze and stop working temporarily, while the code is running

fading marlin
#

yup

#

well, run_in_executor returns whatever the function that you passed returns, so you could figure something out there

slate swan
#

you can await an run_in_executor as well iirc

silk yacht
naive briar
#
await loop.run_in_executor(...)
#

🐈

silk yacht
slate swan
#

run_in_executor actually returns the result of your background_run which on calling would be a coroutine object, so just add an await before loop.run_in_executor

silk yacht
fading marlin
#

func (backgroun_run) can't be a coroutine, run in executor will just return the coroutine without executing it

silk yacht
#

random thought but could this be solved using threads? or are threads not really built for working with async

fading marlin
#

you shouldn't use threads

slate swan
# silk yacht adding await, it still says background_run isn't awaited and needs to be

you can just expect the result from the executor and send it instead of making the function in executor do it ```py
@staticmethod
async def prepare_image_bytes(
attachment: hikari.Attachment, guild_id: int, channel_id: int
) -> None:
loop = asyncio.get_event_loop()
byted = await loop.run_in_executor(
None, GreetingImage._pillow_conversion, (await attachment.read()), guild_id
)
await bot.rest.create_message(attachment=hikari.Bytes(byted))

@staticmethod
def _pillow_conversion(initial_bytes: bytes, guild_id: int) -> bytes:
    # returns bytes``` like i had this for a project
#

threading/multiprocessing with discord.py doesnt work well

silk yacht
fading marlin
#

is ctx.reply the only thing that's awaitable inside your function?

silk yacht
#

hence, I'm trying what app_commands suggested

fading marlin
#

then you could return whatever you'd pass to ctx.reply

silk yacht
slate swan
silk yacht
#

oh right

#

🀦

slate swan
#

a smol workaround around your issue would be using a double await ```py
await ( await loop.run_in_executor(...))

silk yacht
slate swan
#

gg, now lemme steal your christmas gifts

silk yacht
#

lmao I think I'll pass

fading marlin
slate swan
#

😏 i'll throw it in a gather or create_task then

#

but that;s kinda whole against the point of using the executor

fading marlin
#

wot

slate swan
#

asyncio.gather and asyncio.create_task can process blocking coros without blocking....

ember nest
#

Can someone help me to make a slash giveaway command?

abstract kindle
#

anyone know if button labels can be multiline?

fading marlin
#

they won't render as multiline, but you won't get any errors if you add a new line

cerulean folio
#

Hi guys !

message = 'My message'
image = 'https://www.mysite.com/myimage.png'
await ctx.send(message)

How can I add image to ctx.send(message) as an attachment please? :D

fading marlin
#

you can request the image bytes and throw it to discord.File

#

or use an embed

glad cradle
#

is it pycord?

loud flicker
#

Yes!

slate swan
#

ctx.author._roles should return the list of role ids

gusty mango
#

can somone help with my code

#

File "main.py", line 148
)
^
SyntaxError: invalid syntax

loud flicker
unkempt canyonBOT
#

Hey @gusty mango!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

gusty mango
#

help please

slate swan
#

use a pastebin to paste your code and send

glad cradle
slate swan
gusty mango
#

File "main.py", line 148
)
^
SyntaxError: invalid syntax

glad cradle
gusty mango
#

problem is that

slate swan
gusty mango
#

whats worng with it?

slate swan
#

can;t guess without checking full error

gusty mango
#

line 149 and 147 are

#

wait

#

144-148: type=interactions.OptionType.INTEGER,
required=True,
)
]
)

#

@slate swan that is the line 148

slate swan
#

πŸ‘€ this code doesnt' make sense, what library are you using, and where did you get that code?

glad cradle
#

aliens ig

slate swan
gusty mango
#

heres the full code

#

133-223 is all the code

#

@slate swan can u fix it?

#

?

glad cradle
#

send the full error

gusty mango
#

File "main.py", line 148
)
^
SyntaxError: invalid syntax

#

here

#

thats all the code i sent

glad cradle
#

this is not the full error

#

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

cerulean folio
#

Someone can explain me what's happening here? :o

#

self.post_channel = self.ctx.guild.get_channel(channel_id)

#

I'm passing an int to .get_channel()

gusty mango
#

!error

#

@glad cradle its invalid sytanax error

glad cradle
gusty mango
#

but in replit all i get is that

#

so can u help?

regal cove
#

Why do people get discord developer badges of They don’t develop? A guy wanted to pay me to help him get the badge, That’s such a waste

primal token
#

After all who doest want to be a cool developerpithink

frosty umbra
#
import discord

client = discord.Client()

@client.event
async def on_ready():
    print("Bot is ready!")

@client.event
async def on_message(message):
    if message.content.startswith("/hello"):
        await message.channel.send("Hello, world!")

client.run("YOUR_BOT_TOKEN_HERE")
#

The Ai genuinely understood the assignment which is scary

#

I know its basic but the fact that an AI could understand the task is a little scary

loud flicker
#

Guys, could you please help me with another problem πŸ˜„ So I don't know how to add an image to my status to my discord.py bot (I'm using Py-cord). I tried using Dict but something's not working 😦 (I've tried changing the variable's name to "assets" too, but it's still not working)

cerulean folio
#

my embed.set_image(url=self.proof) somehow isn't working, I've tried to print(self.proof) and it's indeed a valid url I'm confused, can someone help me?

wicked atlas
cerulean folio
wicked atlas
#

Can you show the rest of the code for your embed?

cerulean folio
#

here:

def server_report_embed(self):
    embed = discord.Embed(color = 0xff0000, title = 'Scammer Server')
    embed.set_image(url=self.proof)
    embed.add_field(name = 'Server ID:', value = f"`{self.id}`", inline = False)
    embed.add_field(name = 'Owner:', value = f"{self.owner}\n`{self.owner.id}`\n<@{self.owner.id}>", inline = False)  
    embed.add_field(name = 'Reason:', value = self.reason, inline = False)
    return embed
#

all the other values are working fine and the embed is popping out

#

but the image isn't attached at all

wicked atlas
#

What's the image url?

cerulean folio
#

it varies but it's an image that the bot takes from attachement

#

the image shows in the channel when the command user uses the command and the bot reads it fine

wicked atlas
#

I'm not seeing anything clearly wrong here. self.proof is just a string containing this url?

cerulean folio
#

yeah

cerulean folio
#

I also tried str(self.proof) didn't change anything i'm really clueless

wicked atlas
wicked atlas
cerulean folio
wicked atlas
#

😐

cerulean folio
#

ty for your help tho

wicked atlas
#

πŸ‘

wicked atlas
#

make sure it's assets too, not asset

loud flicker
cerulean folio
#

Guys can server ID and user ID be same? like can they conflit?

wicked atlas
cerulean folio
thorn python
#

Guys, how do I pass an image to a slash command?

fluid zephyr
#

can i get some help as to why this wont run?

hushed galleon
fluid zephyr
#

this right?

hushed galleon
#

i wouldnt say "permissions" since that term often relates to server permissions, privileged intents are their own thing, and if your bot is in 100 servers discord will require you to verify your bot in order to use some of those intents

hushed galleon
# thorn python Guys, how do I pass an image to a slash command?

i havent seen what an attachment option looks like on slash commands before, but if you're using discord.py 2.0 you can typehint one of the parameters with discord.Attachment to make it an attachment option, e.g. py @bot.tree.command() async def my_command(self, interaction, file: discord.Attachment): ... # do something with file

shrewd apex
thorn python
#

Great! Much obliged!

pallid mango
#

getting back into python. could someone catch me up on the status of discord.py? i have an old moderation bot i used for personal purposes. and its no longer working. if anyone could help me out thatd be great. πŸ™‚

indigo pilot
#
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/ext/tasks/__init__.py", line 239, in _loop
    await self.coro(*args, **kwargs)
  File "/home/container/cogs/ticket/timeout.py", line 35, in tickettimeout
    channel = guild.get_channel(ticket['_id']) or await guild.fetch_channel(ticket['_id'])
AttributeError: 'NoneType' object has no attribute 'get_channel'```

why am i getting this error? ive tried guild = self.bot.get_guild and guild = self.bot.get_guild or self.bot.fetch_guild

but its stillr eturning none
#

and the guild isnt none, since ive tried a var that i use in multiple other files and striaght up hard coding the id

hushed galleon
hushed galleon
indigo pilot
hushed galleon
indigo pilot
#

ahh makes sense, so that just wont run the loop till it starts bascily?

hushed galleon
#

yeah

indigo pilot
#

would it be the name of the loop

#

wait nvm

dull horizon
#

hi all, just one very quick question this does not properly ping the user on discord, user_id is holding a string with the discord user's ID, so it will say "@ID" but not ping them, any solution? I use
import discord and
from discord.ext import commands

sick birch
shrewd apex
#

!d discord.ext.commands.Context.send

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...
dull horizon
shrewd apex
#

yes

dull horizon
#

how would i format it into the line of code?

shrewd apex
#

u can mention but if won't ping

#

not sure u can check i never tried

dull horizon
shrewd apex
#

so it will say "@ID" but not ping them, any solution? .

dull horizon
#

?

dull horizon
#

What i mean is that I cant @ the specified user,

#

I want to do
@shrewd apex hi
for example

shrewd apex
#

@dull horizon

#

put it in this format or just discord.Member.mention

dull horizon
shrewd apex
#

whats user_id?

#

show whole code

dull horizon
#

string that holds whatever discord ID i want to specify

shrewd apex
#

show the whole command/function

dull horizon
#

honestly now that im testing it, could just be a logical problem because it wont even do this @dull horizon, bot does not respond

sick birch
dull horizon
#

This is the program as a whole

from discord.ext import commands
import time
import asyncio
import random as rand
import os
compliments = ["1","2","3"]
client = discord.Client(intents=discord.Intents.default())
bot = commands.Bot(intents=discord.Intents.all() , command_prefix= "!")
user_id = "360933425361715200"                               
def getToken():
    token = open('token.txt','r').read()
    return token
token = getToken()

@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.author.id == 360933425361715200:
      await message.channel.send(format(message.author.mention) + " " +  compliments[rand.randint(0,2)])
      
  if message.content.startswith("!sayhi"): 
    await message.channel.send(f"<@{user_id}>" + "hi")
  
  if message.content.startswith("!compliment"): #roastList[rand.randomint(len(roastList))]
      await client.send_message(message.channel, compliments[rand.randint(0,2)] % user_id)
  
  if message.content.startswith("!randomkick"):
    if rand.randint(1, 20) == 1:
        await message.channel.send("Bye Friend")
        discord.kick(user_id)
    
    if rand.randint(1, 20) != 1:
        await message.channel.send(format(message.author.mention) + " " + "Roll again!")

client.run(token)```
#

token.txt just holds the bot token

#

if the user that i target says anything in chat, they will be complimented from a list i have not fully specified yet, that part works. But the ! commands do not work

shrewd apex
#

this is stuff of my nightmares @sick birch all for u

#

imma dip

abstract kindle
#

any good pagination examples?

crimson pulsar
dull horizon
#

wait i think ur on to something

#

how would i start that

loud flicker
crimson pulsar
#
@client.command()
async def sayhi(ctx, args):
  await message.channel.send(f"{ctx.author.mention} hi")```
#

try this

dull horizon
#

can i do without ctx? i already have other imports

crimson pulsar
#

ctx is the context passed with the command

sick birch
slate swan
#

help plz

shrewd apex
#
from discord.ext import commands
import random

bot = commands.Bot(intents=discord.Intents.all() , command_prefix= "!")

user_id = 360933425361715200

                               
def getToken() -> str:
    token = open('token.txt','r').read()
    return token

token = getToken()

@bot.event
async def on_ready():
  print(f"We have logged in as {bot.user}")


@bot.event
async def on_message(message: discord.Message) -> None:
  if message.author == bot.user:
    return
  if message.author.id == user_id:
      await message.channel.send(f"{message.author.mention} {random.randint(1,3)}")
   await bot.process_commands(message)
      
@bot.command()
async def sayhi(ctx: commands.Context) -> discord.Message:
    await ctx.send(f"Hi {ctx.author}!")
  

bot.run(token)```
#

@dull horizon

#

figure the rest out urself

vale wing
#

Dpy 2.0 has support for components, no need for third-party libs

slate swan
#

okay thx

slate swan
#

help

vocal snow
#

not sure where you got that code from, but you should try to find an updated version

naive briar
#

Good advice ducky_tube

vocal snow
slate swan
#

IT DID

vocal snow
#

maybe print it and see what's in it

slate swan
#

Ohhhh

#

from utils.database import Database

anyone know why this import isnt working for me? Ive tried to pip install a couple things but hasnt worked

#

Is there any error message

#

when i try pip install db-utils I get this

#

but idk for sure if db-utils is the install that will make
from utils.database import Database be read as a module

naive briar
#

!pip db-utils

unkempt canyonBOT
slate swan
#

!pip googletrans

unkempt canyonBOT
slate swan
#

O.o

#

:c

shrewd apex
# slate swan :c

click the link in the error and install c tools how much more obvious does the error message need to be

#

update if u already have it

slate swan
#

pip install databases ?

#

or is this the right one

#

everything is updated

shrewd apex
#

what?

#

from utils.database import Database is prolly not a package its likely a module or another py file in the project

slate swan
#

that makes sense thank you

crimson horizon
#

Hi guys

#

Is it possible to make a modal input that only accepts numbers? (Without checking when the user clicks send, I mean directly)

slate swan
#

nah you would have to manually check. no way to force a user to input an int

crimson horizon
#

No, it has to be a modal

slate swan
#

yeah he was trying to avoid that

rare echo
crimson horizon
#

Okay

slate swan
#

send a Rick roll if they enter non-int value 🀺

crimson horizon
#

I wanted to make it like this

crimson horizon
#

And can a Discord Modal have a text only field? (without input)

#

@slate swan

loud junco
#

who knows a platform that doesnt rate limit πŸ’€

#

even railway.app rate limits me

summer flume
slate swan
naive briar
timid spade
#
class persistenetViewBot(commands.Bot):
    def __init__(self):
        intents = discord.Intents().all()
        super().__init__(command_prefix = '^', intents = intents)
        async def setup_hooks(self) -> None:
            self.add_view(View())

client = persistenetViewBot()

i used this code from internet to keep drop down menu working
but i am getting error for adding the prefix second time
idk how the code works so i need help

naive briar
#

What's the error

timid spade
#

when i use a command i get this

#

i tired setting prefix to none but it ended up having more errors

naive briar
#

Then the command just simply doesn't exist

#

Read the error

timid spade
#

well it does
the program is calling the command 2 times
one for client = commands.Bot(command_prefix='^', intents = intents)
and for second time in persistent

naive briar
#

What does that mean

timid spade
#

ok wait
i think i have a fix (nvm dint work)

alpine cove
#

lol

timid spade
# naive briar What does that mean

i defined the client on start of program
but the code i copied for persistent is defining client again at the end of program before client.run
thats causing the error

naive briar
#

What

timid spade
#

make sense now?

#

eh

slate swan
#

multiple client instances moment

timid spade
#

yes that

#

thanks

#

i tried others methods of making it persistent but none worked
this one is wroking but with an error everytime a run a command

glad cradle
timid spade
#

idk what i did there
i just copied pasted it.
i will learn how it works later for now i just wanna run my bot

slate swan
#

you copy pasted it wrong

glad cradle
whole sparrow
#

is there a limit on how many times you can edit a message?

slate swan
whole sparrow
glad cradle
pliant gulch
#

Other than that if you stick in 5/5s there is no limit

slate swan
#

But u can give like character limits

crimson horizon
#

I meant to give information

#

like a 2nd title

slate swan
#

discord renders the (0) so poorly in the preview

slate swan
#

Do it πŸ’€

#

32 character limit

#

Sedge

#

lambda*

#

Hmm

pliant gulch
#

bot.on_error=lambda*_:sleep(0)

#

30 chars just removed whitespace

slate swan
#

no spaces fk.pep 8

#

!pip fuk

unkempt canyonBOT
slate swan
#

πŸ’€

#

!pip spooky

unkempt canyonBOT
slate swan
#

O.o

slate swan
pliant gulch
#

Loaded up stable diffusion and immediately heard my GPU fans rev like a motorcyle

slate swan
#

Cul

#

I am just now used with those noise πŸ—Ώ

slate swan
slate swan
pliant gulch
#

Ligands are fun, learned them during my second year or first year of college I'm not sure exactly when

#

Negative feed back loop diagrams might look weird at first but they get easy

#

In a biology context not chemistry

slate swan
#

andy pro biologist

#

Chemistry as always fun, unless some hard chemical reaction 🀷

pliant gulch
#

Yes

#

I majored biology not computer science

slate swan
#

WHAT'S INSIDE THE FROG DUDE TELL MEEE AHH

pliant gulch
#

Organs and stuff

slate swan
#

Cul

#

Anything special? πŸ—Ώ

pliant gulch
#

There are some frogs that have been bred to have transparent skin

#

Allowing students to easier practice on them

slate swan
#

;-;

#

yo Andy, how do you manage to use attrs with pyright ;-;, I'm sick of it already

#

pyright is treating attrs as dataclasses for some what idk reason

pliant gulch
#

attrs is dataclass

slate swan
pliant gulch
#

Holdon let me load up a test env

slate swan
#

also had reportImportCycles under TYPE_CHECKING but ignored it

pliant gulch
#

You can just go into pyproject.toml and ignore reportImportCycles if on strict

#

Also for the attrs thing yea that isn't supported

#

I thought this was for some other stuff like annotations with field()

pliant gulch
#

Can you explain more about your _bar thing

#

Are you trying to make _bar as private var

slate swan
#

but ended up doing so in the end

pallid mango
#

can someone walk me through main.py, for a discord bot. i have all my cogs but for some reason everytime i try to setup my main i just keep getting errors (i would imagine because idk the new discord.py)

slate swan
#

show code and whats the error?

pallid mango
#

okay one second

#

Traceback (most recent call last): File "main.py", line 39, in <module> client.run(os.getenv("Aura")) File "/home/runner/Lost-Aura/venv/lib/python3.8/site-packages/discord/client.py", line 828, in run asyncio.run(runner()) File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/asyncio/runners.py", line 44, in run return loop.run_until_complete(main) File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete return future.result() File "/home/runner/Lost-Aura/venv/lib/python3.8/site-packages/discord/client.py", line 817, in runner await self.start(token, reconnect=reconnect) File "/home/runner/Lost-Aura/venv/lib/python3.8/site-packages/discord/client.py", line 745, in start await self.login(token) File "/home/runner/Lost-Aura/venv/lib/python3.8/site-packages/discord/client.py", line 580, in login data = await self.http.static_login(token) File "/home/runner/Lost-Aura/venv/lib/python3.8/site-packages/discord/http.py", line 801, in static_login data = await self.request(Route('GET', '/users/@me')) File "/home/runner/Lost-Aura/venv/lib/python3.8/site-packages/discord/http.py", line 680, in request raise HTTPException(response, data) discord.errors.HTTPException: 429 Too Many Requests (error code: 0): You are being blocked from accessing our API temporarily due to exceeding our rate limits frequently. Please read our docs at https://discord.com/developers/docs/topics/rate-limits to prevent this moving forward.

naive briar
#

Rate limited

slate swan
#

short answer: don't use replit

naive briar
pallid mango
#

rate limited, my solution was to just "kill 1" in console

pallid mango
#

do you guys host directly off your client or do you use something else?

slate swan
#

i don't host my bot projects

silk fulcrum
pliant gulch
pallid mango
slate swan
silk fulcrum
pliant gulch
#

So, obj.client should be "immutable"

slate swan
#

How do i do something when user clicks a reaction

silk fulcrum
slate swan
#

Howww????

silk fulcrum
#

!d discord.ext.commands.Bot.wait_for

unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.11)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.11)") for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.11)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
errant pecan
#

how do I move a global variable to another file ?

unkempt canyonBOT
#
Not likely.

No documentation found for the requested symbol.

slate swan
silk fulcrum
#

!d discord.ext.commands.Bot.listen

unkempt canyonBOT
#

@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready")

The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.11)").

Example...
silk fulcrum
pliant gulch
#

Also TIL attrs strips _ from the attributes

silk fulcrum
#

there is an example in it

slate swan
#

imo

errant pecan
#
@bot.event
async def on_ready():
    global tdict
    tdict = {}

@bot.event
async def on_voice_state_update(member, before, after):
    author = member.id
    if before.channel is None and after.channel is not None:
        print('1')
        t1 = time.time()
        tdict[author] = t1
    elif before.channel is not None and after.channel is None and author in tdict:
        t2 = time.time() 
        print('0')
        print(t2-tdict[author])```
how do I get a variable out of here and move it to another file ?
slate swan
#

thanks

pliant gulch
#

But it get's a bit more complex

silk fulcrum
#

if txt, then just open it and write

errant pecan
#

move to the file where the command is located, that is, the .py file

silk fulcrum
#

uhm... you could just import it in the file where your command is, but if this variable changes during the bot runtime, then you would need a db or a JSON file to store it

errant pecan
silk fulcrum
#

which file

errant pecan
silk fulcrum
#

alrdy told you?

errant pecan
whole sparrow
#

Hey guys, im using disnake and autocomplete. Im using a subcommand so its /mvp timer but I want to also make an autocomplete for another thing called miniboss so /miniboss timer

#
    @timer.autocomplete("name")
    async def mvp_name_autocomp(self, inter: disnake.ApplicationCommandInteraction, string: str):
        string = string.lower()
        if len(string) == 0:
            return []
        return [i for i in MVP_NAMES if string in i.lower()[0:len(string)]]
silk fulcrum
whole sparrow
#

How do I make autocomplete for /miniboss

silk fulcrum
#

just store in json

#

you already picked that method iirc

naive briar
whole sparrow
#

theyre sub commands

#
    @commands.slash_command()
    async def mvp(self, inter:disnake.CommandInteraction): ...
    
    @commands.slash_command()
    async def miniboss(self, inter:disnake.CommandInteraction): ...
    
naive briar
#

And what's the problem

errant pecan
# silk fulcrum just store in json

and what exactly then do I need to write in the command where the time in the voice is written {what will I need to write in these brackets ?}

whole sparrow
#

so i want a different autocomplete for the timer command

#

cause its going to be

#
@mvp.sub_command()
async def timer():

@miniboss.sub_command()
async def timer():
naive briar
#

Just set a different name for the callback function

#

And set the name kwarg in sub_command decorator

silk fulcrum
whole sparrow
errant pecan
# silk fulcrum you don't know how to read json files?

not work...

dateFormat = "%d/%m/%Y %H:%M:%S"

@bot.event
async def on_voice_state_update(member, before, after):
        with open('data/voice_leaderboard.json', 'r') as file:
            voice_data = json.load(file)
            new_user = str(member.id)
            guild_id = str(member.guild.id)
            
        # Update existing user
        if new_user in voice_data[guild_id]:
            voice_leave_time = datetime.datetime.time().strftime(dateFormat)
            voice_join_time = voice_data[guild_id][new_user]

            calculate_time = (datetime.datetime.strptime(voice_leave_time, dateFormat) - datetime.datetime.strptime(voice_join_time, dateFormat))

            voice_data[guild_id][new_user] = str(calculate_time)

            with open('data/voice_leaderboard.json', 'w') as update_user_data:
                json.dump(voice_data, update_user_data, indent=4)

        else:
            if member.bot:
                return
            else:
                new_voice_join_time = datetime.datetime.utcnow().strftime(dateFormat)
                voice_data[guild_id][new_user] = new_voice_join_time

            with open('data/voice_leaderboard.json', 'w') as new_user_data:
                json.dump(voice_data, new_user_data, indent=4)```
silk fulcrum
#

!doesntwork

#

oh they still haven't added this tag

#

sadness

#

wait that's not what i meant

#

ok so what i mean is u gotta send your problem too

#

not only code, i dont wanna guess, what is your error

errant pecan
#

@silk fulcrum does it seem to me or is it impossible to do this in python at all ?

silk fulcrum
#

there's solution to anything

#

that's how programming works

#

that's almost how world works

#

except for the part where it doesnt

#

other than that, world also works like that

naive briar
#

Relatable

errant pecan
#

@silk fulcrum I've been trying to do this for oh, oh, how long and I don't understand how. And I perceive the words read the documentation as (I'm a shit who only knows how to send to the documentation)

silk fulcrum
errant pecan
silk fulcrum
#

by the way, if you would mind coming back to your problem a little bit, what error do you get? And if you don't get one, what do you expect from your program and what happens instead?

errant pecan
silk fulcrum
#

Yeah, I was expecting it to be a problem with a filename

#

I also had lots of those

vale wing
#

Man read it

#

Yall beginners are like "OMG CRAZY BIG RED TEXT SCARY ima ask pro ppl who aren't scared"

#

It's easy

vale wing
#

Also you gave 2 tracebacks

ember nest
#

How to make command only work for me (bot owner)

silk fulcrum
#

I don't know how is it correctly done, but I myself just go to the file in a file manager, and right click it, and choose "Properties" > "Details" and copy the Folder path, then just write the name of the file after it

#

oh Russian

naive briar
#

!d discord.ext.commands.is_owner

unkempt canyonBOT
#

@discord.ext.commands.is_owner()```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that checks if the person invoking this command is the owner of the bot.

This is powered by [`Bot.is_owner()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.is_owner "discord.ext.commands.Bot.is_owner").

This check raises a special exception, [`NotOwner`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NotOwner "discord.ext.commands.NotOwner") that is derived from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
vale wing
#

I forgor ext πŸ’€

ember nest
#

This work for slash command?

silk fulcrum
#

forgorable, understanrable

silk fulcrum
naive briar
#

🐈

silk fulcrum
#

what

ember nest
#

Lol

vale wing
#

How the heck is that called

errant pecan
silk fulcrum
#

?rtfd is_owner

#

ah bro whyyy

ember nest
#

Hmmm

silk fulcrum
vale wing
#

Dpy placed app commands decos into another module for no reason, why not just make common ones compatible with them like in disnake πŸ’€

silk fulcrum
ember nest
#

I still don't know tho how to make command only for bot owner (slash command)

naive briar
#

Just make your own check at this point

silk fulcrum
#

yeah this

naive briar
#

!d discord.app_commands.check

unkempt canyonBOT
#

@discord.app_commands.check(predicate)```
A decorator that adds a check to an application command.

These checks should be predicates that take in a single parameter taking a [`Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction"). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure "discord.app_commands.CheckFailure") exception is raised and sent to the appropriate error handlers.

These checks can be either a coroutine or not.

Examples

Creating a basic check to see if the command invoker is you...
vale wing
silk fulcrum
#

I just made a normal text command for only myself, i dont need slash commands as an owner

#

what

vale wing
#

Dpy has lots of nonsense stuff that's why I prefer disnake

vale wing
#

🦡😳🦡

ember nest
vale wing
#

Dpy fork

silk fulcrum
#

not cus i have nothing to do, I just enjoy making my own things

#

except for something big, like a discord bot

vale wing
silk fulcrum
#

but you know, i started it

silk fulcrum
upbeat gust
slate swan
#

🌳

upbeat gust
#

Everyone will see

#

Make a text command, or sync to a testing guild or smth

vale wing
#

"Full sync control" which commonly ends up just as a thing you always gotta do, no shortcuts for inter.response.send and inter.followup.send (again they call it "more control" but I see it as an inconvenience). I like their modals implementation tho

#

Separate checks for app commands for no reason (correct me if there is)

slate swan
#

WASSUP

#

pycord tried to fix the same things( 2nd point) by wrapping app interactions to a context and now thats a bad impl

#

the only design mess i feel about dpy is having a single interaction class for all interaction types

vale wing
#

That too

#

Disnake has differentiation of interaction related events like on_button_click which removes the need for additional checks

slate swan
upbeat gust
slate swan
slate swan
vale wing
#

Even tho as a relatively experienced developer I can use dpy with no problems, disnake offers many things that make development faster and more comfortable

slate swan
vale wing
#

Mentioned above

slate swan
#

fair to say disnake is the best fork

#

pycord users stay mad

#

my bot.wait_for("reaction") doesn't work at all

slate swan
vale wing
slate swan
#

oh wait yeah that too

#

i do have bothh

#

reaction_add as exenifix said

slate swan
vale wing
slate swan
vale wing
#

!d discord.Intents.reactions

unkempt canyonBOT
slate swan
#
reaction = bot.wait_for("reaction")
await bot.add_reaction("▢️")
if reaction == "▢️":
   print("go ahead")

is anything wrong with it

slate swan
slate swan
upbeat gust
#

Please pay attention to chat

slate swan
#

noo i have done the reaction_add on the real code

upbeat gust
#

Why don't you show us your real code

slate swan
#

you don't have a proper check, your reaction is probably just getting ditched cause bot tracked another reaction already

slate swan
# upbeat gust Why don't you show us your real code
    msg = await ctx.send(embed=page1)
    await msg.add_reaction("◀️")
    await msg.add_reaction("▢️")
    i = 1  
    r = await bot.wait_for("reaction", timeout=30)
    await msg.edit(embed=pages[i])
    if r == "▢️":
         if i < 10:
           i += 1
           await msg.edit(embed=pages[i])
    elif r == "◀️":
         if i > 1:
           i -= 1
           await msg.edit(embed=pages[i])
vale wing
upbeat gust
#

Oh yeah you don't have a check

slate swan
#

how do i check

slate swan
slate swan
unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.11)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.11)") for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.11)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
upbeat gust
#

!d discord.Client.wait_for

vale wing
#

Yeah I read that thx

upbeat gust
#

There are examples here

vale wing
#

When the 2 waitfors

slate swan
#

πŸ†’

slate swan
vale wing
#

@slate swan are you done with your project

#

What's it about btw

cedar fulcrum
#

What library do u guys use for your bots

cedar fulcrum
winged linden
#

Wym

cedar fulcrum
#

When dpy died

#

There were some forks that continue dpy development

winged linden
#

Its back

cedar fulcrum
#

I know

winged linden
#

Development continued

winged linden
sick birch
winged linden
#

Same

sick birch
#

However now there are options like disnake or nextcord

winged linden
#

disnake grumpchib

cedar fulcrum
sick birch
#

I've never used either

#

So I can't give an accurate opinion

#

Though disnake seems to be the most popular

cedar fulcrum
#

Oh

#

Hmmm

slate swan
cedar fulcrum
#

I heard of that tho

slate swan
#

i use it because of the low level API it provides

cedar fulcrum
#

But the development is sleepy there ,

slate swan
cedar fulcrum
#

But the code is clean

slate swan
#

they released forums just yesterday

cedar fulcrum
#

Sleepy ash

#

Lol

slate swan
#

the development is slow because there's less contributors and the code quality is much higher than average

#

i feel lost when i read their src

cedar fulcrum
primal token
#

Theres a difference in quality and complexity ducky_beer

slate swan
cedar fulcrum
#

LMFAO

slate swan
#
#

released yesterday

#

its a bit buggy on phone

cedar fulcrum
#

Because fuck rtfd

slate swan
#

i prefer the old hikari docs tbh but yeah this ones easier

#

search was broken in old one

primal token
slate swan
primal token
#

I like simple abstractions what can i say

winged linden
slate swan
#

i noticed pycord changes their docs theme too

#

they're using furo instead of the custom discord.py theme

slate swan
winged linden
#

I was going to say, its extremely easy to learn and use

#

I didnt watch a video I just read the docs and came here if I had an issue

primal token
slate swan
#

dark theme toggle is what i used it for

#

but i prefer mkdocs over sphinx now

primal token
#

I want to try mkdocs tbh

polar dawn
#

Hi just wanna ask what should I pass in for ctx?
I kept getting this error:

TypeError: expected string or bytes-like object

Here's what I tried:

h = commands.MemberConverter()
mem = await h.convert(ctx, argument=user.id)
vocal snow
slate swan
vocal snow
#

also curious where you're getting user from

polar dawn
vocal snow
#

it's a command parameter?

polar dawn
vocal snow
#

if so, you can typehint it to discord.Member and get a Member object directly

#

(discord.py uses MemberConverter for the conversion)

polar dawn
#

So I want to convert it to discord.Member if the user is in the server

#

rather than discord.User

mellow verge
#

Can someone help me? My bot isn’t online

import nextcord 
import asyncio 
from config import TOKEN

class CreateTicket(nextcord.ui.view):
    def __init__(self):
        super().__init__(timeout=None)
    
    @nextcord.ui.button(
        label="Create Ticket", style=nextcord.ui.Buttonstyle.Blurple, custom_id="create_ticket:blurple"
    )
    async def create_ticket(self, button: nextcord.ui.Button, interaction: nextcord.Interaction)
        await interaction.response.send_message("A ticket is being created...", ephemeral=True)

class Bot(commands.Bot):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.persistent_views_added = False

    async def on_ready(self):
        if not self.persistent_views_added:
            self.add_view(CreatTicket()) 
            self.persistent_views_added = True
            print("Persistent views added")

        print(f"Bot is up and ready | Logged in as {self.user}")

bot = Bot(command_prefix='!', intents = nextcord.Intents.all())

@bot.command()
@command.has_permission(manage_guild=True)
async def setup_tickets(ctx: commands.Context):
    embed = nextcord.Embed(title="Create a ticket!", description="Click the `Create Ticket` button below to create a ticket. The server's staff wil be notified and shortly aid you with your problem")
    await ctx.send(embed=embed, view=CreateTicket())    
bot.run(TOKEN)```
#

And where do I need to insert my token?

polar dawn
mellow verge
#

Main

polar dawn
mellow verge
#

Is it then fixed?

polar dawn
#

ahh mb i didnt saw your import

#

do you have a config file

mellow verge
#

Euhm no

#

What do you mean by that?

polar dawn
mellow verge
#

Oh idk

polar dawn
mellow verge
#

I watched a tutorial

polar dawn
uncut flume
#

@vale wing I figured out the issue by the way, thank you for the help!

polar dawn
#

so
bot.run("YOUR TOKEN HERE")

uncut flume
mellow verge
#
import nextcord 
import asyncio 
from config import TOKEN

class CreateTicket(nextcord.ui.view):
    def __init__(self):
        super().__init__(timeout=None)
    
    @nextcord.ui.button(
        label="Create Ticket", style=nextcord.ui.Buttonstyle.Blurple, custom_id="create_ticket:blurple"
    )
    async def create_ticket(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
        await interaction.response.send_message("A ticket is being created...", ephemeral=True)

class Bot(commands.Bot):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.persistent_views_added = False

    async def on_ready(self):
        if not self.persistent_views_added:
            self.add_view(CreateTicket()) 
            self.persistent_views_added = True
            print("Persistent views added")

        print(f"Bot is up and ready | Logged in as {self.user}")

bot = Bot(command_prefix='!', intents = nextcord.Intents.all())

@bot.command()
@commands.has_permission(manage_guild=True)
async def setup_tickets(ctx: commands.Context):
    embed = nextcord.Embed(title="Create a ticket!", description="Click the `Create Ticket` button below to create a ticket. The server's staff wil be notified and shortly aid you with your problem")
    await ctx.send(embed=embed, view=CreateTicket())    
#

Can someone please help me with that. My bot isnt online! ^^^

ionic edge
mellow verge
#
import nextcord 
import asyncio 
from config import TOKEN

class CreateTicket(nextcord.ui.view):
    def __init__(self):
        super().__init__(timeout=None)
    
    @nextcord.ui.button(
        label="Create Ticket", style=nextcord.ui.Buttonstyle.Blurple, custom_id="create_ticket:blurple"
    )
    async def create_ticket(self, button: nextcord.ui.Button, interaction: nextcord.Interaction)
        await interaction.response.send_message("A ticket is being created...", ephemeral=True)

class Bot(commands.Bot):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.persistent_views_added = False

    async def on_ready(self):
        if not self.persistent_views_added:
            self.add_view(CreatTicket()) 
            self.persistent_views_added = True
            print("Persistent views added")

        print(f"Bot is up and ready | Logged in as {self.user}")

bot = Bot(command_prefix='!', intents = nextcord.Intents.all())

@bot.command()
@command.has_permission(manage_guild=True)
async def setup_tickets(ctx: commands.Context):
    embed = nextcord.Embed(title="Create a ticket!", description="Click the `Create Ticket` button below to create a ticket. The server's staff wil be notified and shortly aid you with your problem")
    await ctx.send(embed=embed, view=CreateTicket())    
bot.run(TOKEN)```
mellow verge
mellow verge
#

I get these Errors

vale wing
#

Sounds like venv issue to me

mellow verge
#

?

vale wing
ionic edge
#

install the nextcord modules

mellow verge
mellow verge
vale wing
#

Ok take a ss of whole screen

mellow verge
#

Okay?

vale wing
#

πŸ‘

ionic edge
#

left side of VSC

vale wing
#

Bro

ionic edge
#

Locate the file

vale wing
#

You need to open a folder with this file

ionic edge
#

you dont even have the config.py file in the directory

mellow verge
vale wing
vale wing
mellow verge
vale wing
#

Alr perfect

#

Now those issues disappeared but what is from config import TOKEN

mellow verge
#

Idk i did what the guy said in the video

vale wing
#

Fyi hardcoding token into project is bad for security πŸ€—

ionic edge
vale wing
#

Lemme fetch a guide on tokens for you rq

ionic edge
#

reset the token brother

mellow verge
mellow verge
ionic edge
#

good

mellow verge
#

So now it needs to work

vale wing
mellow verge
#

Ty

slate swan
#

yo

#
@commands.has_permissions(administrator=True)
async def purge(ctx, limit: int):
        await ctx.channel.purge(limit=limit)
        await ctx.send('Cleared by {}'.format(ctx.author))
        await ctx.message.delete()

@purge.error
async def clear_error(ctx, error):
    if isinstance(error, commands.MissingPermissions):
        await ctx.send("You can't do that!")```
#

this is my code, but when i want to clear it deletes my clear message too (!clear NUMBER)

#

and i want to not count the !clear NUMBER and delete the 'Cleared by {}'.format(ctx.author) after some seconds

#

how do i do that?

regal cove
#

how do you answer a "/" so that everyone on the server can see it?

rare echo
#

based on defaults im assuming first one and im not sure its possible unless you add it into the bot response

#

interaction.bot.get_guild no?

regal cove
rare echo
#

should be just interaction.client.get_channel

#

im not 100% but im 90% sure itll get the category if thats the id passed

regal cove
rare echo
upbeat basalt
#

How can i make a task that doesn't start again after certain seconds? Because thats handled in the function itself with while true. If i let tasks.loop handle it the list i need for the next iteration won't be saved, and then i would have to use global so regular tasks.loop basically isn't an option

#

Could you maybe do @tasks.loop(seconds=None) or something?

naive briar
#

Why are you even using a while loop in the task

upbeat basalt
#

If i let tasks.loop handle it the list i need for the next iteration won't be saved, and then i would have to use global

#

i have a loop existing of 2 parts that creates 2 lists, i need the second created list in the next iteration but if i don't use the while loop with regular tasks this function runs again and then final_list (the second created list) is set to null. If i don't do it there it will be undefined```py
async def restock():
logchannel = bot.get_channel(960147355691253800)
await logchannel.send('Restock monitor on')
global fl_oos
global sizeoos
final_list = []
count = 0
fcount = 0
global restockkk
restockkk = True

upbeat basalt
fading marlin
#

!d discord.CategoryChannel.text_channels you can iterate through these and check if any have the user's username as its name

unkempt canyonBOT
slate swan
#

Good evening, I'm looking for a way to integrate a key/license system for the script associated with my bot discord to prevent it from being re-shared

#

You can help me ?

gusty mango
honest shoal
slate swan
# ionic edge use delete_after()

so

@commands.has_permissions(administrator=True)
async def purge(ctx, limit: int):
        await ctx.channel.purge(limit=limit)
        await ctx.send('Cleared by {}'.format(ctx.author), delete_after(10s))
        await ctx.message.delete()

@purge.error
async def clear_error(ctx, error):
    if isinstance(error, commands.MissingPermissions):
        await ctx.send("You can't do that!", delete_after(10s))```
#

?