#discord-bots

1 messages ยท Page 264 of 1

turbid condor
#

Can u actually print the error

twilit grotto
#

that too

turbid condor
#

Even if bot got that wouldn't he need to be higher in hierarchy?

twilit grotto
#

yes i believe so

#

mhm

turbid condor
#

Welp error says it

twilit grotto
#

change your bots permissions and make sure its role is above the users role who ur trying to edit

#

make sure his permissions are correct, and can edit users

turbid condor
#

Welp I'd suggest not giving your but admin perms

#

And try changing name of someone else other than yourself

#

Cuz i think bots can't change server owner name not sure tho

winter token
#

!d datetime.datetime

#

!d discord.Member

unkempt canyonBOT
#

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

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

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

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

hash(x) Returns the memberโ€™s hash.

str(x) Returns the memberโ€™s handle (e.g. `name` or `name#discriminator`).
turbid condor
#

What error it prints?

#

Same?

#

Just try changing the name of any other bot

swift trench
#

what bot should I make

#

huh

#

what

#

whats the point in that

#

i dont understand what it does

#

oh

#

its pointless

#

ig

winter token
#
user_perms = []
        perms_list = list(GuildChannel.permissions_for(member))
        for perms in perms_list:
            user_perms.append(perms)
#

Error occured: Command raised an exception: TypeError: GuildChannel.permissions_for() missing 1 required positional argument: 'obj'

swift trench
#

im not making it

winter token
slate swan
#

I do hope you're not importing GuildChannel and that GuildChannel is just a badly named variable

slate swan
#

There we go, OOP krShrug

winter token
#

well

winter token
#

perms_list = list(discord.abc.GuildChannel.permissions_for(member))

slate swan
#

My guy

#

Maube time to learn OOP

#

discord.abc.GuildChannel must be replaced by an instance of such an object

#

E.g. ctx.channel, message.channel or interaction.channel, etc.

winter token
#

o

formal basin
#
if f'antibadwords:{after.guild.id}' not in r2:
        return
    
     
    if after.id == client.user.id:
        return
    if after.nick == "Bad word name":
       pass
    else:
    
    
     words = after.nick
     if not profanity.contains_profanity(after.nick):
        return
     if any(word in profanity.CENSOR_WORDSET and word in after.nick.lower() for word in after.nick.lower().split()):
       new_nickname = "Bad word name"  
       await after.edit(nick=new_nickname) 
       log = r.get(f"log {str(after.guild.id)}")
       embed = discord.Embed(title="nickname changed", description=f"{after.mention}'s nickname was changed")
       embed.add_field(name="Reason", value="contained bad words")
       embed.set_footer(text="Censored by better_profanity")
       log2 = int(log.decode("utf-8"))
       logging = client.get_channel(log2) or await client.fetch_channel(log2)
       await logging.send(embed=embed)
       print(f"bad word detected logs: {after.guild.id}")
``` this code
is changing any nickname I want it to only change it if the nickname contains profanity.CENSOR_WORDSET
cerulean shale
#

import discord
from discord.ext import commands
import wavelink

class Music(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.bot.loop.create_task(self.node_connect())

    async def node_connect(self):
        await self.bot.wait_until_ready()
        await wavelink.NodePool.create_node(bot=self.bot, host="lavalinkinc.ml", port=443, password="incognito", https=True)

    @commands.Cog.listener()
    async def on_wavelink_node_ready(self, node: wavelink.Node):
        print(f"Node <{node.identifier}> is ready!")

    @commands.command()
    async def play(self, ctx, *, search: wavelink.YouTubeTrack):
        if not ctx.voice_client:
            vc: wavelink.Player = await ctx.author.voice.channel.connect(cls=wavelink.Player)
        else:
            vc: wavelink.Player = ctx.voice_client

        vc.play(search)
        
async def setup(bot):
    await bot.add_cog(Music(bot))
#

Traceback (most recent call last):
File "C:\Users\91767\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 947, in _load_from_module_spec
await setup(self)
File "D:\OneDrive\Desktop\Saste Nashe\Coding ke Nashe\Discord ke Nashe\cogs\music.py", line 28, in setup
await bot.add_cog(Music(bot))
^^^^^^^^^^
File "D:\OneDrive\Desktop\Saste Nashe\Coding ke Nashe\Discord ke Nashe\cogs\music.py", line 8, in init
self.bot.loop.create_task(self.node_connect())
^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\91767\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 140, in getattr
raise AttributeError(msg)
AttributeError: loop attribute cannot be accessed in non-async contexts. Consider using either an asynchronous main function and passing it to asyncio.run or using asynchronous initialisation hooks such as Client.setup_hook

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

Traceback (most recent call last):
File "D:\OneDrive\Desktop\Saste Nashe\Coding ke Nashe\Discord ke Nashe\main.py", line 52, in <module>
asyncio.run(main())
File "C:\Users\91767\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "C:\Users\91767\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

#

File "C:\Users\91767\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "D:\OneDrive\Desktop\Saste Nashe\Coding ke Nashe\Discord ke Nashe\main.py", line 18, in main
await bot.load_extension(f'cogs.{file[:-3]}')
File "C:\Users\91767\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 1013, in load_extension
await self._load_from_module_spec(spec, name)
File "C:\Users\91767\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 952, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.music' raised an error: AttributeError: loop attribute cannot be accessed in non-async contexts. Consider using either an asynchronous main function and passing it to asyncio.run or using asynchronous initialisation hooks such as Client.setup_hook
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x00000115FEE46D90>

#

any idea on why i am getting this error? setup function is working fine btw

slate swan
#

Error says it all

#

__init__ cannot be async so you cannot access bot.loop there

cerulean shale
slate swan
#

Make that node connection somewhere else

cerulean shale
#

alright

cerulean shale
slate swan
#

We can, but we won't. We don't code for you, we help you fix your issues.

slate swan
#

Otherwise there may be some async function you can overwrite for an event emitted when the cog is loaded

cerulean shale
#

first i thought of setting up the loop using a listener but it wasnt working

#

alright still thx for the info

winter token
#
    @commands.command()
    async def bal(self, ctx):

        id = ctx.author.id
        data = {}

        if id not in data:
            with open('data.json', 'w') as f:
                data[id]['name'] = ctx.author.name
                data[id]['balance'] = 0
                json.dump(data, f, indent = 4)

        with open('data.json', 'r') as f:
            name = json.load(data[id]['name'], f)
#

Error occured: Command raised an exception: KeyError: 967397351159390218

winter token
#
    @commands.command()
    async def bal(self, ctx):

        id = ctx.author.id 
        with open('data.json', 'r') as f:
            data = f.read()

        if id not in data:
            with open('data.json', 'w') as f:
                data[id] = {}
                data[id]['name'] = ctx.author.name
                data[id]['balance'] = 0
                json.dump(data, f, indent = 4)

        with open('data.json', 'r') as f:
            name = json.load(data[id]['name'], f)

        await ctx.send(name)
#

Error occured: Command raised an exception: TypeError: 'in <string>' requires string as left operand, not int

slate swan
#

Says it all

#

id is an int, it wants a string

winter token
naive briar
#

Send the another error then

winter token
naive briar
#

Show your current code

winter token
#
    @commands.command()
    async def bal(self, ctx):

        id = str(ctx.author.id)
        with open('data.json', 'r') as f:
            data = f.read()

        if id not in data:
            with open('data.json', 'w') as f:
                data[id] = {}
                data[id]['name'] = ctx.author.name
                data[id]['balance'] = 0
                json.dump(data, f, indent = 4)

        with open('data.json', 'r') as f:
            name = json.load(data[id]['name'], f)

        await ctx.send(name)
naive briar
unkempt canyonBOT
#
Traceback

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

A full traceback could look like:

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

If the traceback is long, use our pastebin.

naive briar
#

Always send the full traceback

winter token
winter token
naive briar
#

Full traceback

winter token
naive briar
#

Why would you need to print a traceback

#

It should do it on its own

winter token
slate swan
#

Average error handler eating everything

naive briar
#

That explains it

winter token
#

now its telling me to change id into integer

#

๐Ÿ’€

naive briar
#

Who

winter token
#

bot ofc

naive briar
#

How would your bot tell you to change something to integer

winter token
#

{error}

naive briar
#

Show the error then

winter token
naive briar
#

What are you trying to do now

winter token
#

If i do that it will tell me to convert back to str

slate swan
#

member is an ID, whereas when you ban it must be something like a User that has an ID attribute

hasty pike
slate swan
#

So first of all await guild.ban(entry.user, reason="NULL")

formal basin
#
if after.nick == "Bad word name":
                   pass
               else: 

                if after.id == client.user.id:
                       return

                if f'antibadwords:{after.guild.id}' not in r2:
                             return
                
                message_content = after.nick.lower()
                words = message_content.split()

                for word in words:
                 if re.search(r"\w\W+\w", word) and (word.lower() in words for word in profanity.CENSOR_WORDSET):
                    if any (word in after.nick.lower() for word in "ass"):
                        pass
                else:
                   new_nickname = "Bad word name"  
                   await after.edit(nick=new_nickname) 
                   log = r.get(f"logs:{str(after.guild.id)}")
                   embed = discord.Embed(title="nickname changed", description=f"{after.mention}'s nickname was changed")
                   embed.add_field(name="Reason", value="contained bad words")
                   embed.set_footer(text="Censored by better_profanity")
                   log2 = int(log.decode("utf-8"))
                   logging = client.get_channel(log2) or await client.fetch_channel(log2)
                   await logging.send(embed=embed)
                   print(f"2bad word detected logs: {after.guild.id}")
    ``` this code is changing usernames with special characters I only want it to change it if it has special characters between the letters in profanity.CENSOR_WORDSET
