#discord-bots

1 messages ยท Page 212 of 1

glad cradle
#

Well you're just using what discord.py expose in the Interaction class, docs are cool

fresh fern
#

ohh

glad cradle
#

!d discord.Interaction.message

unkempt canyonBOT
glad cradle
#

note that this is only available if the Interaction comes from a component

fresh fern
#

oh so like if i click a btn so whatever the button gives....as an output

glad cradle
#

wdym

fresh fern
#

nothing nothing

#

thanks btw

glad cradle
#

when someone click a button your Bot receives a INTERACTION_CREATE event

this event payload contains a reference to the message which the button is part of

fresh fern
#

ohhh

#

one more thing......

glad cradle
fresh fern
#

like if the user clicks the btn then i want to bot to edit that btn to the text

glad cradle
#

you want to edit the button text?

fresh fern
#

wait

#

like

#

I clicked the btn now i want the bot to edit that msg with btn and write hello over there

#

get it??

glad cradle
#

it's the same thing but instead of passing just the view here you'll pass a string (or an embed or whatever) too

#

!d discord.InteractionResponse.edit_message

unkempt canyonBOT
#

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

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

i did it but i doesnt remove the btn

#

it just adds the text to the msg

#

i want to remove the btn and add the text to the same msg

glad cradle
#

you need to pass view=self

fresh fern
#
async def on_click(self, interaction: discord.Interaction, button: discord.ui.Button):
    await interaction.response.edit_message(content="You clicked me!")
    await interaction.message.edit(view=self)```
#

im doing this

#

join my test server imma show u

glad cradle
#

you're not disabling the message also you can edit everything in the edit_message

fresh fern
#

im confused

#

im using edit_message only

glad cradle
#

no you're not, you're also using interaction.message.edit

fresh fern
#

ohhhh

#
await interaction.response.edit_messgage(view=self)```
#

like this???

naive briar
#

Are you

glad cradle
#
button.disabled = True
await interaction.response.edit_message(content="some text", view=self)
#

I thought I was clear ๐Ÿ˜”

btw I need to study bye

fresh fern
#

ok ok byee

#

i dont wannt to disable the btn i just want to remove it completely

naive briar
#

Then set view to none

fresh fern
#

but also want some text instead of it

#

either im dumb or im not able to explain my issue

#

ITS DONEEEEEEE I DID IT

fresh fern
#

help again....

#
from discord.ext import commands
from discord import app_commands


class hbday(commands.Cog):
    def __init__(self, client: commands.Bot):
        self.client = client

    @app_commands.command(name='mrhappybday', description="Happy Birthday")
    @app_commands.describe(member="Member to wish (leave empty to with yourself).")
    async def hbday(self, interaction: discord.Interaction, member: str = None):
        view = View()
        await interaction.response.send_message(view=view)

class View(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=3)

    @discord.ui.button(label="Click Me!", style=discord.ButtonStyle.blurple)
    async def on_click(self, interaction: discord.Interaction, button: discord.ui.Button):
        self.remove_item(button)
        await interaction.response.edit_message(view=self, content=f"Happy Birthday {}")


async def setup(client):
    await client.add_cog(hbday(client))```
#

here i want to access member (async def hbday(self, interaction: discord.Interaction, member: str = None):)

#

and use it in await interaction.response.edit_message(view=self, content=f"Happy Birthday {HERE}")

#

how do i do this

#

anyone??

slate swan
#

view.member = something
...

use view.member

#

!d discord.ButtonStyle

unkempt canyonBOT
#

class discord.ButtonStyle```
Represents the style of the button component.

New in version 2.0.
slate swan
#

not with ui

#

from discord import ButtonStyle ?

naive briar
#

Do you know how imports works

naive umbra
#

so you meant no

slate swan
#

ButtonStyle is not in the ui

naive umbra
#
from discord.ui import Button, View
from discord import ButtonStyle
fresh fern
slate swan
fresh fern
#

wait lemme try again

#

worked yay

#

thanks

slate swan
#

๐Ÿ‘

naive briar
#

The button has no callback

#

And there's no on_button_click event

slate swan
fresh ferry
#

whats the update method of using action_row 's ??

#

!paste

vale wing
#

You just update view comps and msg.edit(view=view)

fresh ferry
#

view comps and msg.edit(view=view) ??

vale wing
#

Wait dpy doesn't have row init kwarg?

#

!d discord.ui.Button

unkempt canyonBOT
#

class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.

New in version 2.0.
vale wing
#

Mm it does

#

Ah yes it's not an attribute

vale wing
fresh ferry
#

trying to put clickable buttons inside embeds

#

not below them

naive briar
#

What makes you think this is doable

fresh ferry
tired pollen
naive briar
#

I've always hated that sentence

vale wing
#

Since relative position of embeds and buttons is regulated by client

vale wing
#

There are events that can occur with 0% probability which means they can't occur so that's invalid yeah

slate swan
#

can i use a message sent by a followup as a variable ?

vale wing
#

Yeah I think

slate swan
#

what do I need to import to use discord slash commands

brazen raft
#

from discord import app_commands

velvet tinsel
#

Itโ€™s been ages since Iโ€™ve been here, lol

slate swan
#

is it possible to create a slash command with python requests?

#

yes

#

the example here is using requests :)

slate swan
#

why do you need to use external module for slash commands?

slate swan
slate swan
#

Seems more like a #databases question.
Also don't use sqlite3 with Discord bots as it's a blocking library. Use an async alternative such as aiosqlite.

fresh fern
#

can anyone explain me defer and followup

#

please....

#

i dont get the docs

silk fulcrum
#

what can you not understand there

fresh fern
#

whats corutine

silk fulcrum
silk fulcrum
fresh fern
#

huh!?

silk fulcrum
fresh fern
#

i googled and then came here

silk fulcrum
#

Let's see

fresh fern
#

i can understand from tutorials better but cant find one

silk fulcrum
#

A coroutine is a method that can be paused when we have a potentially long-running task and then resumed when that task is finished.

#

what can you not understand here?

fresh fern
#

ok so like we have a very long task.....

#

so we paused it and did something else and then resumed the big task

vocal snow
vocal snow
#

Although I'd recommend making sure you understand basic python concepts like functions, classes, etc first

fresh fern
#

i do understand thoose

#

whats followup

#

yea and what are the attributes of defer

#

i mean there are 2

#

epheral and thinking

#

what they do

golden portal
#

ephemeral keyword argument is to make your followup ephemeral

fresh fern
#

how to check is_owner() in app_commands

white citrus
#
class ChannelSlowmode(nextcord.ui.StringSelect):
    def __init__(self):
        
        @nextcord.ui.StringSelect(placeholder="Please select a slowmode delay", max_values=1, options=["30 secound", "1 minute", "5 minutes", "10 minutes", "15 minutes", "30 minutes", "1 hour", "2 hours", "4 hours", "6 hours", "8 hours", "16 hours", "24 hours"])
        async def on_select(self, select: nextcord.ui.StringSelect, inter: nextcord.Interaction):
            option = select.values
            match option:
                case "30 secounds":
                    t = 30
                case "1 minute":
                    t = 60
                case "5 minutes":
                    t = 300
                case "10 minutes":
                    t = 600
                case "15 minutes":
                    t = 900
                case "30 minutes":
                    t = 1800
                case "1 hour":
                    t = 3600
                case "2 hours":
                    t = 7200
                case "4 hours":
                    t = 14400
                case "6 hours":
                    t = 21600
                case "8 hours":
                    t = 28800
                case "16 hours":
                    t = 57600
                case "24 hours":
                    t = 86400
            
            await inter.channel.edit(slowmode_delay=t)
            await self.message.edit(content="HI")```
#
Traceback (most recent call last):
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 489, in _run_event
    await coro(*args, **kwargs)
  File "c:\Discord\Maja Projekt\MajaSystem_Test\bot.py", line 296, in on_application_command_error
    raise error
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\application_command.py", line 888, in invoke_callback_with_hooks
    await self(interaction, *args, **kwargs)
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\cooldowns\cooldown.py", line 93, in inner
    result = await func(*args, **kwargs)
  File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\server_moderation\cog.py", line 121, in edit_channel
    view = ChannelSlowmode()
  File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\server_moderation\view.py", line 46, in __init__
    async def on_select(self, select: nextcord.ui.StringSelect, inter: nextcord.Interaction):
TypeError: 'StringSelect' object is not callable````
fresh fern
#
@app_commands.describe(count="Number of messages to delete")
@is_owner()
async def toggle(self, interaction: discord.Interaction, *, command):
    command = self.client.get_command(command)

    if command is None:
        await interaction.response.send_message(f"{command} not found")
    elif interaction.command == command:
        await interaction.response.send_message("You can't disable this command")
    else:
        command.enabled = not command.enabled
        ternary = "enabled" if command.enabled else "disabled"
        await interaction.response.send_message(f"{command.name} {ternary}")```
#

error

#

discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.modCommands' raised an error: TypeError: parameter 'command' is missing a type annotation in callback 'modCommands.toggle'

slate swan
#

add annotation to command parameter

slate swan
slate swan
#

directly when defining options

