#discord-bots

1 messages · Page 206 of 1

fallow mauve
#

DMs work or I can make a forum post thingy

slate swan
#

can u gimme a proper fixed code

#

of that cmd

quick gust
#

I will not spoonfeed you, you must learn on your own

slate swan
#

okay so what i do to fix that

quick gust
#

but I'll make it easier for you, you CAN do guild = ctx.guild

slate swan
quick gust
#

or you can remove that line entirely and replace guild to ctx.guild everywhere in your command

slate swan
#

how to make this script work on bots too, is working only on users (connecting using token)

maiden fable
#

wait, that f string will automatically print log_channel = <log_channel var>?

fallow mauve
velvet compass
unkempt canyonBOT
#

@velvet compass :white_check_mark: Your 3.11 eval job has completed with return code 0.

my_var = 'some value'
maiden fable
#

TIL

velvet compass
#

Thats probably my favorite f-string hack

sick birch
maiden fable
#

Gonna make my life so much easier istg

sick birch
#

It's important that you have Bot literal before the token

quick gust
#

so you can have the my_var = before?

unkempt canyonBOT
#

Hey @sick birch! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discord.com/developers/applications

Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!

sick birch
#

smh

#

@slate swan

slate swan
sick birch
#

No, it doesn't

#

I'm assuming you're good because that's a bot token

slate swan
#

yep

velvet compass
# slate swan depends

It does not depend. If you are automating user actions it is against Discord's ToS and they will obliterate your account

slate swan
#

@velvet compass true

gilded cedar
#

How to make a discord bot send specific channel but on a specific server do you guys any ideas?

sick birch
quick gust
#

I recently reset my bot token and secret, replaced the old token with the new token but the bot isn't responding? I'm not explicitly setting the client secret either so... what am I supposed to do?

gilded cedar
#

yes i have

sick birch
#

!d discord.Client.get_channel

unkempt canyonBOT
#

get_channel(id, /)```
Returns a channel or thread with the given ID.

Changed in version 2.0: `id` parameter is now positional-only.
quick gust
#

enabled

maiden fable
#

in code too?

quick gust
#

yep

maiden fable
#

Processing commands, in case of overriding of on_message?

slate swan
#

still dont work @sick birch

quick gust
#

nope I'm using a listener

slate swan
#

The channel id is correct.

#

shoud i put v9?

quick gust
#

to mention: it was working before I reset the secret and token

sick birch
slate swan
#

how to check errors :)

sick birch
#
r = requests.post(...)
print(r.json())
#

according to the documentation that's a GET method

slate swan
#

yes

#

so i cant use this on bots?

sick birch
#

You're supposed to use this on bots

#

What is the returned error message?

slate swan
sick birch
#

paste the traceback please

#

its too small to read

#

Also what are you trying to do?

#

You're getting the last 50 messages but then ignoring the response

slate swan
#

just send message

#

im just testing :)

#

this is what it does

#

i think i need to rewrite this

#

or?

sick birch
#

it fetches the last 50 messages and returns the result

slate swan
#

so what can i do

sick birch
#

Use the proper endpoint

slate swan
#

i need endpoint?

sick birch
#

Yes

fallow mauve
#

so... how do slash commands work now

#

discord.py is updated since i last used it is it different

slate swan
#

@sick birch but should i remain on v6?

fading wigeon
#

Hey guys I have a problem

fallow mauve
sick birch
fading wigeon
#

I'm actually just starting out, and while following a tutorial, made a small program, but it returns an error.

`
import discord
from discord.ext import commands

TOKEN = "BOT TOKEN"
client = commands.Bot(command_prefix = '.')
#answers with the ms latency
@client.command()
async def ping(ctx):
await ctx.send(f'Pong! {round (client.latency * 1000)}ms ')

client.run(TOKEN)

`

And this is the error:

`
Traceback (most recent call last):
File "C:/Users/alsat/OneDrive/TEJ & SAI/A TEJ/OTHERS/TEMPORARY FILES/temp.py", line 6, in <module>
client = commands.Bot(command_prefix = '.')
TypeError: init() missing 1 required keyword-only argument: 'intents'

`

deep copper
fallow mauve
sick birch
#

np

slate swan
fallow mauve
fading wigeon
fallow mauve
slate swan
#

@sick birch should i use v9?

fading wigeon
fallow mauve
#

in your code do this:

#

from discord import Intents

#

and

#
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix = "!", intents = intents)
slate swan
fallow mauve
peak pilot
#

tp

peak pilot
#

Yo*, my discord bot won’t respond to any commands. Anyone help?

slate swan
#

the limit i guess what can i enter here

slate swan
#

anyone know how to fix

sick birch
slate swan
short ice
#

Hi can someone help me?

white citrus
#

@sick birch I tried that from yesterday, but an await keeps coming up which cannot be executed

sick birch
#

And the get options function should be deleted

short ice
#

@sick birch Can you help me?

#

with me prob

white citrus
sick birch
#

Because the command is asynchronous

white citrus
#

and the options must be created in init

sick birch
#

But do the actual fetching in the command

white citrus
sick birch
#

Yes. Your select class shouldn't do any data fetching

#

Fetch it in the command and pass it down

white citrus
#

And how does the view then get the options?

sick birch
#

Pass it in as parameters

#

The view can then use that and pass it down again to the select

white citrus
#

Create the list in the command or in the view?

sick birch
#

The command, since it's async

#

Command (fetch async data here) -> pass to View -> view passes to select

short ice
#

?

#

can you robin?

#

i don't want to mention you again cause its annoyed .Can you help me with my problem?

steep wedge
#

what are you trying to do with that line of code

#

also i would suggest you delete that screenshot @short ice

white citrus
# sick birch Command (fetch async data here) -> pass to View -> view passes to select
    @warn.subcommand(name="edit-by-user")
    async def warn_edit_by_user(self, inter: nc.Interaction,
                            member: nc.Member = SlashOption(name="member", description="Please select a member", required=True)):
            
        
        async with aiosqlite.connect("maja.db") as db:
            async with db.cursor() as cursor:
                await cursor.execute('SELECT case_id FROM warning_system WHERE user_id, guild_id = ?, ?', (member.id, nc.Interaction.guild.id,))
                cases = await cursor.fetchall()
                options = []
                for case_id in cases:
                    await cursor.execute('SELECT reason FROM warning_system WHERE case_id, guild_id = ?, ?', (case_id, nc.Interaction.guild.id,))
                    reason = await cursor.fetchone()
                    new_option = nc.SelectOption(label=str(case_id), description=reason[0])
                    options.append(new_option)
        
        
                  
            dropdown = EditWarnDropdown(member, options)
            await inter.response.send_message(content="hi", view=dropdown)```
#

@sick birch is this now right?

hushed galleon
#

you wrote an extra m in has_permmissions

short ice
#

wait

short ice
#

but when i use the command clear it shows me that

white citrus
#

@hushed galleon do you know the issue from yesterday?

hushed galleon
hushed galleon
white citrus
# hushed galleon well it seems you're at least kind of getting the idea right now

i found a solution with robin but now i got a error. I think i forgot something but i dont know what

here is the error

