#discord-bots

1 messages · Page 88 of 1

slate swan
#

?

#

ehm..

#

i said like thrice

#

I'm blind..

#

oh last thing how do I make it be in embed? @slate swan

#

!d discord.Embed use this class and construct an embed, later send it using the embed kwarg in .send method

unkempt canyonBOT
#

class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.

len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.

bool(b) Returns whether the embed has any data set.

New in version 2.0.

x == y Checks if two embeds are equal.

New in version 2.0...
slate swan
#
bot.responses = ["WRHEGIRHGH", "GRWHUGRHEAGUH", "FHSUGHUAGU", "FREHUGHEU", "RWGHUEHGU", "GREHIUGHA", "RIGEWFWUAN",
                 "GHERIGHWOD", "GERIAGHI", "GHDIAGH", "GHFDSIGH", "GREGQJOF", "GWEGHUSI", "GWRHGUIHA", "HGIHIGRIS"]


@tasks.loop(hours=2)
async def drops():
    await bot.wait_until_ready()
    channel = bot.get_channel(986712676019359835)
    embed = discord.Embed(title="100 CHAKRA DROP!", description=f"First one to dm Mecha Naruto {}")

#await channel.send(random.choice(bot.responses))

drops.start()```
slate swan
#

whats the issue then

#

do I do it like this

#

embed = discord.Embed(title="100 CHAKRA DROP!", description=f"First one to dm Mecha Naruto {bot.responses} will win")

#

yeah

#

that's correct

#

ayo @slate swan it just sent all codes

#

I need it to send one randomly

limber bison
#

intreaction not wotking why ?

slate swan
slate swan
#

do I just write

#

{random.choice bot.responses} or what

#

how did you do that here?

slate swan
#

this is embed

slate swan
vale wing
slate swan
#

YESSS

vale wing
limber bison
#

still not working

vale wing
#

You need to move it out

limber bison
#

my mistake

limber bison
vale wing
#

Not completely remove

#

This is dpy right?

limber bison
#

like this

limber bison
vale wing
#

Iirc its view doesn't have callback as well

#

!d discord.ui.Button.callback

unkempt canyonBOT
#

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

The callback associated with this UI item.

This can be overridden by subclasses.
slate swan
#

views only have on_interaction iirc

silk fulcrum
#

in dpy yes

lavish fog
silk fulcrum
#

pycord is not an available choice at all

vale wing
#

@limber bison you need to either use @discord.ui.button decorator for each button or make Button subclass

silk fulcrum
#

its just... yeah

lavish fog
vale wing
lavish fog
#

oh

#

well ill try discordpy then

#

thanks

rich geyser
#

hello! how to store data in json file from score with update

limber bison
#

i am using loops

primal token
quaint epoch
#

!d json.dump

unkempt canyonBOT
#

json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)```
Serialize *obj* as a JSON formatted stream to *fp* (a `.write()`-supporting [file-like object](https://docs.python.org/3/glossary.html#term-file-like-object)) using this [conversion table](https://docs.python.org/3/library/json.html#py-to-json-table).

If *skipkeys* is true (default: `False`), then dict keys that are not of a basic type ([`str`](https://docs.python.org/3/library/stdtypes.html#str "str"), [`int`](https://docs.python.org/3/library/functions.html#int "int"), [`float`](https://docs.python.org/3/library/functions.html#float "float"), [`bool`](https://docs.python.org/3/library/functions.html#bool "bool"), `None`) will be skipped instead of raising a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError").

The [`json`](https://docs.python.org/3/library/json.html#module-json "json: Encode and decode the JSON format.") module always produces [`str`](https://docs.python.org/3/library/stdtypes.html#str "str") objects, not [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") objects. Therefore, `fp.write()` must support [`str`](https://docs.python.org/3/library/stdtypes.html#str "str") input.

If *ensure\_ascii* is true (the default), the output is guaranteed to have all incoming non-ASCII characters escaped. If *ensure\_ascii* is false, these characters will be output as-is.
quaint epoch
#
import json
import asyncio
import aiofiles

content = {'test': 'test'}

async def main():
  async with aiofiles.aopen('file.json', 'w') as file:
    json.dump(content, file)
asyncio.run(main())
dull terrace
#

how would i do py list(x, x + 1, x - 1 for x in a_list)

quaint epoch
#

with a local db you could do ```py
import sqlite3

conn = sqlite3.connect('STRING HERE')
conn.execute('CREATE TABLE IF NOT EXISTS scores (primary_key INT PRIMARY KEY NOT NULL, extra_data TEXT NOT NULL)')
conn.execute('INSERT INTO scores VALUES (?,?)', (1, 'test'))
conn.commit()
conn.close()

#

forgor 💀

dull terrace
#

!e

print(list(x + i for i in range(-1, 2) for x in a_list))```
quaint epoch
#

what are you trying to do

#

also incorrect syntax

#

and you need to zip it

#

print(*(x+i for i,x in zip(range(-1,2), a_list)))

dull terrace
#

what do you mean incorrect syntax, it worked as expected

quaint epoch
#

!E
a_list = [1, 2, 3, 4]
print(list(x + i for i in range(-1, 2) for x in a_list))

unkempt canyonBOT
#

@quaint epoch :white_check_mark: Your 3.11 eval job has completed with return code 0.

[0, 1, 2, 3, 1, 2, 3, 4, 2, 3, 4, 5]
quaint epoch
#

what

#

that's valid?

primal token
#

How would it not be valid?

primal token
unkempt canyonBOT
primal token
#

👍

crimson compass
#

how can i make it so that the bot only allows commands to be send in one channel

#

anyone?

sage otter
#

you can use a check.

#

!d discord.ext.commands.check

unkempt canyonBOT
#

@discord.ext.commands.check(predicate)```
A decorator that adds a check to the [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or its subclasses. These checks could be accessed via [`Command.checks`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command.checks "discord.ext.commands.Command.checks").

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

If an exception should be thrown in the predicate then it should be a subclass of [`CommandError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError"). Any exception not subclassed from it will be propagated while those subclassed will be sent to [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error").
sage otter
#

for you it would look like something along the lines of

def some_check(ctx) -> bool:
    return ctx.channel.id == someidhere
limber bison
#

anyone help me with this ?

#

buttons added but intraction failed

slate swan
# limber bison

because the callback won't ever trigger, does it print ok?

limber bison
#

not printing ok

#

how i trigger them

slate swan
#

you'll have to set the callbacks manually

#

inside the for loop

limber bison
#

but i dont know how many buttons command will create !

limber bison
#

pls

slate swan
#
''' let this be inside the for loop '''
button = discord.ui.Button(...)
button.callback = self.callback
buttons.append(button)
self.add_item(button)

''' then inside the callback you can remove the loop that checks for the buttons '''

''' remove the following part '''
for i in self.buttons:
  if i == buttons
''' remove this part and unindent the rest of your code '''
#

this would be actually cleaner

#

@limber bison .

slate swan
#

great!

limber bison
#

let me try thanks

slate swan
#

sure

crimson compass
#

how do i mention a channel?

vale wing
#

<#id>

#

!d discord.TextChannel.mention code variant

unkempt canyonBOT
maiden chasm
#

can someone help me pls. I coded a discord bot but visual studio dont know "import discord , and from discord.ext"

#

is says no definition for discord

shadow vigil
#

lol

maiden chasm
sick birch
shadow vigil
atomic rose
#

I would just use sublime text editor and windows power shell

shadow vigil
cerulean thistle
atomic rose
#

test the import and make sure you got them installed...visual studio could be using a different version of python then the one you installed the packages on for discord

#

hey if your on windows it's not horrible

maiden chasm
#

ah fuck iam dumb ass fuck i didnt even installed power shell thank you all for your help

atomic rose
#

yea you'll def want to get powershell going vs the regular command line

sick birch
#

Set up a venv just to be sure

#

Setting up a venv is always good practice and you should do it always anyway

wanton fractal
wanton fractal
#

or you've installed discord.py on the wrong interpreter

atomic rose
#

yea to see for sure you can goto where python is installed and check the directory that holds installed packages

maiden chasm
#

python is not working when i wanna open it "failture, please enable dc overlay"

#

can someone help ,me

sick birch
maiden chasm
maiden chasm
#

Sorry for dm

sick birch
short silo
#
discord.abc.Messageable.fetch_message(msg_id)

What am i doing wrong ?

short silo
#

error : Missing a positional argument 'id'.

sick birch
#

For instance, a discord.TextChannel, or a discord.VoiceChannel

slate swan
#

how to whitelist someone on my bot by doing .whitelist (id)

slate swan
#

and then an on_command event to check if the command invoker is actually whitelisted or blacklisted

slate swan
#

how to fix anyone know?

#

maybe commands.permissions instead of commands.has.permissions ?

sick birch
unkempt canyonBOT
#

@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member has all of the permissions necessary.

Note that this check operates on the current channel permissions, not the guild wide permissions.

The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions").

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

fixed it i need to do has_permissions

#

how to whitelist someone on my bot by doing .whitelist (id)

primal token
slate swan
primal token
slate swan
#

oh

primal token
#

😅

slate swan
#

but how do i do cuz i dont understand..

sick birch
#

to_d["fields"] has less than 4 elements

#

Access a valid element, so something less than 3

#

Yes

#

Try 1, then 0

#

If both of those don't work it's an empty list

slate swan
#

Hello how do i make a bot only work when you whitelist
Example:
.whitelist @slate swan
bot: succesfully whitelisted Lordoxez into ids.json

gusty shard
#
prsnc = ["Ping me!", f"On {str(len(bot.guilds))} servers!", "Crypto Stuff will be added soon 😶", "wtf is that smell?"]

@tasks.loop(seconds=120)
async def change():
    act = discord.Activity(type=discord.ActivityType.watching, name=random.choice(prsnc))
    await bot.change_presence(status=discord.Status.do_not_disturb, activity=act)```
it's not changing the presence, can somebody help me?
gusty shard
#

add something like that to every command

slate swan
ionic edge
#

Theme??

gusty shard
#

wdym

faint sapphire
#

yo
within a check function of apy @bot.event async def on_message(message):function
am I allowed to make the check function an async function?
cause i wanna check the user ID given in a message

primal token
#

Just use the check/code that's inside the function inside the event?!?!?

faint sapphire
#

its just on discord.py docs the check function u see there isnt async

wicked atlas
#

I'd say the easiest way to find out is to try it

faint sapphire
#

which doesnt allow me to get user from id

#

ight true

primal token
faint sapphire
#

oh i didnt know that yields

#

i thought it just checks if true or false for the check function

primal token
#

the check kwarg takes a callable that returns bool but you can just check the object Bot.wait_for returns which it depends on which you specified

faint sapphire
#

ok thanks

slate swan
#

Hello how do i make a bot only work when you whitelist
Example:
.whitelist @Lordoxez
bot: succesfully whitelisted Lordoxez into ids.json

primal token
# faint sapphire ok thanks

In this case it would be a message object, but it seems like you're hard coding this functionality, what are you trying to do?

rare echo
slate swan
rare echo
#

run cmd, get user id add it into json or db wtv you are using then u need to check if they exist in said db when they run a cmd

primal token
#

Should use a db

rare echo
slate swan
rare echo
#

ok lol

faint sapphire
primal token
faint sapphire
#

is it ok to use a while loop within a py @bot.event async def on_message(message): that verifies if a```py
msg2 = await bot.wait_for('message')


im not using check cause i want to do stuff like `bot.get_user`
#

ah but the while loop is prob not an async thing

hushed galleon
potent vector
#

Hello I’m trying to make a machine learning bot for a discord. I’ve made it with basic commands- how do I make sure it saves when I input commands in python? How do I import to discord. I’ve already imported a bot with predetermined if/else commands before

faint sapphire
#

ight thanks

sick birch
#

a while True with a wait_for is functionally equivalent to an on_message

faint sapphire
#

anyone sees something wrong
even when ids provided are wrong it moves on

its meant to check user ids exist, if they dont the check isnt meant to be positive

hushed galleon
#

wait_for checks cant be async

faint sapphire
#

ah

#

then ill return the wait_for message and check the msg there in a while loop, and not use the check

#

if the person cancels the trade ill verify if the message contains that too to end the loop

hushed galleon
#

id definitely consider refactoring this into a separate function you can call and storing a bot var to keep track of active tickets

#

your on_message is going to get real complicated if its all being done in one place

faint sapphire
#

so like aiosqlite?

hushed galleon
#

if it could potentially be a long-running ticket (where your bot might restart) sure you can keep track of tickets there

faint sapphire
#

ight, thanks for the advice

sick birch
#

Python doesn't do typechecking

primal token
#

!d discord.ext.commands.Context

unkempt canyonBOT
#
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.

This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.

This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable "discord.abc.Messageable") ABC.
primal token
#

Thats its type if youre looking to annotate it

sick birch
#

If you're asking for the right type hint, then it's commands.Context

indigo pilot
#

discord.ext.commands.errors.HybridCommandError: Hybrid command raised an error: Command 'edit' raised an exception: AttributeError: 'FursonaEdit' object has no attribute 'to_components'

anyone know why

#

nvm im dumb

slate swan
#

i need help with a bot that talks when a new channel is opened and it puts a button saying hi or bye

unkempt canyonBOT
#
Not in a million years.

No documentation found for the requested symbol.

unkempt canyonBOT
#
NEGATORY.

No documentation found for the requested symbol.

sick birch
#

ok guess not

torn sail
#

!d discord.on_guild_channel_create

unkempt canyonBOT
#

discord.on_guild_channel_delete(channel)``````py

discord.on_guild_channel_create(channel)```
Called whenever a guild channel is deleted or created.

Note that you can get the guild from [`guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel.guild "discord.abc.GuildChannel.guild").

This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
slate swan
#

ok ty

#

i just started python lol

#

also im trying to make it so after they press the button the bot sends an embed and asks the person to send the persons dev id then it adds them to ticket

slate swan
#

e.g I can only edit 1 message 5 times every 5 seconds.

#

Or can I edit multiple messages

#

Basically, I'm just trying to say, do messages have individual limits, or does it apply to the bot

sick birch
slate swan
#

Damn it!

#

Okay 😦

sick birch
#

Well.. discord isn't a game platform..

slate swan
#

😠 Who said it's not

indigo pilot
#

is it possible to send two emebds in one msg

#

nvm

sick birch
#

That's the second question you've asked and said "nvm" to lol..
the answer is yes, but I suppose you figured that out already

slate swan
#

is there a way i can make it so when i type someones dev id the bot adds the person to ticket

#

im basicaly making a multi tasking ticket tool

#

Someone help me use the API

fickle hamlet
fickle hamlet
#

Buckets are determined based on a few major parameters used for each endpoint, a ratelimit is dependent on the bucket formed. Let's say I send a message in channel with an id 123, I would access the message creation endpoint via channels/123/messages. That has now become a bucket, so any further messages in THAT channel will take a use off the bucket's ratelimit

#

For instance, the message ratelimit currently for sending is 5/5s that means in each channel I could send 1 message per second if your library handles bucket ratelimiting

#

But this is encapsulated by the global ratelimit, meaning you cannot exceed 50 requests a second

#

So it's a make of half and half, your original question that is.

primal token
winged dock
#
@bot.command()
async def slots(ctx, amount=None):
    slots = ['bus', 'train', 'horse', 'tiger', 'monkey', 'cow']
    slot1 = slots[random.randint(0, 5)]
    slot2 = slots[random.randint(0, 5)]
    slot3 = slots[random.randint(0, 5)]

    slotOutput = '| :{}: | :{}: | :{}: |\n'.format(slot1, slot2, slot3)

    ok = discord.Embed(title = "Slots Machine", color = discord.Color(0xFFEC))
    ok.add_field(name = "{}\nWon".format(slotOutput), value = f'You won {2*amount} coins')


    won = discord.Embed(title = "Slots Machine", color = discord.Color(0xFFEC))
    won.add_field(name = "{}\nWon".format(slotOutput), value = f'You won {3*amount} coins')
    

    lost = discord.Embed(title = "Slots Machine", color = discord.Color(0xFFEC))
    lost.add_field(name = "{}\nLost".format(slotOutput), value = f'You lost {1*amount} coins')


    if slot1 == slot2 == slot3:
        await update_bank(ctx.author, 3 * amount)
        await ctx.send(embed = won)
        return

    if slot1 == slot2:
        await update_bank(ctx.author, 2 * amount)
        await ctx.send(embed = ok)
        return

    else:
        await update_bank(ctx.author, -1 * amount)
        await ctx.send(embed = lost)
        return

Error - undefined variable update_bank

#

but im not sure how i should define it.

primal token
#

?

winged dock
#

I need help w that

primal token
#

Its used as an asynchronous function? If you're asking about its functionality we cant really help much as it depends on your abstractions and its purpose

winged dock
#

Well i tried defining it but i got loads of errors like you cannot assign a await function etc

#
#i did this
update_bank==ctx.author
slate swan
#

and its only 1 game per server.

#

1 edit a second

sick birch
# slate swan This is only for 3-4 servers O_O

I think a better alternative would be to move the snake once a user clicks on a button. There should be no ratelimits that way as you're just responding to an interaction, and you should be able to have as many servers as possible running it

slate swan
primal token
#

Your friends are boring

#

😤

sick birch
#

sheeeesh

slate swan
#

Well guess what!

primal token
#

What

slate swan
#

I agree 😭

primal token
slate swan
#

So my plan was to make this bot for my friends, in 2 languages.

#

Java and python just for some experience and learning of syntax

#

After I do that, I plan on releasing one globally that will fail and only get like 1 server invite 😦

#

And after I do that 😭 I'll work on a starcraft 2 machine learning bot

#

not rlly ml but... idk

primal token
slate swan
#

I just want to grasp all of them. Know basic syntax

#

write basic programs, experiment

#

see what I like, and do it 🙂

#

Right now I love python for it's simplicity.

#

I also like C++ because it makes me feel like a professional.

primal token
slate swan
#

Yes.

#

I FIND DOING USELESS THINGS INTERESTING 😦

primal token
slate swan
primal token
#

Me too!

slate swan
#

Oh, in that case, yes that was not a joke.

minor ivy
#
@client.command()
async def person(ctx):
    message = await ctx.send("Please wait while image generates...")
    now = datetime.now()
    print(f'Person command was used at {now.strftime("%m/%d/%Y %H:%M:%S")}')
    r = requests.get("https://thispersondoesnotexist.com/image")
    image_file = io.BytesIO(r.content)
    file1 = Image.open(image_file).convert('RGB')
    file1.save("Img/person.PNG")
    file=discord.File("Img/person.PNG", filename="person.PNG")
    await message.edit(content=file)
#

Help please :(

naive briar
minor ivy
#

Thats what someone else told me and it just spit out a long exception error

naive briar
minor ivy
#

while im at it, why does this

@client.command()
async def person(ctx):
    r = requests.get("https://thispersondoesnotexist.com/image")
    image_file = io.BytesIO(r.content)
    file1 = Image.open(image_file).convert('RGB')
    await ctx.send(file1)
#

Result in this?

#

Those are 2 separate messages

primal token
#

I'm pretty sure thats how discord formats messages now or always has? Blockingio😩

minor ivy
#

But why does it send the <PIL.Image.image part instead of just the image

primal token
#

because thats probably the object's repr and a valid url that got embeded, you should use discord.File which expects a bytes like object in its constructor iirc

torn sail
#

!d discord.Message.edit

unkempt canyonBOT
#

await edit(*, content=..., embed=..., embeds=..., attachments=..., suppress=False, delete_after=None, allowed_mentions=..., view=...)```
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.

Changed in version 2.0: Edits are no longer in-place, the newly edited message is returned instead.

Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") instead of `InvalidArgument`.
minor ivy
#

Its now just sending the image seperately and still not editing

rare echo
#

or use delete_after

slate swan
#
asyncio.run() cannot be called from a running event loop
#
async def input(self, direction: str) -> None:
        valid = is_valid(self.previous_direction, direction)
        
        if valid:
            self.previous_direction = direction
            self.direction = direction
            
            if self.started is False:
                self.started = True
                while self.lost is False:
                    await run(self.move)
                    await asyncio.sleep(1)
#
async def move(self) -> None:
        # Miscellaneous
        y_increment, x_increment = self.TRANSLATIONS[self.direction]
        
        # Movement
        self.head = (self.head[0] + y_increment, self.head[1] + x_increment)
        
        # Pop tail
        self.tail.insert(0, self.previous_head)
        self.tail.pop()
        
        # Update self.previous_head
        self.previous_head = self.head
        
        # Edit post
        await self.post(edit = True)
#

btw run is imported from asyncio

naive briar
slate swan
#

to thread an async function

naive briar
slate swan
#

it might delay every thijng

naive briar
#

asyncio.run also can delay everything

slate swan
#

oh

slate swan
slate swan
#

@sick birch I apologize but are you here to help, I'm sorry for bothering you everytime

sick birch
#

sure what's up

dull terrace
slate swan
#

My new issue is that I'm not able to end the game after it's done.

dull terrace
#

how do you mean

slate swan
#

As in

#

my main.py file uses a class from a different file, and that different class handles all the logic.

#

After the player wins or loses, I have to set their game value to None, but my main.py is not able to identify when it's done.

#

can anyone help me with API's

#

There is no trigger

dull terrace
#
if game_value is None:
   break
```?
slate swan
#

nono

slate swan
slate swan
slate swan
#

{'message': "Authentication failed! The request must include a valid and non-expired bearer token in the 'Authorization' header."}

dull terrace
#

ooo you're having an issue getting the variable into the relevant file?

slate swan
dull terrace
#

no, Christopher

slate swan
slate swan
#

But that dictionary is in main.py, not in the class file

dull terrace
#

yeah, move it to a new file then import it into both files

#

or put it in the main logic file and import it into main

slate swan
sick birch
slate swan
dull terrace
#

put the variable into the logic file then import snake then you can do snake.dictionary_name to access it

slate swan
#

The thing is, after the game is done, main.py has no way of knowing so it cant set the

sick birch
#

Just import the necessary functions and classes from snake.py

slate swan
#

!paste

slate swan
unkempt canyonBOT
#

Pasting large amounts of code

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

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

slate swan
#

Snake class ^

sick birch
dull terrace
slate swan
dull terrace
#

yes, move the dict to snake christopher

sick birch
slate swan
#

ok

dull terrace
#

then to access the dictionary you just do snake.dictionary_name

slate swan
#

It's used to keep track of their games open

#

Would that still work?

dull terrace
#

then i would move it to a config.py or central place that you can import into all of them

#

you can run into issues with circular imports otherwise

#

just make sure you dont do from config import dictionary_name because that creates a new object

spring needle
#

How to make a function that do something like: Type a command first, the bot replies, and type a message, and bot respond to that message?

slate swan
#

!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.10)"). 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.10)") 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.10)") 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**...
slate swan
#
while GAMES_OPEN[interaction.user.id].lost is False:
            await asyncio.sleep(1)
        GAMES_OPEN[interaction.user.id] = None
