#discord-bots

1 messages · Page 281 of 1

shrewd apex
#

bro literally wants to be spoon frd

harsh orbit
#

I saw this also

naive briar
shrewd apex
#

yeah implement your own check

glad cradle
#

in your custom check you're able to check whether the user have the admin permission or has your custom role!

shrewd apex
#

^^

formal basin
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

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

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

formal basin
#

there not raising errors

#

I want it to ignore this error handler and only use the try and except error handlers

@tree.error
async def on_app_command_error(interaction: discord.Interaction, error: AppCommandError):
     
      command = interaction.command.name
      channel2 = client.get_channel(1112053260879147130)
      if isinstance(error, app_commands.CommandOnCooldown):
        await interaction.followup.send(error, ephemeral=True)
      else:
       button = Button(label="support server", url="")
       view = View()
       view.add_item(button)
       embed = discord.Embed(title="An error has occured", description="If you need help with this error join the support server. ", colour=discord.Colour.red())
       await interaction.followup.send(embed=embed, view=view)
       await channel2.send(f"{command} command used by {interaction.user} but an error occured")
       traceback.print_exc(limit=None, file=None, chain=True)
shrewd apex
formal basin
shrewd apex
#

then whats the issue

formal basin
#

when a error is raised it goes to the on_app_command_error

#

instead of except

shrewd apex
#

cause the error dosent fall under category of attribute error or http exception

#

keep a broad exception clause if u want to handle for all cases

shrewd apex
#

show traceback

#

u might wanna register a command specific error handler for this tho

#

seems cleaner than try except

formal basin
# shrewd apex keep a broad exception clause if u want to handle for all cases
  File "/Users/zagzag/vscode/zagzag/zagzag.py", line 627, in kick
    await member.kick()
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/member.py", line 762, in kick
    await self.guild.kick(self, reason=reason)
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/guild.py", line 3643, in kick
    await self._state.http.kick(user.id, self.id, reason=reason)
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/http.py", line 739, in request
    raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/commands.py", line 828, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
  File "/Users/zagzag/vscode/zagzag/zagzag.py", line 639, in kick
    if member not in interaction.guild:
TypeError: argument of type 'Guild' is not iterable

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

Traceback (most recent call last):
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/commands.py", line 853, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/commands.py", line 842, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'kick' raised an exception: TypeError: argument of type 'Guild' is not iterable```
#

oh wait

#

guild is not iterable

shrewd apex
#

its a type error

formal basin
#

if member is not in interaction.guild:

shrewd apex
#

.members

maiden fable
formal basin
shrewd apex
#

pepsi

maiden fable
#

Euw

shrewd apex
#

thumbs up

formal basin
#

ok

maiden fable
formal basin
shrewd apex
#

cant drink it

shrewd apex
maiden fable
formal basin
#

is it if member not in interaction.guild.members:

maiden fable
#

Hmm

slate swan
#

Me when people don't read answers to their already asked question

maiden fable
#

Hi Krypton

formal basin
young dagger
#

I'm currently using this to use custom emoji from a specific guild. Is there any better way to achieve this?

guild = discord.utils.get(client.guilds, id=1135157269328302110)

primary_keystone_emoji = discord.utils.get(guild.emojis, name=primary_keystone.replace(' ', '_'))
secondary_three_emoji = discord.utils.get(guild.emojis, name=secondary_three)

first_shard_emoji = discord.utils.get(guild.emojis, name=first_shard.replace(' ', '_'))
second_shard_emoji = discord.utils.get(guild.emojis, name=second_shard.replace(' ', '_'))
third_shard_emoji = discord.utils.get(guild.emojis, name=third_shard.replace(' ', '_'))```
formal basin
#

no error

young dagger
#

I heard to use <:emoji:emoji id> but the problem is that there are 50 different emojis, which means that I have to save all the emoji ids in a json file anyway?

naive briar
#

What's the problem

young dagger
naive briar
#

Messiness

slate swan
#

useless method calls

naive briar
#

If you already know their IDs, you can just use client.get_guild and guild.get_emoji

#

Or even literally just make a variables of the emoji string, like pit = "![pithink](https://cdn.discordapp.com/emojis/652247559909277706.webp?size=128 "pithink")"

young dagger
slate swan
young dagger
# slate swan you already did that but didnt store ids but names

Not true, I'm actually using a list:

SHARD_OPTIONS = [
    ["Adaptive Force", "Attack Speed", "Ability Haste"],
    ["Adaptive Force", "Armor", "Magic Resist"],
    ["Health Scaling", "Armor", "Magic Resist"]
]

    first_shard = random.choice(SHARD_OPTIONS[0])
    second_shard = random.choice(SHARD_OPTIONS[1])
    third_shard = random.choice(SHARD_OPTIONS[2])```
naive briar
#

And?

formal basin
slate swan
naive briar
#

You're basically doing nothing

formal basin
naive briar
#

Not gonna be any different if you don't have anything after it

formal basin
#

dont raise an error

naive briar
#

What?

formal basin
naive briar
#

Then don't??

#

What's the actual problem you're having

#

I'm not even sure what you're trying to do at this point

formal basin
#

a kick command

slate swan
#

and what are you stuck on?

formal basin
# slate swan and what are you stuck on?
except HTTPException:
    if member == client.user:
        command = interaction.command.name
        channel2 = client.get_channel(1112053260879147130)
        button = Button(label="support server", url="")
        view = View()
        view.add_item(button)
        embed = discord.Embed(title="An error has occured", description="If you need help with this error join the support server. ", colour=discord.Colour.red())
        await interaction.followup.send(embed=embed, view=view)
        await channel2.send(f"{command} command used by {interaction.user} but an error occured 1")
    elif member not in interaction.guild.members:
      pass
      print("1")
    elif member.bot:
       pass
       print("2")```
#

this except handler

#

im trying to check if the member is no in the guild because they prob have their dms off

#

and bots do too

#

but its just going to on_app_command_error

#

I dont want it to

#

@slate swan

#

I know

slate swan
#

May be worth sending the code with proper indentation

slate swan
#

Because here your indentation is screaming

formal basin
slate swan
#

And a more broader overview of your code is probably better

#

E.g. sharing everything instead of parts of it

#

so you have a try except in a command

formal basin
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

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

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

slate swan
slate swan
#

can you put print before the pass?

#

in this lines

formal basin
#

ok

upbeat ice
#

Just use return??

slate swan
#

true ^

upbeat ice
#

This code has too much spaghetti

slate swan
#

You know you can use per command error handers right

#

Would prevent that 🍝 code

#
elif member.bot or member.something:
    return
else:
    raise e

formal basin
#
  File "/Users/zagzag/vscode/zagzag/zagzag.py", line 630, in kick
    log2 = int(log.decode("utf-8"))
