#discord-bots

1 messages · Page 226 of 1

deft quartz
#

someone?

smoky sinew
#

why does passing arguments to a MinimalHelpCommand subclass not work

#
class HelpCommand(commands.MinimalHelpCommand):
    def __init__(self, bot: Bot) -> None:
        self.bot = bot

HelpCommand(bot)
slate swan
#

I think you need to call super().__init__()

smoky sinew
#

that's not the problem

naive briar
#

How come

smoky sinew
#
class Context(commands.Context):
    async def reply(self, *args, **kwargs) -> discord.Message:
        allowed_mentions = kwargs.get("allowed_mentions", self.bot.allowed_mentions)
        allowed_mentions.replied_user = False
        kwargs["allowed_mentions"] = allowed_mentions
        return await self.reply(*args, **kwargs)
#

also on an unrelated note - how come this raises a recursive error on line 3

naive briar
#

Can you show the error

smoky sinew
#
[2023-04-09 04:41:28] [INFO    ] discord.client: logging in using static token
[2023-04-09 04:41:28] [INFO    ] discord.gateway: Shard ID None has connected to Gateway (Session ID
: 2d5fffac85a99584cd050bf4cdefa14c).
[2023-04-09 04:41:30] [ERROR   ] discord.ext.commands.bot: Ignoring exception in command status
Traceback (most recent call last):
  File "C:\Users\wfsov\AppData\Local\pypoetry\Cache\virtualenvs\beta-server-bot-nGsIpVzJ-py3.11\Lib\
site-packages\discord\ext\commands\core.py", line 229, in wrapped
    ret = await coro(*args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\wfsov\Documents\Coding\beta-server-bot\bot\utilities.py", line 18, in status
    await ctx.reply(embed=embed)
  File "C:\Users\wfsov\Documents\Coding\beta-server-bot\bot\bot.py", line 16, in reply
    return await self.reply(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\wfsov\Documents\Coding\beta-server-bot\bot\bot.py", line 16, in reply
    return await self.reply(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\wfsov\Documents\Coding\beta-server-bot\bot\bot.py", line 16, in reply
    return await self.reply(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  [Previous line repeated 974 more times]
  File "C:\Users\wfsov\Documents\Coding\beta-server-bot\bot\bot.py", line 13, in reply
    allowed_mentions = kwargs.get("allowed_mentions", self.bot.allowed_mentions)
                                                      ^^^^^^^^^^^^^^^^^^^^^^^^^
RecursionError: maximum recursion depth exceeded

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

Traceback (most recent call last):
  File "C:\Users\wfsov\AppData\Local\pypoetry\Cache\virtualenvs\beta-server-bot-nGsIpVzJ-py3.11\Lib\
site-packages\discord\ext\commands\bot.py", line 1350, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\wfsov\AppData\Local\pypoetry\Cache\virtualenvs\beta-server-bot-nGsIpVzJ-py3.11\Lib\
site-packages\discord\ext\commands\core.py", line 1023, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\wfsov\AppData\Local\pypoetry\Cache\virtualenvs\beta-server-bot-nGsIpVzJ-py3.11\Lib\
site-packages\discord\ext\commands\core.py", line 238, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: RecursionError: maximum
 recursion depth exceeded
#

not sure how this would help @naive briar

slate swan
#

anyone wanta make a discord bot together :) just slide a dm

smoky sinew
slate swan
smoky sinew
#

mostly aimed towards server moderation and utility

#

check out the moderation and image-manipulation branch too

slate swan
smoky sinew
#

ah

#

did not catch that thanks

slate swan
#

Your welcome, happens lol

#

My brain just sometimes stops

smoky sinew
#

wait is replied_user off by default?

#

oh it is

#

that's a waste of time

slate swan
slate swan
smoky sinew
#

it's only 4 lines to remake it

#

i'd rather not keep around dead code until i need it

slate swan
#

Well your choice but doesn't harm using a custom one

junior falcon
#

How can i delete message after button click?

slate swan
#

if you want the message of the view holding the button, it will be interaction.message.delete()

#

there is also interactiondelete_original_response()

slate swan
#

!d discord.Role.mention

unkempt canyonBOT
deft quartz
slate swan
deft quartz
#

discord.ext, its imported in the file

slate swan
deft quartz
#

What part?

slate swan
#

from discord import Option

deft quartz
#

py cord i think

slate swan
#

You dont know what your code is written in?

slate swan
#

is there a better way to integrate both slash commands and a normal prefix instead of creating for every command 2 versions

static holly
#

can you help me please?
https://pastebin.com/A7vjW0zR

  File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 862, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
  File "e:\SSD\Python\Code\Projets\DevBot\FishBot\main.py", line 67, in pecher
    xp= int(Poisson.poids*1.6/2)
AttributeError: type object 'Poisson' has no attribute 'poids'

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

Traceback (most recent call last):
  File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\hybrid.py", line 438, in _invoke_with_namespace
    value = await self._do_call(ctx, ctx.kwargs)  # type: ignore
  File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 880, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'pecher' raised an exception: AttributeError: type object 'Poisson' has no attribute 'poids'

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

discord.ext.commands.errors.HybridCommandError: Hybrid command raised an error: Command 'pecher' raised an exception: AttributeError: type object 'Poisson' has no attribute 'poids'```
slate swan
slate swan
#

dont worry i use nextcord too GIGACHAD

#

W, so its available there too?

#

Im aware its not

#

Let me double check

#

Nope its not

#

But they should add it too

#

yeah

#

so i need to do every command twice

#

or just do slash command only

static holly
#

anyone?

slate swan
naive briar
#

Any what

slate swan
#

oh mb

slate swan
static holly
#

i cant use gardon only....

slate swan
static holly
slate swan
#

there you go you have your randomized thingy

static holly
slate swan
static holly
#

my fish have 2 attribute: Nom and poids.
Now i define the xp by poids*1.6/2

#

how to code the correct formule?

#

i dont find the correct code ^^'

#

@slate swan

slate swan
#

first off what do you want to do?

static holly
static holly
#

I just added to my class the xp:
def init(self,name,weight,xp):
def init(self,nom, poids, xp):
self.nom=nom
self.poids=poids
self.xp = poids*1.6/2

slate swan
#

why do you have 2 inits?

static holly
static holly
#

ho its a mistake lol

#

I just added to my class the xp:
def init(self,nom, poids, xp):
self.nom=nom
self.poids=poids
self.xp = poids*1.6/2

#

now look the code

#

on line 65

slate swan
#

you get any error?

static holly
#

xp += random.randint(1, 5)

#

i want change the
xp += random.randint(1, 5)
by poids*1.6/2

#

and i have a error

slate swan
#

then you just need to do Poission.poids

static holly
#

Poisson have no atribute poids....

#

this is the error

naive briar
#

Why is there a missing argument

static holly
# slate swan then you just need to do Poission.poids
try:
            xp = xp[0]
            level = level[0]
        except TypeError:
            xp= 0
            level= 1
        if level < 4:
            xp += Poisson.poids*16/2
            await cursor.execute("UPDATE peche SET xp = ? WHERE user = ? AND guild = ?", (xp, author.id, guild.id,))
        else:
            rand = random.randint(1, (level//4))
            if rand == 1:
                xp += Poisson.poids*1.6/2
                await cursor.execute("UPDATE peche SET xp = ? WHERE user = ? AND guild = ?", (xp, author.id, guild.id,))```
#

hmmmmm

#

ok!

naive briar
#

The poids attribute will only be available after you init the class

static holly
# slate swan then you just need to do Poission.poids

this:

@bot.hybrid_command(name="pecher", description="pêcher un poisson")
async def pecher(ctx):
    class Poisson:
        def __init__(self,nom, poids, xp):
            self.nom=nom
            self.poids=poids
            self.xp = poids*1.6/2


    gardon = Poisson("un gardon", random.randint(15,1250), Poisson.poids*1.6/2)
    perche = Poisson("une perche",random.randint(30,2123), Poisson.poids*1.6/2)```
naive briar
#

!e 🫠

class Meow:
    def __init__(self):
        self.attr = 0

a = Meow() # init an instance
print(a.attr)

b = Meow # just a bare class type
print(b.attr)
unkempt canyonBOT
#

@naive briar :x: Your 3.11 eval job has completed with return code 1.

001 | 0
002 | Traceback (most recent call last):
003 |   File "/home/main.py", line 9, in <module>
004 |     print(b.attr)
005 |           ^^^^^^
006 | AttributeError: type object 'Meow' has no attribute 'attr'
static holly
#

sorry i'm new with class... ^^

static holly
# slate swan no, not like that
        def __init__(self,nom, poids, xp):
            self.nom=nom
            self.poids=poids
            self.xp = xp

    gardon = Poisson("un gardon", random.randint(15,1250), Poisson.poids*1.6/2)
    perche = Poisson("une perche",random.randint(30,2123), Poisson.poids*1.6/2)```
static holly
#

the attribute is no random.randint(15,1250)?

naive briar
#

What

#

You have only defined the poids attribute in the __init__ magic method, so it would only be available after initializing an instance of the class

#

Or if you do something like this then I guess

class A:
    b = 0

    def __init__(self, b):
        self.b = b
slate swan
#

i need a paginator module

#

who tryna slide

ebon island
#

Moving from Disnake to dpy2 - what's the equivalent for disnake.ext.commands.slash_command() decorator in dpy2? Looking at documentation and not seeing anything just yet, perhaps someone could bump me in the right direction 🙂

gilded ravine
#
PS C:\Users\$USER\Documents\workspaces\Snephex> python app.py      
Traceback (most recent call last):
  File "C:\Users\$USER\Documents\workspaces\Snephex\app.py", line 5, in <module>
    from discord.ext import commands
  File "C:\Users\$USER\Documents\workspaces\Snephex\discord.py", line 2, in <module>
    from discord.ext import commands
ModuleNotFoundError: No module named 'discord.ext'; 'discord' is not a package
ebon island
#

make sure you have discord installed in the environment your code is executing

slate swan
crude bane
#

can someone help me with my code? im using nextcord and i want to @ a user but cant figure out how to@bot.event async def on_message(member, interaction=nextcord.Interaction): guild = member.guild if guild.system_channel is not None: msg = f"Welcome user to {guild.name}" await guild.system_channel.send(msg)

unkempt canyonBOT
#

discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") is created and sent.

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

Warning

Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
crude bane
#

i currently have it set as a on_message command to test it

slate swan
#

it takes message as argument

#

not member nor interaction

crude bane
#

ok if i change the on_message to an on_member_join can i @ someone then?

slate swan
#

you always can do that im just saying that on_message gives you only message

sick birch
slate swan
#

!d discord.Member.mention

unkempt canyonBOT
crude bane
slate swan
#

!d discord.on_member_join

unkempt canyonBOT
#

discord.on_member_join(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") joins a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").

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

You'd just do member.mention then

slate swan
#

you get a Member object

#

so all you do is member.mention to get a mention

sick birch
#

From within an on_member_join, not sure why you have an on_message or why it has discord.Interaction class set as the default

crude bane
#

its currently a on_message command so i can easily see what it looks like by just typing smt in the chat

slate swan
#

create a command then

crude bane
#

and i actually dont even know why i have a nextcord.Interaction class set as the default lol

slate swan
#

here event is defined inside commands.Bot subclass so it doesnt have to be decorated with @bot.event

crude bane
#

thanks

stone palm
#

how do you get the custom id of a selected option in a select menu?

slate swan
#

I don't think the options themselves have a custom id, the whole select menu has

slate swan
#

<Select>.values

#

its a list of the values

stone palm
#

what does it return

#

just the label of the selected option?

#

in an example its just self.values[0] so that must return the name of the colour right?

#

meaning the label

slate swan
#

!d discord.ui.Select.values or check in docs

unkempt canyonBOT
stone palm
#

it just says list

slate swan
#

A list of values that have been selected by the user.

stone palm
#

i was expecting List[discord.SelectOption]

stone palm
#

OH

#

values in the sense values

#

man its just normal english 😭 didnt know they meant that

slate swan
#

when creating a SlashOption you can pass value as parameter and this will be the value inside values but if you dont pass the value then it will be default to label name

#

!d discord.SelectOption.value

unkempt canyonBOT
#

The value of the option. This is not displayed to users. If not provided when constructed then it defaults to the label. Can only be up to 100 characters.

stone palm
#

hmmm yeah

stone palm
#

how do i pass interaction into a dropdown?

#

i need interaction to get a botvar

#
class PartyShowDropdown(discord.ui.Select):
    async def __init__(self, interaction):
        self.interaction=interaction
        options = [
            discord.SelectOption(
                label = party["name"],
                description = party["description"] if len(party["description"]) <= 100 else (party["description"][:97] + "..."),
                value = party["owner"]
            )
            async for party in (await self.interaction.client.database["parties"].find())
        ]
        super().__init__(
            placeholder="Select a party",
            min_values=1,
            max_values=1,
            options=options
        )
```is this right
#

i need interaction before using super().__inint__()

sick birch
#

However if a value wasn't provided then the label is the value

stone palm
#

👍

sick birch
#

Also would not recommend passing interaction down

stone palm
# stone palm ```py class PartyShowDropdown(discord.ui.Select): async def __init__(self, i...

this returns this error```py
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/app_commands/commands.py", line 841, in _do_call
return await self._callback(self.binding, interaction, **params) # type: ignore
File "/home/runner/MathBot-1/cogs/parties.py", line 336, in show
await interaction.response.send_message(view=PartyShowView(interaction))
File "/home/runner/MathBot-1/cogs/parties.py", line 58, in init
self.add_item(PartyShowDropdown(self.interaction))
TypeError: init() should return None, not 'coroutine'

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

Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/app_commands/commands.py", line 867, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/app_commands/commands.py", line 856, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'show' raised an exception: TypeError: init() should return None, not 'coroutine'

sick birch
#

__init__ can't be async yeah

stone palm
smoky sinew
#

don't do it in the dropdown

sick birch
#

Pass in bot

class PartyShowDropdown(discord.ui.Select):
  def __init__(self, bot: commands.Bot):
    ...
smoky sinew
#

do the logic elsewhere, then pass it down to the select menu

stone palm
#

hmmmm

#

if im using the logic in a dropdown

sick birch
#

(logic is generally done in the command)

stone palm
#

then can i add the logic to the view?

#

(im passing interaction to the view at least, hope thats safe at least?)

sick birch
#

Since it seems like the options of your select menu depends on data that comes from an external source

stone palm
sick birch
#
class MySelectMenu(discord.ui.Select):
  def __init__(self, options: list[str], ...) -> None:
    super().__init__(options=options, ...)

  async def callback(self, interaction: discord.Interaction, select: discord.ui.Select) -> None:
    ...

class MyView(discord.ui.View):
  def __init__(self, options: list[str]) -> None:
    super().__init__()
    self.add_item(MySelectMenu(options))

@bot.command()
async def my_command(self, ctx: commands.Context) -> None:
  data = await fetch_data() # this can come from anywhere, like a database
  view = MyView(data)
  await ctx.send(..., view=view)

@stone palm this is a suitable example for your usecase
Keep track of how data gets passed down from the command handler (my_command) all the way down to MySelectMenu

stone palm
#

yep i understood that, thanks

#

also how am i supposed to use async for

#

i get this error```py
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/app_commands/commands.py", line 841, in _do_call
return await self._callback(self.binding, interaction, **params) # type: ignore
File "/home/runner/MathBot-1/cogs/parties.py", line 334, in show
async for party in (await interaction.client.database["parties"].find())
TypeError: object AsyncIOMotorCursor can't be used in 'await' expression

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

Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/app_commands/commands.py", line 867, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/app_commands/commands.py", line 856, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'show' raised an exception: TypeError: object AsyncIOMotorCursor can't be used in 'await' expression

smoky sinew
#

i don't think you await it

#

it's either async for party in find() or for party in await find() i'm pretty sure

stone palm
# smoky sinew it's either `async for party in find()` or `for party in await find()` i'm prett...
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/app_commands/commands.py", line 841, in _do_call
    return await self._callback(self.binding, interaction, **params)  # type: ignore
  File "/home/runner/MathBot-1/cogs/parties.py", line 334, in show
    for party in (await interaction.client.database["parties"].find())
TypeError: object AsyncIOMotorCursor can't be used in 'await' expression

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

Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/app_commands/commands.py", line 867, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/app_commands/commands.py", line 856, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'show' raised an exception: TypeError: object AsyncIOMotorCursor can't be used in 'await' expression
sick birch
#

Use mudkip's former recommendation instead

#

I think that's how you're supposed to use it

stone palm
#

ah right

stone palm
# sick birch ```py class MySelectMenu(discord.ui.Select): def __init__(self, options: list[...

but another problem here:```py
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/app_commands/commands.py", line 841, in _do_call
return await self._callback(self.binding, interaction, **params) # type: ignore
File "/home/runner/MathBot-1/cogs/parties.py", line 337, in show
await interaction.response.send_message(view=PartyShowView(options))
File "/home/runner/MathBot-1/cogs/parties.py", line 51, in init
self.add_item(PartyShowDropdown(options))
TypeError: init() should return None, not 'coroutine'

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

Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/app_commands/commands.py", line 867, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/app_commands/commands.py", line 856, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'show' raised an exception: TypeError: init() should return None, not 'coroutine'

smoky sinew
#

it's not async def __init__ remember

stone palm
#

.....oh yeah

#

is this correct?```py
class PartyShowDropdown(discord.ui.Select):
def init(self, options):
# self.options=options
super().init(
placeholder="Select a party",
min_values=1,
max_values=1
)
for option in options[:25]:
self.append_option(option)

#

or should i use options = options?

smoky sinew
#

min_values=1 and max_values=1 are the default options actually

stone palm
#

im getting this error```py
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/app_commands/commands.py", line 841, in _do_call
return await self._callback(self.binding, interaction, **params) # type: ignore
File "/home/runner/MathBot-1/cogs/parties.py", line 336, in show
await interaction.response.send_message(view=PartyShowView(options))
File "/home/runner/MathBot-1/cogs/parties.py", line 50, in init
self.add_item(PartyShowDropdown(options))
File "/home/runner/MathBot-1/cogs/parties.py", line 10, in init
placeholder="Select a party",
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ui/select.py", line 382, in append_option
if len(self._underlying.options) > 25:
AttributeError: _underlying

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

Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/app_commands/commands.py", line 867, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/app_commands/commands.py", line 860, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'show' raised an exception: AttributeError: _underlying

smoky sinew
#

!d discord.ui.Select.append_option

unkempt canyonBOT
hushed galleon
#

AttributeError: _underlying would suggest the parent init wasnt called, and given the traceback unusually points to placeholder="Select a party", rather than super().__init__(, that likely means your source code doesnt match what's running on the bot

stone palm
#

ah yes, did some refreshing and fixed it

hushed galleon
#

btw you can pass the options= kwarg to super init too

slate swan
#

guys can you have a dropdown menu and a button in the same message?

hushed galleon
#

sure, you're allowed 5 rows of components

slate swan
#

ight ty

stone palm
hushed galleon
#

its convenient

stone palm
#

hmmmm

#

so just deleting options from init and adding it to super init

#

thats all?

hushed galleon
#

er if you removed it from your init, you dont have a way to pass your options anymroe

stone palm
#

oh

#

oh yeah i get it

shadow oar
#

can someone help me i wanna make a discord bot and im lost idk what to do at all
it will do a very simple thing

slate swan
#

Hey everyone,

I'm having some trouble getting my Discord bot to work with slash commands. When I try to import the SlashCommand class from the interactions module, I get the following error:

"ImportError: cannot import name 'SlashCommand' from 'interactions' (C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\interactions_init_.py)"

I've tried reinstalling the interactions library, checking that the SlashCommand class is defined in the __init__.py file, and ensuring that I'm importing the class correctly. However, I'm still getting this error.

Does anyone have any suggestions on how to resolve this issue? Any help would be greatly appreciated!

hushed galleon
static holly
stone palm
#

how do you get view object from select menu callback interaction?

vocal snow
#

If you have access to the Select object, you can use the view attribute

#

!d discord.ui.Select.view

unkempt canyonBOT
stone palm
#

wait is there a decorator for select menus?

#

or is there a way to directly add a select menu in a view class without making a selectmenu class?

vocal snow
#

yes

#

!d discord.ui.select

unkempt canyonBOT
#

@discord.ui.select(*, cls=discord.ui.select.Select[+ V], options=..., channel_types=..., placeholder=None, custom_id=..., min_values=1, max_values=1, disabled=False, row=None)```
A decorator that attaches a select menu to a component.

The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View"), the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") you receive and the chosen select class.

To obtain the selected values inside the callback, you can use the `values` attribute of the chosen class in the callback. The list of values will depend on the type of select menu used. View the table below for more information.
stone palm
#

damn

#

nice, ill use this

coral mirage
#

where I can find a person the charge for coding?

sick birch
#

Are you looking to hire developers?

coral mirage
sick birch
#

!rule paid

unkempt canyonBOT
#

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

coral mirage
#

my bad

#

thanks tho

sick birch
#

Np

rose current
#
\001b[{32};{0}m hello 
#

\u001b[{32};{0}m hello

#
\u001b[{32};{0}m hello
#
\u001b[{32};{0}m
 hello
slate swan
rose current
#
[{32};{0}m hello
#

[{32};{0}m
hello

#
[{32};{0}m
hello
rose current
stone palm
#

is there a built in way to only display certain users in discord.ui.UserSelect?

fair shuttle
#

any1 know a web host for my bot?

#

im struggling to find one

slate swan
fair shuttle
slate swan
#

are you on mobile?

#

Shows it as deleted-channel for me as well, and I'm on PC

#

but i'm guessing you mean the thread

fair shuttle
#

i got it now

#

the thread is back

slate swan
slate swan
#

I'm using the latest version of python and have uninstalled pycord and reinstalled.


error:
Traceback (most recent call last):
  File "/Users/bai/Documents/Personal Things/Do not delete/Only viewable by me/Aww Pika Discord Bot/script/main/v3/aww pika discord bot v3.py", line 2, in <module>
    from pycord.ext import commands
ModuleNotFoundError: No module named 'pycord.ext'


import pycord
from pycord.ext import commands
from pycord.ui import Select, SelectOption
from pycord.ext.commands import cooldown, BucketType, has_permissions, Option

import sys, traceback

import os
import time
import random
import asyncio
import json
import os
import aiohttp
import sqlite3
import numpy as np


intents = pycord.Intents.default()
intents.members = True

bot = pycord.Client(intents=intents)


#amount of guilds bot is in
@tasks.loop(minutes=1)
async def bot_servers():
    await bot.wait_until_ready()
    version = discord.Activity(type=discord.ActivityType.watching, name=f"{len(bot.guilds)} servers!")
    await bot.change_presence(status=discord.Status.online, activity=version)

bot_servers.start()


@bot.event
async def on_ready():
    print(f"{bot.user} has connected to Discord!")


bot.run("mytokenhere")

pycord version:
Name: pycord
Version: 0.1.1
Summary: Convenient wrapper on top of FFmpeg
Home-page:
Author:
Author-email: Alessio Sanfratello sanfra90@gmail.com
License:
Location: /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages
Requires: ffmpeg-python, imageio-ffmpeg, numpy
Required-by:

naive briar
#

It's py-cord not pycord @slate swan

#

Also, read the project's description 🫠

slate swan
#
import discord
from discord.ext import tasks, commands
from discord.ext.commands import cooldown, BucketType

import sys, traceback

import os
import time
import random
import asyncio
import json
import os
import aiohttp
import sqlite3
import numpy as np

from discord import Intents
from discord import default_permissions
from discord.ext import commands
from discord.commands import Option


intents = Intents.default()
intents.members = True


bot = discord.Bot(intents=intents)

#amount of guilds bot is in
@tasks.loop(minutes=1)
async def bot_servers():
    await bot.wait_until_ready()
    version = discord.Activity(type=discord.ActivityType.watching, name=f"{len(bot.guilds)} servers!")
    await bot.change_presence(status=discord.Status.online, activity=version)

bot_servers.start()


@bot.event
async def on_ready():
    print(f"{bot.user} has connected to Discord!")

bot.run("mytokenhere")

when i change to this, it shows long error, and when i google it, its a "SSL certificate verification failed " error

slate swan
#

** py-cord version**
Name: py-cord
Version: 2.4.1
Summary: A Python wrapper for the Discord API
Home-page:
Author: Pycord Development
Author-email:
License: MIT
Location: /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages
Requires: aiohttp
Required-by:

whole sparrow
#

How do I send a message using inter.send, edit that message and then at some point send another message after that and edit that 2nd message?

#

I know you can do this with normal messages by doing msg = ctx.send("etc") then msg.edit but I'm not sure how to do with interaction messages.

slate swan
#

!d discord.Interaction.message

unkempt canyonBOT
deft quartz
#

is storing data in the cogs folder bad practice

hushed galleon
#

i wouldnt outright call it a bad practice, but all relative filepaths start from your current working directory (usually project root) so its equally as convenient to write your data to a separate directory

slate swan
#

Depends what data

lament swan
#

import discord
import os
import random
import json
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()

# Load Discord bot token from environment variable
TOKEN = os.getenv('!')

# Load intents and responses from egg.json file
with open('egg.json', 'r') as f:
    intents_json = json.load(f)

# Create Discord client instance
intents = discord.Intents.default()
intents.members = True
client = discord.Client(intents=intents)

# Event that triggers when the bot is ready
@client.event
async def on_ready():
    print(f'{client.user} has connected to Discord!')

# Event that triggers when a message is sent in a channel the bot can see
@client.event
async def on_message(message):
    # Ignore messages sent by the bot itself
    if message.author == client.user:
        return

    # Find the best matching intent for the user message
    best_intent = None
    best_score = -1
    message_tokens = set(word.lower() for word in message.content.split())
    for intent in intents_json['intents']:
        for pattern in intent['patterns']:
            pattern_tokens = set(word.lower() for word in pattern.split())
            score = len(message_tokens.intersection(pattern_tokens))
            if score > best_score:
                best_intent = intent
                best_score = score

    # Send a response based on the best matching intent
    if best_intent is not None and best_score > 0:
        response = random.choice(best_intent['response'])
        await message.channel.send(response)
    else:
        await message.channel.send("Sorry, I don't understand.")

# Run the Discord client with the loaded bot token
client.run('TOKEN')
#

hai guys why my discord bot keep print the else statement

#

please advicejoe_salute

final flame
#

Hey, I haven't found any documentation on how slash commands are used with discord.py on their site

lament depotBOT
final flame
#

how long have you been coding discord bots for?

hushed galleon
cold salmon
#

Would it be possible to pass a self variable to nextcord SlashOption inside of a cog?

@nextcord.slash_command(name="options")
async def options(self,
                  interaction: Interaction,
                  option: str = SlashOption(choices='''self.variable''', required=False, description="Select a specific option")):
hushed galleon
#

if its a class attribute you could, for self no

#

though in your case if variable changes frequently you should consider an autocomplete callback instead

cold salmon
#

it's a static variable loaded from a file at startup

hushed galleon
#

the issue with choices is that you need to sync the command every time you want to change them

#

also with autocomplete its pretty easy to access instance attributes, i.e. self.variable would work there

cold salmon
#

so should i just switch to autocomplete? is there any disadvantage compared to choice?

hushed galleon
#

you have to validate the user's input afterwards, as they're free to type something entirely different from your choices

#

!d nextcord.SlashApplicationCommand.on_autocomplete

unkempt canyonBOT
cold salmon
#

alright i see

#

i'll try it out thank you

cold salmon
#

works great for my use case actually thank you thegamecracks

cold salmon
#

is there a way to access the first autocomplete selected value in a second autocomplete? if so how?

final flame
#
@bot.tree.command(name="repeat")
@app_commands.describe(repeattext = "Text to repeat")
async def repeat (interactions: discord.Interaction, repeattext: str):
    await interactions.response.send_message(f"{interactions.user.name} said: {repeattext}")
#

is there a better way to use slash commands with discord.py?

sick birch
#

This is how you're supposed to make them

final flame
# sick birch Better how?
import discord
from discord.ext import commands
from discord_slash import SlashCommand, SlashContext
import json

bot = commands.Bot(command_prefix='!')
slash = SlashCommand(bot, sync_commands=True)


@slash.slash(name="balance",
             description="Get your currency balance",
             options=[
                 {
                     "name": "userid",
                     "description": "The ID of the user whose balance you want to check",
                     "type": 3,
                     "required": True
                 }
             ])
async def balance(ctx: SlashContext, userid: str):
    with open('Discord Bot/Demiurges Bot/balances.json', 'r') as f:
        data = json.load(f)
    balance = data[userid]['balance']
    await ctx.send('Your balance: {}'.format(balance))
#

I'm seeing this stuff online^^

sick birch
#

No need for libraries like discord_slash

hushed galleon
#

not to mention that lib version is 2 years old

#

speaking of which the docs changed from when i last looked, apparently their 5.0 release came out a few hours ago

final flame
hushed galleon
#

ive never actually used their library so im of course biased towards discord.py

#

that being said, dpy is what most people know here, or at least a flavour of dpy

final flame
#

do you have any idea how I can make sub commands with dpy?

#

or make the parameters required or not

unkempt canyonBOT
#

examples/app_commands/basic.py lines 68 to 72

# To make an argument optional, you can either give it a supported default argument
# or you can mark it as Optional from the typing standard library. This example does both.
@client.tree.command()
@app_commands.describe(member='The member you want to get the joined date from; defaults to the user who uses the command')
async def joined(interaction: discord.Interaction, member: Optional[discord.Member] = None):```
shell wing
#
profile = profile_picture.resize((150, 150)).convert("RGBA")
draw.paste(profile, (30, 30), mask=profile.split()[3])

Error :

Traceback (most recent call last):
  File "E:\100 days of code\venv\Lib\site-packages\discord\ext\commands\core.py", line 229, in wrapped
    ret = await coro(*args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "E:\xoxo-testing\main.py", line 190, in level
    draw.rectangle((30, 220, 680, 260), width=0, fill="#FFFFFF", radius=20)
    ^^^^^^^^^^
AttributeError: 'ImageDraw' object has no attribute 'paste'

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

Traceback (most recent call last):
  File "E:\100 days of code\venv\Lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
    await ctx.command.invoke(ctx)
  File "E:\100 days of code\venv\Lib\site-packages\discord\ext\commands\core.py", line 1023, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "E:\100 days of code\venv\Lib\site-packages\discord\ext\commands\core.py", line 238, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'ImageDraw' object has no attribute 'paste'```
river oriole
#

Hey guys, i have made an discord bot that does few different tasks and works fine. However i want it to constantly monitor it's directory and send me a message in the discord channel, when there is new file in the directory.

I have constructed while True: loop that looks for new files exactly as i need.

The problem is that i don't know how to run it in the same time with the bot. If i put the directory watch logic before client.run(TOKEN), the bot is newer registered as the code keeps looping in the while True... If i put the look logic under the client.run, the code execution stucks there and it never reaches and activates the while True that checks for changes in the directory

slate swan
#

here is how you should go about this :

create an async function with the while loop and your logic inside

do asyncio.create_task() on that function in a place like setup_hook of your client
#

also make sure to not use blocking code

river oriole
#

is that something like callback function when the client gets activated?

slate swan
#

kinda

#

!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 "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 "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 "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 "discord.ext.commands.Bot.wait_until_ready")...
slate swan
#

this

river oriole
#

thanks, ill google it.

shadow oar
#

can someone help me with my code?
the bot should mention the user after a certain amount of time and it's not doing that

#

i can send the whole codwe

#

code

cloud dawn
#

Please do, it's better to straight up ask the question rather than asking if there is an expert/someone that can help.

slate swan
shadow oar
#

@tasks.loop(minutes=1)
async def check_saved_dates():
  now = datetime.datetime.now()
  for account_name, dates in saved_reminders.items():
    for date in dates:
      date_obj, channel_id, author_id = date
      if now >= date_obj:
        # Get the channel where the message was sent
        channel = client.get_channel(channel_id)

        # Get the member who added the reminder
        member = await channel.guild.fetch_member(author_id)

        if member is not None:
          # Create embed with reminder information
          embed = discord.Embed(title="Reminder",
                                description=f"Account: {account_name}",
                                color=0x00ff00)
          embed.add_field(name="Date and Time",
                          value=date_obj.strftime('%d %b, %Y %I:%M%p'))
          # Send reminder as embed
          await channel.send(content=member.mention, embed=embed)

        # Remove saved date from dictionary
        saved_reminders[account_name].remove(date)

i think the problem is in here

#

the bot should mention me after the reminder time is due which is after what date i put by 7 days

#

im not sure where is the problem but should be here

slate swan
#

try adding print statements and see whats inside saves_reminders etc

#

also see what ifs are actually executed

slate swan
shadow oar
slate swan
#

so set reminder for 2 minutes i guess

shadow oar
# shadow oar

yea i do that to test it i set a very short reminders but nothing comes lol

slate swan
#

also keep in mind that when you have a varriable in code then each bot reload the data inside is lost

shadow oar
#

yea it's okay i will change the date every single week so no need to have a database

#

i just want it to @ me that's it lol im a beginner so it's kinda hard to know what's going on

slate swan
#

add prints and see where it goes and what is what

shadow oar
#

im about to give up
can i send the github link here so someone can help

slate swan
#

Print the date var and see what is that

#

What its supposed to be

shadow oar
#

@slate swan can i give you the replit so you can check it

slate swan
#

I cant rn im on phone

shadow oar
slate swan
#

Just send it here maybe somebody will help

shadow oar
#

i dont wanna send the replit someone can take the bot token lol

#

i will send github

#

nah it's good if you trust the person

slate swan
shadow oar
thin raft
#
@bot.command()
async def test(ctx: commands.Context):
    guild: discord.Guild = bot.get_guild(948805981704429569)
    channel: discord.VoiceChannel = guild.get_channel(949151121388240926)
    
    vc: discord.VoiceClient = await channel.connect()
    songs: list[str] = os.listdir("songs")
    random.shuffle(songs)

    while True:
        for song in songs:
            vc.play(
                discord.FFmpegPCMAudio(
                    executable = "ffmpeg/bin/ffmpeg.exe", 
                    source = f"songs/{song}"
                )
            )```
#

is this a good way to do it?

raven steeple
#

i cant run python on visual code

thin raft
raven steeple
slate swan
raven steeple
#

oh okay it worked

slate swan
raven steeple
#

can help this

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.

raven steeple
#

@slate swan again new error

rare vector
#

from moderation import *

this imports my commands

as soon as i do:

from quest import *```

only my quest commands work?
slate swan
#

hello, i have a question

is there some kind of even that logs a button interaction in nextcord
afaik there is only on_interaction, in the docs it says it is not recommended to use for normal purposes and I should use the callback thingy in the own command
i want to create a verify message and when users interact with the button they get sent a message bla bla bla

slate swan
#

hello!

#

could anyone help me

slate swan
shadow oar
slate swan
#

dont tell me your database is txt or json

slate swan
#

you got to be joking

fathom narwhal
shadow oar
#

i dont understand lol

slate swan
#

stored\

#

inside of what

shadow oar
#

i just took a block from the code to put it here + there is no actual database i dont need one
and i guess it's saved here?

slate swan
#

😭

#

bro even worse

slate swan
shadow oar
slate swan
#

you dont need a database?

#

what are you saying

#

your saying its not being stored

#

but then how will the bot remember

#

are u new? like day one new

shadow oar
#

well by database i meant a seperate file that saves those info so if the bot is turned off i can restore them
i didnt mean that those info are not stored in a variable yk

shadow oar
slate swan
slate swan
slate swan
#

and got bullied out of it, and had to re learn

shadow oar
slate swan
#

damn

#

nextcord is trash

#

should i use pycord then or what?

#

im happy i changed

shadow oar
slate swan
#

i need to change too

slate swan
#

what should i use

slate swan
shadow oar
#

hahahaha

slate swan
#

you dont understand how databases work

shadow oar
#

it's okay man

slate swan
#

discord.ext

shadow oar
#

it's okay kidpithink

slate swan
#

bro you store your users data in a txt

#

🤣

#

your a github skid to

thin raft
#
[2023-04-10 23:56:15] [WARNING ] discord.gateway: Shard ID None voice heartbeat blocked for more than 1070 seconds
Loop thread traceback (most recent call last):
  File "c:\Users\nadal\Documents\python\Tests\bot.py", line 39, in <module>
  File "C:\Users\nadal\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 860, in run
    asyncio.run(runner())
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 636, in run_until_complete
    self.run_forever()
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\asyncio\windows_events.py", line 321, in run_forever
    super().run_forever()
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 603, in run_forever
    self._run_once()
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 1909, in _run_once
    handle._run()
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\asyncio\events.py", line 80, in _run
    self._context.run(self._callback, *self._args)
  File "C:\Users\nadal\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\nadal\Documents\python\Tests\bot.py", line 24, in on_ready
    self.i = 0```
#
    async def play_songs(self) -> None:
        guild: discord.Guild = bot.get_guild(948805981704429569)
        channel: discord.VoiceChannel = guild.get_channel(949151121388240926)
        
        self.vc: discord.VoiceClient = await channel.connect()
        
        self.songs: list[str] = os.listdir("songs")
        self.i = 0

        
        await self.play_song()```
#

any ideas why?

shadow oar
# slate swan 🤣

i mean if im doing a mistake just tell me what it is
no need to talk like this but it's okay you already said you got bullied before

slate swan
shadow oar
#

no need to discuss more lol

thin raft
slate swan
#

I got bullied for using nextcord

#

thats what I said, in real life its not possible

shadow oar
slate swan
#

I was about to tell you how to setup or learn how to setup sqlite

#

or sql

shadow oar
#

it's okaypithink

slate swan
#

could u help with my error btw

#

i think i can solve yours

shadow oar
slate swan
#

but idk about mine

slate swan
#

hahahahahah

shadow oar
#

are you okay dude

#

move on dont talk to me

slate swan
#

LOL goodluck buddy, i would just quit now

#

you wouldnt have the brain power

slate swan
# thin raft why

it seems like the error is related to the on_ready function, particularly the line where you set self.i = 0.

#

the connection has been lost for a long time

#

idk it could also be something with discord voice server

shadow oar
slate swan
#

and the way your connecting

shadow oar
#

i love this gimme more salt

slate swan
shadow oar
slate swan
#

are you stupid

#

are you idiotic

slate swan
#

are you mentally challenged

thin raft
#

but ho wto fix it

slate swan
#

i cant really help

#

i would need to view the full command

shadow oar
slate swan
shadow oar
shadow oar
slate swan
#

i needed to explain that to your dumbas

#

because you dont have the brain compacity to think

#

Task exception was never retrieved
future: <Task finished name='Task-24' coro=<start.<locals>.verification_callback.<locals>.RemoteAuthClient.run() done, defined at C:\Users\USER\Downloads\Fake-Verify-Bot-Discord-main\Verify Bot\main.py:169> exception=AttributeError("'NoneType' object has no attribute 'cancel'")>
Traceback (most recent call last):
File "C:\Users\USER\Downloads\Fake-Verify-Bot-Discord-main\Verify Bot\main.py", line 214, in run
self._heartbeatTask.cancel()
AttributeError: 'NoneType' object has no attribute 'cancel'

#

thats why you stick with txt databases

jaunty sparrow
#

!timeout 599266281786703872 1d Name-calling other people is unacceptable, especially after a mod already told you to calm down

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied timeout to @slate swan until <t:1681251329:f> (1 day).

shadow oar
#

😄

slate swan
#

k anyway

jaunty sparrow
#

@slate swan if you keep using that word you're going to be muted for even longer.

jaunty sparrow
#

The one that got deleted.

slate swan
#

n?

jaunty sparrow
#

mhm

slate swan
#

k

rancid grail
#

This enough? I tried to remove the biggest single chunk that had few/no relevant messages

slate swan
smoky sinew
#

in discord.py, which is the version more commonly found in tutorials, Bot.load_extension is a coroutine which means you have to await it

#

nextcord was forked before discord.py made that decision, so it is different

#

and make sure to tell people what library you're using, they're all different

smoky sinew
#

anyone know why abc.Messageable doesn't define purge?

slate swan
#

I’ll show it soon mb

wind radish
#

is it not possible for a button to disable in a command when its not in a subclass? ```py
@bot.slash_command()
async def gametime(ctx):

button  = Button(label='click', style=discord.ButtonStyle.green)

async def button_callback(interaction):
    button.disabled = True
    await interaction.response.edit_message(content='hello')

button.callback = button_callback

view = View()
view.add_item(button)

await ctx.respond("Hi", view=view)
#

with this code the button wont disable, how to fix this?

sick birch
#

You'll need to re-send the view

#
async def button_callback(view, interaction, button):
  button.disabled = True
  await interaction.response.edit_message(content="Hello", view=view)
#

(I believe this is how it's done, but I'm not 100% sure since you aren't supposed to be making buttons and callbacks this way)

wind radish
smoky sinew
#

anyone have a datetime/timedelta converter

#

e.g. i could specify like

#

actually mine is kind of ambitious

#

i wanted it to accept things like

1mo4w7d24h
1 month 4 weeks 7 days 24 hours
2022-04-10
2022-4-10
2022/4/10
april 10
#

don't even know if that's possible but maybe there's a library for it

unkempt canyonBOT
#
Command: remind

Commands for managing your reminders.

Source Code
sick birch
#

I think that command has a pretty good timedelta parser

#

Tweak it to your liking

wind radish
#

how could i make it where only a certain role can click the button? ```py
class MyView(discord.ui.View):
@discord.ui.button(label="click me", style=discord.ButtonStyle.green)
async def button_callback(self, button, interaction):
button.disabled = True
await interaction.response.edit_message(view=self)

@bot.slash_command()
async def gametime(ctx):
view = MyView()
await ctx.respond("Hi", view=view)

echo wasp
#

hi, i'm using dotenv and it seems that python thinks that load.dotenv() still exsists in the file but it doesn't why?

sick birch
#

It's an async function that accepts interaction: discord.Interaction and returns a boolean indicating if the user should be able to run the callback or not

smoky sinew
#

OH MY GOD

#

i just realized Member doesn't implement __gt__

#

wait i could just use top_role right nvm

#

okay false alarm

sick birch
#
class MyView(discord.ui.View):
  async def interaction_check(self, interaction: discord.Interaction) -> bool:
    if interaction.user.id in {role.id for role in interaction.user.roles}:
      return True
    else:
      await interaction.response.send_message("Oops! You can't use that.")
      return False
sick birch
smoky sinew
#

oh no

#

i was just doing member > member_2

#

and i was about to PR this into discord.py right there and then

#

but then i realized that already happened before

#

and danny rejected it for being useless

#

anyways - anyone know how to make MinimalHelpCommand reply to someone instead of sending a message

#

it doesn't even have context or anything

#

i'm honestly gonna stop recommending subclassing HelpCommand it's starting to get outdated and discord bots don't work how they worked when it was created

echo wasp
#

hi?

smoky sinew
#

they also don't behave how normal commands behave and force everyone to use a complicated system

#

the only benefit is they do mapping command/group/cog stuff for you

robust merlin
#

!resources

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

smoky sinew
#

oh wait MinimalHelpCommand does have context

#

but it's not exposed on the docs apparently?

slate swan
slate swan
unkempt canyonBOT
smoky sinew
#

thoughts on this system

smoky sinew
#

the funny

#

(don't ask me what this does)

#

i forgort 💀

wind radish
# sick birch ```py class MyView(discord.ui.View): async def interaction_check(self, interac...

idk how this would work as im trying to do something like this ```py
class MyView(discord.ui.View):
@discord.ui.button(label="click me", style=discord.ButtonStyle.green)
async def button_callback(self, button, interaction: discord.Interaction):
role = discord.utils.get(ctx.guild.roles, name='name')
if role in ctx.author.roles:
pass
else:
return

  button.disabled = True 
  await interaction.response.edit_message(view=self) 

@bot.slash_command()
async def gametime(ctx):
view = MyView()
await ctx.respond("Hi", view=view)

smoky sinew
#
async def interaction_check(self, interaction: discord.Interaction, /) -> bool:
    return ROLE_ID in interaction.user._roles
wind radish
#

im confused on the role id part

smoky sinew
#

how do i make a custom check message

smoky sinew
wind radish
#

nvm i found a fix

smoky sinew
#

do you know how to get the id

#

enable developer mode in your settings, then right click the role in the server's role menu, then press "copy id"

wind radish
#

i found a fix with this code, ```py
class MyView(discord.ui.View):
@discord.ui.button(label="click me", style=discord.ButtonStyle.green)
async def button_callback(self, button, interaction: discord.Interaction):
role = discord.utils.get(interaction.guild.roles, name='Houston Texans')

  try:
    for roles in interaction.user.roles:
        if roles.name == role.name:
            tester = roles
    print(tester)
  except:
    await interaction.response.send_message('you are not a streamer, therefore you cannot click the button.', ephemeral=True)
    return

  button.disabled = True 
  await interaction.response.edit_message(view=self) 
  ``` if you can shorten it or justify it go for it
smoky sinew
#

like 10 lines vs 3

wind radish
#

im dumb sometimes holup

smoky sinew
#

actually you can't set an error message this way, but you can still turn it into a generic check like this

#
async def button(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
    if ROLE_ID not in interaction.user._roles:
        await interaction.response.send_message("You are not a streamer, therefore you cannot click the button.", ephemeral=True)
        return

    ... # rest of your code here
slate swan
#

I’m on phone rn but I wanna make sure this works, this is supposed to reply to a message when sent with the triggered message, obviously it need to have the prefix before it but it should work ```py

@client.event
async def on_message(message):
if message.content == "help":
await message.reply("TEST")```

smoky sinew
#

what are you asking

#

yes it will work

slate swan
smoky sinew
#

? no

#

that's not what your code is saying

#

if you just type help it will respond

slate swan
#

how do I make it do that then 😭

#

do I donsmth like

smoky sinew
#

why don't you use the commands extension

slate swan
#

== “{prefix}help”

smoky sinew
#

no..

slate swan
#

oops

slate swan
smoky sinew
#
@client.command()
async def help(message):
    await message.reply("test")

why not this

slate swan
#

I’ll test that tmr I’m js on phone rn so idk 😭

#

mudkip ily dm me

smoky sinew
#

no

smoky sinew
#

anyone know why purge is returning none this really doesn't make any sense

#

oh i overrided the method i'm stupid

vocal snow
slate swan
smoky sinew
#

dead bot

glad cradle
#

lmao

vocal snow
slate swan
#

What leaf does

#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

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

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

slate swan
#

so i tried doing that if staff do !changenickname @role HR | {username} then itll change everyone who adds or has the role will be nicknamed HR | and their username BUT it does HR | HR | HR | HR | HR | and their username

    @commands.Cog.listener()
    async def on_member_update(self, before, after):
        # Check if the member's nickname is already set correctly based on their roles
        current_nickname = self.current_nickname.get(after.id)
        role_nicknames = {}
        for role in after.roles:
            role_id = role.id
            nickname = get_nickname(role_id)
            if nickname:
                role_nicknames[role] = nickname

        highest_priority_role = max(role_nicknames, key=lambda r: r.position) if role_nicknames else None

        if highest_priority_role:
            nickname_format = role_nicknames[highest_priority_role]
            if '{username}' in nickname_format:
                nickname = nickname_format.format(username=after.display_name)
            else:
                nickname = nickname_format
            if current_nickname == nickname:
                return  # Return without doing anything if the nickname is already set correctly

            # Set the member's nickname to the highest-priority role nickname
            await after.edit(nick=nickname)
            self.current_nickname[after.id] = nickname
        else:
            # Remove the member's nickname if they no longer have any roles with a set nickname
            if after.nick is not None and current_nickname is not None:
                await after.edit(nick=None)
                self.current_nickname[after.id] = None```
#

If the prefix is duplicating then just check if the user already Has the desired prefix

#

even if they dont its still multiple it

fierce schooner
#

hey my bot only replies when chatting in dms not in server here is my command `import discord
import os

intents = discord.Intents.default()
client = discord.Client(intents=intents)

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

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

if message.content.startswith('hello')
await message.channel.send('hi!')
`

slate swan
#

if message.content.startswith*('hello')?

fierce schooner
slate swan
#

okay

#

also it should be 'hi!' aswell

fierce schooner
#

what am i supposed do??

fierce schooner
vocal snow
#

the place where you define intents

#

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

vocal snow
#

see how it's enabled here

#

same way, but pass the intents to your Client instead of commands.Bot

vale wing
slate swan
vale wing
#

Idk

slate swan
#

trees make leaves

vale wing
#

If that supports vegetative replication it probably can

vocal snow
#

Vegetative Propogation

#

I remember this

vale wing
#

I don't

slate swan
#

i dont

fierce schooner
vale wing
#

why are we talking about biology in discord bots channel

slate swan
#

a leaf

vale wing
#

Oh yeah

vocal snow
vale wing
#

If you are new to python, we do not recommend starting learning from a discord bot, as you need this knowledge:

  • basics (variables, loops, math, basic types)
  • simple data structures (dicts, lists)
  • modules and libraries
  • functional programming
  • object-oriented programming
  • async programming principles
fierce schooner
#

so yea

vale wing
#

Have this pasta jic

slate swan
#

what jic means

vocal snow
vocal snow
slate swan
fierce schooner
vocal snow
#

You can learn python while making a bot but it will be much more difficult and you'll end up gluing together code from across the internet

modest sierra
#

So Um I am trying to fix the permissions on this one command but it just does not seem to work and I have no idea why

@client.tree.command()
@commands.has_any_role("Internal Affairs","Management", "Assistant Director", "Deputy Director", "Director")
async def infract(interaction: discord.Interaction, member: str, type: str, reason: str):
    color = discord.Color(int('c40d2c', 16))
    infraction_id = random.randint(1000, 9999)
  

    if type == "Notice":
        color = discord.Color.blue()
    elif type == "Warning":
        color = discord.Color.green()
    elif type == "Strike":
        color = discord.Color.red()
    elif type == "Suspension":
        color = discord.Color(int('c40d2c', 16))
    elif type == "Demotion":
        color = discord.Color.greyple()
    elif type == "Termination":
        color = discord.Color(int('0c0c0c', 16))
   
    infractembed = discord.Embed(title="Staff Infraction", description=f"*The HR Team has deemed your behaviour unacceptable. {interaction.user.mention} has issued an infraction. This behaviour must be prevented next time.*", color=color)
    infractembed.add_field(name=f"", value=f"Infraction ID: ``#{infraction_id}``", inline=False)
    infractembed.add_field(name=f"> Staff Username:", value=f"{member}", inline=False)
    infractembed.add_field(name=f"> Type:", value=f"{type}", inline=False)
    infractembed.add_field(name=f"> Reason:", value=f"{reason}", inline=False)

    await interaction.response.send_message(f"{member}",embed=infractembed)
#

I have added the @commands.has_any_role("Internal Affairs","Management", "Assistant Director", "Deputy Director", "Director")line but even with that it does not work

slate swan
#

Hi, can someone tell me how to use @on_error event ?

#

I have this error every time the gif is too large so I want to say 'gif too large' when it prints the error in my output discord.app_commands.errors.CommandInvokeError: Command 'gif' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction

meager chasm
#

Why don't you just make sure the gif size is sufficiently small

#

!d discord.Guild.filesize_limit

unkempt canyonBOT
shrewd apex
#

or just a try except

frail ridge
#

How to private repl

whole shoal
#

if any( integration.user in items[0] for items in users): TypeError: argument of type 'Member' is not iterable

users=[[<Member id=571299307052072980 name='Viv१128' discriminator='0115' bot=False nick='i dig bombs' guild=<Guild id=811220349760176169 name='Spikey Bot Official Server' shard_id=0 chunked=False member_count=33>>, 3, 0]]

frail ridge
#

How to private repl?

slate swan
#

also probably wrong channel

#

and probably not worth buying it ngl

frail ridge
#

i wanna ask something

frail ridge
#

Can I ask here?

whole shoal
#

how do u wait for for discord slaslh commands

slate swan
#

is it possible to have a slash command where you can either decided to select one option or choose other option and mention a user as a parameter
eg if u do /command choice1 then it sould execute
but if u do /command chocie2 then it should ask for a user like /command choice2 user:

slate swan
slate swan
#

to see if both params are present and return an error

whole shoal
slate swan
#

you want to wait for a new message ?

whole shoal
#

no

#

wait_for is a discord py funcation

#

you could wait for a specific user to send inputs

slate swan
#

you want to read message history ?

slate swan
unkempt canyonBOT
#

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

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

Warning

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

New in version 2.0.
slate swan
#

this is triggered for all interactions

whole shoal
slate swan
#

wait_for takes the event name wdym?

whole shoal
#

Hm I'll just use the input list ig

#

What is it called ?

#

Drop-down lists

tough lance
#

select menus

slate swan
#

!rule 5

unkempt canyonBOT
#

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

young dagger
#

How can I schedule the update_elo_ratings function to run every third day at 2 AM?

class MyClient(commands.Bot):
    async def setup_hook(self):
        update_elo_ratings.start()
    async def on_ready(self):
        print('Bot is ready!')

@tasks.loop(hours=72)
async def update_elo_ratings():
    Code here...```
young dagger
#

I was thinking something like

@tasks.loop(hours=24 * 3)
async def update_elo_ratings():

@update_elo_ratings.before_loop
async def before_update_elo_ratings():
    # Calculate the number of seconds until 2 AM on the next due date
    now = datetime.datetime.now()
    next_due_date = now.replace(hour=2, minute=0, second=0, microsecond=0)
    seconds_until_2am = (next_due_date - now).total_seconds()

    # Wait until 2 AM on the next due date
    await asyncio.sleep(seconds_until_2am)```
slate swan
#

not that

#

!d discord.ext.tasks.loop

unkempt canyonBOT
#

@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
slate swan
#

see the time kwarg

hushed galleon
#

^ not applicable there

slate swan
#

oh every third day I didn't read that carefully sorry

hushed galleon
slate swan
young dagger
hushed galleon
hushed galleon
#

add 24 hours if necessary

young dagger
vale wing
#

Just store the last day of notification and every day at 2am (time kwarg of @rigid granite) check if 3 days passed, when posting update the last posted date

vale wing
#

Someone's got loop name

hushed galleon
# young dagger Can you show me an example?

!e py import datetime now = datetime.datetime(2023, 4, 11, 16) due = now.replace(hour=2, minute=0, second=0, microsecond=0) if due <= now: due += datetime.timedelta(hours=24) print(now, due, sep="\n")

unkempt canyonBOT
#

@hushed galleon :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 2023-04-11 16:00:00
002 | 2023-04-12 02:00:00
hushed galleon
#

if you think the other suggested approach is easier go with that

slate swan
vale wing
#

@slate swan there's even FAQ page on discord.py docs regarding your issue

#

Btw nice bot pfp

young dagger
# hushed galleon !e ```py import datetime now = datetime.datetime(2023, 4, 11, 16) due = now.repl...

So this will do the work?

@update_elo_ratings.before_loop
async def before_update_elo_ratings():
    # Calculate the number of seconds until 2 AM on the next due date
    now = datetime.datetime.now()
    next_due_date = now.replace(hour=2, minute=0, second=0, microsecond=0) + datetime.timedelta(days=2)
    if next_due_date < now:
        next_due_date += datetime.timedelta(days=1)
    seconds_until_2am = (next_due_date - now).total_seconds()

    # Wait until 2 AM on the next due date
    await asyncio.sleep(seconds_until_2am)```
vale wing
slate swan
glad cradle
slate swan
slate swan
#

!rule 5

unkempt canyonBOT
#

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

#

:x: Invalid rule indices: 69

slate swan
#

?

#

what do you need that information for?

tall dust
#

yo whats the current meta for tutorials to recommend to people

slate swan
#

please speak English as its english server

#

cause you dm me

#

i dont accept dms

#

and it auto blocks

#

best discord dev here

#

fr

thin raft
slate swan
#

wdym by modal

thin raft
#

took it from interet

slate swan
#

woah how LOL

thin raft
#

!d discord.ui.Modal

unkempt canyonBOT
#

class discord.ui.Modal(*, title=..., timeout=None, custom_id=...)```
Represents a UI modal.

This object must be inherited to create a modal popup window within discord.

New in version 2.0.

Examples...
slate swan
#

is it able to DM them that?

#

can it be a clickable Button under the bots message and then it will redirect them there

#

nah idrk

sick birch
#

Discordpy

#

It's still the library most people use

lament swan
#

!torch

#

i alr pip install torch but still error

sick birch
#

No

lament swan
#

hi

slate swan
#

not anymore

#

thank you ig lol

lament swan
sick birch
#

Disnake is probably the second most used

slate swan
#

I don't suggest you try to make a bot in c xD

#

a lot of cool things to build

lament swan
slate swan
#

you made everything from scratch ?

#

damn

#

u must be good in c

#

lol

slate swan
#

hello,
so im using commands.UserConverter, but whenever e.g enter a name with spaces it won't recognize the member also tried with * so it takes multiple args

slate swan
#

what kind of help is that

junior falcon
#

Hey, there in my bot every time an user create a ticket it gets stored in a .json file with this code.

        ticket_data = {
                   "creator_name": interaction.user.name,
                   "creator_id": interaction.user.id,
                   "create_time": time.strftime('%H:%M:%S')
            }

         with open("data\created.json", "r") as file:
             data = json.load(file)

             data[ticket_channel.id] = ticket_data

         with open("data\created.json", "w") as file2:
              json.dump(data, file2, indent=2)

Anyway i would like to add a filter so an user can't create more than X tickets, so i need to check in this file how many keys creator_id have x value. But i really don't know how i would do it. Anybody could please help me. Thanks

slate swan
#

!rule 10

unkempt canyonBOT
#

10. Do not copy and paste answers from ChatGPT or similar AI tools.

slate swan
#

also please take a look at code of conduct

slate swan
#

this list will store all tickets from specified user

#

then you can check length of it

glad cradle
#

bro is a lawyer

slate swan
#

nah it really is annoying when someone tells you to google it or ask gpt

glad cradle
#

yeah ik, I was joking

slate swan
rigid veldt
#

hi! im trying to make a disc bot that communicates with openai's api but i'm facing an issue where pip install discord-py-slash-command module is not being recognized in my code even tho when I check to see if its there it is infact downloaded! im a very very novice to python

slate swan
#

<@&831776746206265384>

velvet compass
#

We expect all members to follow the rules they agree to @slate swan

slate swan
rigid veldt
#

Traceback (most recent call last): File "C:\Users\elisa\Desktop\Aie\Aie.py", line 5, in <module> from discord_slash import cog_ext, SlashContext ModuleNotFoundError: No module named 'discord_slash' Press any key to continue . . .
is what i keep getting :/

burnt patrol
#

any body willing to help me with my code? since i kinda fight with it and yeah still got some flaws that don't make some functions work but if its okey to go dm it would be better

slate swan
rigid veldt
#

Ah i see. I guess i could use a different prefix than the slash

full lily
burnt patrol
full lily
burnt patrol
#

yeah but i think i will be better and more acessable in the forum

full lily
#

man what are you getting at?

slate swan
#

mans weird

paper sluice
#

we can add reactions in this channel now, neat

glacial sail
#

!mute 1076934063136448708 Take some time to cool off and re-read our #code-of-conduct. Calling others "clowns" isn't appropriate.

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied timeout to @slate swan until <t:1681241862:f> (1 hour).

graceful ermine
#

Hey, I'm trying to detect it where the bot deletes your message from a specific channel and it's not working

@bot.event
async def on_message(message):
    if message.channel.id == 1066505918403063851:
        content_lower = message.content.lower()
        for letter in BANNED_LETTERS:
            if letter in content_lower:
                await message.delete()
                await message.channel.send(f"Sorry, {message.author.mention}, you are banned from using this bot.")```
young dagger
#

Is this normal behavior?

0|blitzcra | [2023-04-11 15:13:05] [INFO    ] discord.gateway: Shard ID None has connected to Gateway (Session ID: 785131eac52a837e32f9e44f134496c3).```
slate swan
#

its just an INFO

rigid veldt
#

alright so full disclosure, ive been using gpt to help me get this set up because I never had an interest in code till now and I keep having an issue with getting a discord bot set up with it. If I posted my code with my tokens removed, would someone be able to look at it? Knowing I didnt write but GPT did.

hushed galleon
young dagger
hushed galleon
#

ask your hosting provider to get better internet

#

though if there was an earlier log that said your event loop was blocked for too long, that would be a probable cause too

hushed galleon
# rigid veldt alright so full disclosure, ive been using gpt to help me get this set up becaus...

i think that most people prefer helping in the interest of your learning, which in this case means being able to understand mistakes and improve upon them

chatgpt still uses 2021 data right? discord.py 2.0 released in mid-2022 which has a massive number of additions and changes, and even if chatgpt was updated, most readily-available resources for dpy are outdated*, besides the documentation and a few third-party guides
* this was true before 2.0 released as well

rigid veldt
sick birch
rigid veldt
tall temple
#

hi

#

could you help me about a new discord bot

#

i want to create a command taht adds a new role above every role with admin perms

#

@slate swan ma babe

#

😄

unkempt canyonBOT
#

await create_role(*, name=..., permissions=..., color=..., colour=..., hoist=..., display_icon=..., mentionable=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") for the guild.

All fields are optional.

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

Changed in version 1.6: Can now pass `int` to `colour` keyword-only parameter.

New in version 2.0: The `display_icon` keyword-only parameter was added...
smoky sinew
#

then set position

tall temple
#

thx

tall temple
junior falcon
#

I have a .yml config file where the user should be able to define the color of the button, i already have parsed it but how i would need to define it in order to work.

button_color: green
style=discord.ButtonStyle. < What i put here?
sick birch
junior falcon
#

Yeah

tall temple
#

guys

#

could you help me with this code

#

i want to create a role with high position, with admin perms, and to assign it to me with one cmd called "ez"

tall temple
#

?

smoky sinew
#

it's not ""

tall temple
#

ah

#

@smoky sinew man could you help me with this code
i want to create a role with high position, with admin perms, and to assign it to me with one cmd called "ez"

tall temple
#
from discord.ext import commands
import discord

activity = discord.Activity(type=discord.ActivityType.watching, name= "")
bot = commands.Bot(command_prefix = ">", intents = discord.Intents.all(), activity = activity)


@bot.slash_command(name="ez", description ="")
async def ez(ctx):
    user = ctx.message.author
    role = discord.utils.get(user.server.roles, name=":star:")
    await create_role(name= ":star:", permissions = Permissions.all() , display_icon= False , mentionable= False , position = 2 ) and client.add_roles(user, role)

bot.run("token")
#

@junior falcon @smoky sinew

tall temple
#

bcq i get hacked and i want to get perms in my server with my bot

#

@smoky sinew it's not for nuking or idk

#

help me with the code pls

slate swan
#

hello, i want to do a persistent view button via nextcord i added the view in the on_readdy event but i get the error: RuntimeError: no running event loop

slate swan
#

Guess who’s back

#

Back again

#

!rule 1

unkempt canyonBOT
slate swan
#

!rule 79

unkempt canyonBOT
#

:x: Invalid rule indices: 79

slate swan
#

!rule 23

unkempt canyonBOT
#

:x: Invalid rule indices: 23

slate swan
#

!rule 6

unkempt canyonBOT
#

6. Do not post unapproved advertising.

junior falcon
#

I have a .yml config file where the user should be able to define the color of the button. What i put for it to change if for example the person as button_color write "danger"

button_color: green
style=discord.ButtonStyle. < What i put here?
#

Like this doesnt work

style="discord.button." + ticketpanelconf['button_color']
smoky sinew
#

or getattr if you'd like

hushed galleon
#

i would use getattr too, or a mapping/enum

smoky sinew
#
if button_color in ("blurple", "gray", "green", "red"):
    style = getattr(discord.ButtonStyle, button_color)
slate swan
#

how can i get the client in a callback from a button?

tough mirage
#

Here's my code https://hastebin.com/share/fubifinezu.python,
I keep on getting error,

Exception has occurred: NotImplementedError
exception: no description
File "C:\Users\Madth\OneDrive\Documents\Projects\discord slash\my_bot.py", line 30, in <module>
@client.command(name="my_command", description="My first command :)")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
NotImplementedError:

smoky sinew
unkempt canyonBOT
#

property client```
The client that is handling this interaction.

Note that [`AutoShardedClient`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AutoShardedClient "discord.AutoShardedClient"), [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot"), and [`AutoShardedBot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.AutoShardedBot "discord.ext.commands.AutoShardedBot") are all subclasses of client.
smoky sinew
#

yep

lament swan
#

def responseCondition(user_Input):
    sentence = tokenize(user_Input) # tokenize user input
    X = bag_of_words(sentence, all_words) # putting tokenized words into Bag of Words
    X = X.reshape(1, X.shape[0])
    X = torch.from_numpy(X).to(device)
    output = model(X)
    _, predicted = torch.max(output, dim=1)

    tag = tags[predicted.item()]

    probs = torch.softmax(output, dim=1)
    prob = probs[0][predicted.item()]
    if prob.item() > 0.75: 
        for intent in intents['intents']:
            if tag == intent['tag']:
                if tag == "predict_humidity": 
                    response = random.choice(intent['responses'])
                    predict_humidity = getDataset()
                    return(f"{response}\n{predict_humidity}")
                elif tag == "egg_condition":
                    response = random.choice(intent['responses'])
                    fuzzification = eggCondition() 
                    return(f"{response}\n{fuzzification}")
                elif tag == "check_temperature":
                    dataset = loadDataset() 
                    Temperature = dataset
                    response = get_temperatureCondition(Temperature)
                    return(f"{response}\n")
                elif tag == "check_humidity":
                    dataset = loadDataset() 
                    Humidity = dataset
                    response = get_humidityCondition(Humidity)
                    return(f"{response}\n")
                elif tag in list_of_eggs:
                    advice = get_eggAdvice(tag)
                    response = random.choice(intent['responses'])
                    response += advice 
                    return(f"{response}")
                else: 
                    response = random.choice(intent['responses'])
                    return(f"{response}")
    else: 
        return("Sorry, I don't understand what you're talking about.")
#

guys anyone can solve this? why my discord bot keep reply the else statement

smoky sinew
#

probably the wrong channel

glad cradle
vale wing
#
return()``` is very sus
sick birch
#

Is that even a syntax error

vale wing
#

We shall rewrite bobux to use return()!

smoky sinew
#

no it just returns an empty tuple

glad cradle
#

why should it be a syntax error

smoky sinew
#

actually, return(x) works everywhere else given it would just return a singleton of x

#

might as well use return(x);

glad cradle
sick birch
#

Oh wait I see what you mean

glad cradle
vale wing
#

Oh heck micro

vale wing
shrewd apex
#

aight lets set a deadline of 69 years

sick birch
#

Rust users when someone says micro instead of macro

slate swan
#

Hey, please do you think someone can use anyhow PC to start game development in Python?

vale wing
#

@sick birch do you know next.js?

sick birch
#

hello yes

vale wing
#

Hello wanna join bobux development

sick birch
#

I am the local nextjs shill

sick birch
vale wing
#

Bobux bot

#

We have quite a team there

sick birch
#

What's it do? :p

glad cradle
#

I'm joking

vale wing
#

You can earn bobux with it

slate swan
sick birch
#

Isn't that like against Roblox's terms of service or something

vale wing
#

Nope that's joke currency

sick birch
#

Oh fair

#

Not really sure. I've got my claws in like 5 different pies at the moment

glad cradle
sick birch
#

metaphorically speaking

vale wing
#

Alright okay

sick birch
#

Let us know if you want to join forces with letsbuilda, shen would probably love to get you guys set up with infra and hosting

glad cradle
#

what's "letsbuilda"

sick birch
#

We call it Shennanigans as a Service (SaaS) as a joke because he manages all our DevOps :p

slate swan
sick birch
vale wing
#

Like a VPS?

slate swan
#

What Python library do you think it's easier for newbie in game development?

sick birch
#

All the jazz

vale wing
#

We need help more like with promotion

glad cradle
glad cradle
#

btw this is the wrong channel to talk about this

slate swan
#

Wow, buy that's quite expensive in my country. So 2gb to 4gb can't run any thing in Python?

glad cradle
#

no they can run programs but it'll be slower and it'll maybe lag/crash

even 8gb should be ok

slate swan
glad cradle
slate swan
#

How did you learn it till this level?

#

How did you learn the strings, the variables n so many of them. How did you get to know what they mean and how to work with them?

glad cradle
slate swan
#

How did you learn it before now?
I mean what you started programming?

vocal snow
#

!resources

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

vocal snow
#

there are free courses and books listed here

fierce schooner
#

hello

#

i am back

stone palm
#

is there any difference between bot.get_message, guild.get_message and channel.fetch_message?

cold sonnet
#

but they usually aren't so you fetch a message from the api to get a message object you can work with

stone palm
#

hmmm

#

for example

#

which one should i use between client.get_message and guild.get_message?

vocal snow
cold sonnet
#

where did get go

stone palm
#

wha

vocal snow
#

possibly removed in 2.0

stone palm
#

yeah right

#

only fetch with message now

cold sonnet
#

yeah I don't think you have an option mate

lone sail
#

Makes sense, as get_x are cached models. Caching every message it sees would be painful. fetch_x always uses the discord api

slate swan
#

what bot?

#

how to install a module to create a discord bot?

#

thats what you mean?

#

if you want to code your own discord bot then you need to install a module

#

pip install discord.py or any other module

#

i personally use nextcord

#

!pypi nextcord

unkempt canyonBOT
slate swan
unkempt canyonBOT
fierce schooner
hollow dune
#

     try:
        user = interaction.user
        member = interaction.guild.get_member(user.id)
        hunter_role = discord.utils.get(interaction.guild.roles, name="Hunteris")
        if hunter_role in member.roles:
            await interaction.response.send_message("Sekmingai priemei uzsakyma")

            # Disable the button
            button.disabled = True
            await interaction.message.edit(view=self)
     except Exception as e:
        print(f"Error: {e}")

why am i getting error here?
Traceback (most recent call last):
File "C:\Users\Aivaras\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ui\view.py", line 414, in _scheduled_task
await item.callback(interaction)
TypeError: MyModal.button_callback() missing 1 required positional argument: 'interaction'

naive briar
#

Show the full code

unkempt canyonBOT
#

examples/views/confirm.py lines 29 to 33

@discord.ui.button(label='Confirm', style=discord.ButtonStyle.green)
async def confirm(self, interaction: discord.Interaction, button: discord.ui.Button):
    await interaction.response.send_message('Confirming', ephemeral=True)
    self.value = True
    self.stop()```
hollow dune
#

alr ill try it out

slate swan
#

i belive you use the button decorator since you named your method button_callback

jovial cape
#

Do you mean running?

#

You can run it locally for debugging

#

Or you can rent a server for actually putting it to use

whole shoal
#

What is the limit of items on the drop-down list made using view

naive briar
#

!d discord.ui.Select

unkempt canyonBOT
#

class discord.ui.Select(*, custom_id=..., placeholder=None, min_values=1, max_values=1, options=..., disabled=False, row=None)```
Represents a UI select menu with a list of custom options. This is represented to the user as a dropdown menu.

New in version 2.0.
naive briar
#

25, read the docs

whole shoal
#

Alrr

shrewd bramble
unkempt canyonBOT
shrewd bramble
#

!pypi discord-py-interactions

unkempt canyonBOT
shrewd bramble
#

^-^

slate swan
shrewd bramble
#

just the module I use ._.

slate swan
#

why

shrewd bramble
#

hmm, no special reason.. just stumbled on it ig..

slate swan
#

mkay