#

while loops are blocking fyi

#

they block everything?

#

right

dull terrace
slate swan
#

yeah nvm didnt see that

#

but I don't see why you would need a loop to just manipulate values

slate swan
#

I want to make my bot so people have to authorize the bot and I can make them join severs

#

Just like a restore bot

wanton fractal
#

do you mind explaining in detail

slate swan
#

Alright, so they verify and authorize the bot, doing that gives us access to pull them to our new server

wanton fractal
#

yes

slate swan
#

Like those

wanton fractal
#

you mean like grant access to their account?

#

oh yeah that's something to do with oauth2 grant

slate swan
#

How would I code that Lmao

wanton fractal
#

if i'm correct

#

well overral you would need the grant for it, when they authorize access to their account

#

i believe its by using an access token

slate swan
#

How do I code it lol

wanton fractal
#

i can try to help you, i'm intrigued by this

wanton fractal
#

well you would obviously need to use json and sessions

#

what ide do you use, visual studio code or pycharm?

slate swan
#

Pycharm

wanton fractal
#

so do i

#

we'll talk in dms, accept my friend request

robust fulcrum
#
import requests

url = "https://discord.com/api/v8/channels/893363878728192041/messages"
data = {"content": "hi navi"}
header = {"Authorization": f"Bot {token}"}