Traceback (most recent call last):
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 489, in _run_event
    await coro(*args, **kwargs)
  File "c:\Discord\Maja Projekt\MajaSystem_Test\bot.py", line 296, in on_application_command_error
    raise error
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\application_command.py", line 888, in invoke_callback_with_hooks
    await self(interaction, *args, **kwargs)
  File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\user_moderation\cog.py", line 840, in warn_edit_by_user
    dropdown = EditWarnDropdown(member, options)
TypeError: EditWarnDropdown.__init__() takes 2 positional arguments but 3 were given```
short ice
#

wait

thin raft
short ice
#

there?

thin raft
#

here

short ice
thin raft
#

you need to load it

rare echo
#

that is the main file?

thin raft
#

and you need to pass a bot object not a client object

#

you should rename client to bot*

short ice
#

ok wait

#

still

rare echo
#

why is it in a class?

#

at that point you might as well make cog

thin raft
#

!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 "(in Python v3.11)").
short ice
mild zephyr
# short ice

why using normal commands? slash are much more effective and easier to use

thin raft
#

I would make hybrid commands

short ice
thin raft
mild zephyr
short ice
mild zephyr
#

you can do text commands, slash command, user command, and message commands

short ice
#

ok ty

#

what do i put there

cloud dawn
rare echo
#

i believe in you panda

unkempt canyonBOT
#
`if __name__ == '__main__'`

This is a statement that is only true if the module (your source code) it appears in is being run directly, as opposed to being imported into another module. When you run your module, the __name__ special variable is automatically set to the string '__main__'. Conversely, when you import that same module into a different one, and run that, __name__ is instead set to the filename of your module minus the .py extension.

Example

# foo.py

print('spam')

if __name__ == '__main__':
    print('eggs')

If you run the above module foo.py directly, both 'spam'and 'eggs' will be printed. Now consider this next example:

# bar.py

import foo

If you run this module named bar.py, it will execute the code in foo.py. First it will print 'spam', and then the if statement will fail, because __name__ will now be the string 'foo'.

Why would I do this?

• Your module is a library, but also has a special case where it can be run directly
• Your module is a library and you want to safeguard it against people running it directly (like what pip does)
• Your module is the main program, but has unit tests and the testing framework works by importing your module, and you want to avoid having your main code run during the test

short ice
cloud dawn
short ice
#

.

mild zephyr
#
@commands.slash_command(name="command name", description="description of what the command show tell")
async def foo(inter: disnake.CommandInteraction,'''your args'''):
    '''your logic'''

this is a simple command

short ice
#

yy

cloud dawn
#

slash_command sweating

mild zephyr
#

if you want better options, without having to use specific stuffs

you can add the "option" param in the command and use a list of "disnake.Option"

cloud dawn
#

Phew Disnake, my heart dropped for a sec.

mild zephyr
#

disnake is times better than discord.py, plsu who knows maybe danny decides again to drop the lib

#

i prefer a stable one

cloud dawn
mild zephyr
#

i mean yeah x3

#

i still prefer disnake, kinda know that tomorrow i wont see a message about "Deprecating the library"

river plank
#

So I kindoff have a dynamic inventory code I wanted to integrate into discord.py, don't exactly know how

#
for x in PlayerDetails["Inventory"]: print("[",PlayerDetails["Inventory"].index(x)+1,"]",".","[",x[0],"]")
#

Just didn't know where to start

#

How would I exactly put all the details into the description of 1 embed

white citrus
#

The button should be under the dropdown

#

how can i fix that

winged notch
#

Traceback (most recent call last):
File "/Users/balthazar/Desktop/PandaBot.py/main.py", line 4, in <module>
bot = commands.Bot(command_prefix = "!",
TypeError: init() missing 1 required keyword-only argument: 'intents'

#

why ?

#

pls

#

i'm a beginer

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.

glad cradle
winged notch
glad cradle
#

I'm not talking with you

winged notch
#

sorry

glad cradle
winged notch
#

thanks

white citrus
winged notch
#

Traceback (most recent call last):
File "/Users/balthazar/Desktop/PandaBot.py/main.py", line 3, in <module>
intents = Intents.default()
NameError: name 'Intents' is not defined

white citrus
#

Why are you copying code you don't understand

winged notch
#

i dont know

peak pilot
#
import random

def handle_response(message) -> str:
    p_message = message.lower()

    if p_message == 'what is paradrift':
        return 'paradrift is a fun sporty game, available on steam & developed mainly by nomaden#940'

    if p_message == 'roll':
        return str(random.randint(1, 6))

    if p_message == 'help':
        return "`How may I assist you?´"
#

why wont my bot respond

thin raft
#

why would it

peak pilot
#

only in responses

#