white citrus
# slate swan also pro tip instead od doing this big match case you can do this: ```py @next...
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\bot.py", line 742, in _load_from_module_spec
    spec.loader.exec_module(lib)  # type: ignore
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\server_moderation\cog.py", line 11, in <module>
    from modules.server_moderation.view import ChannelRename, ChannelSlowmode
  File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\server_moderation\view.py", line 42, in <module>
    class ChannelSlowmode(nextcord.ui.string_select):
TypeError: function() argument 'code' must be code, not str

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

Traceback (most recent call last):
  File "c:\Discord\Maja Projekt\MajaSystem_Test\bot.py", line 369, in <module>
    main()
  File "c:\Discord\Maja Projekt\MajaSystem_Test\bot.py", line 58, in main
    bot.load_extension(f"modules.{folder}.cog")
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\bot.py", line 864, in load_extension
    self._load_from_module_spec(spec, name, extras=extras)
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\bot.py", line 745, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
nextcord.ext.commands.errors.ExtensionFailed: Extension 'modules.server_moderation.cog' raised an error: TypeError: function() argument 'code' must be code, not str```
slate swan
vale wing
#

Select menu for channel SM is meh imho

#

Why not just parse duration

flint heart
#

How could I make this code:

@client.tree.command()
async def commandlist(interaction: discord.Interaction):
    """Lists all the available commands"""
    await interaction.response.send_message("/add [cardname] @[target] (Can only be used by High Staff members and Developers)\n/cardlist\n/inventory @[target]\n/commandlist")``` result in a code block ```(like this)``` instead of being plain text? I've already tried looking it up, but I can't find anything about it
#

