#discord-bots

1 messages · Page 249 of 1

slate swan
#
  File "/home/runner/Atomic/venv/lib/python3.10/site-packages/discord/client.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 293, in on_member_join
    await channel.send(embed=em)
#

The message is never sent

#

!traceback

unkempt canyonBOT
#
Traceback

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

slate swan
#

Show full error

#
@bot.event
async def on_member_join(member):
  role = discord.utils.get(member.guild.roles, name = "Civilian")
  await member.add_roles(role)
  channel = bot.get_channel(1091042545133437015)
  em=discord.Embed(
      title=f"Welcome",
      description=f"{member.mention} Joined {member.guild.name}",
      color=discord.Color.random()
      ).add_field(
      name=f":wave: Rules",
      value=f"[#1091042549273202738](/guild/267624335836053506/channel/1091042549273202738/)"
      ).add_field(
      name=f":wave: Chat",
      value="[#1091042550078525518](/guild/267624335836053506/channel/1091042550078525518/)"
      ).add_field(
      name=f"Total members",
      value=f'{member.guild.member_count}'
      ).set_footer(text=f"{member.name} just joined")
  await channel.send(embed=em)
#

Correct me if I'm wrong, but that's not the error

#
Traceback (most recent call last):
  File "/home/runner/Atomic/venv/lib/python3.10/site-packages/discord/client.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 293, in on_member_join
    await channel.send(embed=em)
AttributeError: 'NoneType' object has no attribute 'send'
#

channel is None

#

channel = bot.get_channel(1091042545133437015) returns None

#

So it could not find channel with id you provided

#

Or it's not cached

#

!d discord.ext.commands.Bot.fetch_channel

unkempt canyonBOT
#

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

Retrieves a [`abc.GuildChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel "discord.abc.GuildChannel"), [`abc.PrivateChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.PrivateChannel "discord.abc.PrivateChannel"), or [`Thread`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Thread "discord.Thread") with the specified ID.

Note