im new 2 coding idk :(

fallow mauve
#

is there a way to make a bot copy text to the users clipboard through a command

thin raft
#

and then start with dpy

fallow mauve
peak pilot
#

alr alr alr ill watch all the way through some day, cuz that i did not do

slate swan
#

if so:

...

description = ", ".join(PlayerDetails["Inventory"])

embed = Embed(description=description)
...``` something like this will work
glad cradle
# white citrus nextcord

you need to modify the row of these components, iirc you can supply that kwarg on the respective object component instantiation, though it depends on the library and actually I haven't used that much nextcord but I know for sure this

slate swan
#

i work with nextcord and to every Item you can provide row argument

glad cradle
#

pretty similar to @lament depot bookmark command

slate swan
#

.src bm

#

hm

sick birch
#

.src bookmark

lament depotBOT
#
Command: bookmark

Teach the invoker how to use the new context-menu based command for a smooth migration.

Source Code
glad cradle
slate swan
glad cradle
#

oh replaced with a new thing

sick birch
#

I have an open PR to bring it back though

steep wedge
#

!d format strings

slate swan
steep wedge
#

nevermind

slate swan
unkempt canyonBOT
#
Format-strings

Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.

>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."

Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.

steep wedge
terse coyote
#

I have a code

file = discord.File(file_path, filename=os.path.basename(file_path))
embed = discord.Embed(
        color=embed_color
    )
    embed.set_image(url=f"attachment://{image_file_path}")
await interaction.followup.send(embed=embed, file=file)

but the bot sends photos and embeds separately

slate swan
wanton pebble
#

how can i wait for a wait for reaction? lol

fading marlin
#

!d discord.Client.wait_for

unkempt canyonBOT
#

wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.11)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.11)") for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.11)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
fading marlin
#

there's an example in the docs

wanton pebble
#

thank you

smoky sinew
#

hello guys

fading marlin
#

hi

wanton pebble
fading marlin
#

what are you looking for exactly?

smoky sinew
#
await bot.wait_for("reaction_add", check = ...)
wanton pebble
#

i used wait for but i make it send a message the line after

but it'll send that message reaction or none
i want it to wait for a reaction before sending ;-;

fading marlin
#

that's what wait_for does

wanton pebble
#

it sends the message without one tho-

fading marlin
#

could you send your code?

wanton pebble
#

sure one sec

wanton pebble
# fading marlin could you send your code?
          def check(reaction, user):
            return message.id==reaction.message.id
          try:
            reaction, user = await bot.wait_for('reaction_add', timeout=60.0, check=check)

          except asyncio.TimeoutError:
            pass
          
          if reactedTimes==0:
            msg_sent=await message.channel.send("Loading")
smoky sinew
slate swan
#

why does datetime always give me issues 😦
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'

tried both of these

import datetime
from datetime import datetime
smoky sinew
#

you only need one @slate swan

#

those are conflicting

wanton pebble
#

ahhh

#

def check has the same indentation as try

smoky sinew
#

it should

wanton pebble
#

it does but still sends without reaction ;-;

smoky sinew
#

what do you mean "sends without reaction"?

wanton pebble
#

like it sends the last line (a message) without any reactions on the message

#

it dosent actually wait for a reaction ;-;

smoky sinew
#

on_reaction_add does not send a message, it returns a reaction and a user

#

oh nvm

#

i'm not sure

wanton pebble
wanton pebble
thin raft
#

Invalid permissions given to keyword arguments.

#
                channel: discord.VoiceChannel = await self.create_channel(member)

                permissions = channel.overwrites_for(member)
                permissions.manage_permissions = True

                await channel.set_permissions(
                    member,
                    permissions = permissions
                )```
#

how can I do it then?

slate swan
#

why would you provide a permission overwrite obj to permissions

thin raft
#

I sent it wrong

slate swan
#

just use channel.edit and use permission_overwrites kwarg

thin raft
#

I was just trying some permissions and sent that one, but I can't also use connect permission, mnanage_channel etc

thin raft
#

!d discord.VoiceChannel.edit

unkempt canyonBOT
#

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

Edits the channel.

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

Changed in version 1.3: The `overwrites` keyword-only parameter was added.

Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead.

Changed in version 2.0: The `region` parameter now accepts [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)") instead of an enum...
thin raft
#

in this way, how could I make it for a single user?

slate swan
#

overwrites are per user/role

#

the passed object for that kwarg should be like this ```py
{ member1: PermissionOverwrite, member2: PermissionOverwrite}

#

!d discord.PermissionOverwrite i think there's an example here

unkempt canyonBOT
#

class discord.PermissionOverwrite(**kwargs)```
A type that is used to represent a channel specific permission.

Unlike a regular [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions"), the default value of a permission is equivalent to `None` and not `False`. Setting a value to `False` is **explicitly** denying that permission, while setting a value to `True` is **explicitly** allowing that permission.

The values supported by this are the same as [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions") with the added possibility of it being set to `None`.

x == y Checks if two overwrites are equal.

x != y Checks if two overwrites are not equal.

iter(x) Returns an iterator of `(perm, value)` pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.
thin raft
#

yeah I am there
let me test it

#

the member ahs permissions for managing but can't manage

wanton pebble
burnt imp
#

Code: py if before.user != before.after: print("Username change")
Error:py AttributeError: 'User' object has no attribute 'user'

naive briar
#

Read the error

burnt imp
#

Yeah I know

#

What do I use to see a username update

burnt imp
#

ah

smoky sinew
#

before and after are both users

sage finch
#

how do I start coding

burnt imp
#

ah I see it now

smoky sinew
unkempt canyonBOT
#
Resources

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

smoky sinew
#

but only if you're somewhat familiar with python

sage finch
#

I don’t get it

#

I’m sped lmao

#

can someone code a server for me? Or is that not possible

smoky sinew
sage finch
#

like members in a discord server

smoky sinew
#

?

#

a discord bot?

sage finch
#

yeah

smoky sinew
#

what do you want it to do

sage finch
#

give me free members

#

or is that not possible ?

#

if not can u give nitro bot

smoky sinew
#

sorry we don't do that here

sage finch
#

wym

#

oh

#

dangit

#

well cns u help me and walk me through how to code

smoky sinew
sage finch
#

oh

#

what else bot can you do

smoky sinew
#

i'm sure you know that

sage finch
#

what other bot can u do ?

smoky sinew
#

i won't code a bot for you, if you have questions or an error with an existing bot ask your question here

#

this is for discord bot help and discussion

sage finch
#

oh ok

slate swan
#

what should i add to my discord bot

smoky sinew
#

surely there's a better way to do that...

fading wigeon
#

While following a tutorial, I wrote the code for a basic discord bot
`
import discord

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

client = discord.Client(intents=intents)

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

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

if message.content.startswith('$hello'):
    await message.channel.send('Hello!')

client.run("my token")

smoky sinew
scarlet aurora
fading wigeon
#

[2023-03-02 05:53:42] [INFO ] discord.client: logging in using static token Traceback (most recent call last): File "C:\Users\alsat\OneDrive\TEJ & SAI\A TEJ\OTHERS\TEMPORARY FILES\temp.py", line 22, in <module> client.run("my token") File "C:\Users\alsat\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 860, in run asyncio.run(runner()) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\asyncio\runners.py", line 44, in run return loop.run_until_complete(main) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 647, in run_until_complete return future.result() File "C:\Users\alsat\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 849, in runner await self.start(token, reconnect=reconnect) File "C:\Users\alsat\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 778, in start await self.connect(reconnect=reconnect) File "C:\Users\alsat\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 704, in connect raise PrivilegedIntentsRequired(exc.shard_id) from None discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.

smoky sinew
smoky sinew
sick birch
# fading wigeon How do it do that?

discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.

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.

smoky sinew
#

people don't read error messages anymore they expect the helpers to read for them

fading wigeon
smoky sinew
sick birch
#

You don't really need to know what it means

smoky sinew
#

this is pretty clearly telling what to do

sick birch
#

Just follow the steps outlined in the error message

scarlet aurora
#

nvm I figured out my problem

scarlet aurora
sick birch
#

Privledged intents are these btw @fading wigeon

sick birch
smoky sinew
#

if you're trying to make reaction roles, just make a message-role map

#
messages = {
    message_id: role
}
#

then, when someone reacts to that message give or take away the role

#

this pretty much cuts down your actual reaction code by half

scarlet aurora
#

ah

#

I see can you redirect me to this module

#

or a tutorialk

slate swan
#

i just learned theres discord menus as an alternative for buttons ;.;... is one better than the other?

fast musk
#

menus?

smoky sinew
#

menus only supports reactions as far as i'm aware

fast musk
#

oh, they mean that ext.menus package

#

meh

smoky sinew
#

menus is a helper extension to make reaction menus but it's pretty much obsolete

slate swan
#

gotcha

fast musk
#

Danny did say they were going to work on Pages which is essentially that, but with views

smoky sinew
#

@slate swan are you making a paginator?

fast musk
#

no eta though. It's easy to roll your own though

smoky sinew
#

it uses buttons

#

it's easy to add your own code on top of it

slate swan
# smoky sinew it's easy to add your own code on top of it

I will probably use it as an example 🙂 ty. someone gave me their paginator w/ that used disnake and a bunch of other stuff a few months ago and i still haven't fully understood it 😄 so i've just pushed it off till i finished my mimo coding lessons.
this is very nicely done though.

smoky sinew
#

thank you

graceful ermine
#

How could I detect a custom status?

Hey, I'm trying to make it so that if a user runs !statuscheck it tells them their custom status how could I code that?
and if the keyword is set to "A" they get a role!

slate swan
#

Checking before.activity and after.activity.
If you’re doing something for games, or streaming, you need to look for those values specifically and some users don’t have it work right for streaming so I just made a twitch parser with the connections from oauth2

smoky sinew
#

custom statuses are not really activities

frosty parrot
#

is it wrong ?

naive briar
#

Can

dull terrace
#

would the calculation change if i removed the outermost brackets? base_xp *= ((cfg.xp.dig_down + cfg.xp.dig_side) / 2)

naive briar
#

Do you know what decorators are

naive briar
dull terrace
#

!e

x = 2
x *= ((10 + 10) / 2)
print(x)
x = 2
x *= (10 + 10) / 2
print(x)
unkempt canyonBOT
#

@dull terrace :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 20.0
002 | 20.0
unkempt mauve
#

where can I get full information on interaction.guild? like how to get its name, members count, owner, roles count, etc

naive briar
#

Read the docs

#

!d discord.Guild

unkempt canyonBOT
#

class discord.Guild```
Represents a Discord guild.

This is referred to as a “server” in the official Discord UI.

x == y Checks if two guilds are equal.

x != y Checks if two guilds are not equal.

hash(x) Returns the guild’s hash.

str(x) Returns the guild’s name.
unkempt mauve
naive briar
#

discord.Interaction.guild returns discord.Guild

smoky sinew
#

that's not a thing

#

well, not capital guild anyway

unkempt mauve
#

discord.app_commands.errors.CommandInvokeError: Command 'server' raised an exception: TypeError: object of type 'property' has no len()

smoky sinew
#

you are trying to use len() on a property

unkempt mauve
smoky sinew
#

can you show your code

#

i can't help like this

unkempt mauve
naive briar
#

Do you know OOP

smoky sinew
#

what catlover said, it needs to be interaction.guild

#

also you should use 4 spaces or a tab as indentation not 2 spaces

unkempt mauve
naive briar
#

No, just try it

unkempt mauve
#

I did already

smoky sinew
#

len(discord.Guild.text_channels) does not work

unkempt mauve
#

then how do I get the count

naive briar
#

Get it from an instance

#

You should at least know what instances are before trying discord.py

unkempt mauve
#

am I dumb or smth. I havent put the line await interaction.response.send_message

#

finally

#

interaction.guild worked

#

Can anyone send me the docs that explains how to make the bot send time like this: <t:1677730495:f>

naive briar
#

!d discord.utils.format_dt

unkempt canyonBOT
#

discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.11)") for presentation within Discord.

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

oh

#

ok\

#
Inventory = [["Heasing",50,"Common"],["Heasing2",30,"Rare"]]
for x in Inventory: 
print("[",Inventory.index(x)+1,"]",".","[",x[0],"]")
#

@slate swan^

slate swan
#

This is really messy

#

You should look into

#

!fstrings

unkempt canyonBOT
#
Format-strings

Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.

>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."

Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.

slate swan
#

!d enumerate

unkempt canyonBOT
#

enumerate(iterable, start=0)```
Return an enumerate object. *iterable* must be a sequence, an [iterator](https://docs.python.org/3/glossary.html#term-iterator), or some other object which supports iteration. The [`__next__()`](https://docs.python.org/3/library/stdtypes.html#iterator.__next__ "iterator.__next__") method of the iterator returned by [`enumerate()`](https://docs.python.org/3/library/functions.html#enumerate "enumerate") returns a tuple containing a count (from *start* which defaults to 0) and the values obtained from iterating over *iterable*.

```py
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
```  Equivalent to...
river plank
#

oh

slate swan
#

For example

#

!e ```py
values = [10, 30, True, "something"]

for i, item in enumerate(values, start=1):
print(i, item)

unkempt canyonBOT
#

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

001 | 1 10
002 | 2 30
003 | 3 True
004 | 4 something
river plank
#

ooo

#

but like how would you use this in description

#

you cant use for loops in f'{}'

#

or atleast from what i tried

naive briar
unkempt canyonBOT
#

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

[0, 1, 1024, 59049, 1048576, 9765625, 60466176, 282475249, 1073741824, 3486784401]
slate swan
#

well you kinda can but if you dont know how you can still do something Like this :

desc = ""

for item in something:
    desc += item
#

!listcomp

unkempt canyonBOT
#
List comprehensions

Do you ever find yourself writing something like this?

>>> squares = []
>>> for n in range(5):
...    squares.append(n ** 2)
[0, 1, 4, 9, 16]

Using list comprehensions can make this both shorter and more readable. As a list comprehension, the same code would look like this:

>>> [n ** 2 for n in range(5)]
[0, 1, 4, 9, 16]

List comprehensions also get an if clause:

>>> [n ** 2 for n in range(5) if n % 2 == 0]
[0, 4, 16]

For more info, see this pythonforbeginners.com post.

slate swan
#

When uses with

#

!d str.join

unkempt canyonBOT
#

str.join(iterable)```
Return a string which is the concatenation of the strings in *iterable*. A [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") will be raised if there are any non-string values in *iterable*, including [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") objects. The separator between elements is the string providing this method.
slate swan
#

You can do description for loop in your code

karmic nimbus
#

how do i change my bot status to playing?

vocal snow
#

!d discord.Client.change_presence

unkempt canyonBOT
#

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

Changes the client’s presence.

Example

```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
```   Changed in version 2.0: Removed the `afk` keyword-only parameter...
static holly
frosty parrot
#
@app_commands.checks.has_permissions(manage_messages=True)
@app_commands.checks.bot_has_permissions(manage_messages=True)
async def clear(interaction:discord.Interaction, amount: int):
    await interaction.response.defer(
        thinking=True,
        ephemeral=True
        )
    await interaction.channel.purge(limit=amount)
    await interaction.followup.send(
        f"deleted {amount} messeges",
        delete_after=5
    )
@clear.error
async def on_error(interaction:discord.interactions, error:commands.CommandError):
    if isinstance(error, app_commands.MissingPermissions):
        await interaction.response.send_message(
            "You don't have permission to use this command.",
            ephemeral=True
            )

    elif isinstance(error, app_commands.BotMissingPermissions):
        await interaction.response.send_message(
            "I don't have permission to manage messages. You can give me the required permissions in the server settings.",
            delete_after=10
        )```
why the bot still showing "The application did not respond"
river plank
woeful magnet
#

Can anybody tell me how to check if message.author is server owner?

languid lark
#

hey guys, does anyone know how to make them commands with the multiple options

#

not the dropdown menus

#

like this^^

slate swan
#

it's a slash command option and it depends on what library you use

naive briar
#

Autocomplete also

frosty parrot
#

can anyone help me ?

slate swan
woeful magnet
#

I wanna send message through bot to other users and message I sent must be displayed in DMs between bot and other users. what can I do for that?

slate swan
#

The application did not respond could be caused by bot not responding in 3 sefonds

#

If your bot takes more than 3 seconds to respond you can usw

frosty parrot
#
        thinking=True,
        ephemeral=True
        )```
naive briar
#

Do you know how to use it through?

#

You still need to respond to it

#

!d discord.Interaction.followup

unkempt canyonBOT
frosty parrot
#

like ?

slate swan
slate swan
frosty parrot
#
        f"deleted {amount} messeges",
        delete_after=5
    )```
#

@naive briar

shrewd apex
frosty parrot
#

yeah I know but I like it

#

is it the problem ?

slate swan
frosty parrot
#

but the bot isn't showing thingking

slate swan
frosty parrot
#

ok

#

same

woeful magnet
slate swan
#

You need to get user you want to message

#

And use .send on it

#

With message you want to send

drifting arrow
#

How do I limit a slash command to 1 guild?

naive briar
#

Sync it to only 1 guild

drifting arrow
#

oh

#

Is this done on load?

slate swan
#

umm is it possible to be friends with your own bot?

#

like i wanted to add it to a group dm to show someone something.

#

but it doesn't let me add them by default

#

not possible

#

ah

#

bots can only be added to Guilds

#

gotcha

unkempt mauve
#

What does discord.Interaction.user.status do?

golden portal
unkempt canyonBOT
#

property status```
The member’s overall status. If the value is unknown, then it will be a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)") instead.
unkempt mauve
golden portal
unkempt mauve
#

I am dnd

golden portal
#

either that user is invisible, offline, or you just dont have presence intents to see it

unkempt mauve
#

not off

unkempt mauve
golden portal
#

presences

#

its privilege

#

!d discord.Intents.presences

unkempt canyonBOT
#

Whether guild presence related events are enabled.

This corresponds to the following events:

on_presence_update()

This also corresponds to the following attributes and classes in terms of cache...

unkempt mauve
golden portal
#

banner iirc require you to fetch the user

#

!d discord.Client.fetch_user

unkempt canyonBOT
#

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

Retrieves a [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") based on their ID. You do not have to share any guilds with the user to get this information, however many operations do require that you do.

Note

This method is an API call. If you have [`discord.Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") and member cache enabled, consider [`get_user()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.get_user "discord.Client.get_user") instead.

Changed in version 2.0: `user_id` parameter is now positional-only.
naive briar
#

Read the error

#

For once

unkempt mauve
#

TypeError: Client.fetch_user() got some positional-only arguments passed as keyword arguments: 'user_id'

#

I tried fixing it before I would ask for help

naive briar
unkempt mauve
#

~~[<Role id=1062301004663623750 name='@everyone'>, <Role id=1062346664385466438 name='Blue'>, <Role id=1062312865798815804 name='👑• Siam Official'>]

How do I turn this mess into role mention s~~

Fixed

drifting arrow
#

@naive briar Hey me again. U available?

#

Either way I'll ask my question and anybody can answer 🙂

#

so I have a series of slash commands, I want to make some of them available everywhere my bot is and some only usable by me in my discordserver.
How would I do that? do I need a specific decorator?

woeful magnet
#

hello why do I have this kind of error?
if message.author.id == message.guild.owner_id:
^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'owner_id'

slate swan
#

is django good?

drifting arrow
slate swan
#

Why is discord py's ui soo bad?

#

Like it cant differentiate two members.

drifting arrow
#

?

#

What do you mean?

slate swan
#

Ill explain

drifting arrow
#

Share some code examples perhaps?

rugged shadow
#

dpy doesn't handle ui

slate swan
#

...

drifting arrow
#

Do you mean with buttons and interactions and stuff?

slate swan
#

yes

drifting arrow
#

In the class, add a discord_user_id variable.
When you need to call the class, you set the discord_user_id to the user who called the button and do a simple if interaction.user.id == discord_user_id

slate swan
#

Alr so here's the overview of what i did:

When a member joins, a private channel is made for them. Inside that private channel, there is a embed message with buttons.
So here's where it fails .. When two members interacts with the buttons, one of them will get a response while the other gets nothing. I even made a custom event just to goddamn get this right but nope, it failed.

naive briar
#

Show the code

slate swan
#
import discord

class Gender(discord.ui.View):
    def __init__(self) -> None:
        super().__init__()

    @discord.ui.button(label="Boy", style=discord.ButtonStyle.blurple)
    async def b(self, it: discord.Interaction, button: discord.ui.Button):
        self.gender = "boy"

        member = it.user
        guild = it.guild

        role = discord.utils.get(member.guild.roles, name="Boy")

        if role:
            await member.add_roles(role)
        else:
            role = await guild.create_role(name="Boy", color=discord.Colour.blue())
    
            await member.add_roles(role)
        await it.response.defer()
        it.client.dispatch(member.name, it, "boy")

        self.stop()
    @discord.ui.button(label="Girl", style=discord.ButtonStyle.red)
    async def g(self, it: discord.Interaction, button: discord.ui.Button):
        self.gender = "girl"

        member = it.user
        guild = it.guild

        role = discord.utils.get(member.guild.roles, name="Girl")

        if role:
            await member.add_roles(role)
        else:
            role = await guild.create_role(name="Girl", color=discord.Colour.red())
            await member.add_roles(role)
        
        await it.response.defer()
        it.client.dispatch("button_click", member, "girl")

        self.stop()
#

oh is self.stop() the issue?

drifting arrow
#

no

#

If you only want to limit it to the specific user

slate swan
#

oops i forgot something

naive briar
#

You're stopping discord.py from listening to the view

#

So it's not handling any interaction from that view after that

slate swan
drifting arrow
# slate swan oops i forgot something

Try this:

import discord
from discord.ext import commands
from discord.utils import get
from discord import app_commands


class TEST(commands.Cog):
    def __init__(self, client):
        print("[Cog] TEST has been initiated")
        self.client = client

    @app_commands.command(name="test")
    @app_commands.guild_only()
    async def test(self, interaction: discord.Interaction):
        mybuttons = Buttons()
        mybuttons.discord_user_id = interaction.user.id
        await interaction.response.send_message("Click!", view=mybuttons)


class Buttons(discord.ui.View):
    def __init__(self):
        super().__init__()
        self.discord_user_id = 0

    # Possible Bug: Seems like this is used nowhere
    # noinspection PyUnusedLocal
    @discord.ui.button(label="Accept", style=discord.ButtonStyle.green)
    async def Accept(self, interaction: discord.Interaction, button: discord.ui.Button):
        if self.discord_user_id == interaction.user.id:
            await interaction.response.send_message("Pressed button", ephemeral=True)


async def setup(client):
    await client.add_cog(TEST(client))

``` I havent tested but I assume it works.
slate swan
#

But im creating more.

drifting arrow
#

woops

#

XD copied and pasted code to make it faster

slate swan
#
TypeError: Guild.create_text_channel() missing 1 required positional argument: 'self'

**i am getting this error pls help me to fix it **

#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

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

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

naive briar
#

!e

class Cat:
    def __init__(self):
        pass

    def meow(self):
        pass

Cat.meow()
unkempt canyonBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 8, in <module>
003 | TypeError: Cat.meow() missing 1 required positional argument: 'self'
thin trout
#

how can i create a permission for a command that works with a specific role?

slate swan
#

!d discord.ext.commands.has_role

unkempt canyonBOT
#

@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.

If a string is specified, you must give the exact name of the role, including caps and spelling.

If an integer is specified, you must give the exact snowflake ID of the role.

If the message is invoked in a private message context then the check will return `False`.

This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").

Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
slate swan
drifting arrow
#

How many discord servers can my discordbot be in before I have to convert all my text commands to slash commands?

unkempt mauve
#

I am trying to make a message cmd that will sync my slash cmds. but when I type the cmd, it doesnt responds. nor it does sync. I do have intents.message_content = True. there's a another message cmd in the on_message and it responds but the syncing one inside the same on_message event does nothing

slate swan
#

which you are need to get verified for after 100 servers ( you can apply after 76 servers )

drifting arrow
#

Neato

unkempt mauve
#
from discord.ext import commands

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

  @commands.Cog.listener()
  async def on_ready(self):
    print('Command sync loaded!')
  @commands.command()
  async def sync(ctx, self) -> None:
    if ctx.author.id == 696623699666665532:
      fmt = await self.bot.tree.sync()
      await ctx.send(f'Synced {len(fmt)} commands')
      print('Command successful')
    else:
      return

async def setup(bot):
  await bot.add_cog(SyncingCog(bot))```
whats wrong with this? the issue is its not responding anything
slate swan
#

you need to add this extenstion (Cog) in your main bot file

#

!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 "(in Python v3.11)").
unkempt mauve
#

