#discord-bots

1 messages ยท Page 337 of 1

slate swan
unkempt canyonBOT
#

property id```
Equivalent to [`User.id`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.id)
restive mantle
#

How do I make so options show up like this? Or what's the name of it?

slate swan
#

Choices

restive mantle
#

!d choices

unkempt canyonBOT
#

Some command-line arguments should be selected from a restricted set of values. These can be handled by passing a sequence object as the choices keyword argument to add_argument(). When the command line is parsed, argument values will be checked, and an error message will be displayed if the argument was not one of the acceptable values:

>>> parser = argparse.ArgumentParser(prog='game.py')
>>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
>>> parser.parse_args(['rock'])
Namespace(move='rock')
>>> parser.parse_args(['fire'])
usage: game.py [-h] {rock,paper,scissors}
game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',
'paper', 'scissors')
restive mantle
slate swan
#

Not that, it's in discord.py or whatever library you're using Facepalm

tiny coyote
#

I printed it and they give 2 completely different values

slate swan
tiny coyote
#

Ohh wait i think i figure it out

#

the other value is the bot.?

slate swan
#

Yeah obviously if your bot sends a message it will trigger the event and you'll get its ID

tiny coyote
#

I think.., there 2 values stored in my sqlite3 database with different id's so I'm guessing

tiny coyote
#

thanks tho

slate swan
#

If you want to ignore these messages, which is recommended, consider adding a check at the top

slate swan
#

Hello, how do I make a discord bot for personal use, I already created the bot, how do I code it

#

See pinned messages and channel description

tiny coyote
#
Traceback (most recent call last):
  File "C:\Users\Naseer\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 235, in wrapped
    ret = await coro(*args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "c:\Users\Naseer\Desktop\That one server\cogs\Fighting_Commands.py", line 117, in fight
    damage = P_style[ctx.author.id][style] + dmg * Mult[FistA]
                                                   ~~~~^^^^^^^
TypeError: unhashable type: 'list'

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

Traceback (most recent call last):
  File "C:\Users\Naseer\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\Naseer\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 1029, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Naseer\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 244, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: unhashable type: 'list'

code:

else:
                    FistA = random.choices(FistAD, weights=[10,5,1], k=1)
                    
                    damage = P_style[ctx.author.id][style] + dmg * Mult[FistA]
lime temple
#

Hey i just wanna ask a long and hard question :D The image i post is generated through a bot like midjourney yk. Do you have any idea how these bots work? Opencv? Deep-learning? I just googled and there is no info about that. I know like these projects need lots of gpu and hardware but wanna make like the image i sent. It makes it with pixels what i mentioned. I just made a bot creates a image with api but it doesn't work the way i want it to and using the API is paid after a while so I don't want to give money. Any idea, tutorial, article or sth?

tiny coyote
#

when I remove choices() and put choice it seems to work but i want to avoid that, to make each scenario have a higher chance of happening..

naive briar
#

You can search up text to image models and find some info

lime temple
naive briar
#

Hmm, I'll test something

lime temple
#

I think it's deep-learning but I'm not sure :/

#

If I don't get it wrong, deep-learning works with math functions and I don't know the functions very well lol (u can ping me)

naive briar
#

Alright, I'm out of ideas

tiny coyote
lime temple
#

Tysm have a good day ๐Ÿ‘

slate swan
#

https://paste.pythondiscord.com/7I4A
TypeError: unsupported type annotation <class 'discord.interactions.Interaction'>

I get this is within the @app_commands.command
I've tried it with both
interaction: discord.Interaction and interaction: discord.interactions.Interaction
I get the same error.
This is just a mock-up.
I just want to get the basic functionality of it sending a message, adding the view, and on_interaction it will respond with adding the role right now.
what do I need to change in to make this work or why? or both

dreamy dune
lime temple
#

This will be very useful to me

#

thank you soo much

slate swan
#

same error if I move it to line 42. I was getting the error prior to adding button in the view.

unkempt canyonBOT
#

examples/views/confirm.py lines 29 to 30

@discord.ui.button(label='Confirm', style=discord.ButtonStyle.green)
async def confirm(self, interaction: discord.Interaction, button: discord.ui.Button):```
slate swan
#

same error if I add it into the callback.

#

I'm guessing theres multiple parts that are wrong, but I don't see much documentation of these going into a class of it's own, calling the view and getting this error. even from what I found searching this discords q/a's on TypeErrors.

#

Also, line 9: You probably don't want to call the function, but just assign it

slate swan
#

You're still calling the function

#

Line 33 now though

#

Not sure why you create a new button as well

#

how is that not assigning the function to button.callback?

slate swan
#

Assigning would be without the ()

#

And look at this example, you don't need to assign the callback explicitly nor create a new button - not quite sure what you're doing

slate swan
#

Look at the example

#

Those are the only ones that matter, you may find outdated or wrong examples on the internet

#

okay.. one shows a class as discord.ui.Button and the others show as discord.ui.View
So you're saying it's automatically a callback for the button. cool.
I still get the same error tho ๐Ÿคฃ

fair hinge
#

woops

slate swan
#

even if I remove the whole button view section. I still get the error within the @app_commands.command

lime temple
subtle jungle
#

how do i get the link from my keep_alive file to be passed into uptimerobot?

#

it showed a complete address before, but now the created tab only shows this address "/"

snow coral
subtle jungle
#

oh ๐Ÿฅฒ when was this feature removed?

#

was it in the january 4th update?

shrewd fjord
subtle jungle
#

i already tried that, and it only allows uptimerobot to be running when the tab is open

subtle jungle
thin beacon
#

Can anyone help me with this ```py
class Pagination(discord.ui.View):
def init(self, ctx, selection):
super().init()

    for k, v in selection.items():
        style = discord.ButtonStyle.secondary if k != "exit" else discord.ButtonStyle.danger
        self.add_item(discord.ui.Button(style=style, custom_id=str(v), emoji=ctx.bot.get_emoji(v), disabled=False))

class Selector:
def init(self, menu, selection, *, timeout=300.0, auto_exit=True, check=None):
self.menu = menu
self.timeout = timeout
self.auto_exit = auto_exit
self.check = check or self._default_check

    self._base_selection = selection

@property
def selection(self):
    return self._base_selection

@selection.setter
def selection(self, value):
    self._base_selection = value

def _default_check(self, reaction, user):
    return (
        reaction.message.id == self.menu.message.id
        and user == self.menu.ctx.author
        and reaction.emoji.name in self.selection
    )

async def _serve(self):
    await self.menu.message.edit(view=None)

    await self.menu.message.edit(view=Pagination(self.menu, self.selection))

async def response(self):
    await self._serve()

    try:
        reaction, user = await self.menu.bot.wait_for("on_interaction", timeout=self.timeout, check=self.check)
        print(reaction, user) #not working
        print(dir(reaction)) #not working
    except asyncio.TimeoutError:
        await self.menu.timeout(chron.long_delta(timedelta(seconds=self.timeout)))
    else:
        if (r := reaction.emoji.name) == "exit" and self.auto_exit:
            await self.menu.stop()
        else:
            return r
#

everything is working except the print statements. the bot is getting timedout on time but upon reacting with the button the print statments not workig

shrewd apex
#

thats not how u get response from button

thin beacon
#

then how?

#

give me some hints

shrewd apex
#

just a sec ill link u an example

thin beacon
#

ok

shrewd apex
#

u register callbacks for buttons either using decorators or assigning to .callback attribute manually

thin beacon
#

can't I use buttons with bot.wait_for()?

shrewd apex
#

these get triggered when the button is interacted with

shrewd apex
thin beacon
#

but it is getting timedout after specified time then why not response?

shrewd apex
#

wdym?

#

the print wont work

#

ur trying to use buttons like reactions thats not how views work

dreamy dune
#

view has a wait method built in

thin beacon
#

for testing...

naive briar
#

Sure

thin beacon
#

but how to get the button custom_id out of that interaction event?

thin beacon
#

Oh

#

Thanks

snow coral
slate swan
#

what am i doing wrong it doesnt send the message when someone joins

snow coral
slate swan
#

yes

pale zenith
slate swan
#

so i should just put print channel under it

#

and what is wrong with this code its from a bot i made 2 years ago ?

#

it says the wow = await.... line is wrong

#

you tell us .. you have the error

slate swan
# slate swan

so from that error all we know is that guild creation failed

#

yeh

#

thats the problem but it worked 2 years ago

#

i didnt change anythign

#

most likely this: Bot accounts in more than 10 guilds are not allowed to create guilds.

#

!d discord.ext.commands.Bot.create_guild

unkempt canyonBOT
#

await create_guild(*, name, icon=..., code=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild).

Bot accounts in more than 10 guilds are not allowed to create guilds.

Changed in version 2.0: `name` and `icon` parameters are now keyword-only. The `region` parameter has been removed.

Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) instead of `InvalidArgument`.
cerulean folio
#

Hi guys !
If you have a bot running on your pc and the connexion crashes for X amount of time, will it reconnect automatically when the connexion is back? If no, what should I do for it, in your opinion? ๐Ÿ˜Š

cerulean folio
#

discord.on_resumed() got it ! :D

cerulean folio
#

now can someone help me install discord.py on windows? I tried py -3 -m pip install discord but didn't work

young dagger
#

What is the correct approach to persist some data for users even after they have been removed from the database so that, when they decide to set up their account again, you can retrieve their historical data and use it to prepopulate certain fields?

#

Experience, Levels etc

pale zenith
#

or store a boolean like is_account_disabled BOOL or have a separate table

#

if this is like GDPR compliance shit then user IDs are considered non-identifying info either way (i think)

young dagger
trail maple
#

is there event i can use await bot.wait_for() to wait for a dropdown select like you can wait for a button_click?

pale zenith
slate swan
#

how do you @ a message id? if it's not <@> or <#> what is it?
like this message id: @runic smelt #1198788396387155998

golden portal
slate swan
#

yes

golden portal
#

that's a message link, not the typical <id> format

#

!d discord.Message.jump_url

unkempt canyonBOT
slate swan
#

ty!

golden portal
#

welcome

#

the format is https://discord.com/channels/{guild id}/{channel id}/{message id}

slate swan
#

I just figured that out ๐Ÿคฃ

#

super useful to make them tho

golden portal
#

oke

slate swan
# golden portal oke

if you want them for certain applications. u can add a prefix for ptb.discord.com, or canary.discord.com too

golden portal
#

no that's just a subdomain according to discord app, but they still work across all discord apps, i sent you a link from canary, it would still work on others

next oracle
#

I need help

#

I forgot how to code

#

in python

#

and in general I have been cauaght up trying to be the "cool guy" I forgot that I had a career ahead of me

shrewd apex
#

?? so take some time to learn python?

drifting arrow
#

What in the actual frick frack?! Can someone help me understand what went wrong? the issue is towards the bottom.

#

I can share functions if necessary.

#

!paste

golden portal
#

the traceback was cutoff, do you have anymore at the bottom there?

desert kiln
#

I have a slash timeout command, everything works, e.g. error handling for anything else, but when I try time someone out, it says "Application did not respond"

#

!paste

drifting arrow
#

I'll also have to wait for it to happen again lol

#

as it stopped happening ;-;

#

It's like when you slap the side of a tv or whatever and shit just starts working again.

golden portal
#

i mean if the bot was blocked for 10 seconds simply from json.loads, its a large string there, u might wanna use orjson for speed tbh

drifting arrow
#

what the heckers is orjson?

golden portal
#

faster json lib for python

golden portal
drifting arrow
#

Do response.defer

dire dock
#

Does anyone have an example of a slash command working with custom convertors? I am getting an unsupported annonation type with bot.tree.command but not with bot.tree

golden portal
#

!d discord.app_commands.Transformer

unkempt canyonBOT
#

class discord.app_commands.Transformer```
The base class that allows a type annotation in an application command parameter to map into a [`AppCommandOptionType`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.AppCommandOptionType) and transform the raw value into one from this type.