winter token
#

wait nvm fixed

#

any way to show balance like tis

#

this*

slate swan
#

!e

i = 53055
print(f"{i:,}")
unkempt canyonBOT
#

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

53,055
winter token
#

cuz fetching the bal from datafile

slate swan
#

i is just the integer

#

Replace it with whatever you want, it's called a variable

fallen imp
#

i try make modal in youtube help me .-.

slate swan
#

well there is no folder named cogs

fallen imp
#

I copied it on youtube .-.

slate swan
#

That's what happens

#

thats why you should not

#

Line 8 already shows the tutorial is most likely shit

#

Same for line 6

slate swan
fallen imp
#

ohhh

vocal laurel
#

Hey @slate swan, do you know about discord presence in vs code?

vocal laurel
slate swan
#

its extension to vs code

vocal laurel
#

yes ik in #editors-ides i showed a problem i have been encountering, could you please check it out?

umbral bay
#

anyone has idea on how to call the display username of a user, like before the discord update of new usernames, we would call the user using message.author.name and it would just use the name part and avoid the discrimnator and # sign,

turbid condor
naive briar
unkempt canyonBOT
#

property display_name```
Returns the userโ€™s display name.

For regular users this is just their global name or their username, but if they have a guild specific nickname then that is returned instead.
naive briar
#

Like this?

umbral bay
umbral bay
turbid condor
#

Mb

#

I thought u were trying to ask how to get new user names as discriminators are gone

slate swan
#

depends what database also its not really related to this channel topic

#

well this could be for anything but the question is related to databases

hasty pike
#

Is there any audit log broadcast event

naive briar
#

Read the docs

#

!d discord.on_audit_log_entry_create

unkempt canyonBOT
#

discord.on_audit_log_entry_create(entry)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild") gets a new audit log entry. You must have [`view_audit_log`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.view_audit_log "discord.Permissions.view_audit_log") to receive this.

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

New in version 2.2.

Warning

Audit log entries received through the gateway are subject to data retrieval from cache rather than REST. This means that some data might not be present when you expect it to be. For example, the [`AuditLogEntry.target`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AuditLogEntry.target "discord.AuditLogEntry.target") attribute will usually be a [`discord.Object`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Object "discord.Object") and the [`AuditLogEntry.user`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AuditLogEntry.user "discord.AuditLogEntry.user") attribute will depend on user and member cache.

To get the user ID of entry, [`AuditLogEntry.user_id`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AuditLogEntry.user_id "discord.AuditLogEntry.user_id") can be used instead.
hasty pike
naive briar
#

Like any other events

hasty pike
#

What do I put in (entry)?

naive briar
#

What?

hasty pike
#

It has entry parameter ryt

naive briar
#

Yes?

hasty pike
#

how do we get specific event from it?

thin raft
#

Am I doing something wrong?

#

I am getting 401 unauthorized

naive briar
hasty pike
naive briar
#

Then just check it

hasty pike
#

using if statement

naive briar
#

Not fully sure though ๐Ÿˆ

thin raft
#

same

quiet badge
#

so cooool

full cosmos
#

Hello!
My bot keeps crashing when it tries to reply to a deleted message. How do I make it so it still sends the message without replying to the original command but still mentioning the command's author?

#

For clarification: I still want it to reply when the message has not been deleted.

naive briar
#

!d discord.User.mention

unkempt canyonBOT
full cosmos
# naive briar Ping them?

It currently does both. I want it to recognize when there's no message to reply to so it only pings. Right now it just crashes the whole bot when that happens.

naive briar
#

Why was the message deleted anyway

full cosmos
left stirrup
#

quick question Is it legal to sell discord bots that can play songs from youtube?

full cosmos
left stirrup
#

damn alright

swift acorn
#

I sometimes get an Unknown Interaction error in random commands that work normally most of the other time, any idea why this might be?

#

I notice that it happens when there is some other action processing in the background like something in the on_message event

young dagger
# hasty pike discord.AuditLogAction.ban

What are you looking for? Here is an example:

    guild = ctx.guild
    bans = []
    async for entry in guild.audit_logs(action=discord.AuditLogAction.ban, limit=10):
        bans.append(entry)

    if not bans:
        await ctx.send("No recent bans found.")
    else:
        embed = discord.Embed(title="Recent Bans", color=discord.Color.red())
        for entry in bans:
            embed.add_field(name="Banned User", value=entry.target)
            embed.add_field(name="Reason", value=entry.reason or "No reason provided")
            embed.set_footer(text=f"Banned by {entry.user} at {entry.created_at}")
        await ctx.send(embed=embed)```
#

Shows the most recent 10 bans in the server

full cosmos
swift acorn
#

yep

#

I suspect it might be that some of the commands take more than 3 seconds at times, so the interaction fails
I am gonna try and defer all interactions first and then followup response, on all of them

#

hopefully this fix works

hasty pike
ivory crypt
#

In discord.py, can I use interaction.followup.send to send ephemeral messages?

vocal laurel
#

yes iirc

ivory crypt
#

Oh oh thx

vocal laurel
#

does it answer ur question?

#

when deferring, if you set ephemeral to True, your first followup will be ephemeral regardless of what you pass to the ephemeral kwarg of followup.send. If you have ephemeral set to False, your first followup won't be ephemeral. - Main point for u

ivory crypt
#

thx, I am gonna to try it

vocal laurel
#

ok

vernal bone
#

what permission do you need to use fetch_channel?

upbeat otter
vernal bone
upbeat otter
vernal bone
#

ah ok

sharp whale
#

how do we get guild icon

#

of a specific guild

north kiln
#

!d discord.Guild.icon

unkempt canyonBOT
formal basin
sharp whale
#

can u show me an example

sharp whale
#

!d discord.Guild.icon

unkempt canyonBOT
swift acorn
#

Is it possible to send a modal with a followup to an interaction?

await interaction.followup.send(emailinputmodal())

This doesn't work

slate swan
#

no sending modal is only available via interaction.response.send_modal

idle surge
#

Hello, I wanted to know if someone could help me with an automated message in discord.py. I have this setup but doesn't work and I get no errors. Let me know, thank you.

@tasks.loop(seconds=10)
async def auto_send(channel : discord.TextChannel):
    embed = discord.Embed(colour=0x182D9F)
    embed.set_author(name="Just Some Subtle Reminders")
    embed.description = f"-n Be sure to use `.register` to register yourself to earn **Raneon** and buy **rewards**! \n *Do .help in #โ”ƒcommands \n \n Learn how to join our team over here #โ”ƒhow-to-join"
    embed.set_image(url="https://cdn.discordapp.com/attachments/1074138997498052760/1125310614147973130/HEADER_22.png")
    await channel.send(embed=embed, delete_after=60)
vernal bone
#

is there a way to detect if the user isn't in the server anymore because I have a list of user ids and need to remove the ids from the list that aren't in the discord server anymore

vocal snow
#

iterate through your list, use guild.get_member to check if the member is in the guild, if it is then pop

silk wasp
vernal bone
#
toRemove = []
        
for i in old:
    member = guild.get_member(int(i))
    print(guild, int(i), member)
    if member is None:
        toRemove.append(i)