I did it already

#

its only adding the slash cmds

slate swan
#

also

#

self must be first argument

#

then context and rest

unkempt mauve
slate swan
slate swan
#
@commands.command()
  async def sync(ctx, self) -> None:
``` in this line
unkempt mauve
#

I did

slate swan
#

does command sync loaded print?

unkempt mauve
slate swan
#

all i can see is that if condition is invalid

#

and in else you return

#

so nothing is done

unkempt mauve
#
from discord.ext import commands

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

  @commands.Cog.listener()
  async def on_ready(self):
    print('Command sync loaded!')
  @commands.command()
  async def sync(self, ctx) -> None:
    if ctx.author.id == 696623699666665532:
      fmt = await self.bot.tree.sync()
      await ctx.send(f'Synced {len(fmt)} commands')
      print('Command successful')
    else:
      await ctx.send('You are not my developer, smh.')

async def setup(bot):
  await bot.add_cog(SyncingCog(bot))``` updated code
#

but no problems solved

quick gust
#

message content intent?

unkempt mauve
naive briar
#

Did you load the extension

unkempt mauve
naive briar
unkempt mauve
#
import discord
import asyncio
import json
import random
from discord.ext import commands
import os
from keep_alive import keep_alive
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
intents.presences = True
bot = commands.Bot(command_prefix='$', intents=intents)```
naive briar
#

Huh

slate swan
#

if you enable all you can just use Intents.all() btw

naive briar
#

Do you have a on_message event

unkempt mauve
slate swan
#

you need to process commands inside

unkempt mauve
#
@bot.event
async def on_message(message):
    if message.channel.id == 1078724782016712805:
        if message.author == bot.user:
            return
        if message.content.startswith(''):
            async with message.channel.typing():
                await asyncio.sleep(2)
                response = random.choice(data)['response']
                await message.reply(response, mention_author=False)
    else:
        return
naive briar
#

Did you call process_commands in it

unkempt mauve
unkempt mauve
#

ok

#

bot has no response

#

bruh I dont want to keep sync on on_ready

naive briar
#

Did you even read something in the link

#

You can just use @bot.listen() instead of @bot.event and the command is working again

#

!d discord.ext.commands.Bot.listen

unkempt canyonBOT
#

@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready")

The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.11)").

Example...
unkempt mauve
#

bot responding

#

fr

#

hey is it possible to load cmds without restarting the bot?

unkempt mauve
#

like I want to make a reload command that reloads all the cmds

#

so that I can sync

cloud dawn
#

Well you'd need a stable base that doesn't require much maintenance then make cogs/groups and load them dynamically. Have the extensions reload using the build-in reload function and re-sync with dev guild. If the bot is public make a separate command/task for updating it globally.

#

You can re-sync the bot 1000 times a day before you get rate-limited and global syncs are much more struct depending on how many commands you have but they generally cap at 1/2 times a day with an added wait time of up to an hour.

#

So ideally you want to do this with git and have a main/ feature branch and do it automatically.

unkempt mauve
#

I already made it

#

while u were typing lol @cloud dawn

#

one question, isnt load and reload same?

naive briar
#

No

drifting arrow
#

🤔

unkempt mauve
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.
unkempt mauve
#

bruh

naive briar
#

You will end up with 2 loaded extension

#

Just use reload

unkempt mauve
#

I made load, unload, reload cmds already. I am thinking to push off reload cmd

naive briar
#

What's the problem

unkempt mauve
#

woah

#

seems awesome! now I dont need to make 2 commands

quick gust
naive briar
#

🤷

#

Probably, I never load anything twice

unkempt mauve
#

while executing the reload cmd

naive briar
#

Read the error

#

You need to load it first before trying to reload it

unkempt mauve
#

breh

#

you said reload will come with two ext

naive briar
#

What??

unkempt mauve
#

nvm

white citrus
#
Traceback (most recent call last):
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\view.py", line 370, in _scheduled_task
    await item.callback(interaction)
  File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\user_moderation\view.py", line 156, in callback
    await inter.response.send_message(view=view)
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\interactions.py", line 866, in send_message
    await adapter.create_interaction_response(
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\webhook\async_.py", line 184, in request
    raise HTTPException(response, data)
nextcord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.0.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).```
#