This class is customisable through the overriding of methods and properties in the class and by using it as the second type parameter of the [`Transform`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Transform) class. For example, to convert a string into a custom pair type:
golden portal
#

see the example in there

dire dock
#

tytyty

honest rover
#

how do u load extensions now? its been a while since ive used this and looks like now you have to await the .load_extension()

I put what i had before inside the on_ready() event since that function is async and awaited .load_extension() is this the standard?

    cogs = os.listdir('./cogs')
    utils = os.listdir('./utils')

    for x, y in [(cogs, utils)]:
        for cog_file in cogs:
            if cog_file.endswith('.py'):
                try:
                    await bot.load_extension(f'cogs.{cog_file[:-3]}')
                except Exception as e:
                    raise e
        for utils_file in utils:
            if utils_file.endswith('.py'):
                try:
                    await bot.load_extension(f'utils.{utils_file[:-3]}')
                except Exception as e:
                    raise e
#

i also changed the setup() functions in the cogs and awaited add_cog()

golden portal
#

!d discord.ext.commands.Bot.setup_hook

unkempt canyonBOT
#

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

A coroutine to be called to setup the bot, by default this is blank.

To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.

This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.login), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready) event.

Warning

Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_for) and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_until_ready)...
drifting arrow
#
[2024-01-22 02:00:22] [ERROR   ] discord.client: Attempting a reconnect in 1.94s
Traceback (most recent call last):
  File "C:\Users\Gnome\AppData\Roaming\Python\Python310\site-packages\discord\client.py", line 659, in connect
    await self.ws.poll_event()
  File "C:\Users\Gnome\AppData\Roaming\Python\Python310\site-packages\discord\gateway.py", line 646, in poll_event
    raise ConnectionClosed(self.socket, shard_id=self.shard_id, code=code) from None
discord.errors.ConnectionClosed: Shard ID None WebSocket closed with 1000
``` What would cause this?
thin beacon
#

can anyone help with this? ```py
async def response(self):
self.set_selection()

    if self.selection != self.last_selection:
        await self._serve()

    try:
        interaction = await self.menu.bot.wait_for("interaction", timeout=self.timeout, check=lambda e: (isinstance(e, discord.Interaction) and e.user == self.menu.ctx.author and e.message == self.menu.message))
    except TimeoutError:
        await self.menu.timeout(chron.long_delta(timedelta(seconds=self.timeout)))
    else:
        if (i := interaction.data["custom_id"]) == str(self.menu.bot.config.EXIT_EMOJI_ID):
            if self.auto_exit:
                await self.menu.stop()
            return
        elif i == str(self.menu.bot.config.STEP_BACK_EMOJI_ID):
            self.page = 0
        elif i == str(self.menu.bot.config.PAGE_BACK_EMOJI_ID):
            self.page -= 1
        elif i == str(self.menu.bot.config.PAGE_NEXT_EMOJI_ID):
            self.page += 1
        elif i == str(self.menu.bot.config.STEP_NEXT_EMOJI_ID):
            self.page = self.max_page

        await self.menu.switch()
        return await self.response()

class MultiPageMenu(Menu):

async def start(self):
    li = [await self.page_field]
    for i in self.selector.pagemaps[self.selector.page]["fields"]:
        li.append(i)
    self.selector.pagemaps[self.selector.page].update({"fields": tuple(li)})
    await super().start()
    return await self.selector.response()

async def switch(self):
    li = [await self.page_field]
    for i in self.selector.pagemaps[self.selector.page]["fields"]:
        if i not in li:
            li.append(i)
    self.selector.pagemaps[self.selector.page].update({"fields": tuple(li)})
    await super().switch(self.selector.pagemaps[self.selector.page])
#

I mean everything is working the buttons are working fine
the pagination is working , is it switching pages but each time a button is pressed after switching the page discord is showing application failed

#

anyone?

ivory turret
#

Hey! I'm using discord.py, it works and login but sometime if there is some error in a cog file it ofc doesnt crashes entirely but because there was some error that command doesnt obviously but it doesnt even show what was wrong or what is the error, before when I used to use pycord everytime my command would break it would show me that this this things is wrong or an exception i should say? so why is it now showing now?

golden portal
ivory turret
#

do I have to pass like logging =True?

naive briar
unkempt canyonBOT
#

discord.utils.setup_logging(*, handler=..., formatter=..., level=..., root=True)```
A helper function to setup logging.

This is superficially similar to [`logging.basicConfig()`](https://docs.python.org/3/library/logging.html#logging.basicConfig) but uses different defaults and a colour formatter if the stream can display colour.

This is used by the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) to set up logging if `log_handler` is not `None`.

New in version 2.0.
ivory turret
#

ok ok I fixed it, now its working, Thanks!

young dagger
# pale zenith then yeah keep a separate table for historical data

So something simple as

    historical_data = {
        "discord_id": existing_user["discord_id"],
        "experience": existing_user.get("experience"),
        "games_played": existing_user.get("games_played"),
    }

    await inactive_users.insert_one(historical_data)

    await collection.delete_one({"discord_id": user_id})
pale zenith
#

It would probably be more memory efficient to have a relational db rather than (what it looks to be) a document-based one, but that's just me being pedantic

young dagger
fiery girder
#

how do you make those timer and things in embeds

#

it ticks down the time

honest rover
drifting arrow
#

anybody know why this is happening?

[2024-01-22 02:00:24] [INFO    ] discord.gateway: Shard ID None has successfully RESUMED session 86e0d5927e143698382d4602ba0e641a.
[2024-01-22 03:48:26] [ERROR   ] discord.client: Attempting a reconnect in 1.16s
Traceback (most recent call last):
  File "C:\Users\Gnome\AppData\Roaming\Python\Python310\site-packages\discord\client.py", line 659, in connect
    await self.ws.poll_event()
  File "C:\Users\Gnome\AppData\Roaming\Python\Python310\site-packages\discord\gateway.py", line 646, in poll_event
    raise ConnectionClosed(self.socket, shard_id=self.shard_id, code=code) from None
discord.errors.ConnectionClosed: Shard ID None WebSocket closed with 1000
[2024-01-22 03:48:27] [INFO    ] discord.gateway: Shard ID None has successfully RESUMED session 86e0d5927e143698382d4602ba0e641a.
[2024-01-22 06:56:41] [ERROR   ] discord.client: Attempting a reconnect in 0.29s
Traceback (most recent call last):
  File "C:\Users\Gnome\AppData\Roaming\Python\Python310\site-packages\discord\client.py", line 659, in connect
    await self.ws.poll_event()
  File "C:\Users\Gnome\AppData\Roaming\Python\Python310\site-packages\discord\gateway.py", line 646, in poll_event
    raise ConnectionClosed(self.socket, shard_id=self.shard_id, code=code) from None
discord.errors.ConnectionClosed: Shard ID None WebSocket closed with 1000
[2024-01-22 06:56:41] [INFO    ] discord.gateway: Shard ID None has successfully RESUMED session 86e0d5927e143698382d4602ba0e641a.
fiery girder
drifting arrow
#

vps

fiery girder
#

vps?

drifting arrow
#

Virtual Private Server.

fiery girder
#

its the internet problem as i can see

drifting arrow
#

Aight

#

I'll wait 24hrs I guess

fiery girder
#

it is saying that it is trying to reconnect

drifting arrow
#

Nothing I can do if it's not caused by my code

fiery girder
#

yea

#

contact your vps or something

drifting arrow
#

na

#

It'll fix itself soon enough

fiery girder
#

how to appcommands group work?

#

!d discord.app_commands.Group

#

does

test = discord.app_commands.Group(name="test")
@test.command(name="testing")
async def testing():
  pass

will this work

pale zenith
#

also don't forget to tree.add_command(test)

young dagger
drifting arrow
#

ovh

young dagger
#

Distro?

drifting arrow
#

idk

young dagger
#

Ubuntu?

drifting arrow
#

oh windows

fiery girder
drifting arrow
#

create a slash command?

fiery girder
#

a group slash command

#

i am getting this error

#

i removved the command

drifting arrow
#

wtf is a group slash command

fiery girder
#

!d discord.app_commands.Group

unkempt canyonBOT
#

class discord.app_commands.Group(*, name=..., description=..., parent=None, guild_ids=None, guild_only=..., nsfw=..., auto_locale_strings=True, default_permissions=..., extras=...)```
A class that implements an application command group.

These are usually inherited rather than created manually.

