#discord-bots

1 messages · Page 325 of 1

rugged shadow
#

weird, i've never seen anyth like that

drifting arrow
#

Outside allows me to pull the data from the file in the decorators

#

and can still be used inside the commands/functions

rugged shadow
#

why are there two separate configs?

#

configs/json and configs

drifting arrow
#

what would the discordpy equivalent be to this?

if message.referenced_message:
            return
```?
i assume it's checking if the message is a response?
drifting arrow
rugged shadow
#

atp just rewrite the entire thing, lmao

drifting arrow
#

I sorta am lol

#

Im trying to keep the integrity of the original setup so those who have already used it before know how to use it in future

hushed galleon
unkempt canyonBOT
#

The message that this message references. This is only applicable to messages of type MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.

New in version 1.5.

drifting arrow
#

I believe he's trying to ignore messages that are in response to others.

#

Why does this guy insist on always opening a json file with every command

#

especially when they're on_message lol

fast musk
#

I do like to dabble in json when I'm lazy. But it is russian roulette

vale wing
#

Json db isn't even close to programming crimes I committed in past

slate swan
compact timber
#

Hi, does someone here have experience with sending pictures with a discord bot?

brazen raft
#

Ye

compact timber
#

Okay so if you are familiar with Images in Python you should get the following i think:
`testzero = Image.open(r'C:\Downloads\tes2.png')
testone = Image.open(r'C:
\Downloads\test.jpg')

get the correct size
x, y = testone.size

testzero.paste(testone, (0,0,x,y))`

Now i try to send that via await message.channel.send(file=testzero)

and get this Error: " 'JpegImageFile' object has no attribute 'to_dict' "

brazen raft
#

Save the image object into a discord.File:

with io.BytesIO() as img_buf:
    testzero.save(img_buf, format="png")
    img_buf.seek(0)
    await message.channel.send(file=discord.File(img_buf))
#

Discord.py provides a bot class with proper command handling and all. You should use it instead of implementing commands in one big on_message event handler if this is the case

compact timber
compact timber
brazen raft
#

io.BytesIO is a file-like type

#

!d io.BytesIO

unkempt canyonBOT
#

class io.BytesIO(initial_bytes=b'')```
A binary stream using an in-memory bytes buffer. It inherits [`BufferedIOBase`](https://docs.python.org/3/library/io.html#io.BufferedIOBase). The buffer is discarded when the [`close()`](https://docs.python.org/3/library/io.html#io.IOBase.close) method is called.

The optional argument *initial\_bytes* is a [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object) that contains initial data.

[`BytesIO`](https://docs.python.org/3/library/io.html#io.BytesIO) provides or overrides these methods in addition to those from [`BufferedIOBase`](https://docs.python.org/3/library/io.html#io.BufferedIOBase) and [`IOBase`](https://docs.python.org/3/library/io.html#io.IOBase):
compact timber
#

okay thx

west shuttle
#

what do you recommend for an alternative to d.py?

brazen raft
#

What do you seek

compact timber
#

@brazen raft Now it does post something but its that :

😮

brazen raft
#

Give it a file name

#

That might work

compact timber
#

you mean instead of ìmg_buff` ?

#

hm well renaming the untitled file works but how can u make it a working picture before sending it

brazen raft
#

discord.File(img_buf, "lol.png") or whatever

compact timber
#

that works

slate swan
#

!pastebin

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.

compact timber
#

Hm got a new Problem tho. I can do all resizing and pasting now but i have this problem:

#

As you can see, somehow the opacity information gets lost as the satin texture should be slightly tranparent on top of the backround layer

brazen raft
#

jpg don't support transparency

compact timber
#

i use png already

#

also tried tiff format

compact timber
#

ye that was test code

#

i got new

#

thats it

robust fulcrum
#

Guys is there a better and library with more features than discord.py ,I don't see a reason to switch to any other but just wana know

sick birch
#

so not really, no

#

it's not like you can have 110% API coverage

shrewd apex
sick birch
unkempt canyonBOT
#
I'll allow it.

Your reminder will arrive on <t:1701022993:F>!

vale wing
#

Idk if dpy supports it

#

But some forks do

vale wing
#

Like disnake has smart sync and .send() shortcut

hushed galleon
# shrewd apex https://fallendeity.github.io/discord.py-masterclass/views/ <@432643355634171905...
  • at the start, i would show off examples of each component (or at least common ones) so the reader can immediately see what they do and have a rough idea of d.py's syntax
  • i wouldn't consider a BaseView class to be that important since discord.ui.View is already sufficient to directly subclass from, so i would bring up that pattern near the end ("subclassing discord.ui.View works well for most cases, but if you find yourself repeating certain features like error handling, you might find it worthwhile to make a BaseView...")
  • for full sentences in comments, it's worth punctuating them for readability
# to handle errors we first notify the user that an error has occurred and then disable all components``` instead of the above, rewrite it as: ```py
# To handle errors, we will first notify the user that an error
# has occurred and then disable all components.```
#
  • in BaseView._disable_all(), instead of if isinstance(item, discord.ui.Button) or isinstance(item, BaseSelect): which references an undocumented class, i would write if hasattr(item, "disabled"):
  • in "Using our view", i suggest clarifying in between the two examples that while assigning callbacks work fine, d.py conventionally uses the decorator and/or item subclass style for defining callbacks (personally i wouldn't mention monkeypatching at all)
  • i suggest having a separate section for "Persistent Views" after buttons and select menus rather than two sub-sections about "Persistent Buttons" and "Persistent Select Menus", since it's a distinct concept from either components
  • i suggest having a separate section for "Dynamic Items" since they're a distinct concept from buttons and select menus (also this is my first time hearing about their existence, i thought it was still in design hell pithink)
  • there's a "dosent" typo in Modals lemon_glass
  • as per BaseViews, i wouldn't consider BaseModals that important, but both could be discussed together in one section at the end like "Creating Base Classes" or something
shrewd apex
#

mhm ty for the review

shrewd apex
latent harness
#

can i ask questions here even if i loaded with disnake?

shrewd apex
#

yeah

unreal pilot
#

disnake, never heard of that

slate swan
latent harness
shrewd apex
#
commands.Bot(help_command=None...

or

bot.reomve_command("help") # prefix not needed
unreal pilot
shrewd apex
#

its not improvements perse its design differences

unreal pilot
#

ive always been a discord.py user as support has been great for it

slate swan
#

That's the case since its development was resumed

#

disnake is a fork that was created when discord.py was abandoned

unreal pilot
#

ah i see

shrewd apex
#

features ars the same few disnake features i like are

  • context menus (user and message menus) in cogs (decorators)
  • hot cog reloading
  • slash command group decorators (dpy dosent have this they use group cogs)
unreal pilot
#

dpy has context menus

shrewd apex
#

yeah but u cant declare them in cogs

slate swan
#

Not in cogs

shrewd apex
#

like how u would expect to

shrewd apex
unreal pilot
#

creating additional custom cogs for that doesnt seem like too big of an issue

#

solely for context menus

slate swan
#

You don't get it

unreal pilot
#

i dont

slate swan
#

You can't add context menus in cogs like you can create commands in cogs

unreal pilot
#

thats kind of annoying

slate swan
#

Adding context menus in cogs will just do nothing or fail, unlike doing them outside of cogs in your e.g. main.py file

unreal pilot
#

so you'll have to add custom decorators for main.py cogs

#

to get the currently used Cog and therefore enable or disable the context menu

#

which does make your main.py less organized

unkempt canyonBOT
vapid parcel
#
    @commands.hybrid_command(name="impersonate")
    @commands.guild_only()
    async def impersonate(self, ctx, member: discord.Member, *, message):
        """
        Impersonate as another member for fun!

        **Usage:** impersonate [member] [message]

        **Examples:**
        - `impersonate @member drugs are good.`
        """
        accept = await ctx.send(f"Impersonating...", ephemeral=True)

        # Copy member's profile information
        nickname = member.display_name
        avatar_url = member.avatar.url

        # Create a webhook
        webhook = await ctx.channel.create_webhook(name=nickname)

        # Send a message as the webhook
        await webhook.send(
            content=f"{message}",
            username=nickname,
            avatar_url=avatar_url
        )

        # Delete the webhook after sending the message
        await webhook.delete()
        await accept.delete()
#

Can this be against ToS?

#

like privacy?

vale wing
#

Privacy is uh when you access other user's secret data so not the case

vapid parcel
#

Okay :)

#

So we are fine then :)

vale wing
#

But might be copyright

vapid parcel
#

How so?

vale wing
#

Might be that member being pissed

vapid parcel
#

its just copying display name and profile

vale wing
#

But I am not law expert

vapid parcel
#

XD

vale wing
#

In these cases it's best to ask discord themselves

vapid parcel
#

Eh if they complain then that is just a cry baby ig

#

How am i gonna ask discord myself 😭

vale wing
#

Through discord support

vapid parcel
#

They never respond GoofySkull

vale wing
#

Where does this bias come from

#

They respond to my every request

vapid parcel
#

Maybe cuz they have a crush on you

vale wing
#

Within reasonable time

vapid parcel
#

but thats just my thoughts

vale wing
vapid parcel
#

Thats fair

#

fair point..

#

Maybe they wanna steal you?

brazen raft
cunning briar
#
@bot.tree.command(name='ai_ask')  
async def ai_ask(ctx, question : str):
    async with aiohttp.ClientSession() as session:
        response = await session.post(url=API_URL, headers=HEADERS, data={'prompt': f'{question}\\n\n', 'max_tokens': 50})
        result = json.loads(await response.text())['choices'][0]['text']['restarted']
        await ctx.send(result)
``` why it dosent work?
brazen raft
#

I have no idea why, but tip: You can use (await response.json()) instead of json.loads(await response.text())

vapid parcel
#

That would be sad lol

#

even tho it would say BOT by the webhook

final iron
brazen raft
#

Good catch

vapid parcel
#

Can you see how many reports a bot has?

robust fulcrum
rugged shadow
#

you will like disnake then

final iron
#

pycord abstracts all the functionality from the user in the name of simplicity which counterintuitively makes the user experience worse

#

They’ve also displayed their inability to create new concepts and frameworks, and the maintainers steal code without permission or credits

final iron
lavish idol
#

@vapid parcel check dms, thanks ✌️

vapid parcel
lavish idol
final iron
vapid parcel
latent harness
#

anyone know what's wrong here? (using Disnake btw)

latent harness
glad cradle
latent harness
#

btw guys to make bold text in an embed, what do i do?
And what about in this type

naive briar
#

No girls? Okay then

latent harness
latent harness
slate swan
#

Yeah the answer is still the same

latent harness
slate swan
#

Yea try

latent harness
vale wing
latent harness
#

Oohh ok

vale wing
#

Ohoho k

latent harness
#

got it. But any text (including footer and title) can be bold right?

vale wing
#

I just said

latent harness
#

Just by adding asterisk inside the apostrophes?

vale wing
#

Titles and footer do not support markdown

#

Hence you can't make anything bold or cursive or whatever

latent harness
latent harness
vale wing
#

Do you know what markdown is

latent harness
vale wing
#

It is what discord uses for all this bold and cursive stuff

latent harness
#

Ok so i want to add a url thumbnail to an embed. How do i do that?

#

@vale wing do you know how to?

vale wing
#

!d discord.Embed.set_thumbnail

unkempt canyonBOT
#

set_thumbnail(*, url)```
Sets the thumbnail for the embed content.

This function returns the class instance to allow for fluent-style chaining.

Changed in version 1.4: Passing `None` removes the thumbnail.
vale wing
#

Pay attention that url is keyword only

latent harness
#

so does this come in embed = disnake.Embed(...)

#

I'm using disnake btw

#

Pls help

slate swan
latent harness
nova vessel
#
@group.command(name="remove_whitelist", description="Removes a user's whitelist")
async def remove_whitelist(self, interaction: discord.Interaction, gamertag: str, user_id: int):

How'd I make this so that I can both inputs are not required but at least one is?

slate swan
#

You add logic and respond with an error accordingly

nova vessel
#

As that was my worry.

shrewd apex
nova vessel
naive briar
#

Set default arguments

nova vessel
nova vessel
naive briar
#

Yes

nova vessel
#

Perfect, thank you!

slate swan
#

python main.py Traceback (most recent call last): \New folder\main.py", line 12, in <module> from discord import Webhook, AsyncWebhookAdapter ImportError: cannot import name 'AsyncWebhookAdapter' from 'discord' (C:\Users\abhay\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\__init__.py)

#

from discord import Webhook, AsyncWebhookAdapter

#

doesnt work-any-fix?

#

code:

`# webhook-for-logs
WEBHOOK_URL = 'my-webhook'

@bot.event
async def on_command_error(ctx, error):
error_channel_id = 1178625906626023484 #channel-id

# error-of-bots
error_channel = bot.get_channel(error_channel_id)
if error_channel:
    error_content = f"Command used: {ctx.message.content}\nError: {str(error)}"
    await error_channel.send(error_content)

# error-sent-by-webhook
async with aiohttp.ClientSession() as session:
    webhook = Webhook.from_url(WEBHOOK_URL, adapter=AsyncWebhookAdapter(session))
    await webhook.send(f"Command used: {ctx.message.content}\nError: {str(error)}")

# error-cmds
print(f"Error in command '{ctx.command}': {error}")`
vapid parcel
#

Can someone help me with reload real quick?

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied timeout to @vapid parcel until <t:1701080191:f> (10 minutes) (reason: newlines spam - sent 101 newlines).

The <@&831776746206265384> have been alerted for review.

shrewd apex
#

hmm

#

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

vapid parcel
#

Okay

#

mb, didnt know i was gonna get muted for sending code 😭

#

Just wondering why unload isnt working

#

load works, but unload doesn't... just really confused on why.

naive briar
#

What about it isn't working?

vapid parcel
#

unloading

#

the commands from other cogs are still working even tho i "unloaded" it?

vapid parcel
white citrus
#

How can i get a subcommand of a subcommand of a basecommand?

white citrus
#

Get

spice hawk
#

Rate

spice hawk
#

whar

vale wing
spice hawk
#

omaga

robust fulcrum
#

guys is pycord/disnake better than discord.py, just a dumb question from me

robust fulcrum
glad cradle
#

this question reminds me the good ol' battles here to state the best library

robust fulcrum
#

i not mean best but wana know if disnake or pycord have any benefit over discord.py

glad cradle
robust fulcrum
glad cradle
#

ok so, pycord (objectively) has some big style issues and other problems, they implement a lot of things for you so it might seem easier but actually it restrict the possibility to handle certain things yourself

i don't think that i need to describe d.py, you used it before, it has some little design issues etc etc, but it's cool

and you can imagine disnake as d.py but with additional things, some things are designed better than d.py

now all of these descriptions are non-detailed and based on what i have heard (for pycord), what i have experienced myself (d.py, disnake), all of these are my opinions (just saying this to prevent someone from coming and start a battle)

#

i work a lot with disnake and my opinion is that it's better than d.py for app commands (Slash commands, message commands, etc...) and UI components

robust fulcrum
#

so it means disnake is discord.py + some other features?

glad cradle
#

well it's a fork of d.py so yes, but it's not a very right way to describe it

robust fulcrum
#

i guess i should try it and see

#

tysm for your opinion

glad cradle
#

probably someone else will come and share other opinions

robust fulcrum
#

i guess ill try disnake some other day

nova vessel
#

Anyone got a reference guide I can use for keywords in discord.py?

#

Like for kicking, banning, adding roles, just something to reference from.

glad cradle
#

with some extra logic you can make them

glad cradle
latent harness
#

How do i delete a row from a database in sqlite3? Whats the command?

vale wing
latent harness
vale wing
#

Check the link

latent harness
slate swan
#

python main.py Traceback (most recent call last): \New folder\main.py", line 12, in <module> from discord import Webhook, AsyncWebhookAdapter ImportError: cannot import name 'AsyncWebhookAdapter' from 'discord' (C:\Users\abhay\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\__init__.py)
from discord import Webhook, AsyncWebhookAdapter
doesnt work-any-fix?
code:

code:

`# webhook-for-logs
WEBHOOK_URL = 'my-webhook'

@bot.event
async def on_command_error(ctx, error):
error_channel_id = 1178625906626023484 #channel-id

# error-of-bots
error_channel = bot.get_channel(error_channel_id)
if error_channel:
    error_content = f"Command used: {ctx.message.content}\nError: {str(error)}"
    await error_channel.send(error_content)

# error-sent-by-webhook
async with aiohttp.ClientSession() as session:
    webhook = Webhook.from_url(WEBHOOK_URL, adapter=AsyncWebhookAdapter(session))
    await webhook.send(f"Command used: {ctx.message.content}\nError: {str(error)}")

# error-cmds
print(f"Error in command '{ctx.command}': {error}")`
#

can-anyone-help??

hushed galleon
final breach
#

can i edit flowups message app_commands?

fluid anchor
#

can you access about me section

#

in python

shrewd apex
fluid anchor
#

yep

shrewd apex
#

no

fluid anchor
#

well that is sad

hushed galleon
# final breach can i edit flowups message app_commands?

yes, interaction.followup returns an application webhook which will always give you a WebhookMessage object you can edit after you send your message
(the 15 minute token expiration still applies as usual) py class MyView(discord.ui.View): @discord.ui.button(label="A button") async def on_click(self, interaction, button): await interaction.response.send_message("Response") await interaction.edit_original_response(content="Edited response") message = await interaction.followup.send("Followup") await message.edit(content="Edited followup")

latent harness
#

Why is that happening?

#

the user_exist isn't getting defined

slate swan
latent harness
#

oh

#

oh. Oof

#

sry!!

latent harness
#

Yeah So what I wanna do is the user should be able to delete his journey (basically delte user info row from database) if he has one. If he hasn't there would be message saying "you haven't started journey yet"

Here's the code. Pls tell me how do i change according to that:

final iron
#

Oh boy

#

You’re mixing code from a prefixed command, slash command and a discord.py fork

latent harness
#

and i'm fairly new

#

pls tell me how to fix this

#

@final iron

shrewd apex
latent harness
#

Pls just could you tell me how to fix?

shrewd apex
#

even if i did u wouldn't understand unless i personally modify the code or spoonfeed u i can tell u whats wrong rest is upto u

  • bot.command is prefix command so it has context not interaction
  • u cannot send buttons like that u need to attach them to a view
  • a synchronous database is blocking the main event loop
latent harness
shrewd apex
#

!d disnake.ui.View

unkempt canyonBOT
#

class disnake.ui.View(*, timeout=180.0)```
Represents a UI view.

This object must be inherited to create a UI within Discord.

Alternatively, components can be handled with [`disnake.ui.ActionRow`](https://docs.disnake.dev/en/latest/api/ui.html#disnake.ui.ActionRow)s and event listeners for a more low-level approach. Relevant events are [`disnake.on_button_click()`](https://docs.disnake.dev/en/latest/api/events.html#disnake.on_button_click), [`disnake.on_dropdown()`](https://docs.disnake.dev/en/latest/api/events.html#disnake.on_dropdown), and the more generic [`disnake.on_message_interaction()`](https://docs.disnake.dev/en/latest/api/events.html#disnake.on_message_interaction).

New in version 2.0.
old frigate
#

Hello

sharp bay
old frigate
#

should i switch?

unreal pilot
#

discord.py is definitely compatible though, so dont worry about that

#

for discord frameworks in python, i just like discord.py the most as the support for it is big

cunning briar
#

what command u need to make a channel with custom name use ctx

#

or interaction anything

proper cape
#

So I made a python discord bot that responds to commands that start with "$" and I made a say command that has the command "$say [message]" which will say the message as the bot. But whenever the say command code structured like "Fun_Commands/say.py" it doesn't work. But when I have the exact same code, in the "main.py" file it works.

final iron
proper cape
#

@final iron what do you mean?

final iron
proper cape
# final iron Saying something doesn’t work isn’t helpful. It tells us nothing about what actu...

import discord
from discord.ext import commands
import os
import json

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

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

@bot.command(name='say')
async def say_message(ctx, *, message):
# Check if the command invoker has the "manage_messages" permission
if ctx.author.guild_permissions.manage_messages:
# Delete the original command message
await ctx.message.delete()

    # Create an embed with the original message and user information
    embed = discord.Embed(
        description=message,
        color=discord.Color.blue()  # You can customize the color
    )

    # Add the user's name and avatar to the embed
    embed.set_author(name=ctx.author.name, icon_url=ctx.author.avatar.url)

    # Load configuration from file
    config_file = os.path.join(os.path.dirname(__file__), 'config.json')
    with open(config_file, 'r') as f:
        config = json.load(f)

    channel_id = config.get('channel_id')  # Get channel ID from config

    print(f"Channel ID: {channel_id}")  # Debugging print

    # Get the channel using the channel ID
    channel = bot.get_channel(channel_id)

    if channel and isinstance(channel, discord.TextChannel):
        try:
            # Send the embed
            await channel.send(embed=embed)
        except discord.HTTPException as e:
            await ctx.send(f"Error sending embed: {e}")
    else:
        await ctx.send('Error: Unable to find or send to the specified channel.')

    # Send the plain text message to the current channel
    await ctx.send(message)
else:
    await ctx.send('You do not have the required permissions to use this command. Please contact an admin.')
final iron
#

I dont help with code generated by ChatGPT or similar

#

It’s a headache to fix

proper cape
#

It wasent generated using chat gpt

proper cape
final iron
#

The comments are obvious

proper cape
#

It helped me to remember that I can change whatever was needed to change

proper cape
final iron
#

You really wrote “You can customise the colour”?

#

Sure

latent pier
#
@commands.Cog.listener()

async def on_voice_state_update(self, member, before, after):

print('tested')

channel = after.channel

if channel.id == 1173576697698848768:

channel = await after.channel.clone(name=f'{member.display_name}\'s Channel')

await member.move_to(channel)
#

This isn't working

final iron
latent pier
final iron
latent pier
final iron
#

Yes, and the indentation was wrong

#

Repaste it with the correct indentation

latent pier
#

Pasting made it wrong

#

It isn't wrong

#
@commands.Cog.listener()
async def on_voice_state_update(self, member, before, after):
    print('tested')
    channel = after.channel
    if channel.id == 1173576697698848768:
        channel = await         after.channel.clone(name=f'{member.display_name}\'s Channel')
        await member.move_to(channel)
final iron
#

Yes, so paste it correctly

#

There we go

#

Define “This isn’t working”

latent pier
#

It is printing tested but not creating channel or anything and no Error

final iron
#

Is the if statement truthy?

latent pier
#

Yes

#

I copied id directly

#

Let me try by adding print statement to it

patent lark
#

Add a print statement inside the if scope to be sure

#

yeah

latent pier
#

It is true

patent lark
#

Show me your current code and terminal output please.

#

Hm.

#

It doesnt create the channel ?

#

!d discord.on_voice_state_update

unkempt canyonBOT
#

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

The following, but not limited to, examples illustrate when this event is called...
patent lark
#

ima look at docs rq.

final iron
#

Do you have logging setup

latent pier
final iron
#

Set it up, see if there are any errors

latent pier
#

okay

vapid parcel
#

How to do sub commands for hybrid? needing to know how to do Group + sub

cunning briar
final iron
#

Or clone the channel the command was invoked in?

sick birch
unkempt canyonBOT
#
await create_text_channel(name, *, reason=None, category=None, news=False, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

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

Note that you must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels) to create the channel.

The `overwrites` parameter can be used to create a ‘secret’ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict) of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role)) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite) as the value.

Note

Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.edit) will be required to update the position of the channel in the channel list...
cunning briar
#

say both i need to learn abt making channels

final iron
# unkempt canyon

This would create a text channel in the guild the command was invoked in

#

Context.guild will return the Guild instance

#

!d discord.TextChannel.clone

unkempt canyonBOT
#

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

Clones this channel. This creates a channel with the same properties as this channel.

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

New in version 1.1.
final iron
#

That'll clone the channel the command was invoked with

cunning briar
#

ohhh

#

i got it

final iron
#

You can get the TextChannel instance with Context.channel

final iron
#

imo they're pretty simple. The only thing that I see people trip on is the overwrites

cunning briar
cold oyster
#
  File "C:\Users\HP\Desktop\pokebot\main.py", line 3, in <module>
    import requests
  File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\requests\__init__.py", line 64, in <module>
    from . import utils
  File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\requests\utils.py", line 28, in <module>
    from .cookies import RequestsCookieJar, cookiejar_from_dict
  File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\requests\cookies.py", line 164, in <module>
    class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping):
                                                 ^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: module 'collections' has no attribute 'MutableMapping'```
whats this error, I tried python 3.10.5, 3.11.5 and 3.8 all give the same error
#

Never mind, It's just a conflict with the packages I have, Use a VENV it works

magic granite
#

Is there a way to enable community through discord.py or the guild owner has to enable it themselves?

hushed galleon
# magic granite Is there a way to enable community through `discord.py` or the guild owner has t...

apparently it can pithink
https://discordpy.readthedocs.io/en/stable/api.html#discord.Guild.edit

community (bool) – Whether the guild should be a Community guild. If set to True, both rules_channel and public_updates_channel parameters are required.
https://discord.com/developers/docs/resources/guild#modify-guild
Attempting to add or remove the COMMUNITY guild feature requires the ADMINISTRATOR permission.

magic granite
#

So it's my library's issue then

#

@hushed galleon Thanks mate

robust fulcrum
#

guys this is my bot.py

import discord
from discord.ext import commands
from src.config import config

class Bot(commands.Bot):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def setup_hook(self) -> None:
        print(f"Logged in as {self.user}")

bot = Bot(command_prefix=config.prefix, intents=discord.Intents.all())

and main.py

from src.bot import bot
from src.config import config

if __name__ == "__main__":
    bot.run(config.token)

why i getting this error, i not able to find where i made mistake

Traceback (most recent call last):
  File "<frozen runpy>", line 198, in _run_module_as_main
  File "<frozen runpy>", line 88, in _run_code
  File "C:\Users\dell\Desktop\projects\python\xbot\src\__main__.py", line 5, in <module>
    bot.run(config.token)
  File "C:\Users\dell\Desktop\projects\python\xbot\.venv\Lib\site-packages\discord\client.py", line 860, in run
    asyncio.run(runner())
  File "C:\Users\dell\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run
    return runner.run(main)
           ^^^^^^^^^^^^^^^^
  File "C:\Users\dell\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run
    return self._loop.run_until_complete(task)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\dell\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "C:\Users\dell\Desktop\projects\python\xbot\.venv\Lib\site-packages\discord\client.py", line 849, in runner
  File "C:\Users\dell\Desktop\projects\python\xbot\.venv\Lib\site-packages\discord\client.py", line 777, in start
    await self.login(token)
  File "C:\Users\dell\Desktop\projects\python\xbot\.venv\Lib\site-packages\discord\client.py", line 621, in login
    await self.setup_hook()
TypeError: object NoneType can't be used in 'await' expression
robust fulcrum
#

thanks for help

acoustic kernel
#

How do I make a command that wont let players run it again for another 10 minutes

acoustic kernel
#

slash

golden portal
unkempt canyonBOT
#

@discord.app_commands.checks.cooldown(rate, per, *, key=...)```
A decorator that adds a cooldown to a command.

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns are based off of the `key` function provided. If a `key` is not provided then it defaults to a user-level cooldown. The `key` function must take a single parameter, the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction) and return a value that is used as a key to the internal cooldown mapping.

The `key` function can optionally be a coroutine.

If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandOnCooldown) is raised to the error handlers.

Examples

Setting a one per 5 seconds per member cooldown on a command:
hushed galleon
#

your py-cord version is out of date (<2.4.0)

white citrus
#

How can i find a subcommand of a subcommand of a basecommand.

Like /help voice setup join-2-create and he get the voice setup join-2-create command.

shrewd apex
#

i am pretty sure u cant have slash commands of more than depth 1

#

thats a discord api limitation

#

max is /parent_group sub_group command

nova vessel
#

Does anyone have a tutorial available for how to setup a Discord bot for multiple servers?

#

Like Dyno for example, how to get it so that the bot is ready to be setup in multiple servers.

naive briar
#

I'm not sure if I understand what you mean

sick birch
#

use the invite link to invite bots to any servers you want to

hushed galleon
# nova vessel Does anyone have a tutorial available for how to setup a Discord bot for multipl...

like in the context of making sure your features can be configured by different guilds and work independently? that's where your database design is important, making sure your tables can uniquely associate data/settings for each guild where appropriate (for example, you might have an automod_config table that uses (guild_id) as its primary key and the rest of the columns are settings for that guild's automod, or you might have an inventory table that uses (guild_id, user_id, item_id) to uniquely identify each item a user has for a particular guild)

#

and of course replacing any hardcoded guild/channel/role IDs with database queries

nova vessel
slim stream
#

hello guys, I need a bot for discord to open/close timeouts on pd

slim stream
#

police department

final iron
#

open/close timeouts on police department is very vague

#

And personally I have no clue what that means

patent lark
#

😂😂

slim stream
#

whait

patent lark
slate swan
#

what

patent lark
#

how do you expect us to help you? we have NO idea what you’re talking about

slim stream
#

I need a bot for discord that can start my timer and calculate it while playing on a fivem sv e.g.:/clocking clock in/, clock out to see how much I played in pd on that sv

patent lark
#

Okay so this is fivem

patent lark
slim stream
#

it's very simple to understand

#

I would send a video but I can't

final iron
slim stream
#

fivem sever

final iron
#

I still don’t know how this clocking in/out occurs. You’re leaving out a lot of necessary context

uneven pollen
#

is it possible to use logging for your own debugging? i tried

async def ping(ctx):
    logging.info("Ping command called")
    await ctx.send("Pong!")

but it doesn't work. i added a basic log handler but i dont see my output in it

patent hull
acoustic kernel
#

If im making react roles how do i set an unlimited time limit to react, i dont want it to timeout

slate plover
#

yo

#
@client.event
async def on_scheduled_event_create(event):
    await event.cancel(reason='womp womp')
    print('event was cancelled.')
slate plover
#

the thing is, i wanna make the creator of the event get dmed by the bot.

#

(I did research, no results that helped.)

unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) objects. **Specifying both parameters will lead to an exception**.
slate swan
#

!d discord.ScheduledEvent.creator

unkempt canyonBOT
slate plover
#

@slate swan like this?

@client.event
async def on_scheduled_event_create(event):
    await event.cancel(reason='womp womp')
    await event.creator.send("Event Cancelled.")
    print('event was cancelled.')
acoustic kernel
slate plover
slate swan
slate plover
#

I swear bro 😭 I kept rereading the scheduled event part more than 5 times but now it decides to work

grand sleet
grand sleet
#

Also anyone know if there’s documentation regarding @lusty spear? Or template for Grafana

sick birch
grand sleet
#

I mean generally set up instructions, I saw the readme bit, was wondering if there’s anything else or if that’s all you need, and usage stuff

sick birch
grand sleet
#

Purely out of curiosity yes

sick birch
#

README should have all the setup instructions

#

knowing how to configure prom and grafana will also help

grand sleet
#

I’ve seen tutorials and documentation so rough idea, stuff is always more fun when you have zero idea what your doing

#

Seeing as I’m unfamiliar with the technologies, I was just curious as to weather any further explanations existed

languid sequoia
grand sleet
#

YouTube has plenty of good tutorials

#

So do their docs

languid sequoia
#

Alright

#

Is it as simple as setting the command_prefix to /

#

Or is it more complicated

grand sleet
#

Ngl don’t fully understand myself but to just get it working fairly easy

#

Lemme find an example for ya

languid sequoia
#

Alright thank you

grand sleet
# languid sequoia Alright thank you

https://github.com/Rapptz/discord.py/blob/master/examples/app_commands/basic.py example from the official repo, there’s also a pretty good stack overflow answer describing it here https://stackoverflow.com/questions/71165431/how-do-i-make-a-working-slash-command-in-discord-py also remember documentation is your best friend

GitHub

An API wrapper for Discord written in Python. Contribute to Rapptz/discord.py development by creating an account on GitHub.

languid sequoia
#

Thank you

grand sleet
reef sonnet
#

Is there a way to print current page with every page switch in pycord pagination? cant find a way to do it

class shopCategory(discord.ui.View):
    @discord.ui.select(
        placeholder="Pick a section",
        min_values=1,
        max_values=1,
        options=[
            discord.SelectOption(
                label="Crates",
                emoji="![DivineCrate](https://cdn.discordapp.com/emojis/1178832157473521664.webp?size=128 "DivineCrate")",
                description="View the crates shop!"
            ),
            discord.SelectOption(
                label="Limited time offers",
                emoji="✨",
                description="View FiveaSide limited time offers!"
            ),
        ]
    )
    async def select_callback(self, select, interaction):
        if select.values[0] == "Crates":
            crate_types = ["Base", "Elite", "Divine", "Golden"]

            crate_buttons = crateButtons(crate_types)

            crates_pages = [
                create_crates_embed(),
                coming_soon_embed(),
            ]
            paginator = pages.Paginator(pages=crates_pages, use_default_buttons=True, timeout=60, custom_view=crate_buttons)
            print(paginator.current_page)
            await paginator.respond(interaction)```
final iron
#

All the tutorials have issues, and even if they didn’t they’re fundamentally flawed

grand sleet
#

There’s always an issue with something, and there’re a good resource to learn the basics imo

final iron
grand sleet
#

I mean on a nitpick level, if you try hard enough there’s gonna be some “issue” but text tutorials are more comprehensive normally yes

final iron
#

Video tutorials have major issues though. Not small ones

grand sleet
#

Depends on the tutorial

final iron
#

Send one you think is good

grand sleet
#

Though even with issues they can still be a good starting point for basics

final iron
#

I have never seen a good, up to date YouTube tutorial

#

If you point a beginner in the wrong direction they will continually follow it. Good tutorials are especially important for beginners as it builds the foundation for their bot

#

Only good video tutorial I’ve ever seen was pre v2

shrewd fjord
#

I know a good tutorial for beginners,, chatgpt 💀 learn python using !resources

shrewd fjord
slate swan
shrewd fjord
#

But yeah some video of him has some problem but he updated those in this latest videos

languid sequoia
#

I am creating a bot for a game that is relatively small, for this bot I need to store usernames in a variable that will be used to do console commands in game . My question is, how can I store user input into a variable with discord commands?

shrewd fjord
#

You need a global variable for that, but i suggest use a database, but since its small you can use json

languid sequoia
#

When I say small I mean like a million people play that game

naive briar
agile berry
#

I have created a discord bot, I don't know how to code, so can someone help please?

#

I want to send a text file and the bot will decode it and send me the file. @naive briar @languid sequoia @shrewd fjord

naive briar
#

Please don't ping random people; just ask your question and someone will (probably) come by to answer it

languid sequoia
#

I’ll be honest I probably know less about coding than you, I started learning Python less than 2 weeks ago.

#

I am the last person you should ask about coding help

agile berry
#

Binary numbers to hax decimal

#

import sys

arr = bytearray()
with open(sys.argv[1], "rb") as f:
for b in f:
arr += bytearray(b)
for i in range(len(arr)):
arr[i] = ~arr[i] + 256

with open(sys.argv[1], "wb") as f:
f.write(arr) @final iron

#

@grand sleet

slate swan
#

I'd recommend learning SQL and becoming familiar with the sqlite3 standard library module

agile berry
#

@slate swan plz help me brother

slate swan
#

What with

agile berry
#

I have created a discord bot, I don't know how to code, I want to send a text file and the bot will decode it and send me the file.

#

import sys

arr = bytearray()
with open(sys.argv[1], "rb") as f:
for b in f:
arr += bytearray(b)
for i in range(len(arr)):
arr[i] = ~arr[i] + 256

with open(sys.argv[1], "wb") as f:
f.write(arr)

slate swan
#

You won't be able to do anything with your bot if you don't know how to code at all

agile berry
#

Brother just give me the code and I can apply please.

slate swan
#

Sorry but we don't spoon feed code here, and I don't know what you mean by "decode".

agile berry
#

Like I send Text file than bot decode my text file and send me

slate swan
#

You'll need to learn stuff like data types, control flow, functions and some OOP before you even begin making a bot

agile berry
#

@languid wagon where I learn in hindi language

meager rock
#

skip stuff that you already know

acoustic kernel
#

how do I get a discord bot to respond more than once to a slash command?

robust fulcrum
#

guys i have a slash command called ping, i want a decorator which gets description and name of command, how can i do that, its a decorator question, but ok

naive briar
#

What?

vale wing
#

To get description, you need to get the command object

#

Nothing to do with decorator

robust fulcrum
vale wing
robust fulcrum
rugged shadow
#

is this for a help command?

robust fulcrum
#

Yep

rugged shadow
#

do you really need one for a slash command bot

#

discord already kinda provides that for you

robust fulcrum
#

I want a help command though for a clean interface

#

The discord one lags pretty well

rugged shadow
#

what library are you using?

robust fulcrum
#

Dpy ⭐

rugged shadow
#

bot.tree.get_commands()

#

or walk_commands, you're probably gonna do it in a for loop anyway

#

!d discord.app_commands.CommandTree.walk_commands

unkempt canyonBOT
torpid birch
#

Hi, how to get the message.content of a webhook? I tried doing this but I got a white space.

novel berry
#

@bot.event
async def on_member_join():
await

I want to send a message to say welcome on a join.

final iron
novel berry
final iron
novel berry
final iron
#

You can use

#

!d discord.Client.get_channel if it’s in the cache, or if you have the ID

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.
final iron
#

If you want to search by name you can use discord.utils.get and pass in the guilds channels as the iterable

final iron
novel berry
#

where do i put it?

final iron
#

You’ll create a listener for the on_member_join event, and put it in the function

#

Do you know how to send messages to a channel?

novel berry
#

no

final iron
#

!d discord.TextChannel.send

unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) objects. **Specifying both parameters will lead to an exception**.
novel berry
#

@bot.event
async def on_member_join():
welcome_channel = bot.get_channel(0) # replace 0 with channel id
await welcome_channel.send("Your message")

#

how do i get the id

final iron
#

You can use

#

!d discord.utils.get to get a TextChannel object

unkempt canyonBOT
#

discord.utils.get(iterable, /, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.utils.find).

When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.

To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.

If nothing is found that matches the attributes passed, then `None` is returned.

Changed in version 2.0: The `iterable` parameter is now positional-only.

Changed in version 2.0: The `iterable` parameter supports [asynchronous iterable](https://docs.python.org/3/glossary.html#term-asynchronous-iterable)s...
novel berry
#

How to find the id of a chanell

final iron
#

Are you asking how to get it pythonically or through discord itself?

novel berry
#

yes!

final iron
#

It’s not a yes or no question lol

novel berry
#

discord

final iron
#

Discord definitely has a page on this

novel berry
#

where?

final iron
#

Google

novel berry
final iron
#

You need to specify discord

novel berry
#

it said right click and press copy id but i dont find it

novel berry
#

where is advansed developer setting?

final iron
#

It’s a setting

novel berry
#

i dont find it

hushed galleon
novel berry
#

Thanks

#

like this?

novel berry
hushed galleon
fringe void
#

how are you hosting the bot btw?

hushed galleon
#

open the secrets menu on the bottom left, read the article that it links to, and then move your token into a secret following their explanation

novel berry
hushed galleon
#

also consider resetting your token regardless, since its already been exposed

novel berry
#

how?!?!?!?

fringe void
#

in ur discord developer portal

hushed galleon
novel berry
#

ok thanks!

#

but does this work?

hushed galleon
#

you leaked your token again...

novel berry
#

no its the old one

#

or i havent replaced it

hushed galleon
#

btw are you using sharex? they have tools to blur/pixelate/smart erase part of your screenshot instead of having to freehand crop it

novel berry
#

but where do i put the token so no one see it

#

i dont have that

#

i do windoes + shift + s

final iron
novel berry
#

like this?

hushed galleon
torpid birch
#

Can I send the kind of message?

hushed galleon
torpid birch
novel berry
#

like this?

torpid birch
#

I think it's webhooks not sure

hushed galleon
# torpid birch

judging from the checkmark that's a bot account, but either way that message has one embed

#

!d discord.Message.embeds

unkempt canyonBOT
hushed galleon
# novel berry like this?

sure, now retrieve your token in your script using the os.getenv() function as described in the article

torpid birch
hushed galleon
hushed galleon
vale wing
#

I remember there was a nice pin with embed structure

#

Here

torpid birch
hushed galleon
#

you can see the embed attributes you can access in the docs, and the reply to chili's message is how those attributes get rendered on discord

#

!d discord.Embed

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...
torpid birch
#

Okay I'll check this tomorrow, it's night now
Thanks for helping

merry sleet
knotty fiber
nova vessel
nova vessel
#

(Didn't mean to do twice, been up for ages 🤣)

slate swan
#

Hi, I need help. My Google colab not can install !pip install chatterbot, Does anyone have the same problem?

hushed galleon
burnt idol
#

F strimg formating for embeds.description is not working like f'{x:<18}' it just prints without extra spaces for some reason
Result should be
Var1. 6
V2. 7
See the space between should be equal but it isent
Any idea y

hushed galleon
burnt idol
#

Yee i just got same idea from someone else ill try code blocks

languid sequoia
#

I have two different files for my discord bot that work in different ways, is it possible to run both files at the same time and have everything work as if it was one?

sick birch
#
python file1.py
python file2.py
languid sequoia
#

Not sure how different that is

sick birch
#

You can do this method if theyr'e independant

languid sequoia
#

Wdym?

#

They are independent

#

If I understand what you’re saying

sick birch
languid sequoia
#

So do I just copy and paste that at the top of both the files with the file name instead of file1/file2?

#

@sick birch

sick birch
#

you'd just run them separately

languid sequoia
#

Alright

latent pier
#

I was wondering if client.wait_('button_clicked', ) still works because i can't find it in docs

naive briar
#

There's no such events as that

latent pier
sick birch
latent pier
#

Oh okay

hushed galleon
latent pier
#

Thanks

cold oyster
#

hey anybody here can test my bot pls?

#

Not mine completly but its a team

#

(dm)

languid sequoia
#

Does discord.Embed work when doing commands that use if.message.starts.with()?

fast musk
#

sure?

#

heh, I once did a fiverr project to identify pictures of pokemon

#

it was fun

final iron
languid sequoia
#

Also, is it possible to change the value of a variable depending on what guild the bot is in?

final iron
languid sequoia
final iron
#

Generally, if you have an abc.Messageable you can send embeds to it

languid sequoia
final iron
#

By server IDs, you mean the VR server IDs right

#

Not Discord guild ones

languid sequoia
#

For in game servers yes. I want to be able to input server ids personally though, the bot will be private.

final iron
#

Yeah, so id just setup a database for that, but if its private and only a couple you could just use a dict to simply it

#

Guild ID as the key, in game server as the value

languid sequoia
#

Alright thanks

latent pier
#

How can i check the voice channel's limit?

naive briar
unkempt canyonBOT
latent pier
#

Thanks

robust fulcrum
#

guys how can i make my discord.py sync commands when a new command gets automatically, i have cog watcher which reloads cogs on update in file, so i want my bot to sync when command sget added?

vale wing
latent pier
#

bot.tree.sync() you mean 👀

robust fulcrum
#

i have now sync commands on every file change in my watcher which will slow my app 💀

vale wing
#

You need smart sync

robust fulcrum
#

what\

vale wing
#

Like check the changes in commands

#

That's what disnake does!

#

Use disnake 🗣️

latent pier
#

🫠

robust fulcrum
#

you mean i check for change in self.tree.commands?

vale wing
#

We don't have tree in disnake

#

It's much better

robust fulcrum
#

idk disnake , i have exp with dpy

#

i was thinking to try disnake

vale wing
#

It's all automated and smart

latent pier
#

PR for disnake

robust fulcrum
#

maybe ill make my next discord bot with disnake

vale wing
latent pier
#

Anyways

robust fulcrum
#

but i found something missing that idk how to make bybrid commands in disnake

vale wing
#

Who needs hybrid commands 😒

robust fulcrum
#

i need i guess

vale wing
#

Anyways you can do them with double decorator

#

Or custom decorator

robust fulcrum
#

but tbh slash commands are slow

#

what do you think, we should focus onmaking slash or prefix commands?

latent pier
vale wing
#

If your bot doesn't need messages content slash is the only option

latent pier
#

Bro is dedicated

vale wing
#

Also slash provide better input filtering imho

latent pier
vale wing
#

Waiting for discord to add datetime selector tho

robust fulcrum
#

but we can't reply to commands while using slash cmds

vale wing
#

Message commands

robust fulcrum
#

what

#

you mean prefix commands?

#

i am confused tbh

vale wing
#

You on pc?

robust fulcrum
#

ye

vale wing
#

Click message options and see apps

#

Those are message commands

#

Aka context menus

#

There's bookmark for example

robust fulcrum
vale wing
#

Ye

robust fulcrum
#

kk

#

ty for helpi guess i should give disnake a try

#

but i hate the sphinx designs which their docs have

vale wing
robust fulcrum
#

btw do disnake also have hot reload for cogs?

proud basalt
#

i guess it does

robust fulcrum
proud basalt
proud basalt
robust fulcrum
proud basalt
#

wut i that

#

is*

robust fulcrum
proud basalt
#

cool

#

you can put them to reload every x amount of time in a bg task tb

#

h

merry sleet
#

nextcord - Print out the AUTOCOMPLETE option selected by the user (not after invoking the command)

storm thorn
#

hello!

#

my forum post was deleted and i don really know why

naive briar
storm thorn
#

oh

#

so people can help me even if its blocked?

#

i mean, this was the message i recieved

shrewd apex
#

if u want smart sync in dpy u would have to make it urself

robust fulcrum
#

Oh

shrewd apex
#

u need to track slash commands and their relative data such as description parameters etc

robust fulcrum
#

That's easy I guess , I need to just sync commands on change?

shrewd apex
#

yeah u would have records preferably along with some sort of timestamp and keep a track to sync

robust fulcrum
#

Don't i just sync all commands to guilds?

shrewd apex
#

initially yes then further on only when some changes need syncing

robust fulcrum
shrewd apex
#

When to Sync

  • When you add a new command.
  • When you remove a command.
  • When a command's name or description changes.
  • When the callback's parameters change.
  • This includes parameter names, types or descriptions.
  • If you change a global to a guild command, or vice versa.
    • NOTE: If you do this, you will need to sync both global and to that guild to reflect the change.
robust fulcrum
#

No I mean how will my bot know if it needs to sync?

shrewd apex
#

u need to manually keep track

merry sleet
#

nextcord - Print out the AUTOCOMPLETE option selected by the user (not after invoking the command)

robust fulcrum
#

Hmm

shrewd apex
robust fulcrum
shrewd apex
#

yeah

merry sleet
robust fulcrum
#

Is there a event for knowing if a command is not registered?

shrewd apex
#

yeah autocomplete is triggered whenever there is an input in the field so once u the user picks the option it should trigger

merry sleet
shrewd apex
merry sleet
#

which is annoying

shrewd apex
#

eh well u get the idea sync returns a list of synced commands

robust fulcrum
merry sleet
#

oh well

shrewd apex
merry sleet
shrewd apex
#

thats why i said sync gives a list of registered commands

merry sleet
#

when I take the inputs from an autocomplete, when I print user, instead of a Member object its a str...

robust fulcrum
#

I guess you not getting what i mean

merry sleet
shrewd apex
#

whats the str? like the value?

merry sleet
#

yeah

#

wait ima send the code in a block 1 sec

robust fulcrum
shrewd apex
merry sleet
#
     @slash_command(name="remove_log",description="Remove a logged Moderation action.",guild_ids=attributes.TESTSERVER,default_member_permissions=(nextcord.Permissions(administrator=True)))
        async def remove_log(self,interaction:nextcord.Interaction,user:nextcord.Member, action, reason):
            print("Remove log")
            # the main code

        
        
        @remove_log.on_autocomplete("reason")
        async def remove_log_type_auto(self,interaction:nextcord.Interaction,user:nextcord.Member,action):
                
            print(action)
            await interaction.response.send_autocomplete(ModLogs.find_one({"guildId":interaction.guild.id,"modHistory":{"$elemMatch":{"$eq":user.id}}}))

err

  await interaction.response.send_autocomplete(ModLogs.find_one({"guildId":interaction.guild.id,"modHistory":{"$elemMatch":{"$eq":user.id}}}))
AttributeError: 'str' object has no attribute 'id'
shrewd apex
merry sleet
#

print(f"user returns '{user}'") doing that

robust fulcrum
shrewd apex
#

!d discord.ext.commands.Cog.get_app_commands

unkempt canyonBOT
robust fulcrum
#

Oh k

merry sleet
robust fulcrum
#

Ty

shrewd apex
merry sleet
#

Well I did that. It did a nextcord.Member onject

#

as in,

shrewd apex
merry sleet
#

mhm

#

take your time

shrewd apex
#

user dont have autocomplete

#

its only strings and numbers

naive briar
#

Numbers?

shrewd apex
#

ints and floats

merry sleet
#

I need it for reason but I need the value from user

shrewd apex
#

u cant tho

merry sleet
#

Which btw, is passed because if I check active, it prints Kick

merry sleet
shrewd apex
#

hmmm

robust fulcrum
shrewd apex
#

!d discord.app_commands.CommandTree.walk_commands

unkempt canyonBOT
merry sleet
#

any idea?

shrewd apex
#

not sure about nextcord but there dosent seem to be a way to get autocomplete option for users cause it cannot be registered since options are provided by discord and not the bot

merry sleet
#

mk

#

thanks for your time though

sharp whale
#

!paste

#

please help

naive briar
sharp whale
#

oh ya

#
def compare_json(file1="old_vps_dataset.json", file2="vps_dataset.json"):
    print("comparing json")
    with open(file1, 'r') as f1, open(file2, 'r') as f2:
        data1 = json.load(f1)
        data2 = json.load(f2)

    for entry1 in data1:
        for entry2 in data2:
            updated_at1 = entry1.get("updatedAt")
            updated_at2 = entry2.get("updatedAt")

            if updated_at1 != updated_at2 and entry1['id'] == entry2['id']:
                print(f"updatedAt changed in entry {entry1['id']}:")
                print(f"File 1: {entry1}")
                print("----------------------------")
                print(f"File 2: {entry2}")
                print("\n")
                updates_dict = entry2
                return updates_dict
    print("[LOG] No changes found")
    return None```
#

here

#

the function

#

halp pls

sharp whale
#

catlover where you gone :((((

robust fulcrum
#

guys is there a global slash command error event?

sharp whale
#

what

#

what do you mean by global slash command error event

robust fulcrum
#

a slash command error event

sharp whale
#

yes

#

there is

#

I think

#

all the errors are under the discord.app_commands class

#

for example

#

!d discord.app_commands.MissingAnyRole

unkempt canyonBOT
#

exception discord.app_commands.MissingAnyRole(missing_roles)```
An exception raised when the command invoker lacks any of the roles specified to run a command.

This inherits from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure).

New in version 2.0.
robust fulcrum
sharp whale
naive briar
#

!d discord.app_commands.CommandTree.error but this

unkempt canyonBOT
#

@error(coro)```
A decorator that registers a coroutine as a local error handler.

This must match the signature of the [`on_error()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.on_error) callback.

The error passed will be derived from [`AppCommandError`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.AppCommandError).
sharp whale
#

catlover

#

you're finally here

robust fulcrum
sharp whale
#

are you using a logging system?

robust fulcrum
#

i guess this is due to i have diabled discord.py's logging

sharp whale
#

bruh

sharp whale
#

help me someone

slate swan
#

Hi, I need help. My Google colab not can install !pip install chatterbot, Does anyone have the same problem?

cunning briar
#
class MyView(View):
    def __init__(self):
        super().__init__()

    @discord.ui.button(label='Click me', style=discord.ButtonStyle.green)
    async def mybutton(self, button: discord.ui.Button, interaction: discord.Interaction):
        await interaction.response.send_message("hi")

@bot.command()
async def button(ctx):
    view = MyView()
    await ctx.send("Here's a button:", view=view)
``` why it says failed when i click the button
final iron
#

Though, this should've given an error so if it didn't I would enable logging

cunning briar
#

oh

#

thx it works now

urban wren
#

hello there, anyone experiencing issue with discord.py ?

final iron
urban wren
#

this is my code : )

urban wren
# final iron Could you run `pip freeze` and show the output please?

aiohttp==3.8.6
aiosignal==1.3.1
anyio==4.0.0
async-timeout==4.0.3
attrs==23.1.0
cachetools==5.3.2
certifi==2023.7.22
cffi==1.16.0
chardet==3.0.4
charset-normalizer==3.3.2
colorama==0.4.6
colorlog==6.7.0
dacite==1.8.1
DateTime==5.2
discord-protos==0.0.2
discord.py-self==2.0.0
exceptiongroup==1.1.3
fore==0.1
frozenlist==1.4.0
google-api-core==2.14.0
google-auth==2.23.4
google-cloud-dialogflow==2.25.0
googleapis-common-protos==1.61.0
grpcio==1.59.2
grpcio-status==1.59.2
h11==0.14.0
httpcore==1.0.2
httpx==0.25.1
idna==3.4
install==1.3.5
intents==0.3.0
keyboard==0.13.5
multidict==4.7.6
proto-plus==1.22.3
protobuf==4.24.4
pyasn1==0.5.0
pyasn1-modules==0.3.0
pycparser==2.21
pygame==2.5.2
pyglet==2.0.10
PyNaCl==1.5.0
pytz==2023.3.post1
PyYAML==5.4.1
requests==2.31.0
rsa==4.9
sniffio==1.3.0
style==1.1.6
timedelta==2020.12.3
typing_extensions==4.8.0
urllib3==2.0.7
yarl==1.5.1
zope.interface==6.1

unkempt canyonBOT
#

5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.

final iron
#

self botting is against discord TOS

urban wren
#

who's talking about self bot

#

is it because i have the self version ?

final iron
#

discord.py-self...

urban wren
#

i can't host it now i'm debugging it

#

on my pc

final iron
#

If you're not self botting uninstall it, and install discord.py

final iron
#

FYI self botting is against discords TOS and will get your account terminated

#

It's strictly disallowed

urban wren
#

but why i'm getting error now on the code

final iron
urban wren
final iron
# unkempt canyon

It's against the servers TOS, and Discord's so we cannot help with that

urban wren
#

thanks pep < 3

sturdy dragon
#

guys Im looking for a library with a decent autocomplete feature for interactions, im having a lot of trouble with discord.py for this

golden portal
#

what are you having trouble with in d.py for autocomplete?

#

just return a list of Choice object

sturdy dragon
#

let me just load up vscode and see where I got to @golden portal

#

thx btw

#

so for example @golden portal Ive made a discord integration for grafana to display dashboards and panels through their render api, heres a command to pull a panel by name @grafana.command(name="panel", description="Display a Grafana panel") async def grafana_panel(self, interaction: discord.Interaction, panel_name: str): """ Display a Grafana panel Usage: /grafana panel [panel_name] """ print("Command invoked: grafana_panel") # Debug print if interaction.response.is_done(): pass return await interaction.response.defer() # Defer the response print("Interaction response deferred") # Debug print try: print(f"Fetching panel: {panel_name}") # Debug print panel_data = await self.fetch_rendered_panel(panel_name) if panel_data: print(f"Panel data fetched for {panel_name}") # Debug print await interaction.followup.send(file=panel_data) self.logger.info(f"Panel {panel_name} sent to {interaction.user.name}") else: print("Failed to fetch panel data") # Debug print await interaction.followup.send("Failed to fetch the panel.") except Exception as e: self.logger.error(f"Error fetching panel: {e}") print(f"Exception occurred: {e}") # Debug print await interaction.followup.send("An error occurred while fetching the panel.")

#

oops messed up the py formatter

#

do I just define the choices in the decorator itself?

final iron
#

!d discord.app_commands.autocomplete

unkempt canyonBOT
#

@discord.app_commands.autocomplete(**parameters)```
Associates the given parameters with the given autocomplete callback.

Autocomplete is only supported on types that have [`str`](https://docs.python.org/3/library/stdtypes.html#str), [`int`](https://docs.python.org/3/library/functions.html#int), or [`float`](https://docs.python.org/3/library/functions.html#float) values.

[`Checks`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check) are supported, however they must be attached to the autocomplete callback in order to work. Checks attached to the command are ignored when invoking the autocomplete callback.

For more information, see the [`Command.autocomplete()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Command.autocomplete) documentation.

Warning

The choices returned from this coroutine are suggestions. The user may ignore them and input their own value...
sturdy dragon
#

like @grafana.command(name="panel", description="Display a Grafana panel", options=" " ?

drifting arrow
#

Oh

drifting arrow
#

🤔

#

lessee how autocomplete works

#

Oh. this is the choices stuff

final iron
#

The gist is that it returns a list of app_commands.Choice()

sturdy dragon
#

thank you

drifting arrow
#

Fun stuff once you get it working.

sturdy dragon
#

yeah im eager to

drifting arrow
#

Fun fun stuff. Took me a while to get it working how I wanted, but once you do.

sturdy dragon
#

lets see if I can get this goijn

drifting arrow
#

If you can't, lemme know, I can give you some example code.

sturdy dragon
#

ive been hella confused by the libraries.. I was discord.py then pycord then interactions and then I just didnt know what I was working with anymore for a bit

sturdy dragon
#

so I can just pull the list of choices from anywhere really

#

as long as its in an accessible namespace

#

?

drifting arrow
#

Pretty much

#

I pull mine from a json file.

sturdy dragon
#

because im parsing the panel names from some json modal

#

^^^

drifting arrow
#

You can even do dynamic, but that's harder to do and it can be slower

sturdy dragon
#

yeah I gotta look into that

final iron
sturdy dragon
#

hey I got more dumb questions buddy buckle up

drifting arrow
#

There's a limit to how many choices you can have, so if you exceed you need to update the list.
The horrors of figuring that out.

final iron
#

Only 25 choices can be displayed at a time

drifting arrow
#

Yes. But you can do it dynamically

#

so while you have a limit of 25 u can setup different sets

#

based on what u want

drifting arrow
# final iron Only 25 choices can be displayed at a time
    async def autocomplete(self, interaction: discord.Interaction, current: str) -> List[app_commands.Choice[str]]:
        choices = []
        for item in self.items_list:
            choices.append(self.items_list[item]['name'])
        if current:
            choicelist = []
            for choice in choices:
                if current.lower() in choice.lower():
                    choicelist.append(choice)
                if len(choicelist) > 20:
                    break
            return [app_commands.Choice(name=c, value=c) for c in choicelist]
        else:
            default = choices[:25]
            default = ["Start typing an item name!"]
            return [app_commands.Choice(name=d, value=d) for d in default]
``` this is my solution. So as you type it'll populate the list based on what you type. my list is a few hundred long
sturdy dragon
#

thank you

#

where am I importing List from

drifting arrow
#

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

final iron
drifting arrow
#

;o

drifting arrow
final iron
#
default = choices[:25]
default = ["Start typing an item name!"]

This reassignment doesn't make any sense either

final iron
#

The code given uses some bad practices that I wouldn't want you to model into your code

drifting arrow
final iron
#

List is imported from typing

#

It's just for type annotations

sturdy dragon
#

thank you

final iron
#

I would really simplify it down into a list comp. It'll help readability a lot

shrewd apex
shrewd fjord
#

Asher be promoting harder

shrewd apex
shrewd fjord
gray gyro
#

Hi

merry cliff
#

hi

gray gyro
#

You know Instagram ban account bot?

final iron
untold rock
#

&aoc lb

dim ruinBOT
#
Wrong Channel

You are not allowed to use that command here. Please use the #aoc-bot-commands, #sir-lancebot-playground, #bot-commands channel(s) instead.

mossy jacinth
#

Hello, I'm trying to fetch information of a Database to tell my bot to either Ban, kick or timeout the user that did something wrong but it ignores the whole if statement.

The code is here: https://paste.nextcord.dev/?id=1701401229604711

Inside the if statement are prints that are being skipped inside the "punishment first" and "punishment end".
The second screenshot is the data that got saved from my server which is being recalled inside the code that's provided

The expected behavior is that it just checks what's inside the "punish", so if its either "Ban", "Kick" or "Timeout" and then do the appropriate punishment to the user.

I hope someone can help me

desert heart
hushed galleon
#

and what database library are you using? your second screenshot implies server-id is some numeric type, but you converted your member.guild.id to a string before passing it to .child() which seems odd

mossy jacinth
mossy jacinth
desert heart
#

Right, I am asking what the value is, not what the value should be. You can print the variable to see what the value is.

#

It would be good to have a catch all here to log any unexpected punishment types you encounter.

elif str(punishment) == "Timeout":
    ...
else:
    # maybe log the user_ref here too since the punishment seems specific to that object
    print(f"Unexpected punishment {punishment}")
mossy jacinth
#

Thanks I'll try that now, tried printing it but it just lists everything "({'punish': 'Ban', 'server-id': 917569655139348540, 'time': '10'}, 'gWYBqrqbKHH2KfdmtwPlCiWFyJY=') but basically it says the punishment is "Ban" so im maybe calling it wrong...

desert heart
#

You probably need something like ```py
punishment, _ = user_ref.get("punishment")

if punishment["punish"] == "Ban":
...```

#

Though that is sort of a guess since I am not familiar with your DB and what it returns besides the one example you just gave

hushed galleon
#

i can only guess that user_ref and punishment are both DocumentReferences, in which case this is the documentation for get()
if punishment shows there's a nested punish key, i would guess that what you actually meant to write was punishment = user_ref.get("punishment.punish")

hushed galleon
#

is google documentation normally this difficult to understand, or is it just me?

desert heart
#

Funnily enough I was looking at DynamoDB docs today and was also not having a great time.

vale wing
#

So not even for python but generally

#

I remember doing something with youtube API and heck I had to ask in their discord server about how to search properly

acoustic kernel
#

https://paste.pythondiscord.com/6ABQ

Can someone help me, Im trying to build a command that allows players to sell resources from the shop. However whenever I run the command back to back without the first command ever running through a return, then the first commands response get overwritten into an insta-sell.

vale wing
#

Even compared to bobux bot's sell command code this looks very hardly readable

robust fulcrum
#

why i get this error in my button in dpy?

    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
    @discord.ui.button(emoji="🗑")
    async def delete(
        self, interaction: discord.Interaction, button: discord.ui.Button[HelpView]
    ) -> None:
        await interaction.delete_original_response()
shrewd apex
robust fulcrum
#
    @app_commands.command(name="help", description="Help command")
    async def help(self, interaction: discord.Interaction) -> None:
        pages: dict[int, discord.Embed] = {
            i: Embed(title=f"Page {i}") for i in range(1, 5)
        }
        view = HelpView(interaction.user, pages)
        await interaction.response.send_message(
            embed=discord.Embed(
                title="Page1",
                color=discord.Color.blurple(),
            ),
            view=view,
        )
shrewd apex
robust fulcrum
#

ty

shrewd apex
#

ight