resp = requests.post(url,data=data,headers=header)
print(resp.status_code)

Guys why i am getting 404 status code?

shrewd apex
#

its just the token i think no need to add Bot

robust fulcrum
shrewd apex
#

check ur token and credentials

robust fulcrum
shrewd apex
#

check link then idk i haven't used discord api directly before pithink

#

and in class so can't check docs

slate swan
slate swan
robust fulcrum
slate swan
#

nice

robust fulcrum
#

So?

robust fulcrum
slate swan
#

Alright, so I have this modal:py class get_ad(discord.ui.Modal): def __init__(self): super().__init__( discord.ui.InputText(style = discord.InputTextStyle.long, label = "Enter your Advertisement", placeholder = "Maxium of 250 characters, 5 lines.", max_length = 250), title = "Advertisement", timeout = None) async def callback(self, interaction: discord.Interaction): await interaction.response.pong() and when open it using ```py
modal = get_ad()
await ctx.send_modal(modal)

slate swan
#

oh wait is that py-cord lmao

#

Yeah

placid skiff
#

is ctx an interactionResponse?

native reef
#

Hi

#

Write a program to prompt the user for hours and rate per hour using input to compute gross pay. Pay the hourly rate for the hours up to 40 and 1.5 times the hourly rate for all hours worked above 40 hours. Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75). You should use input to read a string and float() to convert the string to a number. Do not worry about error checking the user input - assume the user types numbers properly.

native reef
placid skiff
#

!rule 5

unkempt canyonBOT
#

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

placid skiff
#

oh wait fail

#

!rule 8

unkempt canyonBOT
#

8. Do not help with ongoing exams. When helping with homework, help people learn how to do the assignment without doing it for them.

limber bison
#

I have n button in list , now i want to to set there callback , like if button possition in list is 0 then send 0 on discord so on ! How can I achieve?

unkempt canyonBOT
#

exception discord.NotFound(response, message)```
Exception that’s raised for when status code 404 occurs.