This method is an API call. For general usage, consider [`get_channel()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.get_channel "discord.ext.commands.Bot.get_channel") instead.

New in version 1.2.

Changed in version 2.0: `channel_id` parameter is now positional-only.
slate swan
#

Try using this

#
channel = bot.get_channel(1091042545133437015) or await bot.fetch_channel(1091042545133437015)

Is usually something you'd do

#

It first tries to get it from cache, if it's not found it will make the API call with fetch

#

alright

#

if i have a command like !onduty that gives a user the on duty role and the !offduty that gives a user the off duty role

#

and the user runs !onduty while having the off duty roles

#

how to make it to remove the role

#

You know this exists right? Especially for such basic questions

#

!d discord.Member.remove_roles

unkempt canyonBOT
#

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

Removes [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s from this member.

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

i pretty cant understand the way docs explain it

#
if author.has_role("Off-duty"):
  await author.remove_role("Off-duty")
vocal snow
#

you can understand the docs when you properly understand how classes and objects work

slate swan
#
Traceback (most recent call last):
  File "/home/runner/Atomic/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 229, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 233, in onduty
    await author.add_roles("🟢On Duty")
NameError: name 'author' is not defined

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

Traceback (most recent call last):
  File "/home/runner/Atomic/venv/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1350, in invoke
    await ctx.command.invoke(ctx)
  File "/home/runner/Atomic/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 1023, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "/home/runner/Atomic/venv/lib/python3.10/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: NameError: name 'author' is not defined
#

The error tells you what's wrong. You haven't defined author.

#

how should i call it?

#

ctx.author

#

!d discord.ext.commands.Context.author Use this if you want to get the author of a command.

unkempt canyonBOT
slate swan
#

Be mindful that it will return a User instead of a Member under certain circumstances, and Users don't have any attributes/methods relating to guild roles.

#

i have this error now

#
Traceback (most recent call last):
  File "/home/runner/Atomic/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 229, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 233, in onduty
    await discord.ext.commands.Context.author.add_roles("🟢On Duty")
AttributeError: '_cached_property' object has no attribute 'add_roles'

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

Traceback (most recent call last):
  File "/home/runner/Atomic/venv/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1350, in invoke
    await ctx.command.invoke(ctx)
  File "/home/runner/Atomic/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 1023, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "/home/runner/Atomic/venv/lib/python3.10/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: '_cached_property' object has no attribute 'add_roles'
fresh hatch
#

If you're unable to comprehend documentation, just google and look at stackoverflow

slate swan
#

blobpain It's an attribute of a commands.Context instance, not the class itself

naive briar
#

OOP moment

slate swan
#

Usually it's called ctx

vocal snow
#

stackoverflow often has outdated answers

fresh hatch
fresh hatch
slate swan
naive briar
#

Thanks 🐈

slate swan
#

cough Lucas cough

#
Traceback (most recent call last):
  File "/home/runner/Atomic/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 229, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 233, in onduty
    if ctx.author.has_role(ctx.guild.get_role(1115217285683089408)):
AttributeError: 'Member' object has no attribute 'has_role'

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

Traceback (most recent call last):
  File "/home/runner/Atomic/venv/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1350, in invoke
    await ctx.command.invoke(ctx)
  File "/home/runner/Atomic/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 1023, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "/home/runner/Atomic/venv/lib/python3.10/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: 'Member' object has no attribute 'has_role'
#
@bot.command()
@discord.ext.commands.has_role("Staff")
async def onduty(ctx):
  if ctx.author.has_role(ctx.guild.get_role(1115217285683089408)):
    await ctx.author.remove_roles(ctx.guild.get_role(1115217285683089408))
    await ctx.author.add_roles(ctx.guild.get_role(1115217207811637318))
    await ctx.send("Removed off duty and added on duty.")
  else:
    await ctx.author.add_roles(ctx.guild.get_role(1115217207811637318))
    await ctx.send("Successfully gave you on-duty!")
fresh hatch
thin raft
#

!d discord.Member

unkempt canyonBOT
#

class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").

This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User").

x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.

x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.

hash(x) Returns the member’s hash.

str(x) Returns the member’s handle (e.g. `name` or `name#discriminator`).
thin raft
#

you could use

#

!d discord.Member.get_role

unkempt canyonBOT
#

get_role(role_id, /)```
Returns a role with the given ID from roles which the member has.

New in version 2.0.
thin raft
#

or role_id in [role.id for role in member.roles]

robust fulcrum
#

guys how can i fix this error?

aded.
    @commands.command()
    async def reload(self, context: commands.Context):
        await self.bot.reload_extension(f"cogs.commands")
        await context.send(f"Reloaded")
naive briar
#

!d discord.ext.commands.Bot.reload_extension

unkempt canyonBOT
#

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

Atomically reloads an extension.

This replaces the extension with the same extension, only refreshed. This is equivalent to a [`unload_extension()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.unload_extension "discord.ext.commands.Bot.unload_extension") followed by a [`load_extension()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.load_extension "discord.ext.commands.Bot.load_extension") except done in an atomic way. That is, if an operation fails mid-reload then the bot will roll-back to the prior working state.
naive briar
#

It says there in the error

naive briar
#

Then the error shouldn't appear

robust fulcrum
#
    async def setup_hook(self):
        raw_exts = os.listdir("./ext")
        exts = [f"ext.{ext.replace('.py','')}" for ext in raw_exts if ext.endswith(".py")]
        for ext in exts:
            try:
                await self.load_extension(ext)
                print(f"Loaded {ext}")
            except Exception as e:
                print(f"Failed to load {ext}: {e}")
        print(f"Logged in as {self.user}")
naive briar
#

It seems like you're loading extensions from the ext directory in this code, but you're trying to reload an extension from a directory named cogs

#

Isn't it obvious

slate swan
robust fulcrum
#

thanks for help

slate swan
#

basically i have a csv file with a large amount of information and i want a discord bot that does as follows :

when i run a command like !search (input) it should search the file for that term and if found it displays it in the chat

does anyone know a bot on github that works similar to this?

naive briar
#

Why do you want a bot from GitHub? That sounds like a fairly easy thing to implement

slate swan
#

because i need it quite urgently as a last resort kinda thing

#

how easy are we talking?

#

Very easy

#

Get some CSV parser and search with it, that's about it

slate swan
naive briar
unkempt canyonBOT
#
csv

Source code: Lib/csv.py

The so-called CSV (Comma Separated Values) format is the most common import and export format for spreadsheets and databases. CSV format was used for many years prior to attempts to describe the format in a standardized way in RFC 4180. The lack of a well-defined standard means that subtle differences often exist in the data produced and consumed by different applications. These differences can make it annoying to process CSV files from multiple sources. Still, while the delimiters and quoting characters vary, the overall format is similar enough that it is possible to write a single module which can efficiently manipulate such data, hiding the details of reading and writing the data from the programmer.

slate swan
#

That's pretty much... my point..?

naive briar
#

Yes?

slate swan
#

Probably more worth it mentioning them instead of me 3HC_what

quartz viper
#

I use button to edit an embed but each time I have "This interaction failed". How can I remove it ?

slate swan
#

Respond to the interaction correctly

quartz viper
#

How ?

slate swan
#

Multiple ways, without knowing the failing code can't have an overview and can't help much either

quartz viper
north kiln
#

Why interaction.channel.send instead of interaction.response.send_message?

quartz viper
#

I have already sended a response

north kiln
#

The interaction from clicking a button is different from when a slash command is executed

#

You need to respond again

quartz viper
#

Okay but I just want to my button edit the embed not send text

naive briar
#

!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.
quartz viper
#

edit_message is not defined

twilit grotto
slate swan
#

Because it's on an InteractionResponse object

#

So you'll need to use the following first

#

!d discord.Interaction.original_response

unkempt canyonBOT
#

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

Fetches the original interaction response message associated with the interaction.

If the interaction response was a newly created message (i.e. through [`InteractionResponse.send_message()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.send_message "discord.InteractionResponse.send_message") or [`InteractionResponse.defer()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.defer "discord.InteractionResponse.defer"), where `thinking` is `True`) then this returns the message that was sent using that response. Otherwise, this returns the message that triggered the interaction (i.e. through a component).

Repeated calls to this will return a cached value.
slate swan
#

Then on the returned object you can use edit, should be better

#

Otherwise if you have an InteractionResponse object, go ahead and use it

naive briar
#

I'm sure that they can get one

slate swan
#

Considering they never give code and when they give it's the most minimal code e.g. 2 lines, hard to know

quartz viper
# twilit grotto please show your code and not just say the error

My code is very ugly, it's the first time I use button. The aim is to create an embed with buttons that can modify the content of the embed.

import os
import discord
from discord.ext import commands
from discord import app_commands


from lib import minecraftclass as mc
from lib.minecraftdb import db as db

class ServerButtons(discord.ui.View):
    def __init__(self, interaction):
        super().__init__()
        self.interaction = interaction
        
    async def send(self, interaction):
        self.message = await interaction.response.send_message(view=self)
        
    def create_embed(self, embed):
        self.embed = embed
        return self.embed
    
    @discord.ui.button(label="🔄 Lancer", style=discord.ButtonStyle.green)
    async def start(self, button: discord.ui.Button, interaction: discord.Interaction):
        await self.interaction.channel.send("Lancement du serveur")

    
class Minecraft(commands.Cog):

    def __init__(self, bot):
        self.bot = bot
        self.minecraftBootFiles = os.listdir('scripts/minecraft_boot')
        self.minecraftBootFiles = [file.replace(".sh", "") for file in self.minecraftBootFiles]
        
        added = [name[0] for name in db.get_all_server_names()]
        bot.logger.info(str(added))
        for server in self.minecraftBootFiles:
            if server not in db.get_all_server_names() and server not in added:
                db.add_server(server, "Serveur basé sur "+server, 0)
                added.append(server)
        del added
    
    @app_commands.command(name="json", description="See configuration file")
    async def json(self, ctx : discord.Integration, file: str = None, key : str = None):
        if key != None:
            await ctx.response.send_message(globals()[file.value].data[key], ephemeral=True)
        else :
            await ctx.response.send_message(globals()[file.value].data, ephemeral=True)
    

    @app_commands.command(name="minecraft",description="Choose a minecraft servers to manage") 
    async def minecraftserver(self, interaction : discord.Integration):
        servers = db.get_all_servers()
        for server in servers:
            if server[3] == 1:
                serverRunning = server
            else :
                serverRunning = None
        
        if serverRunning == None:
            embed = discord.Embed(title="Serveur Minecraft", description="No server launched", color=0x3EFF00)
            for server in db.get_all_servers():
                embed.add_field(name=server[1], value=server[2], inline=True)
            view = ServerButtons(interaction)
            await interaction.response.send_message(embed=view.create_embed(embed), view=view) 
            
async def setup(bot):
    await bot.add_cog(Minecraft(bot))
twilit grotto
#

give me a minute ill try to read it all, kinda on a small screened laptop so it looks funky haha

quartz viper
#

thank you

twilit grotto
quartz viper
#

I want modify the embed

#

the self.interaction.channel.send in start is just for "debug"

slate swan
#

I Got a question

#

Imagine i have the command !on.

#

I Wanna make a code so only people that are on a SPECIFIC voice channel can run this command

#

how to do it?

slate swan
#

Get their voice state channel and do a comparison

slate swan
#

weyo

#

i need help

#

How to make a code that counts how many hours the user is on a specific voice channel

thin raft
#

and substract them

quartz viper
#
message = await interaction.response.send_message(embed=embed, view=view)

and when I

await message.edit(content="")

I've got this error : AttributeError: 'NoneType' object has no attribute 'edit'
Why my embed is a NoneType ?

vocal snow
quartz viper
#

oh

vocal snow
#

!d discord.Interaction.original_response

unkempt canyonBOT
#

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

Fetches the original interaction response message associated with the interaction.

If the interaction response was a newly created message (i.e. through [`InteractionResponse.send_message()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.send_message "discord.InteractionResponse.send_message") or [`InteractionResponse.defer()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.defer "discord.InteractionResponse.defer"), where `thinking` is `True`) then this returns the message that was sent using that response. Otherwise, this returns the message that triggered the interaction (i.e. through a component).

Repeated calls to this will return a cached value.
vocal snow
#

get it from this

quartz viper
#

ty

slate swan
#
Traceback (most recent call last):
  File "/home/runner/Atomic/venv/lib/python3.10/site-packages/discord/ui/view.py", line 427, in _scheduled_task
    await item.callback(interaction)
  File "main.py", line 228, in ticketcallback
    await interaction.response.send_message("Επιλέξτε παρακάτω", view=view, ephemeral = True)
  File "/home/runner/Atomic/venv/lib/python3.10/site-packages/discord/interactions.py", line 778, in send_message
    await adapter.create_interaction_response(
  File "/home/runner/Atomic/venv/lib/python3.10/site-packages/discord/webhook/async_.py", line 221, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.0.components.0.options.3: The specified option value is already used
#

Whats this?

#

The specified option value is already used

#

what

#

line 221 is

#
created_channels = []
velvet sierra
#

guys, i'm trying to use the

@blablabla.error
async def blablabla_error(ctx, error):
    if isinstance(error, commands.errors.MissingPermissions):
        await ctx.send('> one message')

but when i use the commnd i have this error instead the bot send a message, someone know why?
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'CommandInvokeError' object has no attribute 'missing_perms'

i'm using this in the command

@commands.has_permissions(attach_files=True)```
north kiln
#

Use commands.MissingPermissions

dry kelp
#

How can i check if the deleted webhook from a specific channel is actually the webhook stored in our database??

velvet sierra
north kiln
#

Send your whole code?

#

How would a message be sent when there is unhandled error

velvet sierra
#

maybe

if isinstance(error, commands.CommandInvokeError):
    if isinstance(error.original, MissingPermissions):
north kiln
north kiln
velvet sierra
#

it can with commands.CommandInvokeError but not with the commands.errors.MissingPermissions or commands.MissingPermissions

slate swan
#

Well as first change I'd type-hint to discord.Interaction and not discord.Integration

tall temple
#

can someone help me pls

quartz viper
slate swan
slate swan
# tall temple

first make an embed I think and then get to send it in the ctx.send() so ye

tall temple
#

@slate swan same prob

slate swan
tall temple
#

my bad 🤣

tall temple
slate swan
tall temple
slate swan
tall temple
slate swan
tall temple
#

embed colors can't be strings ....

slate swan
#

wait a second

#

what color are you tryna to use

tall temple
slate swan
tall temple
#

bruh ?

#

what's the importance ?

#

it's a random color ....

slate swan
#

cause you can do like
color = discord.Color.color_name() I think so

tall temple
slate swan
#

interesting

tall temple
slate swan
tall temple
#

a

slate swan
#

Honestly I would do
embed = discord.Embed(color=discord.Color.from_rgb(rgb))

tall temple
#

a

slate swan
#

what does it mean?

tired pollen
#

!d discord.Colour.from_str

unkempt canyonBOT
#

classmethod from_str(value)```
Constructs a [`Colour`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Colour "discord.Colour") from a string.

The following formats are accepted...
tall temple
slate swan
#

bien jouer petit freur

tall temple
slate swan
velvet sierra
#

guys someone know if after i use a await guild.leave() that will call the on_guild_remove event?

slate swan
#

run the .leave method and register the event you want to check

#

and see if it executes

smoky sinew
slate swan
#
if emoji == ('✅'):
await payload.member.add_roles(discord.Object(sample_role_1))
await payload.member.remove_roles(discord.Object(sample_role_2))

so to add and remove roles with reaction I use this, but how do I remove a role when a role is deselected instead, or is that not possible

unkempt canyonBOT
#

discord.on_reaction_remove(reaction, user)```
Called when a message has a reaction removed from it. Similar to on\_message\_edit, if the message is not found in the internal message cache, then this event will not be called.

Note

To get the message being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Reaction.message "discord.Reaction.message").

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