which code triggers the error?

maiden fable
#

EditWarnDropdown code

white citrus
# maiden fable EditWarnDropdown code
class EditWarnModal(nc.ui.Modal):
    def __init__(self, target, case_id, reason):
        self.target = target
        self.case_id = case_id
        self.reason = reason
        super().__init__(f"Edit Warning {self.case_id} for {self.target}")

        self.reason = nc.ui.TextInput(label="Reason", style=nc.TextInputStyle.paragraph, placeholder="Type here your reason", default_value=self.reason, required=True, max_length=50)

        self.add_item(self.reason)


    async def callback(self, inter: nc.Interaction):
        async with aiosqlite.connect("maja.db") as db:
            async with db.cursor() as cursor:
                    
                current_time = int(time.time())
                await cursor.execute('UPDATE warn_system SET reason = ? AND last_edit_time = ? AND last_edit_by = ? WHERE case_id = ? AND guild_id = ?', (self.reason.value, current_time, inter.user.id, self.case_id, inter.guild.id,))
                await db.commit()
                await inter.response.send_message(content="sucess")```
river plank
#

how could i do this in a simplified form ?:

desc = ""
for x in "stuff":
      desc+=x

like [desc+=x for x in "stuff"]

#

but that doesnt work

short ice
#

hi its says that the code 'server_permisions' has no attribute

white citrus
river plank
#

wait

#

that's it ? 😭

slate swan
#

Both do same thing

river plank
#

i mean

slate swan
#

hi

#

Hello

vale wing
slate swan
#

i need help about my discord bot

river plank
vale wing
#

Yeah that's it then

slate swan
#

there a print hidden code in the script but i can't find it

#

could you help me please ?

#

hidden code

slate swan
#

Interesting

slate swan
shell wing
slate swan
vale wing
slate swan
shell wing
slate swan
vale wing
#

And what kind of output do you get

slate swan
vale wing
slate swan
#

Maybe error

slate swan
shell wing
#

then what does prints ?!

slate swan
#

or exception

short ice
#

can someone help me?

slate swan
#

wait

short ice
shell wing
#

Is it life's truth ? cause maybe god be doing it

slate swan
#

"If you bought this, you get scammed"

#

?

#

i bought bot from someone

shell wing
#

and now u got scammed

slate swan
#

you get scammed 💀

shell wing
#

good

slate swan
slate swan
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

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

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

slate swan
#

Here

shell wing
#

then the dev is a stupid ass who like's to disturb the functionality of the world

slate swan
shell wing
slate swan
#

Nice

vale wing
#

The what

shell wing
#

like booster bot

vale wing
river plank
wicked atlas
slate swan
#

@shell wing do you know how can i find this shitty hidden print isso_gn ?

shell wing
slate swan
slate swan
slate swan
shell wing
wicked atlas
#

Ah

slate swan
#

Yeah

slate swan
slate swan
#

Damn

river plank
#

Damn

river plank
#

bro is wilding

slate swan
#

just tell me how the person can hide it and i will try to find it mates

#

Like seriously

shell wing
#

!rule 5

unkempt canyonBOT
#

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

slate swan
#

ah

vale wing
slate swan
#

bruh

shell wing
#

im not even gonna try seeing other channels than this one.

slate swan
#

If u cant provide code how will we tell you what to do

shell wing
#

too much knowledge for me atm when im trying to pass my 12th

slate swan
shell wing
slate swan
unkempt canyonBOT
#

7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.

vale wing
#

!e py import io;_ы_ы_ы_=print;_ы_=sorted;__ы=lambda ь:1;_ы__=str.join;_=chr;__=ord;ы=io.StringIO();_ы_ы_ы_(_ы__("",_ы_([_(__(_(__(____)))) for ____ in "amogus is sus"],key=__ы)),file=ы);print(ы.getvalue())

shell wing
vale wing
#

Sorry forgor

slate swan
#

Here you go

unkempt canyonBOT
#

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

amogus is sus
vale wing
#

Actually this has print

shell wing
slate swan
vale wing
#

But we can hide it

slate swan
#

Just raise

shell wing
slate swan
#

ok sorry

#

i asked there

#

i will wait for answer

slate swan
#

Um thats enough

#

I mean if u buyed code go ask from the developer

shell wing
river plank
#

💀

river plank
#

nice

slate swan
#

Its sus

vale wing
#

No print

velvet compass
#

print(ы.getvalue())

slate swan
#

👀

vale wing
#

Now

slate swan
#

Yeah

river plank
#

💀

vale wing
#

!e py import io;_ы_ы_ы_=eval("".join(chr(_ы) for _ы in [112,114,105,110,116]));_ы_=sorted;__ы=lambda ь:1;_ы__=str.join;_=chr;__=ord;ы=io.StringIO();_ы_ы_ы_(_ы__("",_ы_([_(__(_(__(____)))) for ____ in "amogus is sus"],key=__ы)),file=ы);_ы_ы_ы_(ы.getvalue())

unkempt canyonBOT
#

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

amogus is sus
vale wing
#

Ok that's it

shell wing
slate swan
#

Ok its more sus now

river plank
#

👏

velvet compass
#

This does seem to be wildly off topic though

shell wing
#

i mean tf is that

slate swan
#

Pov : that guy left the chat

#

🗿

vale wing
velvet compass
river plank
#

well uh

#

i tried making it so

#

i could use it in a description of a bot

#

cause f'{}' doesnt support normal for x in etccc

#

just wanted to make a smile inventory system work in a embed 😭

vale wing
river plank
#

well

#

something like:
1 H
2 H
3 H
or atleast tht's what i wanna do in the description of the embed

vale wing
#

M that's like

desc = "\n".join(f"{i} {item[0]}" for i, item[0] in enumerate(items, start=1))```
#