for index in toRemove:
    del old[index]```
formal basin
vernal bone
formal basin
#

true

idle surge
slate swan
#

!d discord.ext.tasks.Loop.start

unkempt canyonBOT
idle surge
#

ty

snow coral
#

how can i make my bot uh log the user who adds a reaction and sends the reaction they put and the user in a log channel

vernal bone
#

when I print guild.members, it sends SequenceProxy(dict_values([])), how can I iterate through this?

slate swan
#

!d discord.Guild.members

unkempt canyonBOT
vernal bone
slate swan
vernal bone
vernal bone
formal basin
#

oh.

vernal bone
#
if role in interaction.user.roles:
        old = None
        await interaction.response.defer()
        with open(f"{file}", "r") as vouchFile:
            old = json.load(vouchFile)
        
        members = guild.members
        memberIds = []
        print(guild.members)
        for i in members:
            memberIds.append(i.id)

        print(memberIds)
        for i in old.copy():
            if not i in memberIds:
                del old[i]

        with open(f"{file}", "w") as vouchFile:
            json.dump(old, vouchFile, indent=4)```
slate swan
vernal bone
#

apologies for formatting

slate swan
#

and what you you get when you print i inside for loop

vernal bone
#

and guild is not None, i've tried printing it

slate swan
slate swan
slate swan
vernal bone
#

ok

slate swan
#

ask here i have no idea why its empty then

shrewd apex
vernal bone
#

yeah, I got it fixed, thank you though.

shrewd apex
#

what was the issue?

#

intents?

midnight stirrup
#

Could someone help me point out the issue here?

slate swan
#

!indent

unkempt canyonBOT
#
Indentation

Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.

Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.

Example

def foo():
    bar = 'baz'  # indented one level
    if bar == 'baz':
        print('ham')  # indented two levels
    return bar  # indented one level

The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.

Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines

More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation

swift acorn
slate swan
#

You can always defer the interaction

swift acorn
#

yeah but then I can't respond with modal

#

because interaction already responded to

slate swan
#

Hm yeah

#

You can always send the modal and do logic inside it

swift acorn
#

Well yeah, but sometimes it's like a check I wanna do to see if I wanna send them the modal at all or not
Which usually does not take more than 3 seconds, but for some reason when there is a lot of other stuff going on too I get Unknown Interaction errors so that's why I was deferring everything to be safe

#

But I guess for this one I will hope it doesn't

midnight stirrup
# unkempt canyon

So, with the last line being the issue. Should removing the indent fix it?

full cosmos
#

Hello!
I have a bot that crashes when it tries to reply to a message, which was deleted in the mean time. Can I somehow make it so the bot sends the message anyway but doesn't reply? (only when the message was deleted)

shrewd apex
#

i just defer everything by default to be safe ๐Ÿ™

slate swan
slate swan
#

and apply changes to your code

shrewd apex
#

try reply if error just send it

slate swan
full cosmos
midnight stirrup
slate swan
shrewd apex
#
try:
    await ctx.reply()
except discord.HTTPException:
    await ctx.send()

@full cosmos

slate swan
#

!d discord.Client.fetch_guild

unkempt canyonBOT
#