Right now, it just looks like this:
/add [cardname] @[target] (Can only be used by High Staff members and Developers
/cardlist
/inventory @[target]
/commandlist

slate swan
#

like you do normally?

#

adding three backticks

flint heart
#

Oh!

slate swan
#

before and after

flint heart
#

I didn't think it would be that easy

#

lemme try that rq

#

It worked, thx!

slate swan
#

๐Ÿ‘

vital glacier
#

anyone here experience with psql databases and on_voice_state_update events (before and after)

unkempt mauve
#

So I have added a sticky message in a channel. How do I make the bot check if there's a sticky message in the channel and deletes it after sending another sticky message?

tired pollen
tired pollen
#

!d discord.on_voice_state_update

unkempt canyonBOT
#

discord.on_voice_state_update(member, before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") changes their [`VoiceState`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceState "discord.VoiceState").

The following, but not limited to, examples illustrate when this event is called...
unkempt mauve
#
if message.channel.id == 1062309347239137320:
      if message.content.startswith(''):
        await asyncio.sleep(20)
        await message.channel.send('This is the channel where you can post images and other contents. Do not send any explicit content here. Doing so will result in a punishment.')
        return```
Its sending multiple messages
vital glacier
# smoky sinew don't ask to ask

i'm working on voicemaster, but i need to do the event handler for it, no idea where to continue from where im from rn LOL

tired pollen
unkempt mauve
smoky sinew
tired pollen
unkempt mauve
vital glacier
#

i know, just dont know how that would work

#

and since my friend isnt responding mad

tired pollen
unkempt mauve
tired pollen
#

Bot responding to its self

unkempt mauve
#

I have this line dude

tired pollen
unkempt mauve
#

wait I dont

tired pollen
vital glacier
#

that's the part im stuck with rn, is using the database info and making it work like that

tired pollen
#

All you need is to save the id of join to create voice

vital glacier
#

That's why I've got this rn

    @commands.Cog.listener()
    async def on_voice_state_update(self, member, before, after):
        data = await self.bot.db.fetch('SELECT voice FROM voicemaster WHERE guild_id = $1', member.guild.id)
        if data:
smoky sinew
#

what's not working

vital glacier
#

Alright that's good to know

#

But how would I make the vc then and move them to it with htis, cus im not 100% sure how that would go then

smoky sinew
unkempt canyonBOT
#

await create_voice_channel(name, *, reason=None, category=None, position=..., bitrate=..., user_limit=..., rtc_region=..., video_quality_mode=..., overwrites=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

This is similar to [`create_text_channel()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.create_text_channel "discord.Guild.create_text_channel") except makes a [`VoiceChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceChannel "discord.VoiceChannel") instead.

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

Just add check and check if someone joined ( before is none) to that voice channel ( join to create)

smoky sinew
#

!d discord.Member.move_to

unkempt canyonBOT
#

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

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

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

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

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

Then also you need to save new voice channel where member moved to so when no one is in the voice channel you delete it

#

That's all ig

vital glacier
#

yeah ive been tryna figure it out but i cant get further

#

purely because of all the database work

tired pollen
#

Check If after is none ( someone leaved) then get new voice channel and with members attr you can get list of members that are in the voice check the len of it if 0 then delete voice

flint heart
#

Hey everyone! I'm trying to implement a /give command to my card bot, but I'm having some trouble. Could someone point me in the right direction? Here's my entire code: https://pastebin.com/P03CB0FG

smoky sinew
#

you should probably remove the with statement and use client.db_conn instead since you already have it created

#

also don't forget to call await super().close() in your MyClient.close

keen cloak
#

hello

cinder tulip
#

Why isnt this working?
just know that the .env is in the same directory and it has written in it "DISCORD_TOKEN = mybottoken"

smoky sinew
cinder tulip
#

wait

#

what you mean

slate swan
#

load_dotenv()

#

from dotenv module

#

!pypi python-dotenv

unkempt canyonBOT
cinder tulip
blazing flint
#

is there any set way to find other files with the same parent directory as main.py using the os package

cinder tulip
#

import os
from dotenv import load_dotenv

slate swan
cinder tulip
#

from dotenv import load_dotenv
from dotenv import dotenv_values

got these too

slate swan
#

and then all_files = os.listdir(parent_dir)

blazing flint
#
import discord
from discord.ext import commands
from discord import app_commands
from main import get_server_data, set_server_data

class Setadmin(commands.Cog):
  def __init__(self, client):
    self.client = client

  @app_commands.command(name="setadmin", description="Set the allowed roles to use moderation commands without any restrictions.")
  @commands.has_permissions(administrator=True)
  @app_commands.describe(name="roles",description='The admin role IDs.')
  async def setadmin(self, interaction: discord.Interaction, roles: str):
    guild = interaction.guild
    admin_roles = [int(role.strip()) for role in roles.split(',')]
    admin_n = [guild.get_role(role).name for role in admin_roles]
    current_config = get_server_data(guild.id)
    new_config = {
      "admin_roles": admin_roles,
      "confirm_roles": current_config.confirm_roles,
      "confirm_channel": current_config.confirm_channel
    }
    set_server_data(guild.id, new_config)
    await interaction.response.send_message(f'Admin roles have been updated to:\n {admin_n}', ephemeral=True)
    print(f"Admin roles in {guild.name}({guild.id}) updated to: {admin_n}")
  
async def setup(client):
  await client.add_cog(Setadmin(client))```
and
```py
@client.event
async def setup_hook():
  print(f"Logged in as {client.user.name}")
  for filename in os.listdir('./cmds'):
    if filename.endswith('.py'):
      print(f'cmds.{filename[:-3]} loaded')
      await client.load_extension(f'cmds.{filename[:-3]}')
  await client.tree.sync()
  print('Extensions loaded successfully!')```
result in the error
https://paste.pythondiscord.com/rerutigafa
#

(I am not auto syncing all the time and I remove the sync line after I sync all of my new commands)

cinder tulip
slate swan
cinder tulip
upbeat otter
blazing flint
#

do I use pip install --upgrade discord.py?

cinder tulip
#

it should be yeah upgrade

slate swan
#

or -U

cinder tulip
#

yeah i use -U

slate swan
#

it's causing your bot to run twice

upbeat otter
#

๐Ÿ’€wtf didn't even notice

#

Sarthy ๐Ÿ›

slate swan
#

or add an ```py
if name == "main":

cinder tulip
slate swan
#

you can do it this way?

#

never seen this way

#
import os

os.environ["INDEXED"]
os.getenv("NOT-INDEXED")
blazing flint
#

An error occurred during configuration: option use-feature: invalid choice: 'content-addressable-pool' (choose from 'fast-deps', 'truststore', 'no-binary-enable-wheel-cache')

blazing flint
slate swan
cinder tulip
blazing flint
#

I dont see what is wrong with that

#

I am just importing necessary functions

slate swan
blazing flint
#

oh

#

what do you want me to do instead

slate swan
#

even if you import a single function, whole file gets interpreted

slate swan
blazing flint
#

?

slate swan
#

!botvar

unkempt canyonBOT
#
Bot variables

Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:

bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"

@bot.command()
async def get(ctx: commands.Context):
    """A command to get the current value of `test`."""
    # Send what the test attribute is currently set to
    await ctx.send(ctx.bot.test)

@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
    """A command to set a new value of `test`."""
    # Here we change the attribute to what was specified in new_text
    bot.test = new_text

This all applies to cogs as well! You can set attributes to self as you wish.

Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!

slate swan
#

like bot.test is being used here, you can attach the function as a variable bound to the bot

#

and then access it using self.bot.<the var> inside the cog

#

or just move the functions to some other file and import them

slate swan
blazing flint
#

mk

blazing flint
#

I still dont quite get it can you give me some example related to my functions

slate swan
#

til then

slate swan
#

it should fix stuff

#

anyone here need help with anything? if so just ping me.

blazing flint
#

I just accidentally deleted pip

quick gust
#

What

blazing flint
#

how do I reinstall it

tired pollen
blazing flint
#

lol

#

how do I reinstall it tho

slate swan
blazing flint
#

how

slate swan
#

just run python installer

#

it should install it

#

run the python installer and select uninstall

#

then run t again and press install

blazing flint
#

how do I do that through shell

cinder tulip
blazing flint
#

I am using replit

slate swan
#

oh

#

then just make a new repl??

languid jungle
#

Please don't use ableist language in this server.

cinder tulip
quick gust
#

๐Ÿ’€

slate swan
slate swan
slate swan
#

its not my fault hes asking stupid questions when he doesnt know basic python why try programming something when u dont even know how to reinstall pip or create a new repl

#

people are wasting time on here instead of asking good legitimate questions

sick birch
#

There's no need to be rude about it

#

You have the choice to just not say anything :)

slate swan
slate swan
# cinder tulip <@456226577798135808> it was this one lol

oh, make sure you did these

  • the .env file should be in same dir as your main file
  • the env should be in this format (usually)
TOKEN = "YOUR TOKEN"
  • you should load the env using python-dotenv lib before trying to access it ```py
    import dotenv
    dotenv.load_dotenv()

os.environ["TOKEN"]
#or
os.getenv("TOKEN")

if all these still don't work try setting the env on system level instead of env file and try
sick birch
#

.load_dotenv() is important! Don't forget it

slate swan
cinder tulip
slate swan
#

wtv dbi

slate swan
blazing flint
#

k I reinstalled it through shell lol

cinder tulip
tired pollen
slate swan
cinder tulip
#

Uhhhhh

#

uhhhh

#

lets see if thatll work, i hope so

#

nooope

slate swan
#

can you try printing os.environ

#

and see if DISCORD_TOKEN is a key there

cinder tulip
#

well anywhere will be fine, let me see

slate swan
#

anywhere after load_dotenv()

#

yeah

cinder tulip
cinder tulip
slate swan
#

yeah it means the env file is not detected

slate swan
cinder tulip
#

aw man, it's there

slate swan
cinder tulip
slate swan
#

if you used that play button it might be the reason

cinder tulip
slate swan
#

yeah don't, use the terminal ```
python main.py

cinder tulip
#

alright then let's try like that

slate swan
#

or whatever your python command is binded to (it could also be py or python3)

cinder tulip
#

it still gave me the error xd

#

do i on the vscode's terminal?

slate swan
#

yeah

cinder tulip
#

that's what i did

slate swan
#

are you in the project's dir inside the vsc terminal

blazing flint
#

poetry add still does not work for installing discord

slate swan
#

the package is called discord.py not discord

slate swan
#

weird error thi

cinder tulip
#

bro always me

blazing flint
#

An error occurred during configuration: option use-feature: invalid choice: 'content-addressable-pool' (choose from '2020-resolver', 'fast-deps', 'truststore')

cinder tulip
#

How am i gonna hide my bot's token on my github :waaa:

slate swan
#

won't be exposed anywhere tho

cinder tulip
#

I know man but i can't use a .env file

smoky sinew
#

why not

cinder tulip
#

cause it always gives an error

smoky sinew
#

what does your full code look like

cinder tulip
#

600+ lines

slate swan
#

how does it looks like inside .env maybe your syntax is wrong

smoky sinew
slate swan
#

@cinder tulip can you show the .env file structure with the token hidden ofc

#

remember to hide actual token

cinder tulip
#

man i almost sent my token MAAN

blazing flint
# blazing flint An error occurred during configuration: option use-feature: invalid choice: 'con...
  File "/home/runner/Mod-Trainer/venv/bin/poetry", line 5, in <module>
    from poetry.console import main
  File "/home/runner/Mod-Trainer/venv/lib/python3.10/site-packages/poetry/console/__init__.py", line 1, in <module>
    from .application import Application
  File "/home/runner/Mod-Trainer/venv/lib/python3.10/site-packages/poetry/console/application.py", line 7, in <module>
    from .commands.about import AboutCommand
  File "/home/runner/Mod-Trainer/venv/lib/python3.10/site-packages/poetry/console/commands/__init__.py", line 4, in <module>
    from .check import CheckCommand
  File "/home/runner/Mod-Trainer/venv/lib/python3.10/site-packages/poetry/console/commands/check.py", line 2, in <module>
    from poetry.factory import Factory
  File "/home/runner/Mod-Trainer/venv/lib/python3.10/site-packages/poetry/factory.py", line 18, in <module>
    from .repositories.pypi_repository import PyPiRepository
  File "/home/runner/Mod-Trainer/venv/lib/python3.10/site-packages/poetry/repositories/pypi_repository.py", line 11, in <module>
    from cachecontrol import CacheControl
  File "/home/runner/Mod-Trainer/venv/lib/python3.10/site-packages/cachecontrol/__init__.py", line 13, in <module>
    from .wrapper import CacheControl
  File "/home/runner/Mod-Trainer/venv/lib/python3.10/site-packages/cachecontrol/wrapper.py", line 5, in <module>
    from .adapter import CacheControlAdapter
  File "/home/runner/Mod-Trainer/venv/lib/python3.10/site-packages/cachecontrol/adapter.py", line 11, in <module>
    from .controller import CacheController, PERMANENT_REDIRECT_STATUSES
  File "/home/runner/Mod-Trainer/venv/lib/python3.10/site-packages/cachecontrol/controller.py", line 17, in <module>
    from .serialize import Serializer
  File "/home/runner/Mod-Trainer/venv/lib/python3.10/site-packages/cachecontrol/serialize.py", line 10, in <module>
    import msgpack
ModuleNotFoundError: No module named 'msgpack'```
#

results from poetry add

cinder tulip
#

just like this

slate swan
#

did you delete some files from your repl?

blazing flint
#

idk

slate swan
slate swan
cinder tulip
#

ok let's see

blazing flint
#

can I duplicate this one

slate swan
cinder tulip
#

THERE'S NO WAY

slate swan
blazing flint
#

ima fork it

cinder tulip
#

BY REMOVING THE SPACES IT WORKED

slate swan
#

no dont

slate swan
blazing flint
#

oh

slate swan
#

it works with spaces for me on linux but not on windows lol

blazing flint
#

I forked it btw and now pip is not installed again lol

cinder tulip
#

I wanna thank you all for helping me with this issue

blazing flint
#

I just making a new replit

#

I migrated to a new repl and changed the end to py if __name__ == "__main__": client.run(token) and it still gets the error

#

do I still need to try botvars

#

@slate swan

slate swan
#

whats the new error

blazing flint
#

!hastebin

#

?

smoky sinew
#

what's your code

slate swan
#

not how describe works

blazing flint
#

oh yeah

slate swan
#

!d discord.app_commands.describe

unkempt canyonBOT
#

@discord.app_commands.describe(**parameters)```
Describes the given parameters by their name using the key of the keyword argument as the name.

Example:

```py
@app_commands.command(description='Bans a member')
@app_commands.describe(member='the member to ban')
async def ban(interaction: discord.Interaction, member: discord.Member):
    await interaction.response.send_message(f'Banned {member}')
```  Alternatively, you can describe parameters using Google, Sphinx, or Numpy style docstrings...
blazing flint
#

lol

#

I had that from so long ago

#

how did I miss that

#

I had it that way cuz someone told me to

#

lol no way that was the problem

#

I promise I knew that

#
@app_commands.describe(member = "The user to mute", reason = "The reason for the mute.")
async def mute(interaction: discord.Interaction, member: discord.Member, reason: str):
  if admin_roles:
    for role in interaction.user.roles:
      if role.id in admin_roles:
        if member.guild_permissions.administrator:
          await interaction.response.send_message("You cannot mute an administrator.", ephemeral=True)
          return
        guild = interaction.guild
        muteRole = discord.utils.get(guild.roles, name="Muted")

        await interaction.response.send_message("Mute was successfull", ephemeral=True)
        if muteRole == None:
          muteRole = await guild.create_role(name="Muted")
          await interaction.user.send("No Muted role was found. One was created, and you may edit it to your liking.")

        for channel in guild.channels:
          await channel.set_permissions(muteRole, speak=False, send_messages=False, read_message_history=True, read_messages=True)
        await member.add_roles(muteRole, reason=reason)
        await member.send(f"You were muted by {interaction.user}.\n Reason: {reason}")
        if confirm_channel:
          await client.get_channel(int(confirm_channel)).send(f"**{interaction.user}** muted **{member}**. \n Reason: **{reason}**")
        return
    await interaction.response.send_message("You are not allowed to use this command.", ephemeral=True)
        
  else:
    await interaction.response.send_message("Admin roles have not been set. Please set atleast one before using any moderation commands.", ephemeral=True)
    print("Moderation command was attempted before admin roles were set.")```
#

I have a separate question

#
    "1111111111": {
        "admin_roles": [],
        "confirm_roles": [],
        "confirm_channel": ""
    },
    "2222222222": {
        "admin_roles": [],
        "confirm_roles": [],
        "confirm_channel": ""
    },
    "1081731158099894293": {
        "admin_roles": [],
        "confirm_roles": [],
        "confirm_channel": ""
    }
}``` I have a json for storing server data that looks like this
#

I also have a function for getting the whole batch of data from one section

#

using that function, how would I be able to get one specific property such as "confirm_channel"

#

@slate swan

smoky sinew
#

someone create a discord.py bingo with "replit" and "json storage" on it

smoky sinew
blazing flint
#

ok

#

YES IT WORKS

#

also

#

is there a way to ask for an input type that is a channel

#

and one that is a role

smoky sinew
#

with slash commands?

blazing flint
#

ye

slate swan
#

annotate parameter as Role

smoky sinew
#

just annotate the argument as discord.TextChannel or discord.Role

slate swan
#

or whatever you want

blazing flint
#

ok

#

how can I make it so you can input multiple roles

#

like as many as you want separated by commas

smoky sinew
#

i dont think you can

blazing flint
#

oh ok

smoky sinew
#

maybe use a roleselect instead

blazing flint
#

how does that work

smoky sinew
#

like any other select menu

#

you just make a view class and put the role select decorator inside

blazing flint
#

ok

#

I think for now I will keep it as a string where you just enter the roles separated by commas

#

How can I subtract the first three and last two characters from a variable

smoky sinew
#

string splicing

#

hold on i wonder if there's a tag

#

!splicing

unkempt canyonBOT
#

You are not allowed to use that command here. Please use the #bot-commands channel instead.

smoky sinew
#

it would be [3:][:-2]

unkempt canyonBOT
#
Sequence slicing

Slicing is a way of accessing a part of a sequence by specifying a start, stop, and step. As with normal indexing, negative numbers can be used to count backwards.

Examples

>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters[2:]  # from element 2 to the end
['c', 'd', 'e', 'f', 'g']
>>> letters[:4]  # up to element 4
['a', 'b', 'c', 'd']
>>> letters[3:5]  # elements 3 and 4 -- the right bound is not included
['d', 'e']
>>> letters[2:-1:2]  # Every other element between 2 and the last
['c', 'e']
>>> letters[::-1]  # The whole list in reverse
['g', 'f', 'e', 'd', 'c', 'b', 'a']
>>> words = "Hello world!"
>>> words[2:7]  # Strings are also sequences
"llo w"
blazing flint
#

how would I be able to do that to the "role" value in admin_roles = [int(role.strip()) for role in roles.split(',')]

smoky sinew
#

oh slicing not splicing

slate swan
#

yep slicing

smoky sinew
#

i don't know why i thought it was named splicing

blazing flint
#

@smoky sinew ?

smoky sinew
#

wdym

blazing flint
smoky sinew
#

why

blazing flint
#

cuz I changed it to mentioning the role instead of inputting the role id

smoky sinew
#

why not just use role select though

#

just put role.strip()[3:][:-1]

#

are you sure it's 2 characters at the end

blazing flint
#

one

smoky sinew
#

ok

blazing flint
#

k I got it working

#

also I just found you can do role.strip()[3:-1]

#

and it does the same thing

smoky sinew
#

yeah

blazing flint
#

ty for your help

flint heart
#

Nothing I've tried has worked

#

I'm using aiosqlite to manage the db

smoky sinew
#

i already responded

flint heart
#

Oh

#

Sorry, I didnt see it

smoky sinew
#

remove all the async with parts in your code and reuse client.db_conn instead

flint heart
#

Ok

cloud dawn
slate swan
velvet tinsel
flint heart
#

How might I go about making the /pack commands able to put duplicates in the user's inventory? I got it working for /add, but it won't work for /pack1, /pack2, or /pack3.
/pack2:

@client.tree.command()
async def pack2(interaction: discord.Interaction):
    """Adds three random cards to the user's inventory"""
    async with aiosqlite.connect('card_inventory.db') as db_conn:
        cards = random.sample(cardList, 3)
        for card in cards:
            cursor = await db_conn.execute('SELECT * FROM inventory WHERE user_id = ? AND card_name = ?',
                                           (interaction.user.id, card))
            row = await cursor.fetchone()
            if row is None:
                await db_conn.execute('INSERT INTO inventory (user_id, card_name) VALUES (?, ?)',
                                       (interaction.user.id, card))

        await db_conn.commit()

    card_names_str = "\n".join(cards)
    embed = discord.Embed(title=f"You got a pack of cards!",
                          description=f"Added the following cards to your inventory:\n{card_names_str}",
                          color=0x00ff00)
    await interaction.response.send_message(embed=embed)```
#

/add: ```py
@client.tree.command()
async def add(interaction: discord.Interaction, cardname: str, recipient: discord.Member):
"""Adds a card to a user's inventory"""
# permissions
allowed_roles = ["VBA | High Staff Team", "VBA | Developer Team"]
if not any(role.name in allowed_roles for role in interaction.user.roles):
await interaction.response.send_message("You are not authorized to use this command!")
return
# checks if card exists
cardname = cardname.capitalize()
if cardname not in cardList:
await interaction.response.send_message(f"Error: '{cardname}' is not a valid card!")
return

async with aiosqlite.connect('card_inventory.db') as db_conn:
    # insert card into db
    await db_conn.execute('INSERT INTO inventory (user_id, card_name) VALUES (?, ?)', (recipient.id, cardname))
    await db_conn.commit()

# calls the proper file
file_path = cardFiles[cardname]
file = discord.File(file_path, filename=f"{cardname.lower()}.jpg")

# response to user
embed = discord.Embed(title=f"{cardname} added",
                      description=f"Added card '{cardname}' to {recipient.mention}'s inventory!", color=0x00ff00)
embed.set_image(url="attachment://card_image.jpg")
await interaction.response.send_message(embed=embed, file=file)```
light flower
#

The role is not given by the reaction of the person who wrote the messages

@client.event
async def on_raw_reaction_add(payload):
# Check that the reaction was added in the "report-increase" channel
    if payload.channel_id == YOUR_CHANNEL_ID:
# Get the message to which the reaction was added
        message = await client.get_channel(payload.channel_id).fetch_message(payload.message_id)
# Get the user who wrote this message
        user = message.author
# Get the server on which the event occurred
        guild = client.get_guild(payload.guild_id)
# Get the "member" role
        role = discord.utils.get(guild.roles, name="member")
# Get the server member object
        member = guild.get_member(user.id)
# Add the "member" role to the member who wrote the message
        await member.add_roles(role)

There are no errors in the console

Also visited the other option did not work

async def on_reaction_add(reaction, user):
    channel_id_otchet = client.get_channel(1084181490730025052)
    role_id_otchet = discord.utils.get(reaction.guild.roles, name="member")
    if reaction.message.channel.id == channel_id_otchet:
        guild = await client.fetch_guild(user.guild.id)
        member = await guild.fetch_member(user.id)
        author = reaction.message.author
        print('#1')
        if author.id != user.id:
            if discord.utils.get(member.roles, id=role_id_otchet) is None:
                role = guild.get_role(role_id_otchet)
                await author.add_roles(role)
                print('on_reaction_add WORKED!')

Pls Help

velvet tinsel
#

Using a phone is cursed, Jesus fuck. Iโ€™ll try to read this

velvet tinsel
velvet tinsel
flint heart
#

Ik what you mean

#

So basically

#

/pack1 gives a user one random card, /pack2 gives 3, and /pack3 gives 5

#

/add directly adds a card to a user's inventory (Can only be done by an admin ofc)

#

I was able to get /add to allow for duplicates

#

So for example, If I were to do "/add jhett @flint heart" twice, when i did /inventory, both would be there

white citrus
#

How to get bot id in application command

flint heart
#

However, let's say I do /pack2 and get Jhett, Paris, and Radiant

velvet tinsel
flint heart
#

If I do it again, lets say I get Pup, Jhett, and Jant

#

If I did /inventory, there would only be Jhett, Paris, Radiant, Pup, and Jant

#

Even though there should be 2 jhetts

white citrus
velvet tinsel
flint heart
white citrus
flint heart
#

Ohhh

#

Right click on the bot

velvet tinsel
flint heart
#

Then copy ID at the bottom

white citrus
flint heart
velvet tinsel
white citrus
flint heart
#

Oh yea

flint heart
#

Then it tells the user its ID?

white citrus
velvet tinsel
#

My brain has deteriorated extremely terribly. You want to get the bot ID through a command, correct?

velvet tinsel
flint heart
#

try this:

#

Ohhhhh

#

The ID of the user?

velvet tinsel
#

Holy shit I HATE USING A PHONE

white citrus
#

Not the user id uff

smoky sinew
#
@bot.tree.command()
async def id(interaction: discord.Interaction) -> None:
    await interaction.response.send_message(bot.user.id)
velvet tinsel
white citrus
#

For noobs client id that is what i want lol

velvet tinsel
#

I really need to re educate myself with this

flint heart
#
id = "[id of your bot]"
@client.tree.command()
async def id_finder(interaction: discord.Interaction):
    await interaction.response.send_message(f"My ID is {id}")```
velvet tinsel
#

Yeah sorry I canโ€™t do this with a phone ๐Ÿ˜ฆ

#

I canโ€™t make sense of the code

white citrus
#

Learning basics

white citrus
flint heart
#

Dawg nobody here gets what you're asking for

white citrus
#

I thought it is interaction.client.id but it isnt @velvet tinsel

smoky sinew
#

what if the bot id changes

flint heart
#

True, true

smoky sinew
white citrus
smoky sinew
#

you probably meant interaction.client.application_id @white citrus

white citrus
smoky sinew
velvet tinsel
#

Oh. Iโ€™ve used those libs but itโ€™s been months since Iโ€™ve used it. I used to be of help, but unfortunately, Iโ€™ve kind of forgotten some prime basics. Iโ€™ll just go and re-learn this stuff.

proven venture
#

Got a quick question guys. So basically I wrote a code that checks for changes on a website and if it changes the bot sends a dm to a person. But how can I stop this loop with another slash command and so the loop is always up to date with the stop slash command. Basically i wanna stop a loop with a command but I donโ€™t know how. Btw I am using interactions obv

glad cradle
proven venture
#

No, I use while

proven venture
glad cradle
#

mh? a bare while loop would block your code so you're running it in some way, are you using an asyncio task?

glad cradle
#

this won't be difficult, you just need a dict with ids as keys and tasks as values

proven venture
#

But I think I know how to solve it will check tomorrow

#

Thx for your help bro โค๏ธ

glad cradle
#

you're welcome

slate swan
#

I don't know whether or not to put this in here but I will, I'm using a webhook to connect multiple roblox profiles to a server for example (If they join a game their instanceID gets sent to my server) but it's having strange errors which say "Error retrieving JoinInstanceID for Roblox ID: 76773338" I'll leave the code below help me if you can.

import json

profiles = [76773338]

roblox_api_endpoint = "https://api.roblox.com/users/{}/currently-playing"

# WEBHOOK HERE
discord_webhook_url = "MY WEBHOOK"

for profile_id in profiles:
    response = requests.get(roblox_api_endpoint.format(profile_id))
    if response.status_code == 200:
        join_instance_id = response.json()["JoinInstanceID"]
    else:
        print("Error retrieving JoinInstanceID for profile ID: {}".format(profile_id))
        continue

    payload = {
        "username": "Roblox Profiles",
        "content": "JoinInstanceID for profile ID {}: {}".format(profile_id, join_instance_id)
    }

    response = requests.post(discord_webhook_url, data=json.dumps(payload), headers={"Content-Type": "application/json"})
    if response.status_code != 204:
        print("Error sending webhook for profile ID: {}".format(profile_id))```
sick birch
flint heart
#

I'm back again! This time, I'm trying to add a money system, and was wondering what the best approach would be. Rn, I'm thinking the only two choices would to make a new db, or add a section to my current db. Note that I'm new to managing databases, so preferably whichever would be easier. Not sure if it means anything, but the money would be used to buy packs (/pack1, /pack2, and /pack3). Here's my code: https://pastebin.com/Awgqhthp

#

And sorry for the super inconsistent commenting, I've been trying to do better with them

smoky sinew
#

that's what tables are for

#

why do you do self.db_conn = ... if you don't use it anyways @flint heart

flint heart
#

I was recommended I use it, but I don't remember from where

#

I was reccomended it from someone in The Coding Den discord server (I think)

smoky sinew
#

just remove all the with statements and replace db_conn with client.db_conn

flint heart
#

Ok

frosty parrot
#

hey I'm using openai api in my bot . Is it free to use ?

flint heart
#

Yea

#

But there's a limit to how many queries you can have

#

Not sure the exact amount

frosty parrot
#

like ?

#

oh k

#

I asked the bot what's your name and then he replied myname is John

frosty parrot
flint heart
#

Im looking up how many you can have rn

frosty parrot
flint heart
#

Yea I can't find it

frosty parrot
#

ok np

#

can I use frequently for now ?

frosty parrot
#

see

lusty tulip
#

Hello, i'm working on the Flask framework to build an http discord bot, everything working fine until i needed to upload file. Can someone explains me (or send me a guide) how to return a multipart form with Flask. Until now, I only returned json / dict to each interaction. I read the discord documentation but I didn't find it useful

naive briar
lusty tulip
#

thank you !

hushed galleon
#

the #965291516031549500 thread would probably be more relevant
oh if its only about returning a multipart response then web dev is fine

shrewd apex
light violet
#

ok ok

turbid canopy
#

today i bought a new chair and im so happy ๐Ÿ˜„

drifting arrow
#

How do I make my discordbot automatically reconnect to any buttons/interactions?
For example, in this image, if my bot goes offline, lets say due to internet outage or coz my cat eats my internet box, and I bring my bot online. Currently it doesnt recognize those buttons.

drifting arrow
hushed galleon
#

yup, a bot token to make the requests would be sufficient and then it would go through interactions endpoint / gateway as usual

hushed galleon
turbid canopy
#

@hushed galleon i sent you the friend request

hushed galleon
#

why? (i dont normally accept frs)

sick birch
#

fr

hushed galleon
#

fr man

vale wing
fresh fern
#
@app_commands.checks.has_permissions(manage_guild=True)
@app_commands.checks.bot_has_permissions(manage_guild=True)
@app_commands.describe(gI="Guild ID", wI="Welcome channel ID", bI="Bye Channel ID")
async def setup(interaction: discord.Interaction, gI: discord.Guild, wI: int, bI: int):
    client.wlcm = wI
    client.bye = bI
    client.guildID = gI
    info = {"sName": client.guildID.id, "wChannel": client.wlcm, "bChannel": client.bye}
    client.col.insert_one(info)
    await interaction.response.send_message(
        f"Guild ID: {client.guildID.id}\nWelcome channel ID: {client.wlcm}\nBye channel ID: {client.bye}",
        epeheral=True)
    await interaction.followup.send("Setup Done", epeheral=True)```
#

code

#
  File "/home/iam/Documents/Python Files/Discord Bot/MrWelcome/main.py", line 39, in <module>
    @app_commands.command(name="mrsetup", description="Setups the guild for welcome and bye features.")
     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/iam/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 2002, in decorator
    return Command(
           ^^^^^^^^
  File "/home/iam/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 665, in __init__
    self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.__globals__)
                                                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/iam/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 373, in _extract_parameters_from_callback
    param = annotation_to_parameter(resolved, parameter)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/iam/.local/lib/python3.11/site-packages/discord/app_commands/transformers.py", line 834, in annotation_to_parameter
    (inner, default, validate_default) = get_supported_annotation(annotation)
                                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/iam/.local/lib/python3.11/site-packages/discord/app_commands/transformers.py", line 793, in get_supported_annotation
    raise TypeError(f'unsupported type annotation {annotation!r}')
TypeError: unsupported type annotation <class 'discord.guild.Guild'>
#

error

#

please help

#

im using mongodb to store the data

#

my command worked earlier but now i was shifting to slash command and got this error

sick birch
#

Discord doesn't have support for guild selection

fresh fern
#

huh??

sick birch
#

It's not a valid parameter type

fresh fern
#

but earlier it worked

sick birch
#

Yeah works fine for prefix commands, since they're more flexible

fresh fern
#

oh so what should i do now

sick birch
#

You will have to go for a workaround like having the user enter in the guild ID

fresh fern
#

i didnt get what u just said

sick birch
#

You'd just accept an int which will be the guild ID

fresh fern
#

ohhhh

#

what if the user enters something else

karmic nimbus
#
reply = f'this user is afk'
    if not message.author.bot:
        for user in message.mentions:
            if user.id == my_id:
                await message.channel.send(reply, reference=message)

how can i add cooldown for the reply?

fresh fern
#

like 123

sick birch
fresh fern
#

howw!!??

sick birch
#
guild = bot.get_guild(user_input)
if guild:
  # guild exists! use it
else:
  # guild doesn't exist!
fresh fern
#

Oh yea

#

thanks

#

robin

#

lemme just try ill let u know if it worked

radiant bough
#
Logs = await ctx.guild.audit_logs(limit=limit).flatten()

How do I flatten this because .flatten() isnโ€™t working

naive briar
#

!d discord.Guild.audit_logs

unkempt canyonBOT
#

async for ... in audit_logs(*, limit=100, before=..., after=..., oldest_first=..., user=..., action=...)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") that enables receiving the guildโ€™s audit logs.

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

Examples

Getting the first 100 entries:

```py
async for entry in guild.audit_logs(limit=100):
    print(f'{entry.user} did {entry.action} to {entry.target}')
```...
naive briar
#

Read the docs

shrewd apex
#

u have to unpack it asynchronously

turbid canopy
velvet tinsel
fresh fern
#

how to see the number of all member in the servers in which the bot is

#

anyone please tell this

#

im really confused

shrewd kraken
#

!d discord.Client.guilds

unkempt canyonBOT
shrewd kraken
#

it returns a list, so you can just run len(bot.guilds)

slate swan
glad cradle
#

no

#

guild isn't even defined in your example

glad cradle
fresh fern
#

what do i use

#

@glad cradle and @slate swan

slate swan
#

use from snipy

fresh fern
#

lets see

#

how

#

like client.guilds

#

what after that'

glad cradle
#

it's just an attribute, you can access it everywhere you have Bot object access

glad cradle
fresh fern
#

client.guilds returns the no. of guilds im in

#

OHHHH

#

GOT IT

glad cradle
glad cradle
#

wdym? why should the Bot be banned

slate swan
#

well thats the point of the discord bot to create commands that everyone can use

depends what the command is supposed to do

#

its supposed to send dms to all server members?

#

well if the discord server is 10 members then its fine but for bigger servers it will be spamming and could get you banned yes

fresh fern
gloomy bramble
#
import discord
from discord.ext import commands
import mysql.connector
import datetime 

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

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

@bot.event
async def on_ready():
    print(f"Bot is ready. Logged in as {bot.user}")
    print("-------------------------------------")

@bot.command()
async def test(ctx):
    print("Test command received")
    await ctx.send('Testing, testing, 1, 2, 3...')
    print("Test command received")

bot.run("Troll")```
#

Guys why this not working :(

glad cradle
fresh fern
#

im confused

#

still

#

about client.guilds

fresh fern
#

it returns a BIGGGGGGGG list

gloomy bramble
glad cradle
fresh fern
glad cradle
#

then it's

#

!d discord.ext.commands.Bot.users

unkempt canyonBOT
fresh fern
#

ohhh

gloomy bramble
fresh fern
#

client.user

glad cradle
gloomy bramble
fresh fern
#

users*

glad cradle
#

ah maybe you don't have the message_content intent enabled

gloomy bramble
#

wait

glad cradle
gloomy bramble
#

message content intent was always enabled

fresh fern
#

THANKS A LOT SNIPY

glad cradle
glad cradle
glad cradle
gloomy bramble
keen lark
#

TypeError: __init__() missing 1 required keyword-only argument: 'intents' how can I fix this

naive briar
#

Read the error, it's already telling you what's the problem

#

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

native saffron
#

!main

lofty jolt
#

Hi, I'm very much a noob at coding in general, but I am learning. What I am doing now is trying to make a custom bot for my 2 discord servers. I want the bot to send a different embed depending on what server is joined. The embed will mention different channels in the respective servers. This is the code I have so far:

from discord.ext import commands

intents = discord.Intents.all()

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

@bot.event
async def on_ready():
    print(f"Logged in as {bot.user} (ID: {bot.user.id})")
    print("-------------")

@bot.event
async def on_member_join(member):
    if member.guild.id == "1051109766002376805":
        austin_channel = bot.get_channel(1051112385869521048)
        austin_welcome_embed = discord.Embed(title="Welcome!" , description="![s_](https://cdn.discordapp.com/emojis/1054137106945036320.webp?size=128 "s_") Read the rules\n ![s_](https://cdn.discordapp.com/emojis/1054137106945036320.webp?size=128 "s_") Grab some roles\n ![s_](https://cdn.discordapp.com/emojis/1054137106945036320.webp?size=128 "s_") Boost our server\n ![s_](https://cdn.discordapp.com/emojis/1054137106945036320.webp?size=128 "s_") Have fun!", color=0xCCCCCC )
        austin_welcome_embed.set_image(url="https://cdn.discordapp.com/attachments/1044880051654635572/1044911108617678908/Welcome.gif")
        print(f"{member.name} has joined the Austin server.")
        await austin_channel.send(f"<@&1084444679921213520> {member.mention}")
        await austin_channel.send(embed=austin_welcome_embed)
    elif member.guild.id == "1052302588688748544":
        central_channel = bot.get_channel(1052307098303741952)
        central_welcome_embed = discord.Embed(title="Welcome", description=f"This is the official staffing server for **Malevolent** and **Sundown**, please find the respective categories of both servers to either appeal or apply for different positions within the servers. If you need any help, ping the <@&1052302821220942015> role")
        print(f"{member.name} has joined the Central server.")
        await central_channel.send(f"{member.mention}")
        await central_channel.send(embed=central_welcome_embed)

bot.run("token will go here lol")```

The problem is that I don't get any messages sent at all - even the print output in the terminal. Any ideas? All help will be greatly appreciate ![sd_gudeUwu](https://cdn.discordapp.com/emojis/1022109387508166797.webp?size=128 "sd_gudeUwu")
dull terrace
#

why is 1/2 rounded 0?

naive briar
dull terrace
#

weird decision, i was always taught in math that you round up for 0.5

warm summit
#

The bot sleeps and when someone interacts with the bottons it doesn't respond

gilded cedar
#

So i want to autoban members with names matching using wildcard but i want to ban multiple banned names even tho i attempted to make it errors came into the way here's the code (only bans one name with wildcard on)
banned_name_pattern = r"Banned_name"

@bot.event
async def on_member_join(member):
# Check if the username matches the banned name pattern
if re.match(banned_name_pattern, member.name):
# Ban the user
await member.ban(reason="Banned name")
else:
# Send a welcome message
channel = member.guild.system_channel
if channel is not None:
await channel.send(f"Welcome to the server, {member.mention}!")

twilit bison
#

**```python
1>>@bot.tree.command(name="lock",description="locks the channel which you send the message on")
2>>@app_commands.checks.has_permissions(manage_channels=True)
3>>async def lock(interaction: discord.Interaction):
4>> await interaction.response.send_message("`lock")

how to check if the author of message has perm other than line 2 ?**
timber wren
#

hey all, I want to make a sound dispatch command somewhat similar to Airhorn Solutions... This is what I made but I am having an error

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'VoiceChannel' object has no attribute 'play'

Code:

@discord.slash_command(name='quack', description = 'Quack, Quack, Quack!')
    async def quack(self, ctx):
        vc = ctx.author.voice.channel
        if vc == None:
            ctx.respond("You must be connected to a voice channel!")
        else:
            vc.connect()
            vc.play(discord.File('duck-quacking-37392.mp3'))
#

where am I going wrong?

glad cradle
#
  1. the VoiceClient.play method doesn't accept a discord.File object, you need to pass a source
#

!d discord.VoiceClient.play

unkempt canyonBOT
#

play(source, *, after=None)```
Plays an [`AudioSource`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AudioSource "discord.AudioSource").

The finalizer, `after` is called after the source has been exhausted or an error occurred.

If an error happens while the audio player is running, the exception is caught and the audio player is then stopped. If no after callback is passed, any caught exception will be logged using the library logger.

Changed in version 2.0: Instead of writing to `sys.stderr`, the libraryโ€™s logger is used.
glad cradle
gloomy bramble
#

i am working on a discord economy bot. so like, how do i create an inventory function?

#

imo there are two ways to go about it. one is creating a separate table for every user (very tedious for me to categorise or something idek)

the second option idk if there is a second option honestly

quick gust
#

you can make a single 'users' table that can store the IDs of every user and the items they have

#

oh and what database are you using

glad cradle
glad cradle
quick gust
gloomy bramble
#

Operation failed: There was an error while applying the SQL script to the database.
Executing:
CREATE TABLE bank.inventory (
id BIGINT UNSIGNED NOT NULL,
item_name VARCHAR(255) NOT NULL,
description VARCHAR(255),
price INT,
quantity INT NOT NULL,
PRIMARY KEY (id, item_name),
FOREIGN KEY (id) REFERENCES users(id),
CONSTRAINT max_items CHECK (id IN (SELECT id FROM inventory GROUP BY id HAVING COUNT(*) <= 20))
);

ERROR 1146: Table 'bank.inventory' doesn't exist
SQL Statement:
CREATE TABLE bank.inventory (
id BIGINT UNSIGNED NOT NULL,
item_name VARCHAR(255) NOT NULL,
description VARCHAR(255),
price INT,
quantity INT NOT NULL,
PRIMARY KEY (id, item_name),
FOREIGN KEY (id) REFERENCES users(id),
CONSTRAINT max_items CHECK (id IN (SELECT id FROM inventory GROUP BY id HAVING COUNT(*) <= 20))
)

quick gust
unkempt canyonBOT
#
Formatting code on discord

Here's how to format Python code on Discord:

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

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

For long code samples, you can use our pastebin.

gloomy bramble
#
Executing:
CREATE TABLE `bank`.`inventory` (
  id BIGINT UNSIGNED NOT NULL,
  item_name VARCHAR(255) NOT NULL,
  description VARCHAR(255),
  price INT,
  quantity INT NOT NULL,
  PRIMARY KEY (id, item_name),
  FOREIGN KEY (id) REFERENCES users(id),
  CONSTRAINT max_items CHECK (id IN (SELECT id FROM inventory GROUP BY id HAVING COUNT(*) <= 20))
);

ERROR 1146: Table 'bank.inventory' doesn't exist
SQL Statement:
CREATE TABLE `bank`.`inventory` (
  id BIGINT UNSIGNED NOT NULL,
  item_name VARCHAR(255) NOT NULL,
  description VARCHAR(255),
  price INT,
  quantity INT NOT NULL,
  PRIMARY KEY (id, item_name),
  FOREIGN KEY (id) REFERENCES users(id),
  CONSTRAINT max_items CHECK (id IN (SELECT id FROM inventory GROUP BY id HAVING COUNT(*) <= 20))
)```
glad cradle
#

btw this is off topic for this channel, you should head to #databases

gloomy bramble
#

sorry

#

no one's responding there :(

quick gust
#

Yeah it's a little in active but you'll probably get a better answer there

unkempt mauve
#

How do I make a link button

unkempt mauve
#

ok

shrewd apex
shrewd apex
#

pgsql has a jsonb data type

#

perfect for an inventory

silk fulcrum
gloomy bramble
shrewd apex
#

wait lemme order my dinner I'll tell u

shrewd apex
#

an example u can expand fields however u want

zealous jay
#

Is there a way to search messages?

#

Like with the search function that users have

undone badge
#

I can't figure out how to check if specified channel is in the same server as the command I used.

Like here's code and I want it to deny if channel id is from another server
async def setlogchannel(self, context: Context, channel_id): server_id = context.guild.id try: await self.bot.fetch_channel(channel_id) id = await db_manager.add_log_channel(channel_id, server_id) embed = discord.Embed(description=f"ะšะฐะฝะฐะป ะดะปั ะธัั‚ะพั€ะธะธ ัะพะพะฑั‰ะตะฝะธะน ัƒัั‚ะฐะฝะพะฒะปะตะฝ ะฝะฐ <#{id}>", color=0x9C84EF) await context.send(embed=embed) except: embed = discord.Embed(description=f"ะขะฐะบะพะณะพ ะบะฐะฝะฐะปะฐ ะฝะต ััƒั‰ะตัั‚ะฒัƒะตั‚ ะธะปะธ ัƒ ะผะตะฝั ะฝะตั‚ ะดะพัั‚ัƒะฟะฐ ะบ ะบะฐะฝะฐะปัƒ.", color=0x9C84EF) await context.send(embed=embed)

sacred vigil
#

hey! I'm having issues trying to do pip install discord.py
(Mac Version 10.13.6)

Says bash: pip: command not found

zealous jay
#

does using py works?

sacred vigil
zealous jay
#

just using py on the console

#

it should open python

#

because if that works you can use py -m pip install discord.py

sacred vigil
#

looks like it doesn't work..

zealous jay
#

did you install python?

sacred vigil
#

yes

zealous jay
#

maybe python -m pip install discord.py

#

idk

sacred vigil
#

ill try to reinstall python if it doesn't work

zealous jay
#

๐Ÿ‘

sacred vigil
zealous jay
#

great

undone badge
#

Toto do you know asnwer for my question?

slate swan
#

need someone to make a fortniite discord bot w me i have no experience with post requests and stuff

young dagger
#

!e

    enemy_points = [1969, 1318, 1971, 1860, 2044, 2381, 1498, 3421, 1146, 1690, 2186, 1368, 1819, 1515, 2270, 2001, 1211]
    med = sum(enemy_points) / len(enemy_points)
    print(round(med))```
unkempt canyonBOT
#

@young dagger :white_check_mark: Your 3.11 eval job has completed with return code 0.

1863
quick gust
#

Please use #bot-commands if it's not related to a conversation

upbeat otter
slate swan
#

is it better to list the event listener once and have multiple guard clauses for functions or to have an event listener for each function?

fallow granite
#

someone can help me ? Contact me privately

slate swan
# thin raft can you explain again

so is it better to repeat each listener for the function. lets say..

async def on_voice_state_update(self, member, before, after)
if after.channel is not None and "Variable" is in after.channel.name:
  #Do Something
async def on_voice_state_update(self, member, before, after)
if after.channel is not None and "Different Variable" is in after.channel.name:
  #Do Something Else

or would it be better to do something like..

async def on_voice_state_update(self, member, before, after)
if after.channel is not None and "Variable" is in after.channel.name:
        return False
  #Do Something
  return True
elif "Different Variable" is in after.channel.name:
        return False
  #Do Something Else
  return True
thin raft
#

depends

#

are those in the same class?

slate swan
#

the top one is not. i have them in a different file for each for dev testing.

thin raft
#

if they're in the same file it is useless

#

the top one will get overwritten

slate swan
#

ohhh cause its in chronological order

#

i got a weird warning. since i left it running for a couple days and wasn't sure if its because of this being in different files or something else
WARNING - discord.gateway : Can't keep up, shard ID None websocket is 25.7s behind.

#

so that's why i was questioning optimizations

#

It may happen when using synchronous modules

slate swan
#

Yes just use async ones for example
dont use requests
use aiohttp instead

slate swan
fiery salmon
#

Hi, is there a way to raise an exception without printing it to console?
I have an error handler, but my errors are getting printed before error handler is called

velvet tinsel
#

or just an example

fiery salmon
#

but it is still printing error to console

velvet tinsel
#

show me the code

smoky sinew
#

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

fiery salmon
# velvet tinsel show me the code

issue isnt with error handler
like i said, exception is getting printed before going to error handler. so clearly it's not looking into the error handler first before printing
error handler still works as expected though.

#

i am using async def on_application_command_error(self, interaction:Interaction, error): instead though

velvet tinsel
#

oh

fiery salmon
#

because on_command_error wasn't working

velvet tinsel
#

well... try @example.error and see if it works instead

fiery salmon
#

how do u mean

#

one of my commands is

@nextcord.slash_command()
@cooldowns.cooldown(1, 5400, bucket=cooldowns.SlashBucket.author)
async def work(self, interaction:Interaction):
velvet tinsel
#
@example.error
async def example_error(self, ctx, error):
  if isinstance(error, commands.WhateverYouWant):
    await ctx.send("Error!")
velvet tinsel
blazing flint
#

Whatโ€™s the problem

fiery salmon
blazing flint
#

Are you getting errors currently?

fiery salmon
#

ok let's back up

#

error is not with handler

velvet tinsel
#

well, I'm very good at taking the worst and longest way possible, so I say...

make one for every single thing ๐Ÿ’€

blazing flint
#

Ok

#

Well

slate swan
fiery salmon
blazing flint
#

Remove the error handler

#

Are you getting any trace back errors

fiery salmon
velvet tinsel
#

ok ye I'll just ๐Ÿšช ๐Ÿšถโ€โ™‚๏ธ

blazing flint
#

Can I know what is happening

#

So I can try to help

slate swan
#

The error is printed cause it wasnt caught in the handler i suppose

fiery salmon
slate swan
#

Hm

blazing flint
#

Can you send me the trace back

fiery salmon
#

let me get example

fiery salmon
# blazing flint Can you send me the trace back
Ignoring exception in command <nextcord.application_command.SlashApplicationCommand object at 0x7f1ea79257f0>:
Traceback (most recent call last):
  File "/home/ubuntu/.local/lib/python3.9/site-packages/nextcord/application_command.py", line 863, in invoke_callback_with_hooks
    await self(interaction, *args, **kwargs)
  File "/home/ubuntu/economy-bot/cogs/bj.py", line 49, in blackjack
    player_hand, player_num, embed = await self.player_turn(dFirstHand, dFirstNum, interaction)
  File "/home/ubuntu/economy-bot/cogs/bj.py", line 151, in player_turn
    raise Exception("timeoutError")
Exception: timeoutError

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

nextcord.errors.ApplicationInvokeError: Command raised an exception: Exception: timeoutError
START OF ERROR HANDLER

blazing flint
#

So I know what the problem is

fiery salmon
#

that's one

slate swan
blazing flint
#

Delete the error handler

#

They can eat up the trace back space

fiery salmon
#

but deleting error handler will 100% guarantee a print to the console

blazing flint
#

And then send the full trace back

cinder tulip
#

Why isn't icon_url not working

slate swan
#

Add another if to check for Exception

#

In error handler

#

And see if it invokes

blazing flint
#

send code formatted messages along with the error

slate swan
#

!d discord.Embed.add_field

unkempt canyonBOT
#

add_field(*, name, value, inline=True)```
Adds a field to the embed object.

This function returns the class instance to allow for fluent-style chaining. Can only be up to 25 fields.
fiery salmon
# blazing flint And then send the full trace back

let's do this one instead:

Ignoring exception in command <nextcord.application_command.SlashApplicationCommand object at 0x7ffb273a8280>:
Traceback (most recent call last):
  File "/home/ubuntu/.local/lib/python3.9/site-packages/nextcord/application_command.py", line 863, in invoke_callback_with_hooks
    await self(interaction, *args, **kwargs)
  File "/home/ubuntu/.local/lib/python3.9/site-packages/cooldowns/cooldown.py", line 104, in inner
    async with _cooldown(*args, **kwargs):
  File "/home/ubuntu/.local/lib/python3.9/site-packages/cooldowns/cooldown.py", line 249, in __aenter__
    async with bucket:
  File "/home/ubuntu/.local/lib/python3.9/site-packages/cooldowns/cooldown_times_per.py", line 50, in __aenter__
    raise CallableOnCooldown(
cooldowns.exceptions.CallableOnCooldown: This function is being rate-limited. Please try again in 5398.027218 seconds.

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

nextcord.errors.ApplicationInvokeError: Command raised an exception: CallableOnCooldown: This function is being rate-limited. Please try again in 5398.027218 seconds.
blazing flint
#

Mmmk

#

That is the problem

#

You are being rare limited by discord because you are sending way too many requests

slate swan
#

N

#

What no

blazing flint
#

Wait nvm

slate swan
#

Its cause there is an cooldown on a command

fiery salmon
#

correct

blazing flint
#

Remove the cooldown

cinder tulip
fiery salmon
blazing flint
#

Exactly

fiery salmon
blazing flint
#

Problem solved

slate swan
#

Do you handle CallableOnCooldown in handler?

fiery salmon
smoky sinew
#

"this function is being ratelimited, please try again in 5398 seconds"

fiery salmon
slate swan
#

That's weird from nextcord

#

I never Had such problem when using it

fiery salmon
#

i have a /work command.
don't want users using it every second, so hence, cooldown.
I have the if isinstance(error, CallableOnCooldown):
and it is handled correctly, tells user it is on cooldown.

but error still printed to console

fiery salmon
slate swan
#

The contributors should know what is causing this

fiery salmon
blazing flint
fiery salmon
blazing flint
#

I donโ€™t have enough context bro

#

The cooldown is the direct cause of the error

#

Are you trying to send the user a message when they canโ€™t use the command because of the cooldown?

slate swan
#

๐Ÿคฆ

tired pollen
blazing flint
#

nvm I fixed it by passing self

fiery salmon
smoky sinew
#

why you're making it so much harder for yourself

#

i thought u said u werent doing that anymore

blazing flint
#

no im not

#

lol this is just temporary so it is easier to find errors while I am converting my commands to cogs

smoky sinew
#

putting everything in a separate file does not help you

slate swan
#

Wondering how pseudo implementation helps catch Bugs in actual implementation

sacred vigil
#

do you guys also get this or is it me?
(the commands does not work so it might have smt to do with it)
WARNING discord.ext.commands.bot Privileged message content intent is missing, commands may not work as expected.

smoky sinew
sacred vigil
#

all the intents is enabled

smoky sinew
#

show your code

slate swan
smoky sinew
#

they are though

slate swan
#

Well this is just warning so

#

Not an actual error

blazing flint
#

for most bots, something like intents = discord.Intents.default() intents.members = True intents.message_content = True should work

#

or just intents = discord.Intents.all() if you have a multi-purpose bot

smoky sinew
#

no..

#

you shouldn't enable all intents unless you're really using them

blazing flint
#

yeah

#

thats what im saying

smoky sinew
#

and even discord.Intents.default() is somewhat bad, because you don't need most of them anyway, (such as typing)

sacred vigil
#

looks like it working now....

blazing flint
#

it works fine for me

sacred vigil
#

it responds so

blazing flint
#

ok

blazing flint
#

wait you use lunar client?

blazing flint
#

lmao

slate swan
#

I hate that turtle

silk fulcrum
#

is this ugly green potato that climbed out of a toilet bowl even a turtle?

slate swan
#

๐Ÿ˜ญ

torpid hare
#

hi can someone help me my command is only returning the message if i reply to the original message otherwise it returns an empty string

@commands.hybrid_command(
        name="trivia",
        description="Get a trivia question on pokemon",
    )
    async def trivia(self, context: Context):
        try:
            with open(self.path, "r") as f:
                data = json.load(f)
                question = data[str(random.randint(1, 100))][str(random.randint(1, 20))]

                if type(question[1]) == list:
                    print(True)
                    question[1] = ' '.join(question[1])

                await context.send(f'{question[0]} {question[1]}')

                def check(message: discord.Message):
                    return message.author.id == context.author.id and message.channel.id == context.channel.id

                user_response = await self.bot.wait_for('message', check=check)
                print(user_response.content.strip())

                if user_response.content.lower() == question[1].lower():
                    await context.send("Correct!")
                else:
                    await context.send(f"Sorry, the correct answer was {question[1]}")

        except Exception as e:
            print(e)
sick birch
torpid hare
slate swan
sick birch
#

bot.run does block so nothing after it will run

wraith knot
#

how can i make the autocomplete input optional?

slate swan
slate swan
#

it's because of some blocking process

flint heart
#

How might I go about allowing a user to have multiple of the same card? I got it working for the /add command, but I can't figure out how to do it for the /pack commands. Could anyone point me in the right direction? I've been stuck on this problem for awhile now. https://pastebin.com/6XWdXefA

smoky sinew
#

how do you write a discord.ext extension? are they the same concept as bot extensions?

#

or do they just use the same name?

slate swan
#

Like commands?

smoky sinew
#

i don't even know tbh

#

discord.ext.commands is just a module but it's confusing that it uses the term "extension"

#

because you don't use bot.load_extension on it

slate swan
#

So thereโ€™s tasks and commands. You just put them in a class and use the decorator

smoky sinew
#

in discord.py extensions are just files which can be loaded

# extension.py
async def setup(bot):
    print("Loaded the extension!")
# main.py
await bot.load_extension("extension")
slate swan
#

@tasks.loop(seconds=60)
@commands.command(name='hello')
i just make a for loop to load the extensions from every folder. in each py file i have a function at the end

class TestCog(commands.Cog):
    def __init__(self, bot):
  @tasks.loop(seconds=60)
#function
  @commands.command(name='hello')
#function
async def setup(bot):
    await bot.add_cog(TestCog(bot))
smoky sinew
#

why would you do that...

#

reloading extensions every minute??

#

and the task is in an extension too

slate swan
#

No you only reload it when the bot launches.

#

Right.

smoky sinew
#

i know how extensions work

slate swan
#

but if you wanna create one you'll just have to create a new package with this tree ```

  • discord
    • ext
      • your_package
        • init.py
smoky sinew
#

i see

slate swan
#

basically an empty discord/ext folder is needed

hushed galleon
smoky sinew
#

and yeah discord.ext.menus was where i got the question from

vital glacier
#
    @commands.Cog.listener()
    async def on_voice_state_update(self, member, before, after):
        data = await self.bot.db.fetchval('SELECT voice FROM voicemaster WHERE guild_id = $1', member.guild.id)
        if data:
            if after.channel.id and after.channel.id == data:
                channel = await member.guild.create_voice_channel(name=f"{member.name}'s channel",
                                                                  user_limit=0,
                                                                  category=after.channel.category)
                await member.move_to(channel)
                await self.bot.db.execute('INSERT INTO voicemaster_data (voice, guild, owner) VALUES ($1, $2, $3)',
                                          channel.id, channel.guild.id, member.id)
            else:
               data = await self.bot.db.fetch('SELECT * FROM voicemaster_data WHERE voice = $1', before.channel.id)
               if data:
                    voice=before.channel.guild.get_channel(data)
                    if voice:
                        if len(voice.members) == 0:
                            await voice.delete()
                            await self.bot.db.execute('DELETE FROM voicemaster_data WHERE voice = $1', before.channel.id)

I'm trying to make it so that if the voice channel is empty it deletes it (it does properly create it and puts it into the database, just can't seem to make it delete it if there are no members in the voice channel)
No errors in console.

smoky sinew
vital glacier
#

uh it should

#

not sure tho

smoky sinew
#

is there a short way of adding a guild_only check to a cog

#

or do i have to implement cog_check

slate swan
#

you can set dm_permissions to False

smoky sinew
#

wait can slash commands even have checks

#

nvm i'm stupid

slate swan
smoky sinew
#

i'm making a tag cog and there is no command that can be used in dms since tags are specific to a guild

slate swan
smoky sinew
#

๐Ÿ’€

#

calling decorator manually

slate swan
#

i mean they could have just allowed a dm_permission argument in the @command decorator

#

they don't even add it as an attribute for Command object ( atleast not documented)

unkempt canyonBOT
#

discord/app_commands/commands.py line 2447

f.guild_only = True```
smoky sinew
#

can't i just do something like

async def cog_check(self, ...):
    return await commands.check(app_commands.guild_only(...))
#

that probably does not make sense

hushed galleon
smoky sinew
#

yeah i was about to say that lol

slate swan
smoky sinew
#

i see

hushed galleon
#

oh yeah i forgot about the last time i tried migrating tags to slash commands, iirc it was infinitely worse at handling formatting

smoky sinew
#

are there any examples of app_commands.Group

hushed galleon
#

modals didnt give you the same syntax preview / autocomplete, and you cant write multi-line tags for a single command parameter

slate swan
hushed galleon
#

funny that they dont have one in the repo, but there's like three different ways to make groups

smoky sinew
#

they should add a TextStyle.markdown tbh

hushed galleon
#

wait, @app_commands.group() and tree.group() dont exist?

smoky sinew
#

i think it's only a class

slate swan
#

they don't ๐Ÿ’€

smoky sinew
hushed galleon
#

ah its still 3 options, creating Group, inheriting Group, or inheriting GroupCog

smoky sinew
#

what's GroupCog

hushed galleon
#

!d discord.ext.commands.GroupCog

unkempt canyonBOT
#

class discord.ext.commands.GroupCog(*args, **kwargs)```
Represents a cog that also doubles as a parent [`discord.app_commands.Group`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Group "discord.app_commands.Group") for the application commands defined within it.

This inherits from [`Cog`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog "discord.ext.commands.Cog") and the options in [`CogMeta`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CogMeta "discord.ext.commands.CogMeta") also apply to this. See the [`Cog`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog "discord.ext.commands.Cog") documentation for methods.

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

Hybrid commands will also be added to the Group, giving the ability to categorize slash commands into groups, while keeping the prefix-style command as a root-level command.

For example...
smoky sinew
#

epic

#

can i still use @app_commands.guild_only() on it?

slate swan
#

app_commands API feels very different than commands extension ๐Ÿ’€

smoky sinew
#

it is

hushed galleon
#

oh shit what if you used a message context menu instead? that might work better

slate swan
smoky sinew
#

yeah obviously it would work better because it's a message command you can literally make it work any way you like by not forcing yourself to use discord's horrible api

hushed galleon
#

nah not prefix commands, message commands

smoky sinew
#

what's the difference

hushed galleon
slate swan
smoky sinew
#

i call those right-click commands

slate swan
#

a modal? perhaps

smoky sinew
#

you can only have up to 5 context menu commands

hushed galleon
#

dpy calls em context menus and distinguishes user/message menus with parameter typehints