AttributeError: 'NoneType' object has no attribute 'decode'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/commands.py", line 828, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
  File "/Users/zagzag/vscode/zagzag/zagzag.py", line 635, in kick
    await member.send(f"you were kicked from ``{interaction.guild.name}`` reason: {reason}")
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/abc.py", line 1516, in send
    channel = await self._get_channel()
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/member.py", line 435, in _get_channel
    ch = await self.create_dm()
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/member.py", line 236, in general
    return await getattr(self._user, x)(*args, **kwargs)
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/user.py", line 530, in create_dm
    data: DMChannelPayload = await state.http.start_private_message(self.id)
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/http.py", line 745, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50007): Cannot send messages to this user

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

slate swan
#

log is None

formal basin
#

thats why i put pass

upbeat ice
#

😟

slate swan
#

what

formal basin
#

you said it was pointless

slate swan
#

cause it is

#

you have a member.send right after it

formal basin
slate swan
#

!e ```py
def x():
pass
print("does code after pass work")
x()

unkempt canyonBOT
#

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

does code after pass work
slate swan
#

drakeNo Proper handling of errors
drakeYes Catch errors, use except X: pass

#

contextlib.suppress would be at least better

formal basin
slate swan
#

no you dont put it at all

#

i think you are missing the point of this keyword

#

!d pass

unkempt canyonBOT
#

7.4. The pass statement


pass_stmt ::=  "pass"
``` [`pass`](https://docs.python.org/3/reference/simple_stmts.html#pass) is a null operation — when it is executed, nothing happens. It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed, for example:

```py
def f(arg): pass    # a function that does nothing (yet)

class C: pass       # a class with no methods (yet)
slate swan
#

when it is executed, nothing happens.

formal basin
#

ok.

#

but why it raised the error then?

slate swan
#

its only useful for example when ```py
def function():
pass

...

formal basin
#
except AttributeError:
    await member.send(f"you were kicked from ``{interaction.guild.name}`` reason: {reason}")
 ``` so this is fine?
slate swan
#

so yeah thats good

#

E.g. you can't do

print("Stuff")

def x():
    # Implement later
x()

so you use pass

formal basin
#

well

#

If log is None

slate swan
#

you make log not None

formal basin
#

thats fine

slate swan
#

idk how you gather it Shrugdge

#

By having log not being None or handling correctly when it's None

slate swan
#

Then you know how to do it, that's good

#
if log is None: pass``` ![swag](https://cdn.discordapp.com/emojis/830869004453019668.webp?size=128 "swag")
slate swan
#

no

naive briar
#

Don't just copy paste everything ducky_sus

slate swan
#

that wont work ☠️

formal basin
slate swan
upbeat ice
formal basin
#

not next to

slate swan
#

Doesn't matter

sonic tinsel
#

How can i make a restart, and turn off command in discord.py?

slate swan
#

Next to it works fine as well

formal basin
slate swan
#

!e py if None is None: pass

unkempt canyonBOT
#

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

[No output]
slate swan
#

totally correct syntax

formal basin
#

oh ok

slate swan
unkempt canyonBOT
#

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

Closes the connection to Discord.
tepid dagger
#

im tryna use discord.Guild.ban but when i run it i get this error:

File "main.py", line 58
await guild.ban(user, *, reason=Reason)
^^^^
SyntaxError: iterable argument unpacking follows keyword argument unpacking

code: ```async def ban(interaction:discord.Interaction, member:discord.Member, *, Reason:str):
await guild.ban(user, *, reason=Reason)
await interaction.response.send_message(f"User {member.mention} has been banned for {Reason} ")

#

how does one fix this

#

i think my syntax is really wrong but idk

tepid dagger
#

reason for ban

slate swan
naive briar
#

Read the error

tepid dagger
#

idk what it means lol

slate swan
#

the * is not a valid argument in simple terms

tepid dagger
#

ok

slate swan
#

meaning dont just copy function definitions from docs

tepid dagger
#

ok

naive briar
#

!e

print(*(1 for _ in range(10)))
unkempt canyonBOT
#

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

1 1 1 1 1 1 1 1 1 1
slate swan
#

all that * means is that everything after it must be passed as keyword only

#

protip you can use .ban() method directly on Member object

tepid dagger
#

so the code would just be

  await guild.ban(user, reason=Reason)
  await interaction.response.send_message(f"User {member.mention} has been banned for {Reason} ")```?
slate swan
#

!d discord.Member.ban

unkempt canyonBOT
#

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

Bans this member. Equivalent to [`Guild.ban()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.ban "discord.Guild.ban").
upbeat ice
#

c++ has entered the chat

tepid dagger
#

whats the difference between guild.ban and member.ban

slate swan
slate swan
#

(the one that method is used on)

tepid dagger
#

so guild.ban lets u pick

slate swan
#

you need Member object anyways to pass to it

#

member.ban is just shortcut

unkempt canyonBOT
#

discord/member.py lines 743 to 748

await self.guild.ban(
    self,
    reason=reason,
    delete_message_days=delete_message_days,
    delete_message_seconds=delete_message_seconds,
)```
slate swan
#

this is how it works in source code if you understand it

#

it just calls guild.ban with self being member itself

tepid dagger
#

delete_message_days is an int right

formal basin
slate swan
unkempt canyonBOT
#

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

Bans 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.
slate swan
#

check the docs

tepid dagger
#

oh

#

bro my brain thought parameters is a different method i should sleep

slate swan
tepid dagger
#

bro i never knew that existed witw is this

formal basin
tepid dagger
#

what is abc.snowflake

#

how do i define "user"

slate swan
#

you cant define it

#

library must provide it to you

tepid dagger
#

File "main.py", line 58, in ban
await interaction.guild.ban(user,reason=reason)
NameError: name 'user' is not defined

slate swan
#

for example if you want the person who ran the command its ctx.author

tepid dagger
#

ok

slate swan
#

if its slash command its actually interaction.user

tepid dagger
#

what

#

so

slate swan
#

but i belive you dont want to ban person who used /ban command

tepid dagger
#

true

tepid dagger
slate swan
#

..

naive briar
#

You

#

Remove it

tepid dagger
#

my brain is failing

slate swan
#

it wont randomly spawn varriable in your code

tepid dagger
#

ok

slate swan
#

you already accept a member member:discord.Member

#

just called it member not user

tepid dagger
#

oh bruh

#

good point

#

not forgetting the varaibles i defined sounds like a good idea

#

also i like ur pfp down

slate swan
#

👍

tepid dagger
#

tortle

weak ingot
#
@bot.tree.command(name = 'kick')
@app_commands.describe(user = 'Who do you want to kick?', reason = 'Why do you want to kick them?')
async def kick(ctx, interaction: discord.Interaction, user: discord.Member, reason: str):
    if interaction.user.permissions.kick_members:
        await bot.kick(user)
        await interaction.response.send_message(f'Seccsesfuly kicked {user}.', ephemeral = True)

    else:
        await interaction.response.send_message(f'{interaction.user.mention} dont have the required permission(s).', ephemeral = True)

Traceback (most recent call last):
File "/home/fady/Documents/Code/public/FlareMod/bot.py", line 29, in <module>
exec(f.read())
File "<string>", line 3, in <module>
File "/home/fady/.local/lib/python3.10/site-packages/discord/app_commands/tree.py", line 887, in decorator
command = Command(
File "/home/fady/.local/lib/python3.10/site-packages/discord/app_commands/commands.py", line 666, in init
self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.globals)
File "/home/fady/.local/lib/python3.10/site-packages/discord/app_commands/commands.py", line 374, in _extract_parameters_from_callback
param = annotation_to_parameter(resolved, parameter)
File "/home/fady/.local/lib/python3.10/site-packages/discord/app_commands/transformers.py", line 833, in annotation_to_parameter
(inner, default, validate_default) = get_supported_annotation(annotation)
File "/home/fady/.local/lib/python3.10/site-packages/discord/app_commands/transformers.py", line 792, in get_supported_annotation
raise TypeError(f'unsupported type annotation {annotation!r}')
TypeError: unsupported type annotation <class 'discord.interactions.Interaction'>

meager chasm
#

Why do you have a ctx parameter

#

Remove it

#

And bot.kick doesn't exist

weak ingot
#

user.kick(reason=reason)

meager chasm
#

That doesn't exist either

buoyant quail
meager chasm
#

Oh nvm it's an instance of Member

#

Might want to rename it to member so it's not misleading

weak ingot
#

okay

lilac vault
#

heyy how to make a button

slate swan
lilac vault
#

thank ya

weak ingot
#

how to check user permissions

sick coyote
#

can you disable slash commands like normal commands with a check?

#

or is it not possible

slate swan
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.
slate swan
unkempt canyonBOT
#

@discord.app_commands.check(predicate)```
A decorator that adds a check to an application command.

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

These checks can be either a coroutine or not.

Examples

Creating a basic check to see if the command invoker is you...
slate swan
#

or built in ones Like has_permissions or has_role

sick coyote
#

thanks

lofty lance
#

@slate swan can u pls look into is sir

sick coyote
#

if i dont have the message content intent can i still get the message type?

unkempt canyonBOT
thin raft
#

yeah you can

#

you just can't read the message

sick coyote
#

ight

#

ty

young dagger
#

How can I handle discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions errors?

sick coyote
#

what

queen wren
young dagger
sick birch
#

Can you give us more context?

young dagger
#

Should I use if isinstance(error, commands.CommandError): for this?

#

Example

    if isinstance(error, commands.CommandError):
        # Handle the Forbidden error here
        try:
            await ctx.author.send(f":x: **Denied Permissions** Please contact an Admin. The following permissions are denied in #{ctx.channel.name} for Ultimate Bravery.")
            return
        except discord.Forbidden:
            return```
sick coyote
#

is it normal for my commands to not work when i have no message content intent? i have already removed the custom prefix feature

sick birch
#

Is this in an error handler for a command?

young dagger
sick birch
sick coyote
#

damn bro

#

alright

sick birch
slate swan
#

help please

cloud dawn
sick birch
#

has it been 3 years already?

#

sheesh

glad cradle
#

but it was enforced only 1+ year ago

slate swan
#

How can I make it so that you don't always have to set a dot, just write something and the embed is created directly

#

?

slate swan
unkempt canyonBOT
#

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

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

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

New in version 2.0.

x == y Checks if two embeds are equal.

New in version 2.0...
slate swan
#

Search for methods it has

#

Im sure you will see what method you want

cloud dawn
sick coyote
#

is there an event when a application command gets invoked like on_command

#

nvm found it, it was hidden

tall temple
#

FileNotFoundError: [WinError 3] Le chemin d’accès spécifié est introuvable : 'pms'

#

can someone help me pls ?..

slate swan
slate swan
#

@slate swan

#

How what

#

what habe i to change ?

#

You are supposed to go to the docs i linked about Embed and read what methods it has

#

And find one matching what you need

#

Im sure you will find it

#

ty

tall temple
upbeat ice
tall temple
slate swan
keen trail
tall temple
#

to get directory files list with os.listdir method sir

keen trail
#

check if its coded correctly

fiery salmon
tall temple
#

it was working before i just changed the dir to another one

#
async def Methods(ctx : discord.AutocompleteContext):
    fileslist = os.listdir(f'pms')
    data = []
    for file in fileslist :
        filename = file.replace(".json", "")
        data.append(filename)
    return data
keen trail
tall temple
keen trail
#

yep i see why u gave wrong dir

#

try to click on file name right button and copy file path

tall temple
#

the code just worked rn wtf 💀

fiery salmon
#

may not have saved it or somethin

#

🤷‍♂️

tall temple
#

i'm sometimes dumb

civic pivot
tall temple
slate swan
marble prism
#

Thanks! I just realized that this probably wasn't the best place to post it : )

bleak brook
#

could someone help my with slash commands in discord.py please?

cloud dawn
#

This is a basic syntax, keep in mind this is not meant to be used as is.

bleak brook
cloud dawn
fiery salmon
#

hi, i am trying to figure out why emojis aren't working

#

is there another way I can specify the 🐡 , 🐟 , and ⚠️ emojis without copying them directly? I am storing these values in a database

slate swan
#

It looks like you're using the footer to write your text but I can't tell properly, try using the description

fiery salmon
hushed galleon
#

footer can render unicode emoji correctly, you just have to actually insert the unicode character for discord to render it

#

!charinfo 🐟

unkempt canyonBOT
#
Character Info

\U0001f41f: FISH - 🐟

fiery salmon
#

😮

hushed galleon
#

either "\U0001f41f", "\N{FISH}", or "🐟"

#

in a python script that is, for a database you'd probably want to insert the actual character (third one)

fast jackal
#

hi yall Im currently learning python and I want to learn how to be a discord bot dev and being able to scrap the web and make automation bots. What are things do I need to learn to become proficent at that? Ive heard of selienum. but yeah thats all ive heard of.

umbral flame
#

stupid indentation? maybe??, but im stuck

slate swan
#

wth is it saying that?

weary fossil
#

pithink Did you ping me?

slate swan
#

?

#

wdym

weary fossil
#

You... pinged me, in this chan--never mind.

slate swan
#

oh yea

#

i did

#

u a hepler right?

#

just i dont know if i cant or can do that here

#

can i?

weary fossil
#

I wouldn't recommend pinging people randomly. Individuals will help you when they are able. I have not used discord_slash.

#

I'm fairly certain that's an invalid module name though.

sick birch
sick birch
#

discord.py has had native support for slash commands for quite a while now

slate swan
#

well its saying this

#

i cant uplaod fiels

#

here

sick birch
#

I haven't used discord_slash either, I just use discord.py for all my slash commands

slate swan
#

can u give an code example ?

turbid condor
slate swan
#

how can I add clear and say?

turbid condor
#

What's this?

slate swan
#

trying to do purge slash command

#

like this

#

*/clear [12]

turbid condor
#

Then what's say?

slate swan
#

and then it clears the messages

turbid condor
#

Tbh did u even look at the example robin sent above

slate swan
#

yea i did and i didnt understand but i got it to work

#

but this is different bug

turbid condor
#

There isn't a bug you are just doing it wrong

slate swan
#

yea i tried a couple of methods that why i asked if someone know who can i have both

#

clear and say

turbid condor
#

What do u mean clear and say both?

#

Like
/clear say

slate swan
turbid condor
#

Or 2 different commands
/clear
And
/say
Like this

slate swan
#

no

turbid condor
#

Then?

turbid condor
slate swan
#

anyone knows how to fix this?

Traceback (most recent call last):
  File "D:\DISCORD BOT\app.py", line 48, in <module>
    @bot.slash_command(guild_id = [1135998495166316577],description = "tets 1")
     ^^^^^^^^^^^^^^^^^
AttributeError: 'Bot' object has no attribute 'slash_command'. Did you mean: 'add_command'?
slate swan
#

wdym

#

it worked for me i changed the version and i switch it for the original version and its says this

slate swan
slate swan
#

yea its pycord

torn solar
#
async def recruited(ctx: discord.Interaction):
    embed = discord.Embed(title="Recruitment Statistics", color=rnp_color, description=f"""
                          
                          Members Recruited Last Minute: {grabRecruited()}""")
    ctx.channel.send(embed=embed)```
#

the command isnt showing up when i do /recruited

#

and i synced the command tree

#

fixed

slate swan
#

maybe you want to use pycord but have installed other libraries

#

check what discord libraries you have

#

pip list to get list of all

lofty lance
#

ahh can anyone just tell me how to do oath2a thing so that when a person type a command in my discord game bot he joins a server directly

sick birch
lofty lance
slate swan
# lofty lance and how can i set this thing up in my bot? i have 0 idea of it so can u pls guil...

if you are new to discord api i wouldnt bother to set it up its hard to understand for beginner but if you wish to give it a try here are the docs and few examples in python https://discord.com/developers/docs/topics/oauth2

Discord Developer Portal

Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.

torn solar
#

i have a problem wehre i update the code for a command, restart the bot, then it still uses the old code

#

i synced the command tree so idk why

naive briar
torn solar
#

yes

#

😫

#
                          ---------------------------------------------------
                          
                          **Members Recruited All Time:** `{grabRecruited("all")}`
                          
                          **Members Recruited Past Month:** `{grabRecruited("month")}`
                          
                          **Members Recruited Past Week:** `{grabRecruited("week")}`
                          
                          **Members Recruited Past Day:** `{grabRecruited("day")}`
                          
                          ---------------------------------------------------
                          """)```
#

thats the new embed ^^

#

thats whats its showing after i restart the bot, make sure the code is saved, and sync the command tree

naive briar
#

What is your previous code?

torn solar
#

i dont have it

naive briar
#

I can't just imagine it and be correct

torn solar
#

because i changed it

#

all that changed was the description of the embed

#

but its not changing

naive briar
#

What was the previous code's embed looks like?

torn solar
#

the image above

#

thats the old code embed

#

and i updated the code to make it look better

#

and it still shows the old code

slate swan
#

how do you restart the bot?

torn solar
#

terminate the program and start it back up

#

dont make fun of me... but i use replit to host it while using uptime robot to ping it every 5 minutes with a keep alive script

#

i know its bad, but it does what i need it to

slate swan
#

if you put for example print in the command

#

and run the command it wont print it out?

torn solar
#

let me try

#

doesnt print

#

idk why its just using the old code when i pasted in the new code

slate swan
#

how about you raise an error

#

cause prints sometimes dont print out

torn solar
#

i dont really use raises

#

could you tell me how

#
async def recruited(ctx: discord.Interaction):
    embed = discord.Embed(title="Recruitment Statistics", color=rnp_color, timestamp=datetime.now(),description=f"""
                          ---------------------------------------------------
                          
                          **Members Recruited All Time:** `{grabRecruited("all")}`
                          
                          **Members Recruited Past Month:** `{grabRecruited("month")}`
                          
                          **Members Recruited Past Week:** `{grabRecruited("week")}`
                          
                          **Members Recruited Past Day:** `{grabRecruited("day")}`
                          
                          ---------------------------------------------------
                          """)
    await ctx.response.send_message(embed=embed)
    print("hi")```
slate swan
#

just raise is fine

torn solar
#

so literally just put raise at the end?

slate swan
#

it should show RuntimeException

#

or RuntimeError

#

!e raise

unkempt canyonBOT
#

@slate swan :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     raise
004 | RuntimeError: No active exception to reraise
slate swan
#

RuntimeError PepoG

torn solar
#

nothing showed in console when i used it

#

not even a runtime error

#

maybe refreshing the page will work

slate swan
#

well then the bot taht is running is not the one hosted on replit

torn solar
#

its not being hosted on my computer

slate swan
#

you have an on_ready event?

torn solar
#

i mightve possibly hosted it on my computer

#

im terminating it to see if thats the problem

slate swan
#

most likely

torn solar
#

its still using old code

torn solar
slate swan
torn solar
#

yes

#

and the sync prints on replit

slate swan
#

you have any text based command?

torn solar
#

like a prefix command?

slate swan
#

yes

torn solar
#

.sync

#

i dont sync on ready

slate swan
#

it outputs something?

#

to discord chat?

torn solar
#

no

slate swan
#

:/

torn solar
#

just prints "Command Tree Synced"

slate swan
#

we could have checked it the bot is running twice by seeing if it outputs double

#

but if you dong send anything to channel

torn solar
#

what if i turn off the repl

#

and then try the commands

#

and if they work then we know its running somehwere else

slate swan
#

can try

torn solar
#

its only running in my repl

#

commands didnt work

slate swan
#

how about you put in this code ```py
@bot.command()
async def test(ctx):
await ctx.send("...?")

torn solar
slate swan
#

@slate swanyo

#

waiting....

slate swan
slate swan
slate swan
#

not really

slate swan
# slate swan not really

oh can i send a question i was stuck in it for 3days i opened diff books but still not got exact answer

#

that would be a great help

torn solar
torn solar
#

no errors

slate swan
slate swan
torn solar
#

ima dm it to u

slate swan
#

why not here

torn solar
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

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

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

torn solar
#

recruited command is on line 149

slate swan
#

does any of this print?

torn solar
#

the bot loaded prints

#

but the bot.commands does not

#

its using the old code as i said

slate swan
#

not even empty list?

torn solar
#

before i updated that one embed

#

nope not even an empty list

slate swan
#

!d discord.ext.commands.Bot.commands

unkempt canyonBOT
torn solar
#

whats that for

slate swan
#

for me seeing the docs about it

torn solar
#

ah

slate swan
#

well but this must print something amegablobsweats

torn solar
#

as i said before, it using the old code

#

right before i updated the embed

slate swan
#

its using old code but prints output to console in current one?

#

thats like not possible

torn solar
#

no

#

basically everything that was put in the code before i updated that one embed works

#

everything after does not

slate swan
#

okay but if you put a print statement it shoud print out right

#

how about we try raising error again

#

in on_ready

torn solar
#

no its not pringint anything

#

im gonna make a new repl

#

see if that works

slate swan
#

could be replit issue

torn solar
#

it probably 100% is

slate swan
#

another point why not use it

torn solar
#

well its free and my bot isnt huge

#

so its managable

slate swan
#

Why you should not use free hosting services for Discord bots
(this message is a temporary pin and will eventually be on our webstie)

Replit
While this may seem like a nice and free service, it has a lot more caveats than you might think, such as:

  • The machines are super underpowered.
    • This means your bot will lag a lot as it gets bigger.
  • You need to run a webserver alongside your bot to prevent it from being shut off.
    • This isn't a trivial task, and eats more of the machines power.
  • Repl.it uses an ephemeral file system.
    • This means any file you saved via your bot will be overwritten when you next launch.
  • They use a shared IP for everything running on the service.
    This one is important - if someone is running a user bot on their service and gets banned, everyone on that IP will be banned. Including you.

from https://discord.com/channels/267624335836053506/965291480992321536

torn solar
#

yeah all that doesnt matter to me

#

as long as the bot runs and works

#

im not paying for hosting for a fun community bot

torn solar
#

@slate swan

#

something is broken 😭

#

im hosting on my computer now and it just wont recognize my slash commands

torn solar
#

pur luck? idk cus i didnt leak it

slate swan
torn solar
slate swan
#

well reset it on dev portal so its not valid anymore

torn solar
#

god nukers fucking suck

#

multiple weeks of work just washed away because some little fucking degenerate eating cheetos over their computer with no friends or real life outside of discord is bored

slate swan
#

What did they do

slate swan
#

Gray = Secondary
Blue = Primary

#

That's the kind of buttons they are

slate swan
#

!d discord.ButtonStyle

unkempt canyonBOT
#

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

New in version 2.0.
slate swan
#

list of all available styles ^

grand moss
#

idk where to start looking but was thinking of a simple bot that shows and update time every minute without user input

slate swan
#

use a task

#

!d discord.ext.tasks.loop

unkempt canyonBOT
#

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

I'll check it out thanks

cloud dawn
#

@slate swan what is a dpy masterclass?

slate swan
#

few people from here make it

cloud dawn
#

Didn't it have site? Cannot find it in the repo.

slate swan
cloud dawn
#

It's in the about, just blind don't mind me

slate swan
#

you wish to contribute?

unkempt canyonBOT
#

@discord.ext.commands.is_owner()```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that checks if the person invoking this command is the owner of the bot.

This is powered by [`Bot.is_owner()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.is_owner "discord.ext.commands.Bot.is_owner").

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

I have this discord chatbot, how do i make it answer when being dm?

slate swan
#

registed on_message event

harsh orbit
#

Can any one give a docs or something to help me in ban command

#

@slate swan

#

How I can set ban time

#

This is my command

@bot.command()
async def ban(ctx, member: discord.Member, *, reason=None):
  if reason == None:
    reason = "this user was been banned by" + ctx.message.author.display_name

  await member.ban(reason=reason)
  await ctx.send(member.name + " Has been banned")
#

..

#

@naive briar
Why you type and delete

naive briar
#

What?

harsh orbit
slate swan
#

There is no such thing as ban time

#

tempbans are community creation

harsh orbit
#

Oh

slate swan
#

It works that bot unbans the user after given amount of time

harsh orbit
#

That means it hard to make

slate swan
#

It means that's not easy idk if so hard

harsh orbit
#

Understood something

#

But

#

Can you give me something to read to learn this?

slate swan
#

All i can give you is tasks guuide

#

Cause i would do it with tasks

harsh orbit
#

Ok thx very much

weak quail
#

Hello, is anyone able to direct me to a guide to working with slash commands in discord-py?

naive briar
weak quail
#

Thank you! It looks great!

clear lark
#

How would you set up a bot so any time a command is sent it checks if the prefix is ._ rather than the normal bot prefix . and if the prefix is ._ then it will send the results of the command to the user's DMs rather than the chat. To be more specific, I want this to work on any command send, not just one. I'm doing this specifically because I don't want to add an if/else to every command.

slate swan
#

easiest solution would be to make 2 commands one normal and one for dms like this ```py
@bot.command()
async def command(ctx):
# normal
@bot.command()
async def _command(ctx):
# dms

clear lark
#

thats honestly kinda tempting, but at that point I might as well do the if/else so the help command isn't completely cluttered

slate swan
#

i just dont know how you could make it notify command handle function should it send to dms or no

naive briar
#

Well, you can probably edit the command handling part of the bot and use your own modified context

slate swan
#

oh via the Context

#

thats a good idea

clear lark
#

Where in the documentation should I start for doing that?

clear lark
#

Thank you heart_02

slate swan
#

and you would need to override on_message to set your own command recognition system

unkempt canyonBOT
#

discord/ext/commands/bot.py lines 1387 to 1395

    if message.author.bot:
        return

    ctx = await self.get_context(message)
    # the type of the invocation context's bot attribute will be correct
    await self.invoke(ctx)  # type: ignore

async def on_message(self, message: Message, /) -> None:
    await self.process_commands(message)```
dense mesa
#

Ok... So im having issues with coding my discord bot using Python and Visual Studio Code.

Im trying to implement a cog system for storing commands and organizing them, but every attempt i make i keep getting "bot.load.extention" errors with the cog system.. what am i doing wrong?

Did Discord.py disconue Cogs?

clear lark
#

Discord.py still uses cogs, could you send an example of how you're loading them and the file structure?

dense mesa
#

Yeah gimme a sec

#
import discord
from discord.ext import commands
import os
from dotenv import load_dotenv

# Load environment variables from .env
load_dotenv()

# Get the bot token from the environment variable
TOKEN = os.getenv('DISCORD_TOKEN')

# Create a discord.Intents object with all intents enabled
intents = discord.Intents.all()

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

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

    @commands.command(name='command1')
    async def command1(self, ctx):
        # Action for command1
        await ctx.send('This is command 1!')

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

    @commands.command(name='command2')
    async def command2(self, ctx):
        # Action for command2
        await ctx.send('This is command 2!')

# Load cogs when the bot is ready
@bot.event
async def on_ready():
    print(f'We have logged in as {bot.user}')
    await bot.add_cog(Command1(bot))
    await bot.add_cog(Command2(bot))

# Run the bot with the loaded token
bot.run(TOKEN)
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.

clear lark
#

Yeah do that first

#

its ` not '

dense mesa
#

got it lol

#

still learning discord formatting

clear lark
#

Are the cogs in the same file or are they seperate?

dense mesa
#

i tried them both ways in same fold and separate and same error

#

the bot refused to load in the cogs lol

#

and lastly i tried in the same .py file and still wouldnt work

clear lark
#

And put the cogs into a folder named cogs

dense mesa
#

is the folder name mandatorily named cogs? or can i code it to be differnt

clear lark
#

I don't know

dense mesa
#

baaaah

clear lark
dense mesa
#

originally the code was suppose to work like this:

import discord
from discord.ext import commands
import os

bot = commands.Bot(command_prefix='!')

# Load commands from the 'commands' folder
for filename in os.listdir('./commands'):
    if filename.endswith('.py'):
        bot.load_extension(f'commands.{filename[:-3]}')

@bot.event
async def on_ready():
    print(f'We have logged in as {bot.user}')

# Replace 'YOUR_BOT_TOKEN' with your actual bot token
bot.run('YOUR_BOT_TOKEN')
#

cuz i was trying to make each command its own .py file

#

but got hung up on the bot not loading the folder commands

#

its like once i take the commands out of the bot.py file and put it in a cog system with the command in its own .py file it just breaks the bot

clear lark
dense mesa
#

well apparently im not skilled enough in coding to figure out the discord.py

#

XD

clear lark
#

Are you adding the proper identifiers to the commands when they're a cog?

cloud dawn
buoyant quail
#

You can i believe. But you need to await it anyways

#

!d discord.ext.commands.Bot.load_extension

unkempt canyonBOT
#

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

Loads an extension.

An extension is a python module that contains commands, cogs, or listeners.

An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.

Changed in version 2.0: This method is now a [coroutine](https://docs.python.org/3/glossary.html#term-coroutine).
cloud dawn
#

Depends on the version he's using but for newer versions that's true, great catch.

dense mesa
#

ok sooo.. .for example im doing this: tell me if its correct or not cuz it just seems like my bot hates me.

|bot.py|

from discord.ext import commands
import os

bot = commands.Bot(command_prefix='!')

# Load commands from the 'commands' folder
for filename in os.listdir('./commands'):
    if filename.endswith('.py'):
        bot.load_extension(f'commands.{filename[:-3]}')

@bot.event
async def on_ready():
    print(f'We have logged in as {bot.user}')

# Replace 'YOUR_BOT_TOKEN' with your actual bot token
bot.run('YOUR_BOT_TOKEN')

|commands1.py| > in the commands folder = commands/command1.py|


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

    @commands.command(name='command1')
    async def command1(self, ctx):
        # Action for command1
        await ctx.send('This is command 1!')

def setup(bot):
    bot.add_cog(Command1(bot))
#

the error comes back on "bot.load_extension(f'commands.{filename[:-3]}')"

#

every time

cloud dawn
dense mesa
#
# Function to load the commands cog
def load_commands_cog():
    bot.load_extension('commands')

# Load cogs using setup_hook when the bot is ready
@bot.event
async def on_ready():
    print(f'We have logged in as {bot.user}')
    bot.add_listener(load_commands_cog)

???

buoyant quail
#

Chat gpt it seems?

dense mesa
#

i have it trying to help me yes,... and its doing a horrible jog for something its MENT for XD

cloud dawn
# dense mesa ``` # Function to load the commands cog def load_commands_cog(): bot.load_ex...

You're looking for something like this ```py
import discord
from discord.ext import commands
import os

class CustomBot(commands.Bot)
def init(self, *args, **kwargs)
super().init(*args, **kwargs)

async def setup_hook(self) -> None:
    # Load commands from the 'commands' folder
    for filename in os.listdir('./commands'):
        if filename.endswith('.py'):
            await bot.load_extension(f'commands.{filename[:-3]}')

async def on_ready() -> None:
    print(f'We have logged in as {bot.user}')

bot = CustomBot(command_prefix='!')

Replace 'YOUR_BOT_TOKEN' with your actual bot token

bot.run('YOUR_BOT_TOKEN')

harsh orbit
buoyant quail
#

It's just a string

#

Ban reason

harsh orbit
#

Oh

dense mesa
#
class CustomBot(commands.Bot)
    def __init__(self, *args, **kwargs)
        super().__init__(*args, **kwargs)

what is this?

buoyant quail
#

Python code pixels_snek_2

cloud dawn
#

It goes trough all the basics and syntax you will need to know in order to get a basic grasp on discord.py

dense mesa
#

ok yeah it seems this system of cogs and extensions ChatGPT has no knowledge of.

just tried an example for it to analyze and it failed and wouldnt generate XD fun fun

cloud dawn
dense mesa
#

yeah and im not paying just yet for gtp 4

#

ugh ... my brain is ganna hate me the next couple week now

hushed galleon
#

i believe most online dpy resources arent comprehensive to begin with

cloud dawn
hushed galleon
#

or to the official guide
Rapptz/discord.py#7654

lament depotBOT
hushed galleon
#

actually im not sure if thats still alive, last edit was a year ago

#

hm last commit to the docs/guide branch was february

cloud dawn
dense mesa
#

bah 😦

#

hense why i reframed from paying for it lol

#

...for now

#

shit i even have AI assistance installed in my Virtual Studio Code. which honestly is very helpful

cloud dawn
#

Well you can use the guide I sent you and ask here.

cloud dawn
#

Yeah it autocompletes some stuff, but when you are working with all the newest versions of different libraries it just doesn't help or just guesses.

dense mesa
#

lol copilot is amazing IF you have limited to no coding knowledge/experience

#

which is me

#

I'm an enthusiast, not a boneified coder.

cloud dawn
#

I'd use copilot for LTS versions of certain programming languages and older libs but for new ones not so much.

spring summit
#

when i dont provide a reason, the command doesnt work, why? py @client.command() async def ban (ctx, member:discord.User=None,*, reason = None): if reason == None: reason = "No Reason Provided." return embed = discord.Embed( title=f"*You have been banned from {ctx.guild.name} for {reason}*", color=0xfa6859) await member.send(embed=embed) embed = discord.Embed(color=0xfa6859) embed = discord.Embed( title= f"__**MEMBER SUCCESSFULLY BANNED**__ {hammer_emoji}", url="", color=0xfa6859) embed.add_field( name=f'**{member_emoji} MEMBER**', value=f' {member} ', inline=False) embed.add_field( name=f'**{scroll_emoji} REASON**', value=f"{reason}", inline=False) await ctx.send(embed=embed) # await ctx.guild.ban(member, reason=reason)

cloud dawn
#

And.. I don't like spending 10 bucks a month on yet another subscription.

cloud dawn
#

It should always state something a tleast.

cloud dawn
#

Ah yeah.

spring summit
#

😭

cloud dawn
spring summit
cloud dawn
formal basin
cloud dawn
buoyant quail
#

pip install library==version

cloud dawn
#

poetry add discord.py

formal basin
buoyant quail
#

?

cloud dawn
formal basin
cloud dawn
#

Do keep in mind this is not recommended and you will not get support if it's a library side issue.

formal basin
#

In pip install git+<git_link>

cloud dawn
#

No just the git+ and then the link.

thin raft
formal basin
#

Ok

cloud dawn
#

Any reason you would need the dev branch @formal basin

harsh orbit
#

What's the name of timeout permission in has_permissions
Like

@has_permission(what should I type here)
hushed galleon
unkempt canyonBOT
harsh orbit
#
@has_permissin(moderate_members=True)

?

clear lark
#

prob ShrugShrug

exotic island
full cosmos
#

I always get the error message in the first image, once the code in the second image runs for a minute or so. The exact time it takes is not consistent and it also happens in roughly the same time frame when I increase the sleep time.
Any idea what could be causing this?

maiden fable
#

The logs mean that the bot has connected to Discord, try seeing if the bot has enough perms to send messages, embeds etc

maiden fable
#

(BTW u do know that u sent a screenshot of this channel right?)

#

And well, I would like to see the code of the command u r tryna invoke

#

do u have an on_message event?

full cosmos
#

I think I may have finally found the culprit though.

maiden fable
#

Show that event

#

Why?

naive briar
maiden fable
#

You mean an event?

#

Cool that u got the issue sorted

full cosmos
#

Seems I managed to fix my issue as well. I spent two days completely perplexed and it turns out that the answer was that a global boolean is (unsurprisingly) not thread safe...

#

I replaced it with a janky queue that just acts like a boolean but as long as it works I guess it's okay. lol

maiden fable
#

Yea globals suck in most of the cases

slate swan
#

global is a deadly keyword to use

full cosmos
#

Looks like there's a different issue now. 😭

#

I guess that happens when I queue too many discord commands and they have to wait for the http request? (not the one from my earlier image)

#

The error message says something about "command hd" which I have currently queued a bunch of.

naive briar
#

Well, it looks like aiohttp timed out the request

full cosmos
maiden fable
#

iirc there was a timeout kwarg in the constructor, lemme find

naive briar
#

!d aiohttp.ClientSession

unkempt canyonBOT
#
class aiohttp.ClientSession(base_url=None, *, connector=None, cookies=None, headers=None, skip_auto_headers=None, auth=None, json_serialize=json.dumps, ...)```
The class for creating client sessions and making requests.
naive briar
#

Set the timeout argument to None

full cosmos
#

thank you!

keen trail
#

guys got question

#

how do i make slash command to purge messages

turbid condor
slate swan
#

Create slash command with the right decorator, make it purge messages when executed

unkempt canyonBOT
#

await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=None, bulk=True, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.

You must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages) to delete messages even if they are your own. Having [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history) is also needed to retrieve message history.

Changed in version 2.0: The `reason` keyword-only parameter was added.

Examples

Deleting bot’s messages...
sweet steeple
#

Struggling rn

full cosmos
#

It is back and now it happens much more quickly. 😭

#

I just tried to make it delete and resend the message in certain cases. As far as I can tell I didn't even touch the http request...

full cosmos
#

I thought I fixed it again (by fixing my weird "async with" stuff and adding "await" in front of the http request) but now it is back again for the third time.

#

This async stuff is complicated man.

glad cradle
full cosmos
quick gust
#

use a pasting service

full cosmos
#

thx

quick gust
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

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

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

full cosmos
#

the error message points at the http request specifically. I have another request to the same server which doesn't have any problems. That one doesn't get spammed as often though.

slate swan
#

global

full cosmos
#

Those are both queues though. Apparently that's fine?

slate swan
#

It may be fine, but the use of global makes your code hell

full cosmos
#

Will the queues work without it?

#

I've seen it used with queues but I'm not sure if that person knew what they were doing either...

#

I'm using a lot of queues because they are the only working way I know of sharing information between asynchronous functions. So far that seems to work.

sweet steeple
#

how to fix

slate swan
#

enable message_content intent

finite geyser
sweet steeple
#

can someone help me out

slate swan
#

There is no ctx argument in the on_message event, only message

#

And you may want to not leak your token, even just parts of it

main holly
#

are application commands available on py

#

because i need help with it

slate swan
#

Yes

main holly
slate swan
sweet steeple
#

hi yall

main holly
sweet steeple
#

heres my script

#

can someone make this into english

naive briar
#

The error explained it in plain English

main holly
#

lmfao

sweet steeple
#

oh

naive briar
#

string indices must be integers, not str

sweet steeple
#

whats an indice

#

and why does it have 2 be integer

naive briar
#

!e

print("meow"["a"])
unkempt canyonBOT
#

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

001 | /home/main.py:1: SyntaxWarning: str indices must be integers or slices, not str; perhaps you missed a comma?
002 |   print("meow"["a"])
003 | Traceback (most recent call last):
004 |   File "/home/main.py", line 1, in <module>
005 |     print("meow"["a"])
006 |           ~~~~~~^^^^^
007 | TypeError: string indices must be integers, not 'str'
slate swan
#

!e "something"[1:2] # works
"something"["some_key"] # wont work

naive briar
#

!e

print("meow"[2])
unkempt canyonBOT
#

@slate swan :x: Your 3.11 eval job has completed with return code 1.

001 | /home/main.py:2: SyntaxWarning: str indices must be integers or slices, not str; perhaps you missed a comma?
002 |   "something"["some_key"] # wont work
003 | Traceback (most recent call last):
004 |   File "/home/main.py", line 2, in <module>
005 |     "something"["some_key"] # wont work
006 |     ~~~~~~~~~~~^^^^^^^^^^^^
007 | TypeError: string indices must be integers, not 'str'
#

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

o
sweet steeple
#

wait then how am i supposed to access my table

naive briar
#

How did you load your "table"

slate swan
#

print out what server actually is

naive briar
#

If you just read the file and didn't load it into a dict, it's only going to be a string

sweet steeple
slate swan
#

im asking for actual value so print it out

sweet steeple
#

also why isnt it looping thru the full table

#

i thought for loops loop through their arrays until broken/ended

slate swan
#

its just the dictionary key not a dictionary

sweet steeple
#

how would i access the key

#

im new to python sry

slate swan
#

what is Configurations["something"]

sweet steeple
slate swan
#

dam bros thinks he is teaching me skull

#

im asking for definition of it

sweet steeple
slate swan
#

thats the json file

#

im asking what Configurations is

sweet steeple
#

its the settings basically

slate swan
#

oh this way

naive briar
#

!e

a = {"key_1": 0, "key_2": 1}
for b in a:
    print(b)
unkempt canyonBOT
#

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

001 | key_1
002 | key_2
slate swan
#

then you need to use .items()

#

!d dict.items

unkempt canyonBOT
#

items()```
Return a new view of the dictionary’s items (`(key, value)` pairs). See the [documentation of view objects](https://docs.python.org/3/library/stdtypes.html#dict-views).
naive briar
#

!e

a = {"key_1": 0, "key_2": 1}
for b in a.values():
    print(b)
unkempt canyonBOT
#

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

001 | 0
002 | 1
slate swan
#

or values if you dont neeed the keys

sweet steeple
#

like dis

slate swan
#

try

sweet steeple
#

ok cool but

#

its still only returning one value in the table out of 5

slate swan
cold sonnet
#

why make serverinformation a dict

#

a dict with no keys and values just items

sweet steeple
naive briar
#

Dictionary keys can't be repeated

slate swan
naive briar
#

!e

a = {"b": 0, "b": 1", b": 2}
print(a)
untold flax
#

wondering how easy (or complicated) will it be to shard a discord bot across multiple hosts
i.e. instead of being sharded on one machine, it will sharded across multiple ones

naive briar
#

!e

a = {"b": 0, "b": "1", b": 2}
print(a)
glad cradle
#

🧐

naive briar
#

!e

a = {"b": 0, "b": "1", "b": 2}
print(a)
unkempt canyonBOT
#

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

{'b': 2}
naive briar
#

Only three tries 🥱

cold sonnet
#

'ServerInformation' : {{}, {}}
'ServerInformation' : [{}, {}]

untold flax
naive briar
#

I was trying to show that dict keys can't be repeated

untold flax
#

oh

naive briar
#

But you're right

untold flax
#

wondering how easy (or complicated) will it be to shard a discord bot across multiple hosts
i.e. instead of being sharded on one machine, it will sharded across multiple ones

sweet steeple
#

It's still not looping through the dictionary until it's printed all the objects, though

#

It's only printing the first one

slate swan
sweet steeple
#

@slate swan hey man can you help me out w this for asec

#

how would isolate AdChannelID's key?

slate swan
#

you want to access this key?

untold flax
blissful lagoon
#

please don't use ableist language

untold flax
slate swan
sweet steeple
#

well python has flipped everything i knew upside down

#

so

sweet steeple
untold flax
untold flax
slate swan
#

ah clusters ducky_sus

glad cradle
#

mhm, I'm not that expert in that camp since I haven't ever tried it since I didn't need it, but I have a guide written by someone that I know, so I could share

#

I mean cluster a bot is something that you do when you reach a considerable amount of guilds and users

main holly
#

is from discord import app_commands for application commands

main holly
glad cradle
untold flax
slate swan
glad cradle
spring summit
#

AttributeError: module 'datetime' has no attribute 'now'

glad cradle
#

the docker thing and github action thing are to deploy the Bot

glad cradle
untold flax
#

i.e if you send a command then only one responds

glad cradle
#

iirc the library should handle that automatically

#

that's why you pass shards info to the AutoShardedBot class

#

lemme take a look

spring summit
# glad cradle it's datetime.datetime.now so ```py from datetime import datetime datetime.now(...
@client.event
async def on_message_edit(before, after):
    z = client.get_channel(1137779370988154936)
    embed = discord.Embed(title=f"{before.author} Edited Their Message",
                          description=f"Before: {before.content}\nAfter: {after.content}\nAuthor: {before.author.mention}\nLocation: {before.channel.mention}",
                          timestamp=datetime.now(), color=discord.Colour.blue())
    embed.set_author(name=after.author.name, icon_url=after.author.display_avatar)
    await z.send(embed=embed)```
#

from datetime import datetime btw

glad cradle
# glad cradle lemme take a look

ah yeah then basically this runs multiple docker services and the AutoShardedInteractionBot starts and listen only X number of shards (with a given ID which is generated)

slate swan
slate swan
#

!e ```py
from datetime import datetime
datetime.now()

unkempt canyonBOT
#

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

[No output]
slate swan
#

show your imports

#

maybe you have something that overrides it

harsh orbit
#
@bot.command()
@has_permissions(moderate_members=True)
async def timeout(ctx, member: discord.Member, time):
  if "s" in time or "S" in time:
    gettime = time.strip("s")
    if (gettime) > 2419200:
      await ctx.reply("Timeout time cannot be more than 28 days")
    else:
      newtime = datetime.timedelta(seconds=int(gettime))
      await member.edit(timed_out_until=discord.utils.utcnow() + newtime)
    await ctx.reply(member.mention + " Has been timed out")

@timeout.error
async def timeout_error(ctx, error):
   if isinstance(error, commands.MissingPermissions):
     await ctx.reply("**You don't Have permissions to use this command**")

Why the command not working

spring summit
slate swan
spring summit
spring summit
#

there was a thingy bellow

slate swan
slate swan
spring summit
harsh orbit
#

Nothing in console and the bot doesn't make any thing

slate swan
#

you have message_content intent right?

harsh orbit
#

Sure

#

I think I made think wrong in ifs and elifs

slate swan
#

firstly check if it even is called

#

put a print at top of function and see if it prints out

main holly
#

my do slash commands not work

#

why

#

mine

slate swan
harsh orbit
#

@slate swan yup its called

glad cradle
#

@harsh orbit do you have an on_message event?

slate swan
#

then debug it more by checking if the if is true

harsh orbit
slate swan
harsh orbit
#

Thats gonna take a lot of time 😫

slate swan
#

i would start by printing out whats stored under member and time varriables

harsh orbit
#

Ok i will start checking

glad cradle
#

hi down

slate swan
#

um hi

#

didnt we like chat 5 minutes ago

glad cradle
#

mhm

#

yes but I didn't greet you

slate swan
harsh orbit
sweet steeple
#

why wont this define

slate swan
#

What is the actual error?

sweet steeple
#

turns out you need async to have await

slate swan
#

Yeah you do

sweet steeple
#

cant figure out why this keeps erroring tho

#

the key is fine so

slate swan
#

If it would be find it wouldnt error

sick birch
#

Can you print out the patron dict?

slate swan
#

Print out patron and see what is has

sweet steeple
#

holy shit

#

im a dumbass

#

i forgot to save my config file

granite agate
#

is there a way for me to put two strings in this conditional?

sick birch
slate swan
granite agate
#

and Roger Guedes is alredy there

#

but i don't know how to put roger guedes and ribamar at the same time

sweet steeple
#

Trying to send a message from a loop. Anyone know how to fix this?

sick birch
#

I'm guessing the AdChannelID is probably a string

#

you can parse the integer out of it by using int(server["AdChannelID"])

sweet steeple
#

y is this key erroring