await fetch_guild(guild_id, /, *, with_counts=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Retrieves a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild") from an ID.

Note

Using this, you will **not** receive [`Guild.channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.channels "discord.Guild.channels"), [`Guild.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.members "discord.Guild.members"), [`Member.activity`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.activity "discord.Member.activity") and [`Member.voice`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.voice "discord.Member.voice") per [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member").

Note

This method is an API call. For general usage, consider [`get_guild()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.get_guild "discord.Client.get_guild") instead...
slate swan
#

read the note under it

shrewd apex
#

ic

slate swan
#

yeah i didnt know it until now

hasty coral
#

Hi all, im creating a leaderboard command to show every users level and xp in their current server. However i keep getting the error nontype has no attribute name anyone know why?

Code:

async def leaderboard(ctx):
    if str(ctx.guild.id) not in level_data:
        await ctx.send('No recorded levels in this server.')
        return

    sorted_data = sorted(level_data[str(ctx.guild.id)].items(), key=lambda x: x[1], reverse=True)
    leaderboard_embed = discord.Embed(title='Level Leaderboard', color=discord.Color.gold())

    for i, (user_id, xp) in enumerate(sorted_data[:10]):
        user = ctx.guild.get_member(int(user_id))
        leaderboard_embed.add_field(name=f'{i+1}. {user.name}', value=f'XP: {xp}', inline=False)

    await ctx.send(embed=leaderboard_embed)```
shrewd apex
#

but fetch_guild like that would raise tracemalloc and not empty iterator

#

get_guild if not changed will just return None

slate swan
unkempt canyonBOT
#

@shrewd apex :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     None.name
004 | AttributeError: 'NoneType' object has no attribute 'name'
shrewd apex
#

user is prolly None

hasty coral
#

yes that exact error

shrewd apex
#

u need to fetch it

#

not get it get gets it from cache

slate swan
#

!d discord.Guild.fetch_member

unkempt canyonBOT
#

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

Retrieves a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") from a guild ID, and a member ID.

Note

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

Changed in version 2.0: `member_id` parameter is now positional-only.
hasty coral
#

riiight i see

full cosmos
shrewd apex
full cosmos
#

I swear I tried that exact same thing earlier and it didn't work

shrewd apex
#

happens to the best of us :p altho u prolly made some error somewhere else

full cosmos
#

Okay, so this works...

#

But this doesn't.

#

"ValueError: I/O operation on closed file"

slate swan
#

what file_objects are?

full cosmos
#

Oh it's the same error as before ("In message_reference: Unknown message") but During handling of it, the "I/O operation" error happens as well.

full cosmos
slate swan
#

definition ...

full cosmos
#

.pngs

#

four png files

slate swan
zenith ginkgo
#

its been over 24 hours and i still cant get the badge

#

anyone know why>

#

i used the / command

vernal bone
#
{
    "1045803353155829800": [
        "946756183862169600",
        "381633823181373443",
        "1028821837964124180"
    ],
    "1008022430620594237": [
        "442012110525038605"
    ],
    "640043175536230411": [
        "915402921590525993",
        "442012110525038605",
        "916151031547723836",
        "954582529065746484",
        "1078907660914671738",
        "1115434227270430830",
        "593837065171632130",
        "498206212270194689",
        "824869231530082334",
        "1011213610548203550",
        "381712712755052544",
        "381712712755052544",
        "1119855238095065198"
    ]
}```

How can I detect duplicates with this in this when its converted into a python dict using `json.load` (used for a discord bot)
proper thicket
zenith ginkgo
#

yeah i did, made sure it was a community server, made sure it was a slash command (global command) and waited 24 hours

#

this is the second time i tried

sick birch
naive briar
drifting arrow
vernal bone
#

Ok, thanks

drifting arrow
#

Alternatively, before you append to the list you make sure the value isnt already in the list

#

if not x in mylist: mylist.append(x)

naive briar
#

set moment

drifting arrow
#

Dont come @ me with your silliness

naive briar
#

What?

drifting arrow
#

idk

#

anyway. hi

#

How are you @naive briar

slate swan
#

**CAn anyone help me Why the emoji's are not showing in embed , tho I have picked all the emoji from the server in which my discord bot is already in **

dry sedge
#

how do I get the id of the current channel

slate swan
slate swan
dry sedge
#

oh wait

#

you dont code nvm I didnt see that

#

its fine

vocal snow
#

Why don't you just ask in the discord.js server?

dry sedge
#

ok

naive briar
#

:pithink:

turbid condor
slate swan
slate swan
echo wasp
#

I keep getting the any for the varible no matter witch i try

quick gust
zenith ginkgo
slate swan
hollow osprey
hasty coral
#
@commands.has_permissions(kick_members=True)
async def kick(ctx, member: discord.Member, *, reason=None):
    if member == ctx.author:
        raise commands.BadArgument("You cannot kick yourself.")
    
    if member is None:
        raise commands.BadArgument("You need to mention a user you want to kick.")
        
    await member.kick(reason=reason)
    await ctx.send(f'{member} has been kicked.')

    mod_log_channel = bot.get_channel(mod_log_channel_id)
    await mod_log_channel.send(f'{member} has been kicked. Reason: {reason}')
    
@kick.error
async def kick_error(ctx, error):
    if isinstance(error, commands.BadArgument):
        await ctx.send(error)
    elif isinstance(error, commands.MissingPermissions):
        await ctx.send("You don't have permission to kick members.")
    else:
        # Handle other errors here
        pass```

No error message appears in the console, but when a user inputs `?kick` without mentioning a user, the custom error message `You need to mention a user you want to kick.` does not appear.
slate swan
#
    if member is None:
        raise commands.BadArgument("You need to mention a user you want to kick.")
``` this will never be raised since if member is not specified `MissingRequiredArgument` will be raised
hasty coral
#

does that mean i have to change BadArgument to MissingRequiredArgument?

slate swan
#

no when user does not pass the member it doesnt even go into the command code

#

it goes to error handler directly so you need to add this case to your handler

hasty coral
#

right i see

ivory crypt
#

Is it possible for channel.fetched_message(message_id) to delete a ephemeral message?

full cosmos
#

Why does it give me an error message saying: "In message_reference: Unknown message" only when the file objects are attached to the message in the "except" part?

slate swan
#

slash.command doesn't work for me, its weird
is this the right code?
@bot.slash_command() async def epic(ctx): await ctx.respond(f"epic !")

#

error: slash_commands it not a real thing do you mean add_command?

slate swan
#

my code

`import discord
from discord.ext import commands
import json

bot = commands.Bot(command_prefix="/", intents=discord.Intents.all())

@bot.slash_command()
async def epic(ctx):
await ctx.respond(f"epic !")

bot.run("bro thought i would show my token ๐Ÿ’€")`

#

there is no such decorator like .slash_command in discord.py

full cosmos
#

@bot.command()
async def epic(ctx):

try that

slate swan
#

alright

slate swan
#

oh yeah

full cosmos
slate swan
#

oh

#

then how to do it?

slate swan
slate swan
#

bro someone grabbed my token from it

#

and raided my discordi

#

when did i tell you to use replit?

#

oops

#

i thought it was replit ๐Ÿ’€

#

sorry

#

it worked thanks ๐Ÿ˜„

sharp whale
#

how do i get guild icon as an url?

slate swan
#

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

docs exist for a reason

sharp whale
#

help server exist for a reason

slate swan
#

yeah i linked you to docs

#

just read attributes its that easy

sharp whale
#

but its not working

#
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\jpash\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 244, in wrapped    
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'url' ```
slate swan
#

what is not working show actual error

sharp whale
#

Default icons are considered as None?

slate swan
#

yes

sharp whale
#

eh

#

thats not good

#

discord should change this

#
  File "C:\Users\jpash\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke     
    await ctx.command.invoke(ctx)
  File "C:\Users\jpash\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 1029, in invoke    
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "C:\Users\jpash\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 244, in wrapped    
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'url'```
#

when i tried it after putting an icon

slate swan
sharp whale
slate swan
#

code?

sharp whale
#
Version: 2.3.1
Summary: A Python wrapper for the Discord API  
Home-page: https://github.com/Rapptz/discord.py
Author: Rapptz
Author-email: 
License: MIT
Location: C:\Users\jpash\AppData\Local\Programs\Python\Python311\Lib\site-packages
Requires: aiohttp
Required-by:```
sharp whale
# slate swan code?
@bot.command(aliases=["si"])
async def serverinfo(ctx):
    guild = ctx.guild
    total_members = guild.member_count
    text_channels = len(guild.text_channels)
    voice_channels = len(guild.voice_channels)
    categories = len(guild.categories)
    server_owner = guild.owner
    created_at = guild.created_at
    guild_icon = guild.icon.url

    embed = discord.Embed(title=f"Server Info - {guild.name}", color=discord.Color.blue())
    embed.set_thumbnail(url=guild_icon)
    embed.add_field(name="Server Owner", value=server_owner.mention, inline=False)
    embed.add_field(name="Total Members", value=str(total_members), inline=False)
    embed.add_field(name="Text Channels", value=str(text_channels), inline=False)
    embed.add_field(name="Voice Channels", value=str(voice_channels), inline=False)
    embed.add_field(name="Categories", value=str(categories), inline=False)
    embed.add_field(name="Created At", value=str(created_at), inline=False)

    await ctx.send(embed=embed)```
slate swan
#

what do you get when you do type(guild.icon)

sharp whale
#

hmm

#

interesting question

#

it works

#

when i do guild.icon

#

but url is icon.url in discord.Guild

kindred iron
#
    @tasks.loop(seconds=30)
    async def temp_ban(self):
        await self.bot.cursor.execute("""SELECT * FROM temp_ban""")
        data = await self.bot.cursor.fetchall()

        print(data)```
Can someone explain why fetchall returning me empty list?  I have data in database.
hoary dagger
#

Can anyone tell me how to Highlight a coding thing

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.

kindred iron
naive briar
#

Why would it be

slate swan
kindred iron
#

Yea that's why i said this question

#
    @commands.command()
    async def test(self, ctx):
        await self.bot.cursor.execute("""SELECT * FROM temp_ban""")
        data = await self.bot.cursor.fetchall()

        print(data)

Like, this work fine

#

It's literally the same code

slate swan
#

how do you define bot.cursor

kindred iron
#
self.db_connection : aiosqlite.Connection = await aiosqlite.connect("./database.db")
        self.cursor : aiosqlite.Cursor = await self.db_connection.cursor()```
slate swan
kindred iron
#

Ye

slate swan
#

and where is task located

kindred iron
#

Cog

slate swan
#

since it takes self

#

try adding this py @temp_ban.before_loop async def _before(self): await self.bot.wait_until_ready()

kindred iron
#

Did this already

slate swan
#

then no idea Shrugdge

kindred iron
naive briar
slate swan
kindred iron
#

Yes

kindred iron
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.

kindred iron
#

Ah wait

#

Btw i start the task on class init

dense barn
slate swan
unkempt canyonBOT
#

class discord.ui.Modal(*, title=..., timeout=None, custom_id=...)```
Represents a UI modal.

This object must be inherited to create a modal popup window within discord.

New in version 2.0.

Examples...
slate swan
kindred iron
#

hmm

rugged shadow
#

do you have an on_command_error?

#

you might be silencing errors

slate swan
#

what happens when you do !help or whatever your prefix is

#

there is a built in help command does this command appear here

#

hm fair enough

#

well how about you add print("Im here") print at top of your command

#

does it prints in console

#

ah so it works just not for you?

#

the voice_channel does not have .owner attribute

#

!d discord.VoiceChannel

unkempt canyonBOT
#

class discord.VoiceChannel```
Represents a Discord guild voice channel.

x == y Checks if two channels are equal.

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

hash(x) Returns the channelโ€™s hash.

str(x) Returns the channelโ€™s name.
slate swan
#

no there are no owners of voice channels on discord

naive briar
#

Do what

slate swan
#

use database i would say

#

your global error handler is silencing the errors either comment it out for debugging or add else: print(error) or smth like that so if the error is not handled it is shown in console

naive briar
#

(or just re-raise it)

slate swan
#

yeah

#
class ErrorNotHandled(Exception):
    pass

raise ErrorNotHandled() from error

``` i wonder if that would work and make sense
naive briar
#

Should be fine

#

You're getting the owner of the guild

#

And there's no such thing as an owner of a voice channel

slate swan
#

if thats how you want to handle it Shrugdge

#

then only the guild owner will be available to delete channels

#

i suppose you have a command to create a channel as well

#

if so you could do as follows:

  • on creating channel save who created a channel and what is the channel id to database
  • on removing channel check if the person trying to remove the channel did create it
#

no json file is not a good idea for database

#

im talking about a real database ile mysql or mongodb

#

there is easiest way

#

but it has one con

#

if you restart the bot all data is gone

#

you could use bot varriables

#

and store it in dictionary

#

!botvar

unkempt canyonBOT
#
Bot variables

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

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

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

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

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

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

slate swan
#

but like i said when you restart the bot all data is gone

cinder tulip
#
client = commands.Bot(command_prefix=".", owner_id = [ID1, ID2],  intents=discord.Intents.all())

why cant i use owner commands now

slate swan
#

owner_ids

cinder tulip
#

oh is that it?

slate swan
#

yes.

cinder tulip
#

i guess i am dumb xD

slate swan
#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

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

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

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

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

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

New in version 2.0.
slate swan
#

always good to check what attributes it has

#

owner_id is when you pass one id

surreal mist
#

hello i am an probleme with my bot discord ```py
import discord
from discord import app_commands
from discord.ext import commands
intents = discord.Intents().all() # Crรฉe une instance des intents par dรฉfaut

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

intents.message_content = True
intents.guilds = True
intents.members = True

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

@bot.command
async def bonjour(ctx):
await ctx.send("bonjour")

slate swan
naive briar
#

Nice

surreal mist
#

?

vocal snow
#

@bot.command() call it

#

and these 3 lines are useless ```py
intents.message_content = True
intents.guilds = True
intents.members = True

surreal mist
#

discord.ext.commands.errors.CommandNotFound: Command "bonjour" is not found

slate swan
#

discord.Intents().all() this correct syntax for class method?

surreal mist
#

the commands is does not word

naive briar
#

!e

class A:
    def __init__(self):
        self.a = 0

    @classmethod
    def dumb(cls):
        cls.a = 1
        return cls()

a = A()
print(a.a)

b = A().dumb()
print(b.a)
unkempt canyonBOT
#

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

001 | 0
002 | 0
slate swan
#

!e ```py
class A:
@classmethod
def all(cls):
return cls()
A.all()
A().all()

unkempt canyonBOT
#

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

[No output]
surreal mist
naive briar
#

Why

slate swan
#

this would make more errors

#

better for him to use .all

#

..

surreal mist
naive briar
#

They will not be able to make prefix commands

slate swan
#

maybe for your use case its good

naive briar
#

Just think for a second

slate swan
#

discord.Intents.all()

surreal mist
#

good

naive briar
#

Call the @bot.command

naive briar
surreal mist
#

what

naive briar
#

Sigh

surreal mist
#

sorry I am French and I start in Discord bot so I do not understand everything

slate swan
#

@bot.command
@bot.command()
see the difference between?

surreal mist
#

its is good

hasty pike
tacit prawn
#

How can I set one of the arguments in a command to have certain options in python?

slate swan
#

Anyone know why on the discord.py docs doesn't work in vs code (slash command)

tacit prawn
slate swan
#

ok

#

@client.slash_command() async def commandName(ctx): await ctx.respond(f"Hello !")

#

i got it from docs

naive briar
#

What docs

tacit prawn
naive briar
#

client.slash_command doesn't exist

tacit prawn
#

But, that will get member count

naive briar
tacit prawn
slate swan
#

ok

tacit prawn
slate swan
#

to coding and stuff ๐Ÿ’€

tacit prawn
slate swan
#

ok

tacit prawn
#

Like the full thing

slate swan
slate swan
tall temple
#

hi how can i generate a new random number between 1 and 2 for every command call

#

because i don't want to get the same random number for all called commands (casino game)

slate swan
#

bro uhh...

tall temple
hexed pilot
#

Hey guys what happens if automod reaches 100 rules?

slate swan
tall temple
tall temple
#

can someone help me pls ?

wooden storm
#

is discord.py the best lib to use? as in most up-to-date and most actively developed

#

compared to like nextcord, pycord, disnake, etc

vocal snow
#

all of those are actively developed

#

the "best" one depends on whether you like the way the library has implemented something

sick birch
#

Though I would recommend discord.py simply because it has the most support

slate swan
#

whatevs Same

#

me always suggesting nextcord huh

#

hikari

#

๐Ÿ—ฟ

slate swan
#

anyone know how to import commands from different files to main python file (discord.py library)

#

why dont you check docs

#

!d discord.Guild.roles

unkempt canyonBOT
#

property roles```
Returns a sequence of the guildโ€™s roles in hierarchy order.

The first element of this sequence will be the lowest role in the hierarchy.
slate swan
#

how would i wait for someone to click my button

slate swan
stark socket
#

im making a bot that needs to associate people across servers as the same person the best way to do this is by getting the username instead of the nick right? how can i do that?

slate swan
sick birch
#

Users can change their usernames however they can't change their ID

midnight oracle
#

Hyo, I'm trying to make a music bot (basic) for personal use and I'm having an error when trying to play the music, when I put the name everything goes has expected, the bot searchs for the song, enters the VC, aaaand, nothing happens, the console says this:

[download] Downloading playlist: Light Switch
[youtube:search] query "Light Switch": Downloading page 1
[youtube:search] playlist Light Switch: Downloading 1 videos
[download] Downloading video 1 of 1
[youtube] WFsAon_TWPQ: Downloading webpage
[download] Finished downloading playlist: Light Switch
2023-07-04 15:46:41 INFO     discord.voice_client Connecting to voice...
2023-07-04 15:46:41 INFO     discord.voice_client Starting voice handshake... (connection attempt 1)
2023-07-04 15:46:42 INFO     discord.voice_client Voice handshake complete. Endpoint found st-pete4186.discord.media
2023-07-04 15:46:45 INFO     discord.player ffmpeg process 7584 successfully terminated with return code of 1.

Any idea what it is?

slate swan
#

!ytdl

unkempt canyonBOT
#
Our youtube-dl, or equivalents, policy

Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.

For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:

The following restrictions apply to your use of the Service. You are not allowed to:

1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service;  (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;

3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTubeโ€™s robots.txt file; (b) with YouTubeโ€™s prior written permission; or (c) as permitted by applicable law;

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
midnight oracle
#

Oh

#

It isn't possible so

#

Rule 9 says i can use it for personal use

#

._.

#

nevermind

snow coral
slate swan
#
from discord.ext import commands

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

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

extracted_messages = 0

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name} ({bot.user.id})')

@bot.event
async def on_message(message):
    global extracted_messages
    if isinstance(message.channel, discord.TextChannel):
        if message.channel.id == 1234567890:  # Replace with your channel ID
            extracted_text = message.content
            save_to_file(extracted_text)
            extracted_messages += 1
            print_extracted_messages()

def save_to_file(text):
    with open('output.txt', 'a', encoding='utf-8') as file:
        file.write(text + '\n')

def print_extracted_messages():
    global extracted_messages
    print(f'Extracted messages: {extracted_messages}')

def run_bot():
    bot.run('YOUR_BOT_TOKEN')  # Replace with your bot token

run_bot()```
#

can someone help im trying to make that it would extract all the messages from discord channel and it doesnt work

#

i did everything correct asked chatgpt and more

#

still the same issue

#

it should even show a extracted messages counter

#

but it just shows this

#

sorry im new

potent spear
potent spear
#

run_bot()
useless function

#

you're missing message_content intents

slate swan
#

It should show the extracted message counter and it should be saved to output.txt but it doesnt work

grand swan
#

what should i write to have a discord bot play audio? (ideally using .play (file))

potent spear
potent spear
#

did you enable message_content intents in the discord dev portal too?

potent spear
grand swan
# potent spear there's an example either on the docs or on their github > examples for this use...

could i have a link to that? also here's some of the code i have so far and it works but i have to type in .play1(song) and it's only for one and i was wondering if there's a way to have it so i do .play space (any song i have on the directory) i tried arg already but it didn't work.

@client.command(pass_context = True)
async def play1example(ctx):
voice = ctx.guild.voice_client
source = FFmpegPCMAudio('discord bot\example.wav')
player = voice.play(source)

potent spear
potent spear
slate swan
potent spear
# slate swan

print the message content in on_message
see if that gets printed

slate swan
#

Alright ill try tomorrow

grand swan
potent spear
grand swan
potent spear
#

if your arg specifies a different audio file, it'll play that different audio file
at least, if you specified the PATH to it correctly

slate swan
#

cause the pass_context = True does not exist any more

grand swan
slate swan
#

it was changed in v1

#

and its 2.3.1 already long time ago

grand swan
potent spear
grand swan
#

sorry if i'm not getting some basic concepts i'm very new to most python

potent spear
#

<your audio files directory> + filename + .wav

grand swan
#

i probably did it wrong

potent spear
#

make a separate variable for the file path, print it and see if you think it's correct
spoiler, it's not

grand swan
potent spear
#

put the lines under voice
and put the file path in the FFmpegPCMAudio ofc

grand swan
potent spear
grand swan
#

this is what imported btw

#

import discord
from discord.ext import commands
from discord import FFmpegPCMAudio

potent spear
#

not relevant ๐Ÿ‘

grand swan
#

@client.command(pass_context = True)
async def play(ctx):
voice = ctx.guild.voice_client
file= 'discord bot\pvzm.wav'
source = FFmpegPCMAudio(file + '.wav')
player = voice.play(source)

i'm not sure if you meant literally under like under the line or under like inside

potent spear
#

alr, now put only the file in FFmpegPCMAudio
beause ofc ...wav.wav makes no sense

#

and you completely removed the arg, not great

grand swan
#

ah i see, so it would be somebody types for example trumpet and trumpet is a variable and it's in the source

potent spear
potent spear
grand swan
potent spear
#

there we go

#

now all that's left for you is to actually use that arg variable of yours

grand swan
#

should i put a bunch of variables under voice like pvzm = file for example

potent spear
#

so change the file variable correctly, so it actually uses the arg variable to create the filepath

grand swan
#

this works for one variable, but what should i do for multiple? should i put
source = FFmpegPCMAudio(A, B, C)

or

source = FFmpegPCMAudio(arg)

grand swan
#

@client.command(pass_context = True)
async def play(ctx, arg):
voice = ctx.guild.voice_client
arg= 'discord bot\pvzm.wav'
source = FFmpegPCMAudio(arg)
player = voice.play(source)

#

hmm

potent spear
#

I'll just give it to you for now, as this will probably take too much time for something quite simple

#
file_path = "discord_bot\\" + arg + ".wav"
source = ...Audio(file_path)```
grand swan
#

is "file_path a variable?

potent spear
#

correct

#

if you want to make it actually work:

from pathlib import Path
# ...

current_file_directory = Path(__file__).parent
audio_file_path = current_file_directory / f"{arg}.wav"
source = ...Audio(audio_file_path)```
grand swan
#

vs code is giving me some errors with ...audio

potent spear
#

that's FFmpegAudio

#

I'm just lazy of typing it all out

#

I hoped you'd understand, so you wouldn't copy paste
I guess you did

sick birch
grand swan
potent spear
#

because you probably either didn't even put it in the command
or you just removed that arg...

grand swan
#

yeah it works, thank you, i appreciate the patience with me lol.

potent spear
#

gl hf

snow coral
#

hey! im trying to get my bot to send a message when a thread is created, but i cant get it to work

async def on_thread_create(Thread, ctx):
    owner_name = Thread.owner
    embed = discord.Embed(title=f"Thank you {owner_name} for creating a suggestion!",
                          description="All suggestions help us improve the server.",
                          colour=discord.Colour.yellow())
    embed.add_field(name="**Remember to:**", value="โ€ข **Explain** as much as you can, don't have short answers; they dont help.", inline=False)
    embed.add_field(name=None, value="โ€ข **Show** an example of your suggestion if possible.", inline=False)
    embed.set_author(name="Suggestion channel opened.", icon_url="blob:https://www.remove.bg/17c608e7-3960-4ec6-b775-8bc0ea33ab99")
    await ctx.send(embed=embed)
slate swan
#

see how the @unkempt canyon bot does it

#
async def scanTrade(channel):
    tradeCorrect = False
    while not tradeCorrect:
        assetIdList = await scanner()
        print(assetIdList)
        imageTrade = await drawTable(assetIdList)

        trade_embed = discord.Embed(title="Is This The Correct Trade?", description="**Sender - ** `Neweraside`", color=discord.Color.blue())
        trade_embed.set_image(url="attachment://new.png")

        class TradeView(View):
            def __init__(self):
                super().__init__()
                self.verify_button = Button(style=discord.ButtonStyle.success, label="Correct", custom_id="verify_trade_button")
                self.incorrect_button = Button(style=discord.ButtonStyle.danger, label="Incorrect", custom_id="incorrect_trade_button")
                self.add_item(self.verify_button)
                self.add_item(self.incorrect_button)

        trade_view = TradeView()
        trade_message = await channel.send(embed=trade_embed, file=imageTrade, view=trade_view)

        try:
            interaction = await bot.wait_for("component", check=lambda i: i.channel == channel and i.message == trade_message)
            custom_id = interaction.data["custom_id"]
            
            if custom_id == "verify_trade_button":
                tradeCorrect = True
                await acceptTrade()
                await interaction.response.send_message("Trade completed!", ephemeral=True)
            elif custom_id == "incorrect_trade_button":
                await interaction.response.send_message("Continuing to scan for new trades...", ephemeral=True)

        except asyncio.TimeoutError:
            await channel.send("No response received. Continuing to scan for new trades...")```


could anyone help

when clicking incorrect or correct button nothing happens
torn solar
#
async def announce(ctx, title, color= discord.Color,*args):
    description = ''.join(args)
    embed = discord.Embed(title=title, color=color, description=description)
    channel = bot.get_channel(anc)
    channel.send(embed=embed)```
#

its giving an error about the color

slate swan
torn solar
#

!paste

torn solar
slate swan
#

Cause default value of color is set to Color class

#

You prolly want to annotate it as Color class

torn solar
#

how do i annotate it as a class

dry kelp
#
    @slash_command(dm_permission=False)
    async def afk(
        self,
        interaction: CommandInteraction,
        reason: str = Param(max_length=100),
    ):
        """
        Set your status to AFK.

        Parameters
        ----------
        reason: Reason for going AFK.
        """

        if "[AFK]" in interaction.author.display_name:
            embed = report_embed(
                False,
                description="AFK detected in name, aborting...",
            )
            await interaction.send(embed=embed, ephemeral=True)
            return

        await interaction.response.defer()

        afk = await AfkModel.get_or_none(
            discord_id=interaction.author.id, guild_id=interaction.guild.id
        )

        if not afk:
            await AfkModel.create(
                discord_id=interaction.author.id,
                guild_id=interaction.guild.id,
                reason=reason,
            )
        else:
            embed = report_embed(
                False,
                description="You are already afk!",
            )
            await interaction.send(embed=embed, ephemeral=True)  # FIXME
            return

        if (
            interaction.author != interaction.guild.owner
            and interaction.author.top_role < interaction.guild.me.top_role
            and interaction.guild.me.guild_permissions.manage_nicknames
        ):
            await interaction.author.edit(nick=f"[AFK]{interaction.author.display_name}")
        await interaction.send(
            f"Set your status to AFK with reason: `{reason}` {format_dt(utcnow(), style='R')}"
        )
#
        else:
            embed = report_embed(
                False,
                description="You are already afk!",
            )
            await interaction.send(embed=embed, ephemeral=True)  # FIXME
            return

Why this part is not being send as ephemeral?

#

I know it happens because of interaction.response.defer But i don't want

await interaction.send(
            f"Set your status to AFK with reason: `{reason}` {format_dt(utcnow(), style='R')}"
        )

to be ephemeral too

torn solar
#

how can i check if a member has a certain role

#

if "Chairman" in ctx.author.roles.name():

#

it says list has no attribute name

naive briar
#

Duh??? Because it doesn't?

#

Where did you get this thing from

torn solar
#

because name is an attribute of discord.Role

naive briar
#

It's not of list

torn solar
#

can you help me fix it

#

or just tell me why im wrong

worthy mortar
#

does this not work?

โ€ฆ
user_has_role = any(role.name == โ€œnameOfRoleโ€ for role in member.roles)
โ€ฆ

naive briar
reef plank
#

Any good recommendations for bot hosting taking into consideration active development? I'm still working on my bot and am pushing out new commands everyday but I want it to be up 24/7 when I'm not working.

slate swan
torn solar
torn solar
#

if "Chairman" in ctx.author.roles.name():
it says list has no attribute name

#

can someone help me fix this

slate swan
slate swan
torn solar
#

if "Chairman" in ctx.author.roles.name():
it says list has no attribute name
can someone help me fix this

torn solar
#

i figured it out

#

thanks tho

#
        description = ' '.join(args)
        embed = discord.Embed(title=title, color=color, description=description)
        channel = bot.get_channel(anc)  # Replace CHANNEL_ID with the actual channel ID
        if description.__contains__('@everyone'):
            await channel.send(embed=embed, content="@everyone", allowed_mentions=discord.AllowedMentions(everyone=True))
        else:
            await channel.send(embed=embed)
    else:
        await ctx.send("You need to have the chairman role to do this")```
#

its not working even tho i have a role named Chairman

naive briar
#

You're comparing string to roles

#

Is it that hard to understand why it won't work

torn solar
#

you gotta be a dick?

naive briar
#

How so

torn solar
#

im asking for help in a help channel

#

and your just telling me im an idiot

naive briar
#

It's just commonsense

fierce crag
#

@naive briar please try to help without being condescending.

turbid condor
# torn solar thanks tho

U will have to first fetch the role using utils.get and then use that to check if the user has that role or not
Like

role = discord.utils.get(ctx.guild.roles, name='role_name')
If role in ctx.author.roles:
torn solar
#

i figured it out

#

chatgpt helps and isnt rude

vocal snow
turbid condor
#

Welp yeah that works too

naive briar
#

lmao

winter token
#

can someone here help me regarding dpy json?

#
    @commands.command()
    async def gchannel(self, ctx, channel: discord.TextChannel):

        gid = ctx.guild.id

        if gid not in data:
            with open('logs_data.json', 'w') as f:
                data[gid] = {}
                data[gid]['cid'] = channel.id
                json.dump(data, f, indent = 4)

        else:
            data[gid]['cid'] = channel.id
                

        await ctx.reply(f'{channel.mention} has been set as greet channel.')
naive briar
#

What's wrong then

#

I guess I don't have to look that long

winter token
#

so when i did for general, it set the gchannel to general and added its id in the json file

naive briar
#

First, the gid is an int, JSON keys can only be strings

winter token
#

but when i did for sexy channel

#

cid wasnt updated in the file

#

@naive briar

#

nvm

#

figured it out

slate swan
#
from discord import app_commands
from discord.ext import commands

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

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

@bot.event
async def on_ready():
    print('metal is online')
    try:
        synced = await bot.tree.sync()
        print(f"Synced {len(synced)} command(s)")
    except Exception as e:
        print(e)

@bot.tree.command(name="send")
async def send(interaction: discord.Interaction):
    await interaction.response.send_message(f"hey",
    ephemeral=True)
    

@bot.command()
async def ping(ctx):
    await ctx.reply('**pong**')
    
bot.run('')```
#

Can someone help me

winter token
#

show code

turbid condor
#

just remove the from discord import app_commands

winter token
#

yea of role cmd

slate swan
turbid condor
slate swan
turbid condor
#

not discord

winter token
#

u sure that u gave correct role name while using the cmd?

turbid condor
slate swan
potent spear
turbid condor
potent spear
#

or that

slate swan
turbid condor
#

Try using utils.get to get the role and then remove it

winter token
#

send ss of the role u are trying to give to the user

turbid condor
#

use pip --upgrade discord.py

#

and then run your code that should solve the problem

#

remove it from the user

#
role = discord.utils.get(ctx.guild.roles, name=f'{role}')
If role in member.roles:

Edit: don't add remove in member.roles.remove that will fetch an error

slate swan
short steppe
slate swan
#

Do you know why its just sent to me?

turbid condor
#

set ephemeral to False

slate swan
#

oh ye ur right

#

i put true for some reason

#

now im gonna try to have it add a button to a message i will be here if i need any help xd

turbid condor
#

๐Ÿ‘

turbid condor
# slate swan now im gonna try to have it add a button to a message i will be here if i need a...

In case you need examples
Check this out

Buttons (or components) are now in the 2.0a version of the library which is only obtainable from GitHub, see ?tag dins for how to install this version.

If you wish to use Buttons (and Selects/Dropdowns), please view the documentation for discord.ui here:
https://discordpy.readthedocs.io/en/latest/interactions/api.html#bot-ui-kit

You can also view examples in the repo: https://github.com/Rapptz/discord.py/tree/master/examples/views

GitHub

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

slate swan
turbid condor
slate swan
#

the link button

turbid condor
#

yeah

slate swan
turbid condor
#

that's how you create buttons the are called views in discord.py

#

those are examples on how to create them and then send them with your message

slate swan
#

ik how to make the button link just dont know how to make all that into an slash command

turbid condor
turbid condor
#

i'll try explaining

#
# This example requires the 'message_content' privileged intent to function.

from discord.ext import commands

import discord
from urllib.parse import quote_plus


class GoogleBot(commands.Bot):
    def __init__(self):
        intents = discord.Intents.default()
        intents.message_content = True

        super().__init__(command_prefix=commands.when_mentioned_or('$'), intents=intents)

    async def on_ready(self):
        print(f'Logged in as {self.user} (ID: {self.user.id})')
        print('------')


# Define a simple View that gives us a google link button.
# We take in `query` as the query that the command author requests for
class Google(discord.ui.View):
    def __init__(self, query: str):
        super().__init__()
        # we need to quote the query string to make a valid url. Discord will raise an error if it isn't valid.
        query = quote_plus(query)
        url = f'https://www.google.com/search?q={query}'

        # Link buttons cannot be made with the decorator
        # Therefore we have to manually create one.
        # We add the quoted url to the button, and add the button to the view.
        self.add_item(discord.ui.Button(label='Click Here', url=url))


bot = GoogleBot()


@bot.command()
async def google(ctx: commands.Context, *, query: str):
    """Returns a google link for a query"""
    await ctx.send(f'Google Result for: `{query}`', view=Google(query))


bot.run('token')```
slate swan
#

Huh?

turbid condor
#

u see the Google class it contains a View(basically a button) which contains

slate swan
#

I see but I'm not using cogs

turbid condor
#

these work even without cogs

#

and this example is not using cogs

#

its using @bot

slate swan
#

There's a class though

#

I wouldn't know how to take that and make a slashcommand with a link button

turbid condor
#

instead of

#
    await ctx.send(f'Google Result for: `{query}`', view=Google(query))```
slate swan
#

interactionn

turbid condor
#

yup

#

that will send the button with the message

slate swan
turbid condor
#
class Google(discord.ui.View):
    def __init__(self, query: str):
        super().__init__()
        # we need to quote the query string to make a valid url. Discord will raise an error if it isn't valid.
        query = quote_plus(query)
        url = f'https://www.google.com/search?q={query}'

        # Link buttons cannot be made with the decorator
        # Therefore we have to manually create one.
        # We add the quoted url to the button, and add the button to the view.
        self.add_item(discord.ui.Button(label='Click Here', url=url))
#

you can change the class name the link and label

slate swan
#

I have this

async def send(interaction: discord.Interaction):
    await interaction.response.send_message(f"https://restorecord.com/verify/1125684013672181801",
    ephemeral=False)```
What I'm confused about is how to add a link button to a message
turbid condor
#

and yeah no need for that query line

#
class XYZ(discord.ui.View):
    def __init__(self, query: str):
        super().__init__()
        url = 'Your Link Here'

        self.add_item(discord.ui.Button(label='Button_Name', url=url))

Then you can send it like

await interanction.response.send_message('Your_message_here', view=XYZ)````
#

This will send the button

slate swan
#

for example

turbid condor
#

just remove the message

slate swan
potent spear
slate swan
#

because he said remove message

turbid condor
#

you have to do that in your command

potent spear
#

you even copy pasted his typo :/

slate swan
#

and I fixed

slate swan
turbid condor
#

when do you want to send that button?

slate swan
#

as soon as I use the slash command /send

turbid condor
#

then why u asking me the command

slate swan
#

I have been saying slash command no?

turbid condor
#

and from when did prefix commands start using interaction?

slate swan
#

._. I will just create python-help channel

#

Thx a lot though

hasty pike
#

You need to level up your python skills

surreal mist
#

hello I make a bot dicord and the I make a system of economy like 1 message reports a number on 10 pieces but when I restart the bot more nobody has piece I was told to make a SQL database but we were obliged?

slate swan
#

yes, store the economy values in database

winter token
#
async def purge(self, ctx, amount: int, target = None):
        
        description = f"**Purged by:** {ctx.author.mention}\n**Amount:** {amount} messages"
        embed = discord.Embed(title = "Purged Successfully!", description = description, colour = colour)

        if target == 'bot':
            def check(message):
                return message.author.bot
            
        elif target == 'attachments':
            def check(message):
                return message.attachments
            
        elif target == 'human':
            def check(message):
                return not message.author.bot
        
        await ctx.channel.purge(limit = amount+1, check = check)
        await ctx.send(embed = embed, delete_after = 5)
#

bot wont delete msg when I do $purge amt bot

#

but sends the embed

slate swan
#

did you try debugging it?

#

printing what if block is triggered etc?

winter token
#

and when i do $purge amt attachments, it won't delete the msg used for invoking it

winter token
slate swan
#

it will delete only messages containing attachments

winter token
#

oh yea

#

so what should I do

slate swan
#

what do you want to do

winter token
slate swan
#

!d discord.ext.commands.Context.message

unkempt canyonBOT
#

The message that triggered the command being executed.

Note

In the case of an interaction based context, this message is โ€œsyntheticโ€ and does not actually exist. Therefore, the ID on it is invalid similar to ephemeral messages.

slate swan
#

delete the message yourself

winter token
slate swan
#

how am i supposed to know

winter token
slate swan
#

it deletes the messages only from the bot accounts

winter token
winter token
#

when i execute it just sends the embed and does nothing

unkempt canyonBOT
slate swan
#

!d discord.TextChannel.purge

unkempt canyonBOT
#

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

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

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

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

Examples

Deleting botโ€™s messages...
slate swan
#

see what it returns and see what it does for you

winter token
young dagger
#

Is this a good way to implement a ping command for the bot?

    message = await ctx.channel.send("Pong!")  # Send initial "Pong!" message
    latency = int(client.latency * 1000)
    await message.edit(content=f"Pong! `{latency}ms`")  # Edit message with actual latency```
turbid condor
#

When u can get the latency before the message and send it in the message

young dagger
#

I noticed other bots do that as well

turbid condor
#

Welp u could have sent it in the first message

#

You are sending an extra request when it's not needed

young dagger
turbid condor
#

?

#

Oh the edited part

young dagger
#

Yeah

turbid condor
#

Welp that's ok too

#

Depends on what u want to do

slate swan
proud fossil
#

can anyone help me on making a pokemon bot?

slate swan
#

@shrewd apex

winter token
young dagger
turbid condor
#

It's their choice nothing else we can say

#

But yeah I'll stick with down since the message will be edited almost instantaneously so no need to send an extra req

slate swan
winter token
#

..

slate swan
#

limit (Optional[int]) โ€“ The number of messages to search through. This is not the number of messages that will be deleted, though it can be.

winter token
#

then what do I do

#

loop?

slate swan
#

Write some code that determines the purge limit from the target & the count

young dagger
slate swan
#

No its not

young dagger
slate swan
#

so thats not how long it took to send a message via api

young dagger
# slate swan so thats not how long it took to send a message via api

Any ideas on how I can accomplish that?

    start_time = ctx.message.created_at
    message = await ctx.channel.send("Pong!")  # Send initial "Pong!" message
    end_time = message.created_at
    latency = int((end_time - start_time).total_seconds() * 1000) 
    await message.edit(content=f"Pong! `{latency}ms`")  # Edit message with actual latency```
#

Or would you have done it differently?

slate swan
#

!e ```py
import datetime
import time

start = datetime.datetime.now()

do something

time.sleep(1)

end = datetime.datetime.now()

print(f"Took: {end - start}")

unkempt canyonBOT
#

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

Took: 0:00:01.000097
young dagger
#

My code:

   start_time = datetime.datetime.now()
   # message = send message
   end_time = datetime.datetime.now()
   latency = int((end_time - start_time).total_seconds() * 1000)
   # edit message with latency```
slate swan
#

should be good

naive briar
#

!d time.perf_counter me when

unkempt canyonBOT
#

time.perf_counter() โ†’ float```
Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. The reference point of the returned value is undefined, so that only the difference between the results of two calls is valid.

Use [`perf_counter_ns()`](https://docs.python.org/3/library/time.html#time.perf_counter_ns "time.perf_counter_ns") to avoid the precision loss caused by the [`float`](https://docs.python.org/3/library/functions.html#float "float") type.

New in version 3.3.

Changed in version 3.10: On Windows, the function is now system-wide.
slate swan
slate swan
#

!di discord.waitfor

unkempt canyonBOT
#
Did you mean ...

ยป dict-get
ยป iterate-dict
ยป dictcomps
ยป discord-bot-hosting

slate swan
#

could anyone tell me how i can wait for a button click

slate swan
turbid condor
#

Try looking at the gist

#

You need to define a button and then send it with your message

#

And button uses interaction

slate swan
#

help

turbid condor
#

Where are you sending the button?

#

Isn't your await channel.send inside the class?

slate swan
naive briar
#

Someone sent the example of discord.ui.View, look at it

shut river
#

hi

gilded cedar
#

does anyone uses nextcord? uhh on_command_error doesn't work properly

shut river
turbid condor
#

u can try using another device to run your bot

shut river
#

thats fixed a long time ago,

#

im just struggling with something else atm

fallen imp
#

help me .-.

turbid condor
#

if it's discord.py then dpy doesn't have anything like slash_commands

shut river
#

Hey guys can you help me im running into this error:

        split = content.split(".")
        author = split[0].lower()
        item = split[1]
        amount = split[1]
``` this is the code
fallen imp
shut river
#

this is the error:

2023-07-05 18:35:16 ERROR    discord.client Ignoring exception in on_message
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/client.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "/Users/mac/Desktop/GrowBet/main.py", line 47, in on_message
    item = split[1]
           ~~~~~^^^
IndexError: list index out of range
turbid condor
#

dpy doesn't have anything like that

shut river
#

im struggling a lot honestly..

fallen imp
turbid condor
#

dpy also has slash commands but the are not defined using slash_commands

#

so please stop using old tutorials and guides or gpt for coding

turbid condor
# fallen imp what lib can i get slash_cammand .-.

Use this instead

Here is a short example of how to use discord.py's slash commands as well as general information on them:

https://gist.github.com/AbstractUmbra/a9c188797ae194e592efe05fa129c57f

This currently covers free commands and groups at the Bot level, as well as within Cog classes.
It also includes information and gotchas relating to syncing and whatnot.

NOTE: This will be migrating to https://about.abstractumbra.dev/ as soon as I can be bothered to finish it.

Gist

discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.

fickle crown
#
@bot.command()
async def ping(ctx):
 XXX
 XXX```



I can't type commands right now.
before.
What has changed in Discord?
Can someone type $ping?
naive briar
#

What

sick birch
#

?

vocal snow
#

selfbot thinkmon

swift trench
#
Traceback (most recent call last):
  File "main.py", line 11, in <module>
    import cfscrape
  File "/home/runner/XTool/venv/lib/python3.10/site-packages/cfscrape/__init__.py", line 19, in <module>
    from urllib3.util.ssl_ import create_urllib3_context, DEFAULT_CIPHERS
ImportError: cannot import name 'DEFAULT_CIPHERS' from 'urllib3.util.ssl_' (/home/runner/XTool/venv/lib/python3.10/site-packages/urllib3/util/ssl_.py)
#
import cfscrape

surreal mist
#

"Hello, can someone help me? I would like my bot to respond to a person when someone writes on the server. The bot doesn't have any issues, but it's not responding. Thank you."

slate swan
swift trench
#

i have no udea

slate swan
#

doesnt look like it is

vocal snow
# surreal mist

do you have message content intents enabled? Do you have another on_message event?

surreal mist
#

yes a have another on_message event

vocal snow
#

the event decorator will override the internal event handler of your bot instance, hence you can only have one

#

it's better to use a listener instead

slate swan
vocal snow
#

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

bot.listen

torn solar
#
async def join(ctx):
    channel = bot.get_channel(join)
    await ctx.send("To join the party, go to" + channel.mention + "!")```
#

its saying nonetype has no attribute mention

#

i double checked and join is the id of the channel

slate swan
#

cause you pass join to .get_channel but join is name of the command

torn solar
#

oops

worthy ridge
#

guys having trouble with commands

#

the command keeps on getting registered as a message

#

@bot.command(name="hello") async def hello(ctx, arg: str): await ctx.channel.send("hello")

regal tiger
regal tiger
worthy ridge
#

tried with and without arg

regal tiger
#

Use bot.tree.command instead

worthy ridge
#

ah ok

regal tiger
#

and add the following to your on_ready function:

try:
    synced = await bot.tree.sync()
    print(f"Synced {len(synced)} command(s)")
except Exception as e:
    print(f"Houston, we have a problem.....\n\nException upon syncing commands: {e}")
#

@worthy ridge

worthy ridge
#

ah thanks

#

what does await bot.tree.sync() do by

#

btw*

slate swan
worthy ridge
slate swan
worthy ridge
#

yea

slate swan
#

you dont pass the guild

#

!d discord.app_commands.CommandTree.sync

unkempt canyonBOT
#

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

Syncs the application commands to Discord.

This also runs the translator to get the translated strings necessary for feeding back into Discord.

This must be called for the application commands to show up.
slate swan
#

guild (Optional[Snowflake]) โ€“ The guild to sync the commands to. If None then it syncs all global commands instead.

worthy ridge
torn solar
#

await ctx.send('**ROLES**\nl\nlFounder - The Founder is the Founder of the whole party.\nlChairman - The Chairman mkes decisions for the party, Chairman is the party leader.\nlAdmin - Admin Means that you help with the party and the Discord server.\nlCampaign Manager - Campaign Manager is the position that gets supporters for the party.\nlParty Member - A party member means you are a member of the DMP\nlVisitor - Visitor means you are visiting our discord server, maybe reading policies.\nl\nl**POLICIES**\nl\nlView Crime Policies - View all of our policies about Crime\nlView Government Policies - View all of our policies about Government\nlView Business Policies - View all of our policies about Business\nl\nl' + ctx.author.mention)

#

why is it doing that

#

i fixed the POLICIES cus i didnt close it

#

but i dont understand why all the l's

slate swan
#

cause you coded it to?

#

you put \nl everywhere

torn solar
#

isnt that the newline

slate swan
#

\n is

torn solar
#

bruh i forgot im dumb

#

thanks tho