Note

Consider using [`on_raw_reaction_remove()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_remove "discord.on_raw_reaction_remove") if you need this and do not want to enable the members intent.
slate swan
# smoky sinew !d discord.on_reaction_remove
@commands.Cog.listener()
async def on_raw_reaction_add(self, payload) -> None:
    
    if verify_message_id == payload.message_id:
        emoji = payload.emoji.name
        if emoji == (verify_emoji):
            await payload.member.add_roles(discord.Object(verify_role))

this is how I add it,

with on_raw_reaction_remove, there is no member attribute, how would I apply it to the on_raw_reaction_remove?

merry cliff
#

Probably

smoky sinew
#

yes

slate swan
#

anyone know how i can get the invite code a member used to join using dpy?

smoky sinew
dry sedge
#

how do I restart a websocket connection in a voice call

meager chasm
#

This channel for discord bots

sleek cedar
clear lark
#

How do you get a bot to join a voice channel? In this specific case I want the bot to join the same VC as a certain user, play an mp3, then leave

naive briar
unkempt canyonBOT
#

await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>, self_deaf=False, self_mute=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Connects to voice and creates a [`VoiceClient`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceClient "discord.VoiceClient") to establish your connection to the voice server.

This requires [`voice_states`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.voice_states "discord.Intents.voice_states").
clear lark
#

What specifically do I need to import from PyNaCl? Everytime I try to import it PyCharm just says no module found even though the package is installed

slate swan
#

also this is a discord bots channel

#

so basically im trying to run a discord bot 24/7 so I purchased a vps but when I installed python and tried to run the bot it js said mdules installed

clear lark
#

Its working now so ShrugShrug

#

Thank you for the help though!

slate swan
#

Microsoft Windows [Version 10.0.20348.1129]
(c) Microsoft Corporation. All rights reserved.

C:\Users\Administrator\Desktop\test bot>py main.py
Exception when importing modules
Installing necessary modules....
'pip3' is not recognized as an internal or external command,
operable program or batch file.
'pip3' is not recognized as an internal or external command,
operable program or batch file.
'pip3' is not recognized as an internal or external command,
operable program or batch file.
Modules installed!

C:\Users\Administrator\Desktop\test bot>

#

yes I am

#

i bought the windows version on vibegames because thats what my friend told me to do

#

dang it

slate swan
smoky sinew
#

also why are you using a game host for a VPS

smoky sinew
slate swan
#

im very new to this

slate swan
slate swan
#

i need to host my bot b4 i go on vaca

slate swan
formal basin
#
@client.tree.command(name="random-number-button", description="sends a random number choose a number e.g 1 10 in a button")
async def randomnumberbutton(interaction: discord.Interaction, number1: int, number2: int):
     button = Button(label=f"Random number from {number1} to {number2}", style=discord.ButtonStyle.primary)
     channel = client.get_channel(1112053260879147130)
     
     
  
  
     async def button_callback(interaction):
       try:
          await interaction.response.send_message(random.randint(number1, number2))
          await channel.send(f"random number button clicked by {interaction.user}")
       except:
          channel2 = client.get_channel(1112053260879147130)
          await interaction.response.send_message("error: number1 needs to be bigger than number2")
          await channel2.send(f"random-number-button clicked by {interaction.user} but an error occured")

           
    
    

     button.callback = button_callback
  
     view = View()
     view.add_item(button)
     await interaction.response.send_message(f"Click the button to get a random number from {number1} to {number2}", view=view)
     await channel.send(f"random-number-button command used by {interaction.user}")
``` how can i make it so when a user clicks it a certain amount of times disable the button
north kiln
#

add a counter and check if counter > some number

formal basin
#

ok

smoky sinew
#
class CounterView(View):
    MAX_VALUE = 5
    
    def __init__(self, *, timeout: int) -> None:
        super().__init__(timeout=timeout)
        self.counter = 0

    @discord.ui.button(label="0", custom_id="button")
    async def button(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
        self.counter += 1
        button.label = self.counter
        await interaction.edit_original_response(view=self)
        
        if self.counter >= MAX_VALUE:
            for item in self.children:
                item.disabled = True
smoky sinew
formal basin
naive briar
#

Why

north kiln
naive briar
#

What

smoky sinew
formal basin
formal basin
slate swan
#

Why not learning classes instead, it's a fundamental knowledge you should have - especially for discord.py

#

Not rocket science either, takes a few minutes to at least understand the basics and then with the time you'll learn more

smoky sinew
#

i literally already gave you the working code with classes yert

formal basin
clear lark
#

I'm trying to get a discord bot to automatically leave after a certain duration, but this is an event not command since the bot automatically joins the channel when a specified user joins a voice channel, how do I set that up?

Currently have :

@client.event
async def on_voice_state_update(member, before, after):
    if not before.channel and after.channel and member.id == config.ashy_id:
        await discord.VoiceChannel.connect(after.channel, timeout=30, reconnect=True, self_deaf=False, self_mute=False) # Bot Joins Channel that the specified user joins
        time.sleep(2) # the duration doesn't matter here
# Need to Disconnect Here

The joining works fine, but I can't get the leaving to

slate swan
#

That... isn't how OOP works

#

The entire

await discord.VoiceChannel.connect(after.channel, timeout=30, reconnect=True, self_deaf=False, self_mute=False)

line is wrong

#

It may work apparently, but it's wrong

clear lark
#

Please explain?

slate swan
#

In the documentation when you see something like discord.VoiceChannel.method() it means you're calling method on a discord.VoiceChannel object

vocal snow
#

they are passing the instance to it as well

#

(after.channel)

slate swan
#

Now with your event, you have the member, before and after parameters

clear lark
#

I'm still super new to python, so sorry if I say something super dumb

slate swan
#

You've already used before.channel and after.channel

#

Which areeeee

#

!d discord.VoiceState.channel

unkempt canyonBOT
#

The voice channel that the user is currently connected to. None if the user is not currently in a voice channel.

slate swan
#

discord.VoiceChannel objects

#

So you can just use

await after.channel.connect()
clear lark
#

Got it, I've changed the line heart_02 Thank you for the explanation

slate swan
#

Disconnect is a bit different

#

You'll need to use the voice_clients attribute in your bot

#

In your case bot seems to be client

clear lark
slate swan
#

It will give you a list of voice connections

#

There you can iterate over them and check the channel and/or guild IDs to see if they match the channel and/or guild IDs you want your bot to leave

#

Normally you just need to check the channel ID

#

Or I think you can just use await member.guild.voice_client.disconnect()

#

Not sure if that will work correctly, never really used voice channels in the past

clear lark
#

client.voice_clients and member.guild.voice_client both give the same output, and await member.guild.voice_client.disconnect() does in-fact make it leave the voice channel; tysm! This is helping me significantly

#

Now I just need to get it to play an mp3 before it leaves

slate swan
#

No problem and for that I have no idea LULW

clear lark
#

RIP, I'm so screwed

smoky sinew
#

it's pretty simple

#

you need to create an ffmpegpcmaudio

#

you need to install ffmpeg though

clear lark
vocal snow
#

it's not a python package

clear lark
#

Got it

vale wing
vale wing
#

I swear they were there during first md extension update

slate swan
#

i know

#

😭

vale wing
#

Does it display correctly on desktop

smoky sinew
slate swan
#

no

vale wing
#

😭

slate swan
#

it works on canary prolly

clear lark
#

Well I believe I got ffmpeg installed onto my system properly ffmpeg in cmd prompt results in (also yes I know cringe Windows, I'm currently working on switching over to Linux soon)

ffmpeg version 2023-05-31-git-baa9fccf8d-full_build-www.gyan.dev Copyright (c) 2000-2023 the FFmpeg developers
  built with gcc 12.2.0 (Rev10, Built by MSYS2 project)
  configuration: --enable-gpl --enable-version3 --enable-static --disable-w32threads --disable-autodetect --enable-fontconfig --enable-iconv --enable-gnutls --enable-libxml2 --enable-gmp --enable-bzlib --enable-lzma --enable-libsnappy --enable-zlib --enable-librist --enable-libsrt --enable-libssh --enable-libzmq --enable-avisynth --enable-libbluray --enable-libcaca --enable-sdl2 --enable-libaribb24 --enable-libaribcaption --enable-libdav1d --enable-libdavs2 --enable-libuavs3d --enable-libzvbi --enable-librav1e --enable-libsvtav1 --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxavs2 --enable-libxvid --enable-libaom --enable-libjxl --enable-libopenjpeg --enable-libvpx --enable-mediafoundation --enable-libass --enable-frei0r --enable-libfreetype --enable-libfribidi --enable-liblensfun --enable-libvidstab --enable-libvmaf --enable-libzimg --enable-amf --enable-cuda-llvm --enable-cuvid --enable-ffnvcodec --enable-nvdec --enable-nvenc --enable-d3d11va --enable-dxva2 --enable-libvpl --enable-libshaderc --enable-vulkan --enable-libplacebo --enable-opencl --enable-libcdio --enable-libgme --enable-libmodplug --enable-libopenmpt --enable-libopencore-amrwb --enable-libmp3lame --enable-libshine --enable-libtheora --enable-libtwolame --enable-libvo-amrwbenc --enable-libcodec2 --enable-libilbc --enable-libgsm --enable-libopencore-amrnb --enable-libopus --enable-libspeex --enable-libvorbis --enable-ladspa --enable-libbs2b --enable-libflite --enable-libmysofa --enable-librubberband --enable-libsoxr --enable-chromaprint
  libavutil      58. 12.100 / 58. 12.100
  libavcodec     60. 16.100 / 60. 16.100
  libavformat    60.  5.100 / 60.  5.100
  libavdevice    60.  2.100 / 60.  2.100
  libavfilter     9.  8.101 /  9.  8.101
  libswscale      7.  3.100 /  7.  3.100
  libswresample   4. 11.100 /  4. 11.100
  libpostproc    57.  2.100 / 57.  2.100
Hyper fast Audio and Video encoder
usage: ffmpeg [options] [[infile options] -i infile]... {[outfile options] outfile}...

Though pycharm still says its missing, what do I need to do so PyCharm can use it?

smoky sinew
#

what do you mean pycharm says it's missing, pycharm won't know if it's missing or not

#

if you're importing it you're doing it wrong

clear lark
#

I've never used ffmpeg, I just installed it, its not being imported and even when I do so it doesn't work. The error is discord.errors.ClientException: ffmpeg was not found. or more specifically

File "C:\Users\ashy\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\state.py", line 158, in logging_coroutine
    await coroutine
  File "C:\Users\ashy\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\voice_client.py", line 337, in on_voice_server_update
    await self.ws.close(4000)
          ^^^^^^^^^^^^^
AttributeError: '_MissingSentinel' object has no attribute 'close'
2023-06-06 03:29:34 ERROR    discord.client Ignoring exception in on_voice_state_update
Traceback (most recent call last):
  File "C:\Users\ashy\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\ashy\Desktop\PythonProgramming\exodusAutomatonDiPy\bot.py", line 131, in on_voice_state_update
    audio_source = discord.FFmpegPCMAudio('spooder.mp3')
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\ashy\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\player.py", line 289, in __init__
    super().__init__(source, executable=executable, args=args, **subprocess_kwargs)
  File "C:\Users\ashy\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\player.py", line 166, in __init__
    self._process = self._spawn_process(args, **kwargs)
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\ashy\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\player.py", line 183, in _spawn_process
    raise ClientException(executable + ' was not found.') from None
discord.errors.ClientException: ffmpeg was not found.
smoky sinew
#

then it's not on your path

#

go to edit environment variables on windows

clear lark
#

I added it there, or atleast thought I did

smoky sinew
#

and add the path to the executable in the path variable

clear lark
slate swan
clear lark
#

Should it just be C:\ffmpeg ?

smoky sinew
#

a

slate swan
#

ok

smoky sinew
#

did you download the exe

clear lark
#

Yes

smoky sinew
#

huh how do i have ffmpeg but i didn't install it

clear lark
#

I downloaded ffmpeg-2023-05-31-git-baa9fccf8d-full_build.7z and ran the exe inside

#

as well as have the folder for ffmpeg in C:\

smoky sinew
#

ah i have it from scoop

clear lark
#

It also responds in cmd prompt

smoky sinew
#

where is the ffmpeg.exe

clear lark
#

C:\ffmpeg\bin\ffmpeg.exe

clear lark
slate swan
#

ok

smoky sinew
#

wait

#

just add ffmpeg path to your pycharm run config

clear lark
#

This is going to make me sound even more stupid, how do I get to that? I've never had to alter that until now

#

nevermind

#

also PYTHONUNBUFFERED=1 is already there, do I just add a , between or just remove it?

smoky sinew
#

it's either : or ; in between

#

ok it's ;

clear lark
#

Alright, it now knows where ffmpeg is and can use it cool, but shit my code doesn't work

#

Whats the proper way to get the bot to play a specified mp3?

smoky sinew
#

create a new FFmpegPCMAudio

#

then i think you can just pass it to voice_client.play

#

@clear lark you need to create a new ffmpegpcmaudio

#

like i said

#

also discord.Client.voice_client does not exist

clear lark
#

I would make a new ffmpegpcaudio by?

smoky sinew
#

wdym

#

do you know how to make an object

clear lark
#

Yes

smoky sinew
#

you do object_name = Class(arguments...)

clear lark
#

Correction: I'm being dumb, and am failing at python

glad cradle
#

cool

clear lark
# smoky sinew you do `object_name = Class(arguments...)`

I'm now getting

Traceback (most recent call last):
  File "C:\Users\ashy\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\ashy\Desktop\PythonProgramming\exodusAutomatonDiPy\bot.py", line 132, in on_voice_state_update
    voice_client.play(player)
    ^^^^^^^^^^^^^^^^^
AttributeError: module 'discord.voice_client' has no attribute 'play'
2023-06-06 04:06:42 INFO     discord.player ffmpeg process 17456 has not terminated. Waiting to terminate...
2023-06-06 04:06:42 INFO     discord.player ffmpeg process 17456 should have terminated with a return code of 1.

and here is what the event looks like

@client.event
async def on_voice_state_update(member, before, after):
    if not before.channel and after.channel and member.id == config.ashy_id:
        await after.channel.connect()

        # problem child
        sound_file = 'spooder.mp3'
        player = discord.FFmpegPCMAudio(sound_file)
        voice_client.play(player)
        # problem child

        time.sleep(2)
        await member.guild.voice_client.disconnect()
vocal snow
#

voice_client.play(player)

#

voice_client is supposed to be an instance of discord.VoiceClient

#

not the discord.voice_client module

vocal snow
#

VoiceChannel.connect returns a VoiceClient object, you can get it from that

smoky sinew
#

again discord.Client.voice_client does not exist

#

!d discord.Guild.voice_client

unkempt canyonBOT
#

property voice_client```
Returns the [`VoiceProtocol`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceProtocol "discord.VoiceProtocol") associated with this guild, if any.
glad cradle
slate swan
#

voice_clients is not voice_client

#

So yes, it doesn't exist

glad cradle
#

bro

#

I'm not serious💀

slate swan
#

apparently it was such a funny joke everyone skipped over it

amber scroll
smoky sinew
#

don't be rude to snipy 😔

slate swan
#

The command help is already an existing command or alias.

smoky sinew
#

you have to pass help_command=None to the bot

slate swan
#

Either remove the existing help command or subclass it

unkempt canyonBOT
#
Custom help commands in discord.py

To learn more about how to create custom help commands in discord.py by subclassing the help command, please see this tutorial by Stella#2000

amber scroll
#

alr

smoky sinew
glad cradle
slate swan
#

That feels like just a way to get over something lmfao

#

"It's just a joke, I wasn't really meaning it"

vocal snow
slate swan
#

peepoMmmYea we know it

clear lark
#

VoiceClient.play(source=player) results in TypeError: VoiceClient.play() missing 1 required positional argument: 'self'

slate swan
#

its not static method

#

you need to gather instance of VoiceClient

#

most likely from guild.voice_client

vocal snow
slate swan
#

or from connect

smoky sinew
clear lark
#

most likely yeah

#

I've been awake way too long and am barely functioning, but I need to finish this

I've only touched python for a couple of days now, if it wasn't obvious, and I'm still lost on how to get the instance of VoiceClient from connect() as I just keep getting AttributeError: 'VoiceChannel' object has no attribute 'is_connected'

upbeat otter
#

!d discord.Guild.voice_client does

unkempt canyonBOT
#

property voice_client```
Returns the [`VoiceProtocol`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceProtocol "discord.VoiceProtocol") associated with this guild, if any.
upbeat otter
#

no wait that doesn't too

#

pff

clear lark
vocal snow
#

well it returns VoiceProtocol, but for most cases that is VoiceClient

clear lark
#

So I do I get it to the self={instance here} ?

vocal snow
#

yeah im not sure when it doesn't return VoiceClient

upbeat otter
#

This is an abstract class. The library provides a concrete implementation under VoiceClient.

clear lark
#

Okay, for simplicity, what does
THIS

        sound_file = 'spooder.mp3'
        player = discord.FFmpegPCMAudio(sound_file)
        VoiceClient.play(source=player, self=VoiceProtocol)

need to be to function, so I can see what it needs to be so I can see what I'm doing wrong

slate swan
#

its not static method

clear lark
vocal snow
slate swan
#

and passing self as class makes no sense at all

upbeat otter
slate swan
clear lark
slate swan
#

or at least what instance is

upbeat otter
upbeat otter
upbeat otter
vocal snow
#

they will copy this word for word

upbeat otter
#

now i feel sorry

#

btw hi zeffo, it's been a long time

clear lark
# slate swan or at least what instance is

not completely honestly, again I am super new to Python & programming as a whole. I'm only making a discord bot because It gives me tangiable results and I can make it do things I want it to do for things I do often

upbeat otter
#

oh wait when did they give reaction perms here 💀

vocal snow
#

recently

#

and then discord added this super reaction nonsense so they might take it away again

glad cradle
#

for more than a month acffftually

vocal snow
#

its been a month already 😭

#

i am growing old

glad cradle
#

you're an old cat

upbeat otter
vocal snow
smoky sinew
clear lark
smoky sinew
#

yes because you only use Class.method() for when it's a staticmethod or classmethod

#

in other cases you need an object

unkempt canyonBOT
#
Classes

Classes are used to create objects that have specific behavior.

Every object in python has a class, including lists, dictionaries and even numbers. Using a class to group code and data like this is the foundation of Object Oriented Programming. Classes allow you to expose a simple, consistent interface while hiding the more complicated details. This simplifies the rest of your program and makes it easier to separately maintain and debug each component.

Here is an example class:

class Foo:
    def __init__(self, somedata):
        self.my_attrib = somedata

    def show(self):
        print(self.my_attrib)

To use a class, you need to instantiate it. The following creates a new object named bar, with Foo as its class.

bar = Foo('data')
bar.show()

We can access any of Foo's methods via bar.my_method(), and access any of bars data via bar.my_attribute.

upbeat otter
#

they're literally new to python, dont expect beginners to understand those complicated terms too 💀

clear lark
#

I've literally only started python about 4 or 5 days ago at this point, and before then I knew a bit of javascript

glad cradle
#
AClass().foo()
# is not equal to
AClass.foo()
slate swan
#

learn basic python and basic OOP then before starting a discord bot its not good project for someone who just started

glad cradle
#

you can't even understand d.py's docs without understanding python's OOP

clear lark
#

Any recommendations on where to learn basic python? (sure thats the 7000th time you've heard that question) Also Snipy you very very correct

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.

clear lark
#

I'll go through that tmrw, but I'm going to go to bed since its late here, night yall, and thank you so, so, so, SO, much for dealing with my stupidity and helping me.

And here is what I finally ended on, which does work as intended

@client.event
async def on_voice_state_update(member, before, after):
    if not before.channel and after.channel and member.id == config.muw_id:
        sound_file = 'spooder.mp3'
        voice_client = await after.channel.connect()
        voice_client.play(discord.FFmpegPCMAudio(sound_file))
        await asyncio.sleep(2.5) # was time.sleep(2.5)
        await member.guild.voice_client.disconnect()

There is mostly likely something wrong with it (besides error handling), but I do not care enough to fix it until I learn more

slate swan
gilded oxide
#

What other fun community commands should I add

slate swan
gilded oxide
smoky sinew
slate swan
smoky sinew
#

a word speed game

gilded oxide
#

like TEA are the letters and teacher has those letters

thin raft
tawdry tundra
#

I need help

#

@smoky sinew

smoky sinew
tawdry tundra
#

?

vocal snow
#

unfortunately we are not mind readers

tawdry tundra
#

What do you mean?

smoky sinew
vocal snow
#

you have to tell us what you need help with

tawdry tundra
#

Ok

smoky sinew
#

lmaoo

tawdry tundra
#

Wait

#

``import discord
from discord.ext import commands
import os

client = discord.Client(commands_prefix="s")

@client.event
async def on_ready():
print("online")

@client.event
async def begin(ctx):
await ctx.send("lets start")

my_secret = os.environ['Token']
client. run(my_secret)``

#

This is my code

#

But why it not send any message by commands
sbegin

#

?

#

@smoky sinew

vocal snow
#

Because you haven't made any commands

tawdry tundra
#

When I make it command it go to error

#

I Will send it here

smoky sinew
#

clients cannot have commands only bots

tawdry tundra
#

Oh

#

I will try

tawdry tundra
#

But in line 5

smoky sinew
#

maybe because you put commands_prefix

vocal snow
#

Consider reading the error

dry sedge
#

My thing crashes sometimes in a voice call will restarting the ws connection work

tawdry tundra
vocal snow
#

Your script crashes?

dry sedge
#

most times

smoky sinew
vocal snow
dry sedge
dry sedge
tawdry tundra
#

``Traceback (most recent call last):

File "main.py", line 5, in <module>
bot = discord.Bot(commands_prefix="s")
AttributeError: module 'discord' has no attribute 'Bot',``

smoky sinew
unkempt canyonBOT
#

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

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

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

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

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

New in version 2.0.
dry sedge
#

Use client

#

Because that means your on like 1.7.3 because that happened to me

tawdry tundra
#

I didn't under stand

dry sedge
smoky sinew
dry sedge
tawdry tundra
# unkempt canyon

Can any one please copy this code and send it to me because I'm in phone

dry sedge
tawdry tundra
#

.

glad cradle
tawdry tundra
glad cradle
#

do you know python basics?

tawdry tundra
#

Yes

#

Look at my problem

vocal snow
#

what is the problem

#

did you do what mudkip said

tawdry tundra
#

I have error with
@client.command()

#

You tell me to make it bot not client

#

And i made it but there is another problem happend

vocal snow
#

what error

vocal snow
#

because discord.Bot doesn't exist like the error says

vocal snow
tawdry tundra
#

I need to know how i make prefix to my bot

vocal snow
#

you set the prefix in the commands.Bot constructor

vocal snow
tawdry tundra
#

Were is the error bere
bot = discord.Bot()

#

AttributeError: module 'discord' has no attribute 'Bot'

#

@vocal snow

smoky sinew
tawdry tundra
#

What should I replace it with

vocal snow
#

how many times do you need us to repeat

vocal snow
#

discord.ext.commands.Bot

tawdry tundra
#

I will try

tawdry tundra
#

Finally its worked

slate swan
tawdry tundra
#

@vocal snow
I have another question

#

But it is very simple

#

How can I make the bot send the message in spasific channel

proven crest
vocal snow
vocal snow
vocal snow
tawdry tundra
#

I will try

vocal snow
#

if you're trying to construct a webhook from it's url just call Webhook.from_url

#

run your code and see if it works

proven crest
vocal snow
#

pretty sure the webhook system was overhauled in 2.0

proven crest
#

I do not speak English fluently

vocal snow
#

btw, you should remake your webhook

#

and dont share its url

#

with anyone

slate swan
#

2 member objects, one for partner one for author

atomic forge
#

Looking for a person who will develop a script in python I PAY

unkempt canyonBOT
#

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

atomic forge
#

i pay

slate swan
# atomic forge i pay

Reading may help, let me put it in bold just for you

Do not offer or ask for paid work of any kind

#

You've been told so many times as well that it's not allowed

amber scroll
slate swan
amber scroll
agile lark
#

Where did Member.permissions go? Do I need to walk through Member.roles instead?

slate swan
#

!d discord.Member.guild_permissions

unkempt canyonBOT
#

property guild_permissions```
Returns the member’s guild permissions.

This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use [`abc.GuildChannel.permissions_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel.permissions_for "discord.abc.GuildChannel.permissions_for").

This does take into consideration guild ownership, the administrator implication, and whether the member is timed out.

Changed in version 2.0: Member timeouts are taken into consideration.
agile lark
#

Oh my god - I'm blind. Thanks.

slate swan
amber scroll
#

my bot turned on for the first time but it didnt load the rest of the commands

naive briar
#

What library are you using

#

If it's discord.py, you should await the bot.load_extention methods

twilit grotto
slate swan
#

Also cogs are not meant to be one per command but rather one per category which contains multiple commands

#

Two member objects yeah

#

One that corresponds to the author and another one to the partner

north kiln
#

did you copy this code

slate swan
formal basin
#

how can i disable a button?

slate swan
#

!d discord.ui.Button.disabled

unkempt canyonBOT
twilit grotto
#

^

slate swan
#

Set this to True/False then edit your message with the new view

formal basin
#

it doesnt show me code

#

it just says propery disabled

slate swan
#

Because there's no code to copy paste

#

You set disabled of your button to True/False as already mentioned

formal basin
#

so is it py disabled = True

slate swan
#

On your button, yes

#

Just doing disabled = True will create a new variable which is not what you want, you want to edit that attribute from a button

#

Here once again, learning OOP basics would be helpful

twilit grotto
#

oml lol

glad cradle
#
disabled = True
button.disabled = disabled

😳

atomic forge
#

@slate swanis scameur

swift acorn
#

Hey so I tried hosting my bot on a server, and since it's been added to a big server it is having a lot of issues starting

Even if it gets going it's taking around 1 GB of memory which doesn't make sense it shouldn't, and it didn't when we hosted it while it wasn't in the big server

Is there something we need to do to make it work properly while being in a big server?

echo wasp
#

Hi I have a question I am using slash commands but the int in the option of the slash command won't take a decimal how do I make it take the decimal?

twilit grotto
echo wasp
twilit grotto
#

yes

slate swan
#
const { Client, GatewayIntentBits  } = require('discord.js');
const axios = require('axios');

const client = new Client({
    intents: [
        GatewayIntentBits.Guilds,
        GatewayIntentBits.GuildMessages,
        GatewayIntentBits.MessageContent,
        GatewayIntentBits.GuildMembers,
    ],
});
const prefix = '!';

client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}`);
});

client.on('messageCreate', async (message) => {
  if (message.content.startsWith(prefix) && !message.author.bot) {
    const args = message.content.slice(prefix.length).trim().split(/ +/);
    const command = args.shift().toLowerCase();

    if (command === 'team') {
      try {
        const response = await axios.get('https://ctftime.org/api/v1/teams/227975/');
        const teamData = response.data;

        const embed = {
          title: teamData.name,
          description: `Country: ${teamData.country}\nPrimary Alias: ${teamData.primary_alias}`,
          thumbnail: { url: teamData.logo },
          fields: [],
        };

        for (const year in teamData.rating) {
          const place = teamData.rating[year].country_place;
          if (place) {
            embed.fields.push({ name: year, value: `Country Place: ${place}`, inline: true });
          }
        }

        message.channel.send({ embeds: [embed] });
      } catch (error) {
        console.error('Failed to fetch team data:', error);
        message.channel.send('Failed to fetch team data. Please try again later.');
      }
    }
  }
});

client.login(process.env.token);
#

i am trying to get informations from json format api

formal basin
#

thats java

slate swan
#

using axios but it shows this

twilit grotto
#

thats javascript not python

slate swan
#

oh

formal basin
slate swan
#

sorry where is the js room

twilit grotto
slate swan
#

i was thinking that discord bots for all languages

formal basin
formal basin
slate swan
#

i know but i was thinking is a discord bots room in general not for only python sorry

surreal timber
#

hi

#

can someone help me with this error?

#

for running my bot

echo wasp
surreal timber
#

what exactly i have to do?

echo wasp
#
intents.members = True
intents.message_content = True
client = discord.Client(intents=intents)```
#

that should work

#

but discord.Client is different from my bot = commands.Bot

#

so give that a try and see what happens

surreal timber
#

wich line should i copy it?

#

befor token?

glad cradle
surreal timber
#

and now says name 'intents' is not defined

slate swan
#

Because you need to initialize it duh

#
intents = discord.Intents.default()
#

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

swift acorn
slate swan
#

Start by not enabling all intents

swift acorn
#

Alright

#

But just curious as to why it happens only here, I have another bot with a lot more stuff happening that's only taking 60MB of storage

#
  • it has all intents enabled too
swift acorn
#

I'll just post it here since the post keeps closing

I made a Discord bot that tracks the activity of specific individuals that are specified on a database.

This ran fine while testing I tried to spam it too, didn't have any problems but once I got it into the big server it was going to be used in, it was not starting up properly, kept crashing and was using extreme amounts of CPU power and Memory.

After implementing the Event Queue it seemed to be a little better, still a lot of CPU usage on startup but it was fine afterwards. For some reason it still takes up 950MB of memory on the server and I am not sure why.

Any help would be much appreciated, thanks

Code: https://paste.pythondiscord.com/hatemaresu

glad cradle
#

as someone has already said you're caching everything because you're using discord.Intents.all() i suggest to enable only the intents that you need so the library won't cache things that you don't use

swift acorn
#

alright will try that

#

My other bot is also doing all but only using 60MB of Memory, that's what I find weird

#

Alright I suppose that is because it was not in as big of a server, thank you so much that worked

slate swan
#

Big servers lead to more events, if you have all intents you're using much more resources than what you really need

smoky sinew
#

that's javascript

smoky sinew
amber scroll
#

question do i replace bot.load_extension('command.afk') with await load_extensions("afk)

turbid condor
smoky sinew
swift acorn
#
intents = discord.Intents(messages=True)
bot = commands.Bot(command_prefix='-', intents=intents)

I am using this to declare intents, and the intents are given on the developer portal too, but it still can't access message.content

#

I get this in the console on startup

smoky sinew
#

also don't use discord.Intents(...) that doesn't enable any of the other non-privileged intents

#

use discord.Intents.default() instead

swift acorn
#

That worked thank you

#

I thought message content was included in messages

tall linden
#

I need someone who can create custom bots. Im starting an agency that creates, manages discord servers and creates custom bots

slate swan
#

Then you can get developers on websites such as Fiverr, not here

tall linden
north kiln
#

wth

slate swan
#

Then you're in the wrong place

sonic vapor
#

how to make balance or economy feature with embed link? pls tell experts

smoky sinew
#

simply set up a database and fetch a value from it

sonic vapor
smoky sinew
#

?

sonic vapor
#

what are codes for that am new to learn python

sonic vapor
# smoky sinew ?

my import discord and from discord.ext are coming in yellow line also

north kiln
#

try, fail and ask

sonic vapor
smoky sinew
turbid condor
sonic vapor
glad cradle
sonic vapor
smoky sinew
#

noted

glad cradle
north kiln
#

🔥

sonic vapor
#

how to set up database

jade flare
#

i tried using bridge commands but i get this error: ImportError: cannot import name 'SlashCommandOptionType' from 'discord.enums'

slate swan
naive briar
#

Well, that

jade flare
naive briar
#

ImportError: cannot import name 'SlashCommandOptionType' from 'discord.enums'

naive briar
#

Whoops, didn't mean to edit the message

slate swan
# jade flare wym?

are you trying to import it yourself or it happens in the library source code

slate swan
naive briar
#

You sure? You can show the whole traceback

slate swan
#

what is that

jade flare
#

oh whoops

#

i copypasted more than i intened

#

the error comes from here

naive briar
#

Why did you delete the traceback

slate swan
naive briar
jade flare
jade flare
naive briar
#

What

slate swan
naive briar
#

!d discord.ext.commands.hybrid_command

unkempt canyonBOT
#

@discord.ext.commands.hybrid_command(name=..., *, with_app_command=True, **attrs)```
A decorator that transforms a function into a [`HybridCommand`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.HybridCommand "discord.ext.commands.HybridCommand").

A hybrid command is one that functions both as a regular [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") and one that is also a [`app_commands.Command`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Command "discord.app_commands.Command").

The callback being attached to the command must be representable as an application command callback. Converters are silently converted into a [`Transformer`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Transformer "discord.app_commands.Transformer") with a [`discord.AppCommandOptionType.string`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.AppCommandOptionType.string "discord.AppCommandOptionType.string") type.

Checks and error handlers are dispatched and called as-if they were commands similar to [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command"). This means that they take [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context") as a parameter rather than [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction").

All checks added using the [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") & co. decorators are added into the function. There is no way to supply your own checks through this decorator.

New in version 2.0.
naive briar
#

🫠

unkempt canyonBOT
#

discord/ext/commands/core.py lines 51 to 63

from ._types import _BaseCommand, CogT
from .cog import Cog
from .context import Context
from .converter import Greedy, run_converters
from .cooldowns import BucketType, Cooldown, CooldownMapping, DynamicCooldownMapping, MaxConcurrency
from .errors import *
from .parameters import Parameter, Signature
from discord.app_commands.commands import NUMPY_DOCSTRING_ARG_REGEX

if TYPE_CHECKING:
    from typing_extensions import Concatenate, ParamSpec, Self

    from ._types import BotT, Check, ContextT, Coro, CoroFunc, Error, Hook, UserCheck```
slate swan
#

i dont see this in discord.py source try updating to newest version

jade flare
naive briar
jade flare
#

now theres a big question mark above my head pithink

slate swan
#

?

jade flare
#

i am

slate swan
#

do pip show discord.py in terminal

jade flare
slate swan
#

can you do pip list and check if there are no modules named: py-cord nextcord disnake

jade flare
#

my discord bot worked just fine until i tried using bridge commands

naive briar
#

nextcord and disnake has their own namespace

naive briar
slate swan
#

at least you can do with nextcord

naive briar
naive briar
#

That explains it

slate swan
#

you have py-cord

jade flare
#

oh

#

is that bad? hahaha

#

and how do i uninstall it

naive briar
#

pip uninstall py-cord

slate swan
smoky sinew
# jade flare

it was pretty obvious from the start as discord.py does not use the name "slash command" anywhere in its code

jade flare
unkempt canyonBOT
#

discord/app_commands/commands.py line 144

VALID_SLASH_COMMAND_NAME = re.compile(r'^[-_\w' + THAI_COMBINING + DEVANAGARI_COMBINING + r']{1,32}$')```
slate swan
naive briar
slate swan
jade flare
#

but now my normal bot wont work anymore 😭

#

it worked just fine before

naive briar
#

Did you delete both py-cord and discord.py?

jade flare
#

no just py-cord

#

oh nvm

#

i fixed it now it seems to work

#

tysm 💗

median hull
#

Hi

#

was looking for help , wondering if something like this exists

#

Can you reroute a discord bot to display the message as a desktop notifcation?

#

I cant find anything online about it

golden portal
#

"the message" what message? DMs?

median hull
#

not message

#

i mean not dms

#

well i guess dms and server

#

I just want the message to display on my discord so i dont have to tab to discord to see it

#

when im on fullscreen

median hull
#

is that setting in server settings @smoky sinew

smoky sinew
median hull
#

is there anyway to copy text from the notification to your clipboard

#

from what ive seen online its impossible through discord

#

also is there a way to increase the notification size

#

the message gets cut off

atomic forge
#

Hello I am paying a person for a python script ME DM

smoky sinew
median hull
#

wdym

#

yeah basically

smoky sinew
#

that's against discord's TOS and against this server's rules

median hull
#

wdym its not discord related

smoky sinew
#

you want to listen to notifications and copy their texts?

median hull
#

its not something thats like crazy important just would be less tedious

#

from having to manually go into my dms/server

#

and yeah if its possible create a custom notifcation

#

cause the message gets cut off

#

@smoky sinew windows

smoky sinew
#

i don't think there is any way to do that then

#

unless you're using a custom version of discord

median hull
#

wait why

#

is it possible with any notification?

#

also if its not, is there an option where i can resize the notification window because it gets cutoff

north kiln
#

this is no longer related to discord bot

spiral axle
#

atleast two or three

median hull
#

which libraries do you have in mind

spiral axle
#

which platform are you on

median hull
#

windows

spiral axle
#

if you want we can take this to dms since this is the discord bots channel and this topic isnt deriving around the discord.py lib i just dont wanna get warned or banned

median hull
#

sure thanks

amber scroll
spiral axle
amber scroll
#

yea

spiral axle
#

parantheses was not closed

#

basically means you did not add another ')' to the very end of the line and finish the string literal

plucky sun
#

How to make modal ?

#

@slate swan

slate swan
thin raft
smoky sinew
amber scroll
spiral axle
#

nah it's perfectly fine bro

spiral axle
#

wait explain what the error is if you mind

slate swan
#

That doesn't look like the full traceback to me

spiral axle
#

yeah^

#

there should be a full error log you can copy and paste into a file here

#

it would look like this

#
Traceback (most recent call last):
  File "/tmp/teste.py", line 9, in <module>
    run_my_stuff()
NameError: name 'run_my_stuff' is not defined
``` or
#
>>> def greet(someone):
...   print('Hello, ' + someon)
... 
>>> greet('Chad')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in greet
NameError: name 'someon' is not defined```
#

but from what i see, its an error to do with .send()

#

so let me read over your code

#

looks like you're fetching the wrong id

#

nothing at all, it seems okay

#

it might be channel_id

#

alright give me a second to read over it

slate swan
#

The channel is probably not cached if I had to guess

spiral axle
#

bc theres no other way this error would appear

#

even intellisense recognizes .send()

#

what i would recommend is try with a different channel id and see your problem

#

it isnt a permissions error bc you didnt send the full traceback to do with that specific line

slate swan
#

Use fetch_channel if get is returning None

spiral axle
#

more effective solution, try his

#

it's practically like get_channel

#

except you await it and it fetches it directly off of the discord api instead of the cache

hushed galleon
#

most of the time all channels get cached if your guilds intent is enabled

#

what intents did you pass to your client?

#

oh wait your issue never had anything to do with get_channel returning None, this partial traceback proves it didnt

#

discord's API returned some error code when you tried sending a message, for example 403 Forbidden when your bot doesnt have the necessary permissions in that channel

spiral axle
#

so i was going off of what line it was

#

oh then yes, use administrator or the permission you require

hushed galleon
slate swan
spiral axle
#

yeah they're right

twilit grotto
#

you need to await it

spiral axle
#

what library are you using

#

you would need to GET the data

smoky sinew
#

for which API

spiral axle
#

if youre doing this in a discord bot use aiohttp, that way it wont stall your code

amber scroll
#

back at this error again

#

but the
@bot.command()
is new

spiral axle
amber scroll
spiral axle
amber scroll
#

😭 i see it

#

nah i dont

amber scroll
# spiral axle any other commands registered under "ban"

@bot.command()
@commands.has_permissions(ban_members=True)
async def ban(ctx, member: discord.Member, *, reason=None):
"""Ban a member from the server"""
await member.ban(reason=reason)
await ctx.send(f'{member} has been banned from the server.')

spiral axle
#

dms

amber scroll
#

alr

smoky sinew
#

why do you keep asking people to go to dms

naive briar
#

Sus

spiral axle
#

i just prefer dms so i can swear

tawdry tundra
#

how I can make my bot spam messages by command I tried for loop but when I use the command it show big error to me

spiral axle
#

and await ctx.send()

tawdry tundra
#

Its channel send

#

Wait i will give you the code

slate swan
spiral axle
#

okay

slate swan
tawdry tundra
#

``import discord
from discord.ext import commands
import os
import requests
import string
import random

bot = discord.ext.commands.Bot("a")

@bot.command()
async def start():
channel = bot.get_channel(1115921187164409918)
for i in range(15):
channel.send("Im working")

@bot.event
async def on_ready():
print("online")

my_secret = os.environ['Token']
bot. run(my_secret)``

spiral axle
spiral axle
slate swan
spiral axle
#

for channel.send

#

oh i read it

tawdry tundra
#

But what is start

slate swan
spiral axle
#

youre missing ctx in the function

slate swan
#

that too

tawdry tundra
#

It's not ctx

#

It's channel

#

I will try and tell you what hapen

spiral axle
#

no no

#

basically, in the command you are missing a mandatory paramater

#

its start(ctx):

smoky sinew
spiral axle
#

oh is it not?

smoky sinew
#

no

spiral axle
#

fine then

smoky sinew
#

as long as it's not a slur

spiral axle
#

^

vocal snow
#

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

spiral axle
slate swan
#

This dude better post the error he's getting , to get the full idea of what he's facing

turbid condor
#

The Unban in async def should be small capped

#

You can't use capital letters for command name

#

And can u show the error traceback

#

Is this the whole traceback??

#

Who are you trying to unban??

#

It is unable to find any guy with the user id that you are trying to unban from your server

naive briar
#

I don't see anything in the traceback that is implying that

turbid condor
#

Is this acc banned in the server?

turbid condor
#

Yeah second one is related to your connection

naive briar
#

Oh right

turbid condor
#

Ofc bad

#

U can try creating a new terminal but as far as i can tell first one is that you are trying to unban someone whose id is not accessible to the bot and second is the connection

#

Still the same error the bot is unable to detect the user id

naive briar
#

Do you have members intent?

turbid condor
#

Enabled in dev portal?

north kiln
#

Mars Community is not in your server?

#

Use discord.User instead

#

Yes

naive briar
#

!d discord.Guild.unban

unkempt canyonBOT
#

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

Unbans a user from the guild.

The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.

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

Use that instead

thin raft
#

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

thin raft
#

my bot got verified :D

north kiln
vale wing
thin raft
vale wing
#

It took them 2 months for them to verify my first bot and second got things done within an hour

thin raft
#

it took a morning

#

because they emailed me for some extra stuff

#

discord support is also like this 🤡

vale wing
#

Their support is significantly faster than it used to be

thin raft
#

still useless

vale wing
#

@thin raft what's your bot btw

thin raft
#

It's a music bot that plays music from a single artist

#

it was meant as the server bot but people wanted to invite it

#

so it ended up verified lol

#

do you know python?

smoky sinew
#

that's not how objects work, you need to get a guild object such as interaction.guild

#
await interaction.guild.unban(...)
#

and make sure the command is guild_only and locked to the proper permissions

#

which it isn't here

vale wing
#

To disable all slash commands in dms I typically do

for commands in self.slash_commands:
    command.body.dm_permission = False

Is there fr no other nice solution for that (disnake)

thin raft
#

man these days I've been learning about networking with twisted and it is interesting ngl

smoky sinew
#

does disnake not have app_commands.guild_only

#

and GuildInteractionContext or something

vale wing
#

It does but why add deco to every fricking command

#

That thing does it all at once

thin raft
#

!d discord

smoky sinew
#

still no

thin raft
#

why does it change every day

formal basin
#

!d python

smoky sinew
#
@app_commands.guild_only()
@app_commands.checks.bot_has_permissions(ban_members=True)
@app_commands.checks.has_permissions(ban_members=True)
vale wing
#

But I wondered if there are any constructor kwargs or methods to disable them without that (I couldn't find any)

smoky sinew
#

makes it so your command can't be used in dms

vale wing
#

Yes

slate swan
#

Do you recommend "Automate the boring stuff with python" to a beginner like me to learn at least the basics?

thin raft
#

does anyone have a app_commands.group example

smoky sinew
smoky sinew
vale wing
#

Is it in bot's dms

smoky sinew
#

in your bot dms

#

how can a bot use commands in a dm it doesn't have access to??

thin raft
#

can I declare commands inside of it?

vale wing
#

There's a literal example below isn't there

thin raft
#

@app_commands.guild_only()
class MyGroup(app_commands.Group):
pass

vale wing
thin raft
#

literally shows how to declare it

smoky sinew
#

yes

#

go to dms with your bot

#

type /ban

vale wing
smoky sinew
#

that's not how that works

#

you can't ban anyone

#

you're not in a server it's impossible to ban anyone in dms

smoky sinew
thin raft
#

wait what

vale wing
#

I remember one dude had code like this

for user in ctx.guild:
    await ctx.author.ban()

The command was supposed to ban a single member 💀

#

It practically does

smoky sinew
vocal snow
#

Since when is Guild iterable

vale wing
#

I forgor

thin raft
vale wing
#

I really forgor 💀💀

#

Because they haven't loaded yet

thin raft
#

can you make a

#

app_commands.user_only()

#

so only 1 user can use it

smoky sinew
#

that's what checks are for

vale wing
#

Make bot private and that's it

thin raft
vale wing
#

Checks then

smoky sinew
#

probably because you used has_any_role

thin raft
#

the channel isnt yours man

smoky sinew
#

still, it's better to explicitly state @app_commands.guild_only()