Decorators such as [`guild_only()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guild_only), [`guilds()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guilds), and [`default_permissions()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.default_permissions) will apply to the group if used on top of a subclass. For example:

```py
from discord import app_commands

@app_commands.guild_only()
class MyGroup(app_commands.Group):
    pass
```...
drifting arrow
#

oh okay

#

so instead of needing the "guild_only()" for each command, you just apply it globally

little lava
#

How to interaction Modal question with buttons?

shrewd apex
fast musk
#

I am so scared to click this link

#

Oh god I'm so curious though too

#

Ok, I've seen enough... hahaha

little lava
# shrewd apex u cant have buttons in a modal only text inputs

but i saw a server has a function that interact Modal with Select menu. so i wonder if i can do that same thing. (for the verification purpose)

i have done make a Modal question and it trigger with slash command is fine, but i don't know how to interact with Buttons or Select menu.

slate swan
#

You can create an option and when its pressed then you can
send the model to the user with

await interaction.response.send_modal()
#

!d discord.InteractionResponse.send_modal

unkempt canyonBOT
#

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

Responds to this interaction by sending a modal.
slate swan
#

why am i getting this error

fast musk
#

More info needed. How are you invoking the package etc

mighty pilot
#

Is there a way to check if a user triggered a hybrid command from a slash or text command? I tried this
if message.type == discord.MessageType.chat_input_command: but it didn't seem to work

#

Reversing it worked for some reason.

if message.type != discord.MessageType.context_menu_command:

stoic tusk
#

How do I dm someone with the bot when I ban/kick/mute/warn them? I have troubles coding that

final iron
stoic tusk
#

it makes me understand easier

final iron
#

You just use the send() method on a discord.Member instance

#

!d discord.Member.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.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) objects. **Specifying both parameters will lead to an exception**.
young dagger
#

Example

        try:
            await member.send(embed=embed)
        except discord.Forbidden:
            print("Not allowed to send DMs to the user.")
            pass
#

Or however you want handle it

slate swan
young dagger
golden portal
loud flicker
#

Can someone please help me, I'm trying to sync my commands (and adding new slash commands) without restarting the bot using pycord. Both self.bot.sync_commands() and self.bot.register_commands() threw me an error "Application command names must be unique" while all my command names are unique.

hushed galleon
hushed galleon
#

silver-volt there mentions a workaround for it, using bot._pending_application_commands = [] before reloading the extension

loud flicker
#

Thank you!

desert kiln
#

hm, this doesn't wanna work, I'm not sure why.

uptime = datetime.utcnow() - self.start_time```
#

I tried self.bot and it didn't fix it either

pale zenith
#

what part of it doesn't work?

desert kiln
# pale zenith what part of it doesn't work?

The uptime = part, for my uptime command

@app_commands.command(name="uptime")
    async def slash_uptcmd(self, interaction):
        """โš™๏ธ | Checks The Bots Uptime."""
        uptime = datetime.utcnow() - self.start_time
        upt = str(uptime).split(".")[0]
        embed = discord.Embed(title='Uptime', description=f'{upt}', color=discord.Color.purple())
        await interaction.response.send_message(embed=embed)```
pale zenith
#

ok, and where do you define self.start_time?

#

(this is not something that discord.py provides. You need to create that variable somewhere. Probably better to have it attached to Bot instead)

#

e.g. in your main file bot.start_time = datetime.datetime.now()

desert kiln
#

oh, that explains it, 1 moment

fiery girder
#

i alr removed the old command and switched it with a group it still giving error

slate swan
#

hmmm

fiery girder
#

its app commands btw

slate swan
#

no sorry i cant solve it afterall i dont know discord.py anyway

#

sorry abt that

fiery girder
#

then what the hmmm for

slate swan
fiery girder
#

i just changed the name

#

iot should bve fixed

slate swan
fiery girder
#

it still give error

slate swan
#

what are a beginner or an itermidiate

fiery girder
#

in the middle

slate swan
#

ic

fiery girder
#

beginner is someone new

slate swan
#

when u started?

fiery girder
#

june 2023

slate swan
#

ic

#

and u gave up on it in between?

fiery girder
#

no

slate swan
#

@slate swan u still exist?

vale wing
fiery girder
#

so is this error

slate swan
vale wing
#

Time to find more developers for bobux

slate swan
#

am not a bot dev so i cant help him

vale wing
fiery girder
#

nope

#

only in 1 file

vale wing
#

Tried searching?

fiery girder
#

yes

vale wing
#

Gib the results

#

Because that error only happens on duplicate command

fiery girder
vale wing
#

There are 2 groups named tinyurl?

fiery girder
#

no

vale wing
#

Well there are

fiery girder
#

this is that result

#

its just the name and the group name

vale wing
#

Where's second result

fiery girder
#

its in the same line

#

you can see the highlighting

slate swan
slate swan
slate swan
fiery girder
#

it was befire called shorten url but i wanted it as group i made it a group but it gave error so i even changed the name of the group still

vale wing
fiery girder
#

url shortner

vale wing
#

Okay let's do it the hard way ๐Ÿ˜ˆ

fiery girder
#

with many things

#

like create stats change maybe delete

vale wing
fiery girder
#

ok

fiery girder
#

here full tracback

vale wing
#

Hopefully I can solve this before I need to go

fiery girder
#

hopefully

#

weill it be fixed if i turned override on?

#

nope

vale wing
#

@fiery girder in api.py setup, add this line

print("\n".join(f"{c.cog_name} - {c.qualified_name}" for c in bot.walk_commands()))```
#

And oops I need to go

fiery girder
#

but where

vale wing
#

Ping me with this I will return to this later

vale wing
fiery girder
#

ok

spark nimbus
#

Is there a Google translate library that I can use to create a command for my bot?

fiery girder
#

it just shows a empty line @vale wing

unkempt canyonBOT
#
Huh? No.

No documentation found for the requested symbol.

fiery girder
#

there is a pacakge calls translators tho

spark nimbus
#

Ok

#

I'll check that out

#

Thx

fiery girder
# spark nimbus Ok

or you can use google official but the docs arent in python so its hard to figure

fiery girder
#

thes are all appcommands

#

i fixed it

vale wing
fiery girder
vale wing
#

What was the cause

fiery girder
#

some guy from this discord was helping me and said you need to do self.bot.tree.add_command(group) so i did that caused it to malfunction

vale wing
#

Oh yeah

pale zenith
#

Because it looked like a command defined in the main file (no self parameter). You don't need to do that when within cogs

faint rapids
#

Hi, in discord.py, how do I disable automatic reconnection if the bot was forcefully disconnected?

2024-01-23 20:26:34 INFO     discord.voice_client Disconnected from voice by force... potentially reconnecting.
2024-01-23 20:26:34 INFO     discord.voice_client Starting voice handshake... (connection attempt 2)
2024-01-23 20:27:34 INFO     discord.voice_client The voice handshake is being terminated for Channel ID 1199359436997808209 (Guild ID 1003940162046263347)
2024-01-23 20:27:34 INFO     discord.voice_client Reconnect was unsuccessful, disconnecting from voice normally...
drifting arrow
#

Is there a way to get every message in a channel?

vale wing
#

Otherwise bot will be fetching them forever and you typically never need that

#

!d discord.TextChannel.history

unkempt canyonBOT
#

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator) that enables receiving the destinationโ€™s message history.

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

Examples

Usage...
vale wing
faint rapids
faint rapids
#

this "Disconnect" button

vale wing
#

Oh so bot automatically reconnects if you disconnect it as mod

faint rapids
vale wing
#

Does it actually reconnect or there's just this message

faint rapids
#

no

vale wing
#

About reconnection attempt

faint rapids
#

it doesn't reconnect

vale wing
#

Then there's nothing to worry about

faint rapids
#

2024-01-23 20:27:34 INFO discord.voice_client Reconnect was unsuccessful, disconnecting from voice normally...

#

"Reconnect was unsuccessful"

vale wing
faint rapids
#

okay

faint rapids
slate swan
#

Hi, how do I do this? I want to enter a command and the bot will ask what is your name? After my reply, the bot remembers it. When re-entering the command. the bot outputs my name. Also, how can I change my name in the database in the bot, for example, if I made a mistake

Player: !team
Bot: Hi, what's your name
Player: Steve
Bot: I remember it well
Player: !team 
Bot: Hi Steve!

well, also delete the name if the player made a mistake

vale wing
vale wing
slate swan
vale wing
slate swan
#

understood, but how to do it?

vale wing
#

Well if you got no experience of working with them, I recommend checking #databases pins for learning resources

slate swan
vale wing
#

You too comrade

proud schooner
#

??

#

I wrote this on phone so i apologise if any of it is out of line etc.

sour bone
#

Could someone help me correct this code?
Itโ€™s for a discord slash command called** /Giveaway (time) (prize) (emoji)**
The error message is the image

from discord.ext import commands
import random
import asyncio
import os
from discord.utils import get
import re
import itertools
import requests
import schedule
import time

intents = discord.Intents.all()
client = commands.Bot(command_prefix="/", intents=intents)

@client.event
async def on_ready():
    await client.tree.sync()
    await client.change_presence(activity=discord.Game(name="Playing Forever Long SMP"),
                                 status=discord.Status.online)
    print(f"{client.user.name} is now online")

@client.tree.command(name="giveaway", description="creates a giveaway")
async def giveaway(ctx, duration_seconds: int, *, prize: str):
    if duration_seconds <= 0:
        await ctx.send(f"Invalid duration. Please specify a positive number of seconds.")
        return

    embed = discord.Embed(
        title="๐ŸŽ‰ **Giveaway started!** ๐ŸŽ‰",
        description=f"Prize: {prize}\nDuration: {duration_seconds} second(s)\nHosted by: {ctx.user.mention}\n\nReact with ๐ŸŽ‰ to participate!",
        color=discord.Color.blue()
    )

    message = await ctx.send(embed=embed)
    await message.add_reaction('๐ŸŽ‰')

    await asyncio.sleep(duration_seconds)

    message = await ctx.channel.fetch_message(message.id)
    reaction = discord.utils.get(message.reactions, emoji="๐ŸŽ‰")
    participants = [user for user in await reaction.users() if user != client.user]

    if participants:
        winner = random.choice(participants)
        winner_embed = discord.Embed(
            title="๐ŸŽ‰ **Giveaway ended!** ๐ŸŽ‰",
            description=f"Prize: {prize}\nWinner: {winner.mention}",
            color=discord.Color.blue()
        )
        await ctx.send(embed=winner_embed) ```
proud schooner
#

The error is message = ctx.send(embed=embed) as it shows in the command prompt.

sour bone
proud schooner
#

Can someone else do this? I cant for another 4 minutes

hushed galleon
proud schooner
#

Thanks

sour bone
hushed galleon
#

well its not only renaming, since context and interaction have different attributes/methods which you'll need to take into account

#

does replit have type checking? that'd make it a lot easier to know when you're misusing parameters, assuming said parameter is type hinted

#

@proud schooner oh yeah, member.status returns a discord.Status enum so if you want to check for a specific status, you'll need to compare it to a member of that enumeration directly, for example member.status == discord.Status.offline

proud schooner
hushed galleon
#

oh your user variable is literally a string...

proud schooner
#

Yeah thats what i meant

hushed galleon
#

what user are you trying to refer to?

#

you just want to check for a member's status by their ID?

proud schooner
#

Yeah thats basically it

hushed galleon
#

you'll need to retrieve their member object from a guild that they're in using Guild.get_member(), which also requires having the members and presences intent enabled in your client

#

if it returns the member object, you can then check their .status as usual

there's a bit more complexity to it, more specifically that discord doesnt send offline member objects for "large" guilds, i.e. 250+ members as set by discord.py, but in short if get_member() returns None you should assume that user is offline

sour bone
# hushed galleon tree commands receive a [discord.Interaction](<https://discordpy.readthedocs.io/...

I did this. The new code is -

@client.tree.command(name = "giveaway", description = "creates a giveaway")
async def giveaway (Interaction, duration_seconds: int, *, prize: str):
 if duration_seconds <= 0:
   await Interaction.response.send_message(f"Invalid duration. Please specify a positive number of seconds.")
   return
 else:
   message = await Interaction.response.send_message(embed=discord.Embed(
     title="๐ŸŽ‰ **Giveaway started!** ๐ŸŽ‰",
     description=f"Prize: {prize}\nDuration: {duration_seconds} second(s)\nHosted by: {Interaction.user.mention}\n\nReact with ๐ŸŽ‰ to participate!",
     color=discord.Color.blue()
   ))
   await Interaction.message.add_reaction('๐ŸŽ‰')
   await asyncio.sleep(duration_seconds)
   message = await Interaction.channel.fetch_message(message.id)
   reaction = discord.utils.get(message.reactions, emoji="๐ŸŽ‰")
   participants = [user for user in await reaction.users() if user != client.user]
   if participants:
       winner = random.choice(participants)
       winner_embed = discord.Embed(
           title="๐ŸŽ‰ **Giveaway ended!** ๐ŸŽ‰",
           description=f"Prize: {prize}\nWinner: {winner.mention}",
           color=discord.Color.blue()
       )
       await Interaction.response.send_message(embed=winner_embed)

And the error is in the image -

#

AttributeError: โ€˜nonetypeโ€™ objective has not attribute โ€˜add_reactionโ€™

hushed galleon
#

actually i'm not sure if calling original_response() updates the reaction count given that it gets cached...

#

btw speaking of count, you can use reaction.count to get the total for that reaction rather than looping through reaction.users() which makes an unnecessary API call

sour bone
hushed galleon
#

er no, original_response() is how you retrieve the message sent by send_message()

#

the caching issue might make that approach a problem though...

sour bone
#

What would you recommend doing?

hushed galleon
proud schooner
#

Yeah it gets the user. I then further carried on the command after testing it. i requested and it worked. I appreciate your help.

hushed galleon
#

in other words it might look like: ```py
await interaction.response.send_message("Starting giveaway...", ephemeral=True)
message = await interaction.channel.send("This is the giveaway!")
... # Wait for reactions, then fetch the users that reacted:
participants = [user async for user in reaction.users() if ...]