This is pretty much readable also

river plank
#

😭

#

thanks

gilded cedar
#

i'm trying to make a command based on account age (example 14 day or lower the bot say no and 14 day or higher should say yes) can y'all send me code template?

unkempt canyonBOT
#

property created_at```
Returns the user’s creation time in UTC.

This is when the user’s Discord account was created.
vale wing
#

For determining age you could use like ```py
from datetime import datetime

age = (datetime.utcnow() - user.created_at).days```

opaque trail
#

anyone here knows telethon and can dm me?

marble nacelle
#

hi, can you help me find an error in the code, everything seems to be correct, but it doesn't work

slate swan
#

and error

#

@marble nacelle send it here not in dms

#

also use discord formatting for code

#

!code

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.

marble nacelle
#

oh sorry

#

I don't know, I'm sorry

slate swan
#

now you know

river plank
#

@vale wingyea just wanted to say thanks for it, it works with a bit more tweaking!

slate swan
#

Nice

river plank
#

yea it was pretty simple, my ass did not understand

slate swan
river plank
#

thanks to down too

slate swan
#

How do u disable a button in discord py?

#

For a specific user/role *

#

you cant disable a button for a group of users so they cant click it, you only can disable a button globally or enable globally although you can check in code if user that clicked a button has permissions to click it

bitter sonnet
#

PS C:\VSC - Coding> & C:/Python310/python.exe "c:/VSC - Coding/Izu-Discord/main.py"
Traceback (most recent call last):
File "c:\VSC - Coding\Izu-Discord\main.py", line 3, in <module>
from discord_slash import SlashCommand, SlashContext
ModuleNotFoundError: No module named 'discord_slash'

But I installed discord_slash commands...

vale wing
vale wing
#

I strongly recommend to use virtual environment as well

#

!venv

unkempt canyonBOT
#
Virtual environments

Virtual environments are isolated Python environments, which make it easier to keep your system clean and manage dependencies. By default, when activated, only libraries and scripts installed in the virtual environment are accessible, preventing cross-project dependency conflicts, and allowing easy isolation of requirements.

To create a new virtual environment, you can use the standard library venv module: python3 -m venv .venv (replace python3 with python or py on Windows)

Then, to activate the new virtual environment:

Windows (PowerShell): .venv\Scripts\Activate.ps1
or (Command Prompt): .venv\Scripts\activate.bat
MacOS / Linux (Bash): source .venv/bin/activate

Packages can then be installed to the virtual environment using pip, as normal.

For more information, take a read of the documentation. If you run code through your editor, check its documentation on how to make it use your virtual environment. For example, see the VSCode or PyCharm docs.

Tools such as poetry and pipenv can manage the creation of virtual environments as well as project dependencies, making packaging and installing your project easier.

Note: When using PowerShell in Windows, you may need to change the execution policy first. This is only required once per user:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
vale wing
# bitter sonnet better?

Btw to remove that invalid distribution warning check your site-packages directory and remove all folders with incomplete names like -ip ~whatever etc.

slate swan
smoky sinew
#

hello

smoky sinew
#

also, you shouldn't use replit for discord bots

#

and i'm pretty sure replit uses poetry not pip

slate swan
slate swan
smoky sinew
#

i already asked that

#

also, are you just copy pasting code from somewhere else

grand warren
#

Hi! I want to get into making discord bots. I've been using auto code for a bit and then I got an old sad computer I can run it on, any suggestions for where to start?

pulsar bridge
#

Any way of using Application Commands with COGs through discord.Client?
Or do I have to use hybrid commands?

languid oxide
#

hey all

#

can anyone share a good video on bot hosting and "writing" on a database?

slate swan
#

!intents

unkempt canyonBOT
#
Using intents in discord.py

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

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

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

from discord import Intents
from discord.ext import commands

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

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

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

smoky sinew
#

hosting on windows is fine but it's not as reliable, unless you use something like windows server

velvet compass
#

We will not assist with an account generator @graceful ermine

graceful ermine
#

Can someone could help me?

I'm trying to make it where after a user changes their status it logs it as a print message

@bot.event
async def on_member_update(before, after):
    if not isinstance(after.activity, discord.CustomActivity):
        return

    if "vvvc" in before.activity.name.lower() and "vvvc" not in after.activity.name.lower():
        duration_hours = calculate_duration_hours(before.activity.created_at)
        log_message = f"{after.display_name} took off 'vvvc' after wearing it for {duration_hours} hours."
        print(log_message)  

def calculate_duration_hours(start_time):
    utc = pytz.utc
    duration_seconds = (datetime.datetime.now(utc) - start_time).total_seconds()
    duration_hours = duration_seconds / 3600
    return round(duration_hours, 2) ```