Subclass of [`HTTPException`](https://discordpy.readthedocs.io/en/latest/api.html#discord.HTTPException "discord.HTTPException")
robust fulcrum
placid skiff
#

Yeah but that's the same exception D_D

#

I would send you links but my google searches on Italian sites D_D

dull terrace
#

401 is invalid credentials

robust fulcrum
#

But i got 404

placid skiff
#

It's not found D_D
can be both the channel or the token

robust fulcrum
placid skiff
#

i suggest you to try some easier API, since discord ones are pretty advanced, so you can learn requests and responses D_D

robust fulcrum
placid skiff
#

LMAO the id of an user is not the ID of his channel
When you use a bot and do await User.send you call the send method that before sending the message to the user it creates a DMChannel, once the channel is created the bot can send the message

wicked linden
#

Hi

#

can i have / commands only for a particular channel instead of a server or a particular grp of people

#

like i want the command only for admin

#

I have #admin channel and @admin role in my server but i dont want that / command to be known by others

placid skiff
unkempt canyonBOT
#

@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member has all of the permissions necessary.

Note that this check operates on the current channel permissions, not the guild wide permissions.

The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions").

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

!d discord.ext.commands.has_role

unkempt canyonBOT
#

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

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

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

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

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

Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
austere vale
#
  @commands.Cog.listener()
  async def on_message_edit(self,before,after):
    if not after.author.bot:
      if before.content != after.content:
        embed=nextcord.Embed(title="Message edit",description=f"Edit by {after.author.mention} in {before.channel.mention} {before.jump_url}", color=0xfd9fa1, timestamp=datetime.datetime.utcnow())
        fields=[("Before",before.content,False),("After",after.content,False)]
        for name, value, inline in fields:
          embed.add_field(name=name,value=value,inline=inline)
        chan = self.bot.get_channel(933978399280599080)
        await chan.send(embed=embed)

what does this error mean?

slate swan
#

before.content or after.content was none

placid skiff
# wicked linden I have `#admin` channel and `@admin` role in my server but i dont want that / co...

For channels i think that you will have to create a custom check, this is the structure:

from discord.ext.commands import check, CheckFailure
from discord import Context

class MyCustomCheckError(CheckFailure):
  def __init__(self, message):
    self.message = message
    super().__init__(message=self.message)

def my_check():
  def predicate(ctx: Context):
    if ctx.author.id != ctx.guild.owner_id:
      raise MyCustomCheckError("only the owner of the guild can execute this command")
  return check(predicate)
wicked linden
slate swan
#

that will just leave it to admins and owners

wicked linden
#

oh smart

placid skiff
placid skiff
#

!d disnake.Embed.check_limits lmao disnake is on another level

unkempt canyonBOT
#

check_limits()```
Checks if this embed fits within the limits dictated by Discord. There is also a 6000 character limit across all embeds in a message.

Returns nothing on success, raises [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.10)") if an attribute exceeds the limits...
robust fulcrum
#

Guys is it possible to make a api in my discord bot
Like a api using flask when anyone hit that api my bot sends a message
How to make?

slate swan
#

create the api using flask, on the request invocation use the discord REST API and create a message

#

why is the time shifted?

robust fulcrum
slate swan
#

how do i fix this? i just updated the discord.py to the newest version

#

and its showing this now

placid skiff
#

now it's InteractionResponse, but it is edit_message without original, you can get the InteractionResponse object by Interaction.response

#

!d discord.Interaction.response

unkempt canyonBOT
#

Returns an object responsible for handling responding to the interaction.

A response can only be done once. If secondary messages need to be sent, consider using followup instead.

placid skiff
#

!d discord.InteractionResponse.edit_message

unkempt canyonBOT
#

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

Responds to this interaction by editing the original message of a component or modal interaction.
slate swan
#

or edits a message at all unless deleting counts as editing

placid skiff
#

bruh the error is saying that you are trying to use the edit_original_message method with an Interaction object D_D

robust fulcrum
#

Guys how i can dm a user with its id in dpy?

slate swan
#

if .send @rich otter
member: discord.member, arg
await member.send(arg)

slate swan
#

something like this?

placid skiff
#

Bruh what package are you using D_D
what is that from discord.commands import Option? that doesn't exist

slate swan
robust fulcrum
slate swan
#

it used to work

placid skiff
slate swan
placid skiff
#

Yeah VS is telling to you that Option is not recognized

#

in fact it doesn't exist D_D

slate swan
#

wait how was it working then

placid skiff
#

what version of d.py was that code?

slate swan
#

2.0

placid skiff
#

2.0 is the new

slate swan
#

i think

#

yes

placid skiff
#

i want the old one, when you coded that

slate swan
#

that was coded in 2.0

#

i think its 2.0.1 now

placid skiff
#

Bruh Option didn't exist in 2.0 neither

slate swan
#

how was it working im confused

#

that aint make sense

placid skiff
#

and the commands module is child of the ext module

slate swan
#

im on discord 2.1.0a

#

from discord.py==2.1.0a4599+g68607181)

placid skiff
#

Well, the code is wrong D_D

slate swan
#

i guess so

#

ok so then i need help please

#

how would i make the / option type of command

#

so it shows options

#

self, interaction: discord.Interaction, opt: Option(str, choices = ["Tickets Channel","Commands Channel","Verification Channel","Joins Channel"], required = True),

placid skiff
#

!d discord.app_commands.AppCommand.options

unkempt canyonBOT
slate swan
#

so like what this used to be

#

ohhh

primal token
placid skiff
slate swan
slate swan
#

YES THIS IS WHAT I WAS LOOKING FOR TOO THANK YOU VERY MUCH

slate swan
#
async def setupchannels(self, interaction: discord.Interaction, opt: discord.app_commands.AppCommand.options(str, choices = ["Tickets Channel","Commands Channel","Verification Channel","Joins Channel"], required = True), channel: discord.TextChannel):
TypeError: 'member_descriptor' object is not callable```
#

is interaction the member_descritpor

placid skiff
#

app commands are a mess with d.py, do you want to add an OptionList? or that the parameters of the command are showed when you type /command ?

naive briar
#

What's this

naive briar
slate swan
placid skiff
#

yup this one

slate swan
#

OHHHH

#

this user that literal

#

wait nvm

naive briar
unkempt canyonBOT
#

examples/app_commands/transformers.py lines 80 to 89

# In order to support choices, the library has a few ways of doing this.
# The first one is using a typing.Literal for basic choices.

# On Discord, this will show up as two choices, Buy and Sell.
# In the code, you will receive either 'Buy' or 'Sell' as a string.
@client.tree.command()
@app_commands.describe(action='The action to do in the shop', item='The target item')
async def shop(interaction: discord.Interaction, action: Literal['Buy', 'Sell'], item: str):
    """Interact with the shop"""
    await interaction.response.send_message(f'Action: {action}\nItem: {item}')```
slate swan
#

alrighty thank you both

limber bison
#

!e print(f"{number:03}")

unkempt canyonBOT
#

@limber bison :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | NameError: name 'number' is not defined
limber bison
#

!e print(f"{7:03}")

unkempt canyonBOT
#

@limber bison :white_check_mark: Your 3.11 eval job has completed with return code 0.

007
limber bison
#

got ir

#

got it

edgy tundra
#

I'm getting this error🙄

placid skiff
#

then don't use replit D_D

edgy tundra
naive briar
slate swan
#

How to tag someone with discord.py in message.

Example
@slate swan
Embed:
Here's your daily reward!
DM me /claim to claim ur rewards

crimson compass
slate swan
vocal snow
#

on_command_error is a global error handler... not a command specific one

edgy tundra
crimson compass
vocal snow
#

!d discord.ext.commands.MissingPermissions

unkempt canyonBOT
#

exception discord.ext.commands.MissingPermissions(missing_permissions, *args)```
Exception raised when the command invoker lacks permissions to run a command.

This inherits from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
vocal snow
#

you can access the permissions missing through the exception obj ^

primal token
#

!d discord.ext.commands.Context.author

unkempt canyonBOT
edgy tundra
#

!invite

#

🙂

primal token
#

@unkempt canyon is exclusive to this server, but you can check out its src by using !src in #bot-commands

crimson compass
#

@vocal snow

light jungle
#

Who can tell me how to make a button that removes the last message?

placid skiff
slate swan
#

F

#

i wanna add them in fiedlds

#

fields***

light jungle
placid skiff
unkempt canyonBOT
slate swan
#
@app_commands.choices(channelchoices = [
        Select(name = 'Tickets Channel'),
        Select(name = 'Commands Channel'),
        Select(name = 'Joins Channel'),
        Select(name = 'Chat Channel'),
        Select(name = 'Verify Channel'),
        Select(name = 'Vouch Channel')
    ])
    async def setupchannels(self, int: discord.Interaction, channelchoices: Select[int], channel: discord.TextChannel):```
#

Select is showing up yellow scribbles

placid skiff
#

Select class is under ui modules, it is not used with commands

slate swan
#
@app_commands.command()
@app_commands.describe(fruits='fruits to choose from')
@app_commands.choices(fruits=[
    Choice(name='apple', value=1),
    Choice(name='banana', value=2),
    Choice(name='cherry', value=3),
])
async def fruit(interaction: discord.Interaction, fruits: Choice[int]):
    await interaction.response.send_message(f'Your favourite fruit is {fruits.name}.')```
placid skiff
#

because it is not choice neither D_D

slate swan
#

.-.

slate swan
placid skiff
#

readed choice lowercase sorry, you have to import it

#

!d discord.app_commands.Choice

unkempt canyonBOT
#

class discord.app_commands.Choice(*, name, value)```
Represents an application command argument choice.

New in version 2.0.

x == y Checks if two choices are equal.

x != y Checks if two choices are not equal.

hash(x) Returns the choice’s hash.
slate swan
#

from discord.app_commands import Choice?

placid skiff
#

yup

slate swan
#

that fixed it thank you

primal token
#

mentions != pings

placid skiff
#

cuz I forget to add the descriptions before D_D

primal token
placid skiff
#

So the components which has the user highlighted can have the mention inside the embed, So the author, the title, the field name and the footer cannot have a mention inside them.
Even if the mention is highlighted, the mentioned user will not receive any ping or notification from the mentions inside the embed

pulsar solstice
honest shoal
pulsar solstice
honest shoal
#

nope

pulsar solstice
#

or format?

honest shoal
#

it's just like how u do in github

honest shoal
#

and you can only have them in embeds and webhooks

short silo
#

I have the category ID, need to fetch that category to make a channel in.
how would i do that ?

slate swan
#

get_channel or fetch_channel

short silo
slate swan
#

categories are channels

short silo
pulsar solstice
#

I wanna make a avatar command that will send a person's avatar

#

CODE:

#
@bot.command()
async def avatar(ctx, *, avamember: discord.Member = None):
    if avamember == None:
        embed = discord.Embed(description='❌ Error! Please specify a user', color=discord.Color.red())
        await ctx.reply(embed=embed, mention_author=False)
    else:
        userAvatarUrl = avamember.avatar_url
        embed = discord.Embed(title=('{}\'s Avatar'.format(avamember.name)), colour=discord.Colour.red())
        embed.set_image(url='{}'.format(userAvatarUrl))
        await ctx.reply(embed=embed, mention_author=False)
#

Error:

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

PLS HELP ME OUT

short silo
placid verge
#

hello, im trying to make a ticket bot. my problem is that if someone selects for example report section, then they can't select it again. they have to select something else and then click report. ( as you see there is a checkmark next to report because its already clicked ) how can do that so when someone selects a section, their selection gets removed?

limber bison
#

!e f"{365:02}"

unkempt canyonBOT
#

@limber bison :warning: Your 3.11 eval job has completed with return code 0.

[No output]
limber bison
#

!e print(f"{365:02}")

unkempt canyonBOT
#

@limber bison :white_check_mark: Your 3.11 eval job has completed with return code 0.

365
slate swan
#

how do i convert a exe file to python ???

limber bison
#

!e print(f"{5:02}")

unkempt canyonBOT
#

@limber bison :white_check_mark: Your 3.11 eval job has completed with return code 0.

05
placid verge
placid verge
honest shoal
placid verge
limber bison
#

how to add role to a member ?

#

single role

naive briar
unkempt canyonBOT
#

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

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

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

why tf is this getting a error

#
url=ctx.guild.icon_url```
#

literally

#

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

naive briar
unkempt canyonBOT
limber bison
# unkempt canyon

interaction.user.add_roles([5673479347694876202358]) @naive briarlike this ?

pulsar solstice
limber bison
#

or ([discord.object(id)])

naive briar
#

!d discord.Asset.url

unkempt canyonBOT
pulsar solstice
#

I am getting this error

#

because I coded this:

embed.set_thumbnail(url=discord.Guild.icon) 

naive briar
#

You have to get the url from it first

embed.set_thumbnail(url=guild.icon.url)
pulsar solstice
#

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

slate swan
naive briar
#

Then the guild has no icon

limber bison
#

how to add single role to a member

tidal hawk
limber bison
tidal hawk
#

First you gotta get the role object - role = guild.get_role(4567498426694927) and then await member.add_roles(role)

naive briar
#

Or role

tidal hawk
#

oh you can do it with an id?

naive briar
#

Can't remember pithink

limber bison
tidal hawk
#

no idea

placid verge
slate swan
#

yea that's exactly what you had to do

limber bison
# slate swan nope

await interaction.user.add_roles([interaction.guild.get_role(1021123493804384266)])
this ?

slate swan
#

shouldn't be a list

limber bison
#

this right

#

dont say no pls

slate swan
#

its correct

primal token
#

But error prone

limber bison
#

How can I disconnect a member from vc ?

edgy tundra
placid skiff
unkempt canyonBOT
#

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

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

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

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

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

what is this error how i slove it

slate swan
#

I have this, ```py
await commands.ColourConverter().convert(ctx, "#fff223")

slate swan
slate swan
dull terrace
#

.title() method is useless, it capitalizes letters after apostrophes so i get stuff like Don'T

#

how fix 😤

slate swan
#

it does?

#

also, rule 7

dull terrace
#

!e

print("don't".title())```
unkempt canyonBOT
#

@dull terrace :white_check_mark: Your 3.11 eval job has completed with return code 0.

Don'T
dull terrace
#

which is rule 7

slate swan
dull terrace
#

nevermind found the answer, can use capwords()

slate swan
#

I'm brain dead lmao

dull terrace
#

!e

import string
print(string.capwords("don't"))
unkempt canyonBOT
#

@dull terrace :white_check_mark: Your 3.11 eval job has completed with return code 0.

Don't
slate swan
slate swan
unkempt canyonBOT
#

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

slate swan
#

where and how did xml come up

slate swan
edgy tundra
#

Bruh

#

Ok nothing

slate swan
#

?

edgy tundra
#

@slate swan i was saying what to do with that async def setup(bot: commands.Bot) -> None:

slate swan
short silo
#

How to delete the original response while making a followup ?

slate swan
#

wha-

#

!d discord.Interaction.delete_original_response

unkempt canyonBOT
#

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

Deletes the original interaction response message.

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

indeed

slate swan
#

why don't people state their libs when it's not dpy smh

short silo
slate swan
#

also, use an interaction not appctx

#

that method won't work with an AppCtx

short silo
short silo
slate swan
edgy tundra
slate swan
#

and why would you ever switch to py-cord lmao, that's like so much worse

slate swan
short silo
slate swan
#

ew py-cord

short silo
#

maybe there is a better way

#

idk

edgy tundra
slate swan
# edgy tundra

jesus, the indentation, it needs to be outside the cog but inside the file

short silo
# slate swan .

idk ran into a problem with dpy which no one was experiencing, i updated the version, it broke a lot of stuff, py-cord seemed to solve both

pulsar solstice
#

how to check that if the server has a icon and if it, then continue

slate swan
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

pulsar solstice
slate swan
#

!d discord.utils.format_dt

unkempt canyonBOT
#

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

This allows for a locale-independent way of presenting data using Discord specific Markdown...
slate swan
edgy tundra
slate swan
#

nice

pulsar solstice
slate swan
pulsar solstice
#

but thanks

slate swan
slate swan
edgy tundra
#

@slate swan do you have any step that i can understand properly

short silo
slate swan
edgy tundra
slate swan
#

dpy ain't a beginner friendly library.

#

@slate swan wut dpy

edgy tundra
slate swan
pulsar solstice
#

btw I was wondering something.
if we do not make discord command a async function then how would it behave?
Like it would only run one command each at a time?

edgy tundra
slate swan
slate swan
#

no that's not how discord's formatting works

timestamp = f"<t:{datetime.datetime.utcnow().timestamp()}:R>"

this is represented with utils.format_dt as

timestamp = discord.utils.format_dt(datetime.datetime.utcnow(), style="R")```
#

😐 before you reference this in your embed

edgy tundra
#

no😂

#

like what

#

so what to do now

slate swan
#
class Cog(...):
  def __str__(...):
    ...

async def setup(...):
  ...
#

here ya go

#

now add it to the embed too

#

^

#

right

#

yeah

naive briar
#

That's because the format's timestamp is 9 seconds ago

#

Add more time to it?

slate swan
#

that's how it'll work, you'll have to add the duration of time after which the giveaway will end create a timestamp out of that

#

HHMMSSFormat nice function name

#

(utcnow() + timedelta(seconds=duration_seconds)).timestamp()

#

and timedelta is imported from datetime

#

!e

duration_seconds = 1069

import datetime

now = datetime.datetime.utcnow()
delta = datetime.timedelta(seconds=duration_seconds)
future_time = now + delta
print(future_time.timestamp())
unkempt canyonBOT
#

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

1663600633.321189
slate swan
#

easy as that

#

Hello how do i make a bot only choose a mine?
Like when i do .mines 1 i want the bot to choose only 1 mine
This is my attempt

a = random.choice([0, *range(1,5)])
b = random.choice([0, *range(6,10)])
c = random.choice([0, *range(11,15)])
d = random.choice([0, *range(16,20)])
e = random.choice([0, *range(21,25)])

@discord.ext.commands.guild_only()
@bot.slash_command(name="mines", description="Predicts Mines for a lordoxez game")
async def mines(ctx, bombs, round_id):
    1 = a
naive briar
#

You have to add the timedelta to it before making timestamp from it

timestamp = discord.utils.format_dt(
    datetime.utcnow() + datetime.timedelta(seconds=duration_seconds),
    style="R",
)
limber bison
#

for numbers we use range(x) what for capital ABCD.. ?

naive briar
#

If it's unused, ye

slate swan
#

Hello how do i make a bot only choose a mine?
Like when i do .mines 1 i want the bot to choose only 1 mine
This is my attempt

a = random.choice([0, *range(1,5)])
b = random.choice([0, *range(6,10)])
c = random.choice([0, *range(11,15)])
d = random.choice([0, *range(16,20)])
e = random.choice([0, *range(21,25)])

@discord.ext.commands.guild_only()
@bot.slash_command(name="mines", description="Predicts Mines for a lordoxez game")
async def mines(ctx, bombs, round_id):
    1 = a
zinc reef
#

weird question, but how would you add "creation of discord bots" in a professional way in a resume? 🤔

naive briar
#

It's datetime.timedelta not datetime.datetime.timedelta

#

!d datetime.timedelta

unkempt canyonBOT
#

class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)```
All arguments are optional and default to `0`. Arguments may be integers or floats, and may be positive or negative.

Only *days*, *seconds* and *microseconds* are stored internally. Arguments are converted to those units...
naive briar
#

I said it's datetime.timedelta not datetime.datetime.timedelta

#

!e

from datetime import timedelta

print(timedelta(seconds=10))
unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.

0:00:10
naive briar
#

Let's just import timedelta

from datetime import timedelta

...

timestamp = discord.utils.format_dt(
    datetime.utcnow() + timedelta(seconds=duration_seconds),
    style="R",
)
#

🫠

hearty cove
#

anyone know any youtube vidoes on how to make a ticket system with discord.py

placid skiff
#

this is the "giveaway"?

#

ctx.guild.name or inter.guild.name

#

!d discord.TextChannel.create_invite

unkempt canyonBOT
#

await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates an instant invite from a text or voice channel.

You must have [`create_instant_invite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_instant_invite "discord.Permissions.create_instant_invite") to do this.
placid skiff
#

that is an hyperlink, you will do it like you do in a markdown file text

#

you don't need to put the * D_D

#

you didn't add the f before the string

#

!fstrings

unkempt canyonBOT
#

Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.

>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."

Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.

placid skiff
#

you put the text in the square brackets and the url in the parentheses

#

with an invite D_D

mental hollow
#

Anyone know why I’m recieving this error?
Code:```py
async def on_guild_join(self, guild: discord.Guild):
print(f"I was invited to {guild.name} - ({guild.id}). It has been added to the database.")
db = self.cluster["Aziel"]
collection = db["Main"]

    data = {"_id": guild.id, "prefix": "!"}
    collection.insert_one(data)
**Error:** https://paste.pythondiscord.com/siqovomodo
*For content, I’m using mongodb.*
hearty cove
#

i need a good example

placid skiff
#

I picked up the first one that i found, i told you that you can search others, there are tons of them on github

velvet jacinth
#

Hello, would someone help me how to program the discord bot?

slate swan
vale wing
vale wing
#

Pymongo isn't async is it

#

Honestly I don't know async wrappers for mongo but imma look them up rq

#

!pypi motor you need to use this I think @mental hollow

unkempt canyonBOT
mental hollow
#

yeah I’m using motor

limber bison
#

role: typing.Optional[discord.role] will this work ?

#

cmd argument

vale wing
mental hollow
#

it was purely an IP issue

honest shoal
#

just wondering

#

is it possible to make HTTP bot on heroku

feral frost
#

anyone knows how i can make a music play command ?

#

spotify or youtube

#

or smth else

crimson compass
#

I use this commands twice in two different places and it sends them both at the same time

@bot.listen()
async def on_command_error(ctx, error):
    if isinstance(error, commands.MissingPermissions):
        await ctx.send(
            ctx.message.author.mention + "  **You do not have the  __`Administrator Permission`__  to use this command.**")
@bot.listen()
async def on_command_error(ctx, error):
    if isinstance(error, commands.MissingPermissions):
        await ctx.send(
            ctx.message.author.mention + "  **You do not have the  __`Manage Messages Permission`__  to use this command.**")
hushed galleon
#

the MissingPermissions exception has a .missing_permissions attribute containing a list of whatever permissions were missing (e.g. 'administrator' or 'manage_messages'), you can format your bot's response based on that rather than having two on_command_errors

primal token
primal token
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)
primal token
#

Even if you arent using youtube as your source for music it would be a problem getting all the licenses of each song you play

feral frost
#

ok

#

RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited
bot.add_cog(music_cog(bot))

#

what is that error ?

primal token
#

The setup function is now an async function and discord.ext.commands.Bot.add_cog is also an async method

feral frost
#

ok so what do i do ? how do i fix it ?

short silo
#

any way to give Colors in discord.Colours as an OptionChoice ?

primal token
slate swan
primal token
#

I think you should have a grasp of that knowledge as this library does use asynchronous abstractions?

feral frost
#

?

crimson roost
primal token
slate swan
#

where and how would i do that

primal token
# crimson roost

You have been ratelimited by the Discord REST API, Use the command kill 1 in your terminal to kill your container that also changed your IP

vale wing
#

Just don't use replit

primal token
vale wing
#

I used to convert it with int with base 16

crimson roost
#

how can i restart my bot using a cmd

short silo
vale wing
#

!e py print(int("ffaaff", 16))

unkempt canyonBOT
#

@vale wing :white_check_mark: Your 3.11 eval job has completed with return code 0.

16755455
primal token
crimson roost
primal token
short silo
primal token
#

?

crimson roost
primal token
feral frost
#

Anyone knows how to fix this ?RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited bot.add_cog(help_cog(bot))

slate swan
primal token
#

I've already helped both of you? I'm not willing to spoonfeed either

unkempt canyonBOT
#

Concurrency in Python

Python provides the ability to run multiple tasks and coroutines simultaneously with the use of the asyncio library, which is included in the Python standard library.

This works by running these coroutines in an event loop, where the context of the running coroutine switches periodically to allow all other coroutines to run, thus giving the appearance of running at the same time. This is different to using threads or processes in that all code runs in the main process and thread, although it is possible to run coroutines in other threads.

To call an async function we can either await it, or run it in an event loop which we get from asyncio.

To create a coroutine that can be used with asyncio we need to define a function using the async keyword:

async def main():
    await something_awaitable()

Which means we can call await something_awaitable() directly from within the function. If this were a non-async function, it would raise the exception SyntaxError: 'await' outside async function

To run the top level async function from outside the event loop we need to use asyncio.run(), like this:

import asyncio

async def main():
    await something_awaitable()

asyncio.run(main())

Note that in the asyncio.run(), where we appear to be calling main(), this does not execute the code in main. Rather, it creates and returns a new coroutine object (i.e main() is not main()) which is then handled and run by the event loop via asyncio.run().

To learn more about asyncio and its use, see the asyncio documentation.

feral frost
primal token
#

What did you not understand exactly?

feral frost
#

everything

short silo
feral frost
#

i didnt get that from his explanation

feral frost
short silo
feral frost
#

how do i await it ?

#

like it says in the error

short silo
primal token
feral frost
#

and how do i add this to it ? bot.add_cog(help_cog(bot)) ?

primal token
#

You make setup an async function?

feral frost
#

why a question mark ?

#

is that a question for me

#

primal token
#

Its a rhetorical question?

short silo
#

damn these are some good resources

primal token
#

I know right, ive used them allot through my journey in python

short silo
feral frost
primal token
feral frost
#

how do i put buttons under each other instead of next?

glad cradle
#

mh, I'll watch the async thing too 👀

short silo
primal token
primal token
short silo
primal token
#

Exception groups and the Self type look nice as well

slate swan
glad cradle
primal token
#

Well then you're in luck as it also shows the history of asyncio in python. Yep thats how deep it goes!

glad cradle
#

🙏

short silo
primal token
#

I was mostly interested in speed

feral frost
#

how do i put buttons under each other ?

slate swan
sick birch
slate swan
#

where and how?

primal token
sick birch
#

Your view would take a member parameter

#

You’d have an interaction_check that checks if interaction.user == self.author

#

Return true if yes return false if no with an optional ephemeral message

primal token
slate swan
#

"self" is not defined

primal token
#

Did you just pasted Robin's code to yours?

slate swan
#

somewhat

feral frost
#

how do i put buttons under each other ?

sick birch
feral frost
#

ah just enter ?

sick birch
sick birch
feral frost
#

just \n ?

#

and how do i put for example 2 buttons in 1 button_callback ?

primal token
sick birch
#

point proven

sick birch
unkempt canyonBOT
#

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

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

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

The default implementation of this returns `True`.

Note

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

I'd also suggest responding to it like you would an interaction, so you can make it emphemeral

#

Like

await interaction.response.send_message("This is not your Button!", ephemeral=True)
wicked atlas
#
guild = "whatever you want it to be"
ripe jackal
#

hey guys do someone know how to add a url leading to a file in my bot's folder? Cuz it gives me this error In embeds.0.image.url: Scheme "assets/motivation.png" is not supported. Scheme must be one of ('http', 'https').

wicked atlas
ripe jackal
#

tysm brother. Will try it

faint sapphire
#

u can only react to messages with on_message yh?
no way to do it in a command right

wicked atlas
primal token
unkempt canyonBOT
#

The message that triggered the command being executed.

Note

In the case of an interaction based context, this message is “synthetic” and does not actually exist. Therefore, the ID on it is invalid similar to ephemeral messages.

faint sapphire
#

ok thanks

slate swan
#

the bot sends an embed saying type dev id and once the person sends the dev id the bot adds them to ticket thats all i need PLEASE HELP

primal token
#

What do you mean by ticket? It's just ID no such thing as developer ID

slate swan
#

and paste it then the bot adds them to the channel

#

this is what i have

#

import discord
client = discord.Client(intents=discord.Intents.default())
class YourBetterClassName(discord.ui.View):
def init(self):
super().init()
self.value = None

@discord.ui.button(label='B', style=discord.ButtonStyle.green)
async def a(self, interaction: discord.Interaction, button: discord.ui.Button):
    await interaction.response.send_message('Works', ephemeral=True)
    self.value = True
    self.stop()

@discord.ui.button(label='A', style=discord.ButtonStyle.grey)
async def b(self, interaction: discord.Interaction, button: discord.ui.Button):
    await interaction.response.send_message('Works', ephemeral=True)
    self.value = False
    self.stop()

@client.event
async def on_guild_channel_create(channel):
await channel.send(view=YourBetterClassName())

#

if anyone can add on to it thatll be greatly appreciated

primal token
unkempt canyonBOT
#

await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sets the channel specific permission overwrites for a target in the channel.

The `target` parameter should either be a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") that belongs to guild.

The `overwrite` parameter, if given, must either be `None` or [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite"). For convenience, you can pass in keyword arguments denoting [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions") attributes. If this is done, then you cannot mix the keyword arguments with the `overwrite` parameter.

If the `overwrite` parameter is `None`, then the permission overwrites are deleted.

You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to do this...