Pick winner as you used to, and use interaction.channel.send() to show the winner```

note: i missed the random.choice(participants) part and thought you just wanted the number of people that reacted, so ignore what i mentioned earlier about reaction.count

yet another note: the await reaction.users() syntax had a breaking change with discord.py 2.0 so it's outdated now, hence why i'm showing async for in the example
https://discordpy.readthedocs.io/en/stable/migrating.html#moving-away-from-custom-asynciterator

sour bone
#

Sorry

fickle aurora
#

Hey! I have a modal that requests 3 text inputs, one of those is server invite link, it is not required because I thought I could generate a server invite myself, but struggling with that. I have not found a method on discord.Guild that would create an invite, and using await interaction.channel.create_invite() results in a 404: Unknown Channel. How could I fix that? Or do I have to force invite link from the user in the modal?

sick birch
fickle aurora
#

wait what

#

this time it didnt do 404, but another error

#
  File "D:\bogdan\p\pikastats\venv\lib\site-packages\discord\ui\modal.py", line 188, in _scheduled_task
    await self.on_submit(interaction)
  File "D:\bogdan\p\pikastats\cogs\guild.py", line 141, in on_submit
    await channel.send(embed=embed)
TypeError: send() takes no keyword arguments```
#

since when does send take no kwargs ๐Ÿ’€

sour bone
#

I removed the adding reaction so it could just out the member that just pur the reaction there themselves . The code -

@client.tree.command(name = "giveaway", description = "creates a giveaway")
async def giveaway (Interaction, duration_seconds: int, *, prize: str):
if duration_seconds <= 0:
await Interaction.response.send_message(f"Invalid duration. Please specify a positive number of seconds.")
return
else:
message = await Interaction.response.send_message(embed=discord.Embed(
title="๐ŸŽ‰ Giveaway started! ๐ŸŽ‰",
description=f"Prize: {prize}\nDuration: {duration_seconds} second(s)\nHosted by: {Interaction.user.mention}\n\nReact with ๐ŸŽ‰ to participate!",
color=discord.Color.blue()
))
await asyncio.sleep(duration_seconds)
Interaction.channel.fetch_message(message.id)
reaction = discord.utils.get(message.reactions, emoji="๐ŸŽ‰")
participants = [user for user in await reaction.users() if user != client.user]
if participants:
winner = random.choice(participants)
winner_embed = discord.Embed(
title="๐ŸŽ‰ Giveaway ended! ๐ŸŽ‰",
description=f"Prize: {prize}\nWinner: {winner.mention}",
color=discord.Color.blue()
)

    await Interaction.response.send_message(embed=winner_embed)

And it still got a error โ€˜nonetypeโ€™ objective has no attribute โ€˜idโ€™ @hushed galleon

unkempt canyonBOT
#
Formatting code on Discord

Here's how to format Python code on Discord:

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

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

For long code samples, you can use our pastebin.

young dagger
#

How can you delete messages in bulk without getting ratelimited?

tardy crater
#

@proud schooner you need to await bot.fetch_guild i believe.

proud schooner
tardy crater
young dagger
proud schooner
#

It comes up at โ€œguildโ€ is not defined in vscode, thats trying to define the guild. The guild is fetching from a guild id (gid)

proud schooner
tardy crater
#

you also need @bot.event on the on_ready call i believe.

#

(that might be why guild isnt defined, because it isnt running)

pale zenith
#

discord.py preemptively sleeps before hitting them anyway

tardy crater
#

(its not anymore in case that wasnt clear)

#

thats really weird, i have almost the exact same code and it doesnt error out.

proud schooner
#

it works fine if i don't define guild, when i try to define guild it won't let me run it.

tardy crater
#

guild = await bot.fetch(gid) not the other way around.

proud schooner
#

That might be why..

pale zenith
tardy crater
pale zenith
#

the only thing that could mess with this is having multiple bots on the same IP address and they adding up to the global 50request/1s ratelimit, but that only happens in like repl.it shared IPs

tardy crater
pale zenith
#

I am... concerned

proud schooner
#

Okay, thank you guild is now defined. It was a stupid ass error on my half and I appreciate the help, I'm going to try figure out the rest of this now, thanks again!

proud schooner
# tardy crater cool, happy to help :)

Hey one quick question. I was wanting to @task.loop() something but I donโ€™t want it to end up spamming the channel unless my discord status changes, do you know how i could do that?

hushed galleon
#

and get_member() only works on cached guilds rather than one retrieved with fetch_guild()

tardy crater
tardy crater
proud schooner
#

Change a channel permission and send a message to a channel

tardy crater
#

having had a quick look though the docs, i just dont think discord.py has the listeners for this so you'll just have to loop your task and check each time.

#

if you really need it like this there might be a better solution

hushed galleon
tardy crater
pale zenith
#

cached Member.status is updated by discord.py through listening to on_presence_update since none of that is gettable through rest api

hushed galleon
tardy crater
pale zenith
#

!d discord.on_presence_update

unkempt canyonBOT
#

discord.on_presence_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) updates their presence.

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

โ€ข status

โ€ข activity

This requires [`Intents.presences`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.presences) and [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members) to be enabled...
tardy crater
pale zenith
#

yeah, but for the other person :)

tardy crater
#

fair enough

proud schooner
#

Wing it and see where i end up?

tardy crater
#

ye, just have a search around a see what you find. It should look something like this:/

#
@bot.event
async def on_presence_update(before, after):
  ...
#

seems pretty straightforward, what have you tried so far?

slate swan
#
    account_name = discord.ui.TextInput(label="The account name", placeholder="", required=True, max_length=20, style=discord.TextStyle.short)
    notable_items = discord.ui.TextInput(label="Account notable items", placeholder="", required=True, max_length=50, style=discord.TextStyle.short)
    sell_for = discord.ui.TextInput(label="Price", placeholder="", required=True, max_length=20, style=discord.TextStyle.short)
    extra = discord.ui.TextInput(label="Extra", placeholder="", required=False, max_length=20, style=discord.TextStyle.short)

    async def on_submit(self, interaction: discord.Interaction):
        await interaction.response.send_message(f"{interaction.user.mention} Thank you for submitting we will be with you as soon as possible!", ephemeral=True)
        channel = discord.utils.get(interaction.guild.channels, name="application")
        embed = discord.Embed(title='Application', description=f'Application Submitted By: {interaction.user.mention}')
        await channel.send(embed=embed)



@bot.tree.command(name="account", description="Apply to sell")
async def account(interaction: discord.Interaction):
    await interaction.response.send_modal(AccountModal())```

*I want to add a command that sends a embed with a button on it and then it pops up the modal i already coded can someone help me?*
pale zenith
#

discord.X will never refer to a specific instance/object of X. That's the class

#

The same can be said for any class

slate swan
#
    def __init__(self, app: str):
        super().__init__()
        self.app = app
        self.add_item(discord.ui.Button(label="Just a Test"))

        @discord.ui.button("Test Btn", style=discord.ButtonStyle.blurple)
        async def applyBtn(self, interaction: discord.Interaction):
            await interaction.response.send_message(self.app, ephemeral=True)

@bot.command()
async def apply(ctx: commands.Context):
    app = await ctx.channel.send()
    embed = discord.Embed(title="Apply at ", description=f"Press the button below to apply!")
    await ctx.send(embed=embed, view=ApplyButtons(str(app)))

class AccountModal(discord.ui.Modal, title=""):
    account_name = discord.ui.TextInput(label="", placeholder="", required=True, max_length=20, style=discord.TextStyle.short)
    notable_items = discord.ui.TextInput(label="", placeholder="", required=True, max_length=50, style=discord.TextStyle.short)
    sell_for = discord.ui.TextInput(label="", placeholder="", required=True, max_length=20, style=discord.TextStyle.short)
    extra = discord.ui.TextInput(label="", placeholder="n", required=False, max_length=20, style=discord.TextStyle.short)

    async def on_submit(self, interaction: discord.Interaction):
        await interaction.response.send_message(f"{interaction.user.mention} Thank you for submitting we will be with you as soon as possible!", ephemeral=True)
        channel = discord.utils.get(interaction.guild.channels, name="application")
        embed = discord.Embed(title='Application', description=f'Application Submitted By: {interaction.user.mention} \n Account Name: {self.account_name} \n Notable: {self.notable_items} \n Price: {self.sell_for} \n Extra: {self.extra}')```
#

i want a modal to pop up when a user clicks the button on the embed but i dont know how to do that this is my code can somsone help me?

sick birch
#

In applyBtn, that is

sick birch
#

Can you show your new code

slate swan
sick birch
# slate swan

It's just await interaction.response.send_modal(AccountModal())
Right now discord doesn't know what modal you want to send

slate swan
#

Yo I need help

#

it says something like @bot.command() expected an indented after function

vale wing
slate swan
#

Theres a new problem that im facing can u help

vale wing
slate swan
vale wing
slate swan
#

dm me ill send the problem

vale wing
#

No

slate swan
#

i made it in a server

#

so like i dont know if this ok or not

#

but let me screenshot

vale wing
#

You can describe the problem here

slate swan
#

The intent stuff

vale wing
#

Are you using some tutorial or something

slate swan
#

no

vale wing
#

Most of them are outdated and the only reliable way is to refer to documentation

#

!intents

unkempt canyonBOT
#
Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

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

For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.