graceful ermine
smoky sinew
#

bruh

smoky sinew
graceful ermine
slate swan
smoky sinew
#

there's a guide on the python discord website explaining why

slate swan
smoky sinew
#

yes

slate swan
#

nah

smoky sinew
#

💀

slate swan
#

replit is easyer

smoky sinew
#

not really

slate swan
#

iv been doing it for 1 year now i got use to it

#

Who wants to make a replit python discord bot with me?

smoky sinew
#

nobody

#

it's a bad idea

slate swan
smoky sinew
#

anyone think a wakatime command would be fun

silk yacht
#

what are the differences between all the discord api wrappers?

#

I've used pycord since discord.py stopped being developed

#

but it seems discord.py is now back in development, is it better than pycord?

smoky sinew
silk yacht
#

yeah

smoky sinew
#

(hikari)

silk yacht
#

so many options lol

smoky sinew
#

the main ones are discord.py, hikari, pycord, nextcord, and disnake

slate swan
#

Who wants to teach me how to make my first python bot

smoky sinew
slate swan
#

Nope i dont

#

wanna help me with basics tho? im tryna learn

smoky sinew
slate swan
#

Bet

#

@smoky sinew Can you call?

smoky sinew
#

no

#

maybe later

woeful magnet
#

Hello. can anybody teach me code to make my bot access my DMs with others for retrieving data?