slate swan
#

heh

#

still the same

slate swan
#

they should be on

#

I did

#

NVM

#

I FIXED IT tysm

shrewd fjord
vale wing
#

@final iron accept my friend request plz ๐Ÿ˜€

glad cradle
vale wing
slate swan
#

bruh

vale wing
#

Anyone seen sarth recently?

slate swan
#
    def __init__(self, app: str):
        super().__init__()
        self.app = app
        self.add_item(discord.ui.Button(label="Just a Test"))

        @discord.ui.button("Test Btn", style=discord.ButtonStyle.blurple)
        async def applyBtn(self, interaction: discord.Interaction):
            await interaction.response.send_modal(self.app, ephemeral=True)

@bot.command()
async def apply(ctx: commands.Context):
    app = await ctx.channel.send()
    embed = discord.Embed(title="Apply at rbxaccs", description=f"Press the button below to apply!")
    await ctx.send(embed=embed, view=ApplyButtons(str(app)))

class AccountModal(discord.ui.Modal, title="Sell your account!"):
    account_name = discord.ui.TextInput(label="The account name", placeholder="eg. exploit", required=True, max_length=20, style=discord.TextStyle.short)
    notable_items = discord.ui.TextInput(label="Account notable items", placeholder="eg. epic face", required=True, max_length=50, style=discord.TextStyle.short)
    sell_for = discord.ui.TextInput(label="Price", placeholder="eg. $200", required=True, max_length=20, style=discord.TextStyle.short)
    extra = discord.ui.TextInput(label="Extra", placeholder="eg. extra information", required=False, max_length=20, style=discord.TextStyle.short)

    async def on_submit(self, interaction: discord.Interaction):
        await interaction.response.send_message(f"{interaction.user.mention} Thank you for submitting we will be with you as soon as possible!", ephemeral=True)
        channel = discord.utils.get(interaction.guild.channels, name="application")
        embed = discord.Embed(title='Application', description=f'Application Submitted By: {interaction.user.mention} \n Account Name: {self.account_name} \n Notable: {self.notable_items} \n Price: {self.sell_for} \n Extra: {self.extra}')
        await channel.send(embed=embed)```

Error is I cant send an empty message? I want the button to be clicked then the modal pops up
naive briar
unkempt canyonBOT
#
Traceback

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.

slate swan
# naive briar !traceback send the traceback

Traceback (most recent call last):
File "C:\Users\RHG\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 235, in wrapped
ret = await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\RHG\Documents\rbxaccs\main.py", line 23, in apply
app = await ctx.channel.send()
^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\RHG\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\abc.py", line 1561, in send
data = await state.http.send_message(channel.id, params=params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\RHG\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\http.py", line 745, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message

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

Traceback (most recent call last):
File "C:\Users\RHG\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\RHG\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 1029, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\RHG\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 244, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message

winter hare
#

so i have this lfg modal code:

    async def on_submit(self, interaction: discord.Interaction):
        category_name = "Games"  
        category = discord.utils.get(interaction.guild.categories, name=category_name)
        vc_name = f"{self.game} - {interaction.user.display_name}"
        vc = await category.create_voice_channel(vc_name)
        ck = discord.Embed(title= f'Description: {self.info}', timestamp= datetime.now(), type='rich', color=discord.Color.random())
        ck.add_field(name=' Game',value=f'{self.game}', inline=True)
        ck.add_field(name=f' Game Mode',value=f' {self.type}', inline=True)
        ck.add_field(name=f' Region',value=f'{self.region}', inline=True)
        ck.add_field(name='  VC/Lobby Space', value=f'{len(vc.members)}/{vc.user_limit} members in VC right now!')
        ck.set_footer(text='use /invite to create your own game invite!')
        invite = await vc.create_invite(max_age=0, max_uses=0, unique=True)
        ck.add_field(name=f'**{vc.name} | {vc.category}** ', value=f'**[Click here to join]({invite.url})** ', inline=True)
        ck.set_author(name=f' {interaction.user.display_name} is looking for party members!', icon_url=f'{interaction.user.guild.icon}', url = 'https://discord.com/users/' + str(interaction.user.id))
        ck.set_thumbnail(url=f'{str(random.choice(list))}')
        await interaction.response.send_message(embed=ck)
        await interaction.user.edit(voice_channel=vc)
        await vc.set_permissions(interaction.user,manage_members=True,move_members=True,moderate_members=True)```
everything works fine but it gives an error saying "Target user is not connected to voice." i was initally using `await interaction.user.edit(voice_channel=vc)` but that doesnt work so what's a way of adding a user to a voice channel

i want to add a user to a vc without them being in a vc previously
shrewd apex
#

college stuff

#

y tho?

vale wing
#

@naive briar can you add me? Got a personal invitation for you

naive briar
#

Sounds suspicious

vale wing
#

๐Ÿ‘๏ธ๐Ÿ‘„๐Ÿ‘๏ธ

vale wing
naive briar
#

I'm not into bot dev currently, so no

vale wing
#

Ok

glad cradle
glad cradle
vale wing
#

๐Ÿ˜ญ

#

Idek what to tell people to convince them

stoic tusk
#

how do I do a timeout command ?

naive briar
#

Your own timeout command or the built-in one?

naive briar
glad cradle
stoic tusk
vale wing
#

Snipy turned into white van kidnapper

glad cradle
vale wing
# stoic tusk my own

y do you need one sure, you will need a database and background loop with tasks.loop

stoic tusk
sick birch
sick birch
odd pawn
#

@sick birch-

slate swan
# sick birch ```diff @discord.ui.button("Test Btn", style=discord.ButtonStyle.blurple) async ...

Traceback (most recent call last):
File "C:\Users\RHG\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 235, in wrapped
ret = await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\RHG\Documents\rbxaccs\main.py", line 23, in apply
app = await ctx.channel.send()
^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\RHG\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\abc.py", line 1561, in send
data = await state.http.send_message(channel.id, params=params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\RHG\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\http.py", line 745, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message

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

Traceback (most recent call last):
File "C:\Users\RHG\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\RHG\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 1029, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\RHG\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 244, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message

#

still getting this

odd pawn
sick birch
slate swan
sick birch
slate swan
#

i dont know what to put so i just tried that

lime temple
#

Hey i have a bot that creates pictures with pixels. This is the first print but i wanna train and improve it. The bot is currently selecting a sample visual from the database and changing it but what i want to do is that when it changes the picture, it detects it when i press the yes or no buttons that appear underneath it it will regenerate a image. if i press the yes button it will say ''ahh he like this image and that's how I need to do the next pictures''. (This is cringe ik but dont know how to explain it :D) any idea, video, article? (please ping me <3)

mighty pilot
#

If I import something in my main file does that cover it for cogs too or do I have to import from inside the cog

pale zenith
mighty pilot
#

Ok thanks

slate swan
#

!intents

unkempt canyonBOT
#
Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

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

For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.

slate swan
#

currently making a bot which screenshots an html page

#
<style>
        * {
            margin: 0;
            padding: 0;
        }
        @font-face {
            font-family: 'Whitney';
            src: url('fonts/Whitneyfont.woff') format('woff');
        }
        @font-face {
            font-family: 'WhitneyMedium';
            src: url('fonts/Whitneymedium.woff') format('woff');
        }
        body {
            background-color: #36393f;
            font-family: 'Whitney', sans-serif; 
        }
        .whitney-medium {
            font-family: 'WhitneyMedium', sans-serif;
        }
    </style>
#

the html isnt changing to my desired font in the screenshot

#

instead of whitney its changing to sans serif and idk why/how to fix or change it

proud schooner
#

Thats cool

vale wing
shrewd apex
slate swan
slate swan
#

anyone here know digital art anyhow?

naive briar
#

That doesn't sound to be related to Discord bots

slate swan
vital axle
#

!e

a = 1
print(a*100)
unkempt canyonBOT
#

@vital axle :white_check_mark: Your 3.12 eval job has completed with return code 0.

100
near sail
#

You can use on_command_completion

proud schooner
#

Thanks. Iโ€™ll give it a shot!

proud schooner
#

Thank you!

timid sparrow
#

!e

unkempt canyonBOT
#
Missing required argument

code

timid sparrow
#

!e

a = 10
e = 20
b = 50
print("a+b+e*1000)```
unkempt canyonBOT
#

@timid sparrow :x: Your 3.12 eval job has completed with return code 1.

001 |   File "/home/main.py", line 4
002 |     print("a+b+e*1000)
003 |           ^
004 | SyntaxError: unterminated string literal (detected at line 4)
timid sparrow
#

!e

a = 10
e = 20
b = 50
print("a + b + e * 1000)โ€Š```
unkempt canyonBOT
#

@timid sparrow :x: Your 3.12 eval job has completed with return code 1.

001 |   File "/home/main.py", line 4
002 |     print("a + b + e * 1000)
003 |           ^
004 | SyntaxError: unterminated string literal (detected at line 4)
civic reef
#

has anyone used codeforces API?

#

DM me

unkempt canyonBOT
#

@simple surge :white_check_mark: Your 3.12 eval job has completed with return code 0.

even numbers: 30
finite salmon
#

If you need help you can ask it here itself

#

You're more likely to get help in the server than dms

civic reef
#

๐Ÿ™

summer axle
#

my interaction.response.send_message dont work

Traceback (most recent call last):
  File "/home/container/.local/lib/python3.9/site-packages/discord/ui/view.py", line 427, in _scheduled_task
    await item.callback(interaction)
  File "/home/container/python.py", line 62, in select_callback
    await interaction.response.send_message(f"Hienoa! Pidรคn myรถs {select.values[0]}:sta!")
AttributeError: 'Select' object has no attribute 'response'```
dreamy dune
slate swan
#

its Select object

azure tulip
#

please help code doesn't work, no errors

import io

from PIL import Image, ImageDraw, ImageFont
from nextcord.ext import commands, tasks


class Banner(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_ready(self):
        self.update_banner.start()
        self.last = 0

    @tasks.loop(minutes=1)
    async def update_banner(self):
        await self.bot.wait_until_ready()
        guild = self.bot.get_guild(1048990513568686080)
        with Image.open("Banner.png") as img:
            draw = ImageDraw.Draw(img)

            font = ImageFont.truetype("Gilroy-Medium.ttf", 130)
            total = len(guild.members)
            voice = len([m for m in guild.members if m.voice])
            # check if the voice count is different from the last value
            if voice != self.last:
                x = 1040 #945
                y = 300   #400          #311
                draw.text((x, y), str(voice), font=font)
                img_bytes = io.BytesIO()
                img.save(img_bytes, format="png")
                img_bytes.seek(0)
                bytes = img_bytes.read()
                # use banner_url instead of banner
                await guild.edit(banner_url=bytes)
                # save only the voice count
                self.last = voice


def setup(bot):
    bot.add_cog(Banner(bot))
drifting arrow
#

What's the decorator for giving slash command params descriptions?

drifting arrow
#

This doesn't necessarily mean the code above is working as intended, it just means the code above might not be where the error lies. You'd also want to print the variables above the print statement to ensure it's storing the expected value

golden portal
drifting arrow
#

ty ty

drifting arrow
#

Does discordpy have a param thingy for dates/datetime?
Like how it does for things like channels, users and true/false?

drifting arrow
#

;-;

pale zenith
#

This is harder to implement than you think if one would want it implemented into the library itself

drifting arrow
#

So what you're saying is.. I could do /remindme date:<date> and the <date> is calender picker?

pale zenith
#

Because you need to take into consideration different date formats and shit. For example most of the western world uses dd/mm/yy, but the united has it backwards. So like 10/12 would mean the 10 of December for most people, except some

#

So you need to take some biased decisions implementing this, that could mildly inconvenience some people

#

(the code itself for parsing a date is trivial tho)

pale zenith
#

I fucking wish they did.

drifting arrow
#

D:

pale zenith
#

It's all string parsing

#

Always_has_been_astronaut.png

vale wing
pale zenith
flat solstice
#

I haven't used timestamps with bots in ages so I don't really remember what does and doesn't work, but can bots use timestamps like <t:1706269244:R>. in Embeds, specifically in field values and footers?

blazing condor
#

yeah, think you're thinking of Embed.timestamp

golden portal
#

^only for footer

#

!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) for presentation within Discord.

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

for others

blazing condor
#

ah that's it, thanks flower.

#

couldn't remember.

flat solstice
#

okay thanks

slate swan
#

using my old discord code to fix some stuff, have to instal easy_pil but i get this error whats it mean?

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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

vale wing
#

But I suspect it's cause ms build tools are not installed

hushed galleon
#

doesnt aiohttp already have 3.12 wheels though? why is it trying to build from (a presumably outdated) source?

drifting arrow
#

How do I get how many users are in my server?

#

it's something like guild.get_users() right?

dreamy dune
drifting arrow
#

lol that simple huh?

hushed galleon
#

as per docs, you'll also need member caching nvm just the intents for join/leave events if you want member_count to stay in sync after on_ready

young dagger
#

How can I make the bot delete any discord link without deleting my own servers link?

hushed galleon
#

assuming you have an invite regex, you can compare the invite code against some whitelist

#

or if you want to support any valid invite, like those created by users, you can use Client.fetch_invite() to verify that it points to your server

vocal plover
#

not with a simple api call, you'd either need to start fetching messages until you find (or don't find - this can end up as a very big pointless search) a message from them, please don't do that, or you listen for messages from when your bot joins the server and just go from there, storing the message or whatever your usecase is, as you see them

hushed galleon
#

maybe one day, discord's API could open the search functionality to bots

quiet venture
#

How can i make bot

timid sparrow
#

!e

unkempt canyonBOT
#
Missing required argument

code

timid sparrow
#

!e for i in range ("1,1000")
print("Hello, World!")

unkempt canyonBOT
#

@timid sparrow :x: Your 3.12 eval job has completed with return code 1.

001 |   File "/home/main.py", line 1
002 |     for i in range ("1,1000")
003 |                              ^
004 | SyntaxError: expected ':'
timid sparrow
#

!e for i in range ("1,1000");
print("Hello, World!")

unkempt canyonBOT
#

@timid sparrow :x: Your 3.12 eval job has completed with return code 1.

001 |   File "/home/main.py", line 1
002 |     for i in range ("1,1000");
003 |                              ^
004 | SyntaxError: invalid syntax
timid sparrow
#

!e for i in range ("1,1000"):
print("Hello, World!")

unkempt canyonBOT
#

@timid sparrow :x: Your 3.12 eval job has completed with return code 1.

001 |   File "/home/main.py", line 2
002 |     print("Hello, World!")
003 |     ^
004 | IndentationError: expected an indented block after 'for' statement on line 1
pale zenith
ornate crater
#

What the problem?

shrewd apex
#

u dont need to call intents again ()

#

also its discord.Client

#

!d discord.Client

unkempt canyonBOT
#

class discord.Client(*, intents, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.

async with x Asynchronously initialises the client and automatically cleans up.

New in version 2.0.

A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client).
shrewd apex
#

!d discord.ext.commands.Bot ideally you should use this tho

unkempt canyonBOT
#

class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.

This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) you can do with this bot.

This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin) to provide the functionality to manage commands.

Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree) and is automatically set upon instantiating the class.

async with x Asynchronously initialises the bot and automatically cleans up.

New in version 2.0.
shrewd apex
#

from discord.ext import commands and then commands.Bot()

plain lake
#

im making a discord bot integrated with the google classroom api. its my first time working making a discord bot and i kinda need help on it

#

mainly with authentication

young dagger
#

AttributeError: 'PartialMessage' object has no attribute 'embeds'

dm_message = client.get_partial_messageable(case["dm_channel_id"]).get_partial_message(
                        case["dm_message_id"])

embed = dm_message.embeds[0]

await dm_message.edit(embed=embed)
#

Why can't I edit the embed?

pale zenith
#

a partial message is basically just an ID

#

for when you don't need any information.

#

!d discord.PartialMessageable.fetch_message

unkempt canyonBOT
#

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

Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message) from the destination.
young dagger
pale zenith
#

if you don't need it, yes. if you are planning to edit that embed, you will need to actually retrieve it thru fetching

young dagger
pale zenith
young dagger
# pale zenith if (need to access data from message) -> you fetch so no, not for deleting/editi...

Do you know what this could be?

            # Fetch the channel and message using the action_log message ID
            channel = client.get_channel(745832392404762695)
            message = await channel.fetch_message(case["action_log"])

            # Update the embed with the new reason
            message_embed = message.embeds[0]  # Assuming there is only one embed in the message
            message_embed.set_field_at(index=3, name="Reason", value=new_reason, inline=False)

            # Update the message with the modified embed
            await message.edit(embed=message_embed)
#
Traceback (most recent call last):
  File "C:\Users\Gamer\PycharmProjects\pythonProject\venv\lib\site-packages\discord\ext\commands\core.py", line 235, in wrapped
    ret = await coro(*args, **kwargs)
  File "D:\discord bots\blitzcrank.py", line 2857, in set_reason
    message_embed.set_field_at(index=3, name="Reason", value=new_reason, inline=False)
  File "C:\Users\Gamer\PycharmProjects\pythonProject\venv\lib\site-packages\discord\embeds.py", line 704, in set_field_at
    raise IndexError('field index out of range')
IndexError: field index out of range
pale zenith
#

Your embed has less than 4 fields.

#

you're trying to modiy the fourth field (3) and there isn't one.

young dagger
#

What does this mean?

Traceback (most recent call last):
  File "C:\Users\Gamer\PycharmProjects\pythonProject\venv\lib\site-packages\discord\ext\commands\core.py", line 235, in wrapped
    ret = await coro(*args, **kwargs)
  File "D:\discord bots\blitzcrank.py", line 2908, in set_reason
    await dm_message.edit(embed=embed, view=view)
  File "C:\Users\Gamer\PycharmProjects\pythonProject\venv\lib\site-packages\discord\message.py", line 983, in edit
    data = await self._state.http.edit_message(self.channel.id, self.id, params=params)
  File "C:\Users\Gamer\PycharmProjects\pythonProject\venv\lib\site-packages\discord\http.py", line 745, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In channel_id: Value "None" is not snowflake.
In message_id: Value "None" is not snowflake.
hushed galleon
young dagger
#

I simply changed it to:

if "dm_channel_id" in case and "dm_message_id" in case and case["dm_channel_id"] is not None and case[
                    "dm_message_id"] is not None:
somber sky
#
@client.tree.command(description='List of all Franchise Owners')
async def folist(ctx):
    teams = discord.utils.find(lambda r: r.name in nflRoleListNames, ctx.user.roles)
    mapping = {
      role: discord.utils.get(ctx.guild.emojis, name=emoji.strip(":"))
      for role, emoji in zip(nflRoleListNames, nflEmojiListNames)
    }
    emoji = mapping.get(teams.name)
    client.memberList = []

    nflRoleNum = range(len(r.nflRoleListNames))
    nflRoleList = []
    i = 0
    for i in nflRoleNum:
        role = discord.utils.get(ctx.guild.roles, name=r.nflRoleListNames[i])
        nflRoleList.append(role)
        i = i + 1

    role = discord.utils.get(ctx.guild.roles, name="Franchise Owner")

    empty = True
    for member in ctx.guild.members:
        if role in member.roles:
            userRoleSet = set(member.roles)
            teamRoleSet = set(nflRoleList)
            currentTeam = userRoleSet.intersection(teamRoleSet)
            if currentTeam == set():
                currentTeam = "No Team Detected"
            else:
                currentTeam = list(currentTeam)
                currentTeam = currentTeam[0].mention
            client.memberList.append(
                f"{emoji }{currentTeam} - {member.mention} `{member}`")

            empty = False
    if empty:
        await ctx.response.send_message(f"There are no franchise owners.", ephemeral=True)
        return
    foNum = len(client.memberList)
    embed = discord.Embed(title="Franchise Owners",
                          description='\n'.join(client.memberList))
    embed.add_field(name="Amount", value=f"{foNum}/32")
    embed.set_thumbnail(url=ctx.guild.icon)
    embed.set_author(name=f"{ctx.guild.name}", icon_url=ctx.guild.icon)
    await ctx.response.send_message(embed=embed, ephemeral=True)```

how do i make it where it puts the emoji that connects with the current team like the image, ik it checks for the role in the user so im tryna figure out how to make it where it its like the pic
vale wing
#

Action on message edit?

proud schooner
# vale wing Action on message edit?

Basically when someone wins a game I want it to edit the message that was sent in the logs channel. I know it's possible but my brain is ๐Ÿ’ฉ when it comes to things i've not got the grip of or learnt.

#

I know self.edit_original_reponse would work but it's as a async so self is not supported.

vale wing
#

Associate the sent message object with some game ID or store it in the game, like

async def log(...):
    ...
    return await channel.send(...)
#

I don't know how you handle games so can't provide example code for the storage itself

#

Key thing is you can store message object

#

Not persistently but I assume you don't need it to be persistent

proud schooner
#

It's not a proper game, it's just a discord bot coded game. I might remove the async and just do it so it will edit original response.

vale wing
vale wing
proud schooner
#

would that work?

vale wing
#

๐Ÿง

proud schooner
#

I'll try it

vale wing
#

I don't get how this is related

#

Your log must return the message, you store that message, when need to edit, just access it

proud schooner
#

So how would i log it?

vale wing
proud schooner
#

As i said its a discord coded bot itโ€™d have to be logged in a json file or?

vale wing
#

It's a discord bot coded in python, this is python code

#

Don't get where the issue is

#

And how is json related to this

#

Could you show your game code

proud schooner
#

Basically iโ€™m asking its all fully coded in python. No game related so would i have to log the log in json and read the json file?

vale wing
#

I don't understand anything from your descriptions, sorry

proud schooner
#

The game code was fully made in discord.py. There is no game it links to.

#

Let me get the code

proud schooner
#
@bot.tree.command(name="mines", description="mines")
async def mines(interaction: discord.Interaction, mines_amount: int, bet: str):
    valid = True
    uid = str(interaction.user.id)
    bet = suffix_to_int(bet)
    
    if mines_amount >= 25 or mines_amount <= 0:
        valid = False
        embed = discord.Embed(title=":x: Error",
                              description="Invalid Number Of Mines",
                              color=0xff0000)
        embed.set_author(name="Bot Central",
                         icon_url="https://cdn.discordapp.com/icons/1189054412459622400/b8533545e1e91a4ca2ada9f4d5a4e1.png?size=4096")
        embed.set_footer(text="games")
        await interaction.response.send_message(embed=embed)
        return
    if valid:
        subtract_gems(uid, bet)
        af = get_affiliate(str(interaction.user.id))
        add_gems(af, bet * 0.1)
        board = generate_board(mines_amount)
        userboard = [
            ["", "", "", "", ""],
            ["", "", "", "", ""],
            ["", "", "", "", ""],
            ["", "", "", "", ""],
            ["", "", "", "", ""],
        ]
        coollooking = '\n'.join([' '.join(sublist) for sublist in board])
        await log(f"{interaction.user.name} Started A Mines Game! Board:\n\n{coollooking}")
        await interaction.response.send_message(
            content=f":moneybag: **Winnings:** ``{add_suffix(bet * 0.80)}`` :star: **Multiplier:** ``0.80``",
            view=MinesButtons(bet=bet, board=board, bombs=mines_amount, interaction=interaction, usersafes=0,
                              userboard=userboard, exploded=False))```
vale wing
#

Okay, so the game is handled in MinesButtons view I presume?

proud schooner
#

That is correct.

vale wing
#

When does it finish? When you press sort of end button?

proud schooner
#

When it finishes you have to press a button let me get that bit of the code.

#
 async def button_cashout(self, interaction: discord.Interaction):
        if interaction.user.id == self.interaction.user.id:
            multi = round(calculate_mines_multiplier(
                self.bombs, self.usersafes, MineHouseEdge), 2)
            add_bet(str(interaction.user.id), self.bet, round(self.bet * multi))
            bet = self.bet
            winnings = self.bet * multi - bet
            total = winnings + bet
            add_bet(str(self.interaction.user.id), bet, winnings )
            await self.interaction.edit_original_response(
                content=f":star: Cashed Out! (**Profit:** ``{add_suffix(round(winnings))}``, **Multiplier:** ``{multi}``\n Total: ``{total}``)",
                view=MinesButtons(bet=self.bet, board=self.board, bombs=self.bombs, interaction=self.interaction,
                                  usersafes=self.usersafes, userboard=self.userboard, exploded=True))
vale wing
#

All you need to do is make your log return message, add the message attribute to your view, and just access it in finish callback

proud schooner
vale wing
#

Pseudo

proud schooner
#

Im shit at discord.py idk what goes in the โ€ฆโ€™s ๐Ÿ˜ญ

somber sky
vale wing
proud schooner
#

I get you now.

vale wing
somber sky
#

not really good with databases so i just found an easier way

vale wing
#

There are also some weird constructions like

for i in range(...):
    ...
    i += 1
#

One question tho, how exactly are emojis connected to roles? Are those role icons? Or do you define the emojis by yourself

somber sky
#

i have a list of emojis names and also the roles so it like checks both and finds what names are connected

#

idk how to explain it without in sounding confusing

vale wing
#

Wouldn't it be better to map roles names to emojis

#

Are emojis yours

vale wing
#

Even code looks confusing

somber sky
#
nflRoleListNames = [
    "Arizona Cardinals", "Baltimore Ravens", "Atlanta Falcons",
    "Buffalo Bills", "Carolina Panthers", "Cincinnati Bengals",
    "Chicago Bears", "Cleveland Browns", "Dallas Cowboys", "Denver Broncos",
    "Detroit Lions", "Houston Texans", "Green Bay Packers",
    "Indianapolis Colts", "Los Angeles Rams", "Jacksonville Jaguars",
    "Minnesota Vikings", "Kansas City Chiefs", "New Orleans Saints",
    "Las Vegas Raiders", "New York Giants", "Los Angeles Chargers",
    "Philadelphia Eagles", "Miami Dolphins", "San Francisco 49ers",
    "New England Patriots", "Seattle Seahawks", "New York Jets",
    "Tampa Bay Buccaneers", "Pittsburgh Steelers", "Washington Commanders",
    "Tennessee Titans"
]

nflEmojiListNames = [
    ":Arizona_Cardinals:", ":Baltimore_Ravens:", ":Atlanta_Falcons:",
    ":Buffalo_Bills:", ":Carolina_Panthers:", ":Cincinnati_Bengals:",
    ":Chicago_Bears:", ":Cleveland_Browns:", ":Dallas_Cowboys:",
    ":Denver_Broncos:", ":Detroit_Lions:", ":Houston_Texans:",
    ":Green_Bay_Packers:", ":Indianapolis_Colts:", ":Los_Angeles_Rams:",
    ":Jacksonville_Jaguars:", ":Minnesota_Vikings:", ":Kansas_City_Chiefs:",
    ":New_Orleans_Saints:", ":Las_Vegas_Raiders:", ":New_York_Giants:",
    ":Los_Angeles_Chargers:", ":Philadelphia_Eagles:", ":Miami_Dolphins:",
    ":San_Francisco_49ers:", ":New_England_Patriots:", ":Seattle_Seahawks:",
    ":New_York_Jets:", ":Tampa_Bay_Buccaneers:", ":Pittsburgh_Steelers:",
    ":Washington_Commanders:", ":Tennessee_Titans:"
]```


```py
    teams = discord.utils.find(lambda r: r.name in nflRoleListNames, ctx.user.roles)
    mapping = {
      role: discord.utils.get(ctx.guild.emojis, name=emoji.strip(":"))
      for role, emoji in zip(nflRoleListNames, nflEmojiListNames)
    }
    emoji = mapping.get(teams.name)```
vale wing
#

Not just name inside colons

#

To get this format, send a message yourself, not with bot with emoji and put a \ before it, like

\:emoji_name:
somber sky
# vale wing Not just name inside colons

the bot is a public bot, the emojis are like that because i have a command which generates emojis with the names like that. every person who has the bot generates the emojis with that name

fast musk
#

what is the question?

vale wing
unkempt canyonBOT
#

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

001 | ๐Ÿ˜€ - Sus Role
002 | ๐Ÿ”ฅ - Fire Role
003 | ๐Ÿ˜ˆ - idiot
vale wing
somber sky
#

i'd have to re write mad code and learn it when it alrerady works fine

vale wing
#

You will just continue to lose braincells if you keep using names

fast musk
#

well, tbf database only helps a lot when you are trying to make it work for multi guild

vale wing
#

And just let someone rename role/emoji and the whole thing is screwed

fast musk
#

sounds like this is a 1 guild bot

#

likely they are the admin

vale wing
#

@somber sky is this single server bot

somber sky
#

its supposed to be a a multi but like i said if it works fine im not about to learn databases and re write my whole code which is over 2.3k lines

fast musk
#

oh sweet summer child

#

Don't worry, you'll rewrite it eventually haha

somber sky
#

i dont see why

fast musk
#

That's the fun part

#

(not knowing why yet haha)

vale wing
#

However before rewriting it completely take a look into cogs as well

#

2.3k lines in one file ain't good

#

Especially considering that's probably entire project in one file

#

And of course naming convention

#

Learn these things on side project and proceed to rewriting โ˜บ๏ธ

  1. Style conventions (see PEP 8)
  2. Cogs and extensions (dpy devs are bad, couldn't even include proper example of using cogs in extensions), will need a guide for this however
  3. Databases: start with sqlite, switch to aiosqlite (it's just async version of builtin lib) when understood how things work
proud schooner
#
@bot.tree.command(name="claim-rakeback", description="View Your Rakeback")
async def claimrake(interaction: discord.Interaction):
    uid = str(interaction.user.id)
    if is_registered(str(interaction.user.id)):
        rake_back = get_rake_back(uid)
        rbclaimed = GetTotalRbClaimed
        totalrb = rbclaimed+rake_back
        if rake_back > 0:
            add_rbc(uid, rake_back)
            set_rake_back(uid, 0)
            add_gems(uid, rake_back)
            await log(f"<@{uid}> Claimed {add_suffix(rake_back)} Rakeback")
            embed = discord.Embed(title=f":white_check_mark: Claimed Rakeback",
                                  description=f"You Claimed :gem: ``{add_suffix(rake_back)}\n You now have a total of ``{add_suffix(totalrb)}`` rakeback claimed. Nice!",
                                  color=0x88ff70)
            await interaction.response.send_message(embed=embed)

I get an error when trying to add the two together. The error is: discord.app_commands.errors.CommandInvokeError: Command 'claim-rakeback' raised an exception: TypeError: unsupported operand type(s) for +: 'function' and 'int' meaning the + is the error. Is there any way i can fix this, any help will do! Thanks.

dreamy dune
#

You should also use the same naming convention as other functions

proud schooner
proud schooner
dreamy dune
#

You usually name classes like that, with a capital first letter (PascalCase)

proud schooner
proud schooner
slate swan
#

!e ```py
x = 1
x + 2
print(x)

unkempt canyonBOT
#

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

1
slate swan
#

!e ```py
x = 1
x += 2
print(x)

unkempt canyonBOT
#

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

3
proud schooner
#

?

#

So plus on it's own = 0 and += means 1?

slate swan
#

no when you do x + 1 it doesnt save x value for later with one added

proud schooner
#

I'll look into changing that for all my command. can you help with my other error?

proud schooner
#

it isnt adding my data

slate swan
#

didnt i just help you with that?

proud schooner
#

no that was something completely different

#

thats adding a total of said amount

slate swan
#

but i was writing that for this problem

proud schooner
#

it works I appreciate your time!

faint rapids
proud schooner
naive briar
naive briar
unkempt canyonBOT
#
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!
young dagger
#

I haven't seen XOR (Exclusive OR) being used in Discord bots a lot, why is that?

smoky anvil
#

2024-01-27 11:59:03 ERROR discord.client Ignoring exception in on_member_join
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "/home/container/cogs/invites.py", line 223, in on_member_join
inv = invites[invite.id]
~~~~~~~^^^^^^^^^^^
KeyError: '3a9g4XQe'

#

How do i solve this?

#
    @commands.Cog.listener()
    async def on_member_join(self, member: discord.Member) -> None:
        guild = member.guild
        if guild.id != GUILD_ID:
            return

        guild_invites = await guild.invites()
        invites = {inv.id: inv for inv in guild_invites}
        for invite in self.cached.values():
            inv = invites[invite.id]
            assert inv.uses is not None
            if inv.uses > invite.uses:
                await invite.add_uses(1)
                await self.add_invite_to_user(inv)
                await self.send_join_message(member, inv)
young dagger
# slate swan what you mean by that

This kind of stuff:

team_1_scored = 5
team_2_scored = 5

has_winner = team_1_scored ^ team_2_scored

if has_winner:
    print("There is a winner!")
else:
    print("It's a tie!")
shrewd apex
#

do uk what xor does?

young dagger
#

Using the exclusive or

young dagger
shrewd apex
#

binary for 5 is 101
101 ^ 101 will give 000
truth table for xor is

a b
0 0 0
0 1 1
1 0 1
1 1 0
#

so its entirety logic dependent where u want to use it

#

usually its more verbose to use relational operators as far more people are used to it

#

u generally see bit operations in stuff like bit packing, saving some space during computation, flags and so on ur day to day logic dosent require u to meddle with these much

young dagger
#

Right?

vale wing
#

There should be != instead

young dagger
#

That is what I just said ๐Ÿ™‚

#

Can you give me an example when you could use the xor operator?

vale wing
#

XOR is widely used in cryptography, cause if you add c column to asher's table, you will see that

a ^ b = c
a ^ c = b
b ^ c = a

Which means you can make any of these original data, key and encrypted data

vale wing
young dagger
#

Can somebody explain why there always is a winner?

A = 5
B = 5

if A or B and A != B:
    result = "There is a winner."
else:
    result = "It's a tie!"

print (result)```
young dagger
slate swan
#

cause you didnt wrap those in ()

#

if (A or B) and (A != B):

#

but like i said this can be simplified to if A != B:

young dagger
young dagger
slate swan
#

cause python interprets this as if it was if A or (B and A != B):

young dagger
#

My friend just told me "Don't be shy of your parentheses" I will try to keep that in mind ๐Ÿ˜„

hazy kraken
#

hello

golden portal
#

hello

hazy kraken
#

i've a problem

golden portal
#

same, but irl

#

if you have a question you can ask here

hazy kraken
hazy kraken
#

And Iโ€™m not understanding why ..

hazy kraken
#
Traceback (most recent call last):
  File "/home/container/bot.py", line 32, in <module>
    asyncio.run(main())
  File "/usr/local/lib/python3.10/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/usr/local/lib/python3.10/asyncio/base_events.py", line 649, in run_until_complete
    return future.result()
  File "/home/container/bot.py", line 29, in main
    async with client: 
AttributeError: __aenter__
golden portal
#

maybe a mismatch of discordpy versions

#

whats the dpy version?

hazy kraken
vocal snow
#

on both your local enviroment and the host?

hazy kraken
#

mm idk how to see the version in my host

golden portal
#

print(discord.__version__)

hazy kraken
#

but-

#

how to print??

vocal snow
#

which host are you using?

hazy kraken
#

is mine

#

mmm i'm using pterodactyl panel-

golden portal
hazy kraken
#

discord.py==2.3.2

golden portal
#

hmm

#

latest dpy should have Client.__aenter__

vocal snow
#

do you have any other discord api wrappers installed on the host?

#

like py-cord or disnake or whatever

hazy kraken
#

let me see

#

py-cord==2.0.0b7

vocal snow
#

that might be why

hazy kraken
#

aha-

vocal snow
#

try uninstalling it and see if it helps

hazy kraken
#

alr

#

i've other inquirement

#

my vsc using phython 3.10.11 and my host 3.10.13

#

how to change my vsc? -

golden portal
#

shouldn't matter, only thing that affects dpy is python 3.12, and also dpy forks

hazy kraken
golden portal
#

maybe a clean reinstall

hazy kraken
golden portal
#

pip install -U --force-reinstall discord.py

hazy kraken
#

idk why-

golden portal
#

i see

hazy kraken
hazy kraken
half reef
#

Hello guys
I'm python beginner and need some help

half reef
#

I can't learn
I need someone to help me
Cause I started to learn and couldn't because the course is full of rules and stuff without projects so you learn for no particular reason

hazy kraken
#

oh

half reef
#

Then I started the projects
It's just tasks
Nobody does both teach and projects at the same time

slate swan
half reef
#

I wanna know how did you start
Cause I've no clou about the journey and how should it be

cold sonnet
shrewd apex
#

this is a python server? thats js?

#

also u didn't send the code how would we know whats wrong best we have is the error telling "this '}' was unexpected/not needed"

smoky anvil
#

2024-01-27 11:59:03 ERROR discord.client Ignoring exception in on_member_join
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "/home/container/cogs/invites.py", line 223, in on_member_join
inv = invites[invite.id]
~~~^^^^^^^^^^^
KeyError: '3a9g4XQe'
How do i solve this?

slate swan
#

@oak orchid

#

u free rn?

slate swan
shrewd apex
#

is it python related if it is then ask here

slate swan
#

tottaly python related

shrewd apex
#

then ask here

slate swan
#

what specific file do i make to work on the bot

vast crest
#

visual studio code?

slate swan
#

like any extension

shrewd apex
#

ur run the main bot code containing the bot class

#

any other extensions or cogs are loaded from the main bot class

young dagger
#

@pale zenith Can you edit an embed with discord.PartialMessageable in a channel as well?

#

Instead of using message = await channel.fetch_message(case["action_log"])

naive briar
#

Try and see

pale zenith
young dagger
#

There is no idea to fetch the message as I already got the message ID

pale zenith
naive briar
unkempt canyonBOT
#

class discord.PartialMessage(*, channel, id)```
Represents a partial message to aid with working messages when only a message and channel ID are present.

There are two ways to construct this class. The first one is through the constructor itself, and the second is via the following...
young dagger
pale zenith
#

only if you need info from the channel

naive briar
pale zenith
#

ParialX -> no info, only api calls

young dagger
pale zenith
#

what?

#

no?

leaden olive
#

why isnt that working?

young dagger
# pale zenith no?

So fetching users will not result in the same as fetching the message, as we still need to obtain some data?

glad marsh
leaden olive
pale zenith
glad marsh
leaden olive
#

np ๐Ÿ‘

dreamy dune
leaden olive
#

๐Ÿ˜‚ thought it will underline the problem but it didnt, let me try fixing it

young dagger
pale zenith
#

So I literally cannot answer that in a satisfactory manner, because the answer is: It depends.

#

If you need data from the message then you fetch it, simple as that

#

I cannot see how there's any correlation between fetching a user and fetching a message. they're different things. Unless you mean like... fetch message-> message.author vs fetch the author itself. I'm still quite confused.

young dagger
pale zenith
#

that is all factually correct

young dagger
pale zenith
#

yeah if that's what you need to do

#

if the info is already in a pre-existing embed, then reusing it seems fine.

glad marsh
#

anyone recommend any courses or tutorials for beginners?

shrewd apex
glad marsh
#

yes

slate swan
#

this should be useful

glad marsh
#

thanks

smoky anvil
#

Someone accesiable for help?

pale zenith
young dagger
smoky anvil
#

2024-01-27 11:59:03 ERROR discord.client Ignoring exception in on_member_join
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "/home/container/cogs/invites.py", line 223, in on_member_join
inv = invites[invite.id]
~~~^^^^^^^^^^^
KeyError: '3a9g4XQe'
How do i solve this?

#
    @commands.Cog.listener()
    async def on_member_join(self, member: discord.Member) -> None:
        guild = member.guild
        if guild.id != GUILD_ID:
            return

        guild_invites = await guild.invites()
        invites = {inv.id: inv for inv in guild_invites}
        for invite in self.cached.values():
            inv = invites[invite.id]
            assert inv.uses is not None
            if inv.uses > invite.uses:
                await invite.add_uses(1)
                await self.add_invite_to_user(inv)
                await self.send_join_message(member, inv)
pale zenith
smoky anvil
pale zenith
graceful ermine
#

How can I prevent my for loop from stopping due to an error?

Traceback (most recent call last):
  File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 827, in _do_call
    return await self._callback(self.binding, interaction, **params)  # type: ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/cogs/partner.py", line 564, in partner_all_guilds
    channel1 = await self.bot.fetch_channel(channel_id)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 2565, in fetch_channel
    data = await self.http.get_channel(channel_id)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/.local/lib/python3.11/site-packages/discord/http.py", line 741, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10003): Unknown Channel
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 853, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 846, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'partner-all-guilds' raised an exception: NotFound: 404 Not Found (error code: 10003): Unknown Channel```
#
if guild:
            if manager or interaction.guild.owner:

                async with self.bot.db.cursor() as cursor:
                    await cursor.execute("SELECT ps_request, guild FROM setup ORDER BY RANDOM() DESC LIMIT 20")
                    channel = await cursor.fetchall()
                for i, (channel_id, guild) in enumerate(channel, start=1):
                    print(channel_id)
                    try:
                        channel1 = await self.bot.fetch_channel(channel_id)
                    except discord.app_commands.CommandInvokeError or discord.errors.Forbidden or discord.errors.NotFound or discord.app_commands.errors.CommandInvokeError:
                        print(f"Missing access to channel {channel_id}")
                        continue

                    async with self.bot.db2.cursor() as cursor:
                        await cursor.execute("SELECT ad FROM ad WHERE guild=?", (guild,))
                        ad = await cursor.fetchone()

                    if not ad:
                        continue

                    await channel1.send(embed=embed, view=partner.buttons(timeout=None, guild=interaction.guild_id, bot=self.bot, member=interaction.user, embed=None, guild_member_count=interaction.guild.member_count, guild2=guild))
                await interaction.followup.send("Partner shipped all servers!", ephemeral=True)
                return
            else:
                await interaction.followup.send("You are not a trusted manager to run this command!", ephemeral=True)
        else:
            await interaction.followup.send("Please by premium to access this command!", ephemeral=True)```
shrewd apex
slate swan
#

im using spotipy and ffmpeg for music, and i cant seem to get it to play.. theres no errors but it doesnt actually play any audio it just loads the track

shrewd apex
shrewd apex
#

u seem to be fetching only the track object

slate swan
#

wym?

#

i just send the spotify song link

#

does it not support this?

shrewd apex
#

why u need ffmpeg if u just want to send the song link?

slate swan
#

thought i should for audio playback

shrewd apex
#

u need ffmpeg when directly working with audio streaming/downloading/converting

slate swan
#

Oh

shrewd apex
#

spotify dosent expose the tracks or audio data in their api (iirc they have a 30s demo at best)

slate swan
#

wym?

shrewd apex
#

meaning u cant download the song from spotify using the track id

slate swan
#

meaning i cant make it play music from link?

shrewd apex
#

not the whole song

#

as the link shows its a preview

slate swan
#

yeah

shrewd apex
slate swan
#

yes

#

so it would play that

shrewd apex
#

yeah

slate swan
#

any way to change that..?

#

i know youtube was a thing but that is off limits now. but i couldve sworn ppl use spotipy now

shrewd apex
#

not legally no that would be breaking spotify tos

slate swan
#

so every music bot is what. illegal?

#

bit confused lol

shrewd apex
#

most if not all