smoky sinew
#

if it's some data that has been set by the user you should use a database

woeful magnet
#

When I receive dm from others, I want my bot in my server display that dm in my server.

smoky sinew
#

use an on_message event and check if the message is in a DM

woeful magnet
#

can you check my code if you are available now? I also used on_message event but it didn't catch dm from other users to me.

graceful ermine
#

How could I fix this??

#
@bot.event
async def on_presence_update(before, after):
    if not isinstance(after.activity, discord.CustomActivity):
        return
    
    if before.status != discord.Status.offline and after.status == discord.Status.offline:
        custom_activities = [
            activity for activity in before.activities
            if isinstance(activity, discord.CustomActivity) and "x" in activity.name.lower()
        ]
        if len(custom_activities) > 0:
            custom_activity = custom_activities[0]
            duration = calculate_duration(custom_activity.created_at)
            duration_str = format_duration(duration)
            log_message = f"{before.display_name} went offline after wearing 'x' for {duration_str}."
            log_channel = bot.get_channel(log_channel_id)
            await log_channel.send(log_message)

    if "x" in before.activity.name.lower() and "x" not in after.activity.name.lower():
        duration = calculate_duration(before.activity.created_at)
        duration_str = format_duration(duration)
        log_message = f"{after.display_name} stopped wearing 'x' after wearing it for {duration_str}."
        log_channel = bot.get_channel(log_channel_id)
        await log_channel.send(log_message)

def calculate_duration(start_time):
    duration = datetime.datetime.now(pytz.utc) - start_time
    return duration

def format_duration(duration):
    total_seconds = duration.total_seconds()
    if total_seconds < 60:
        return f"{int(total_seconds)} seconds"
    elif total_seconds < 3600:
        total_minutes = total_seconds / 60
        return f"{int(total_minutes)} minutes"
    elif total_seconds < 86400:
        total_hours = total_seconds / 3600
        return f"{int(total_hours)} hours"
    else:
        total_days = total_seconds / 86400
        return f"{int(total_days)} days"```
smoky sinew
graceful ermine
smoky sinew
#

you don't receive any activity data if you don't enable it

graceful ermine
#

I have it on

#

@smoky sinew

naive briar
#

Did you turn it on in the code?

graceful ermine
#

Yes

smoky sinew
#

why are you using replit

graceful ermine
#

when I debug stuff it gives me false errors

graceful ermine
smoky sinew
#

wdym

gusty flax
austere vale
smoky sinew
#

hi fawn

woeful magnet
#

not watching. just copy dm from log

smoky sinew
#

do you mean retrieve the DM after it has been sent, or when it's sent?

#

how would that look like

woeful magnet
#

retrieve the DM after it has been sent

#

...

smoky sinew
#

what do you mean by dm log

#

though

karmic nimbus
#

I made my bot display member count on a server in game presence, but why the member count don't changed when a new member joins?

@client.event
async def on_ready():
	server = client.get_guild(guild_id)
	playing = discord.Game(f'With {server.member_count} members')
	await client.change_presence(status=discord.Status.idle, activity=playing)
	print('Presence ready')```
shell wing
#

The bot would show the member count that was when the bot started

#

to change the member count as a new user joins, you need to make a loop that checks if a new user has joined or any left after every 10mins or 5 mins

#

cause if you do it every 5s or so, it's gonna spam the API and get ratelimited

shrewd fjord
#

Anyone has the hex code for making embed color transparent?

glad cradle
#

transparent?

#

do you mean the same color as the discord dark mode?

smoky sinew
unkempt canyonBOT
#
Not gonna happen.

No documentation found for the requested symbol.

smoky sinew
#

it’s a 2.2 feature

#

discord.Color.dark_embed @shrewd fjord

shrewd fjord
#

Oh didnt saw

#

Thanks anyway
#2f3136

#

I used this hex code 💀

smoky sinew
light violet
#

how do i make a transcript of the chat

#

in html

grave canopy
#

which library do you suggest for making a telegram bot?

smoky sinew
#

or something like that, i used it once

karmic nimbus
grave canopy
shrewd fjord
shell wing
# karmic nimbus how?
async def on_ready():
    print('whatever you want') #normal print statement 
    client.loop.create_task(status_task())
    

async def status_task():
    while True:
        server = client.get_guild(guild_id)
        await bot.change_presence(
            activity=discord.Activity(
                type=discord.ActivityType.watching,
                name=f'{server.member_count} members'),
            status=discord.Status.online)
        await asyncio.sleep(5) #time in seconds
#

smh like this

naive briar
#

!d discord.ext.tasks.loop

unkempt canyonBOT
#

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

You shouldn't be changing your presence every 5 seconds btw

karmic nimbus
#

ok tysm

shell wing
clear elm
#
@bot.tree.command(name="add", description="Adds a user to the ticket.")
async def add(interaction, member:discord.Member):
  if not interaction.channel.name.startswith('ticket-'):
    await interaction.response.send_message('This is not a ticket channel.', ephemeral=True)
    return
    await interaction.channel.set_permission(interaction.member, view_channel=True, send_messages=True, read_messages=True)
    await interaction.response.send_message(f"{interaction.member.mention} has been added from the ticket.", ephemeral=True)```
no errors, should this work becuase it's currently not?
naive briar
#

What does it even supposed to do