#discord-bots

1 messages · Page 1046 of 1

glad cradle
#

you cannot access a user's warnings if this does not exist in the json file

formal basin
#

Like what?

heady sluice
#

but it would still be stuck wouldn't it

glad cradle
#

also a json file is not great to use so

stray carbon
#

still confused here :hmm:

heady sluice
#

why

formal basin
heady sluice
#

it gets all the messages into a list if they're in a certain channel (because I didn't know what your condition was), then if the time is already more than what you define end_of_time, it exits the wait_for

glad cradle
heady sluice
#

returning True

dire folio
formal basin
honest shoal
#
<p>The owner of this website (discord.com) has banned you temporarily from accessing this website.</p>```
#

why I'm getting this

glad cradle
#

can't you use a database?

#

maybe the replit database

formal basin
glad cradle
#

pain

loud junco
honest shoal
supple thorn
honest shoal
formal basin
#

It’s dumping the id

#

But not the amount of warnings

loud junco
#

my vs code thing not working ;-;

placid verge
exotic maple
#

How would i make it ignore the bots reaction? Only react if its 2 reactions

granite parcel
#

can i ask a query related to dislash?

dire folio
#

Yh

granite parcel
#

i am using dislash for drop down menus

#

and i want that when someone clicks in menu bot responds

forest bramble
#

I am getting this error. Can someone help me?

#

@slate swan ^^

#

Long time no help 😦

vale wing
#

!ytdl

unkempt canyonBOT
#

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)
granite parcel
#

@vale wingcan u help me ?

forest bramble
#

it's not youtube_dl @vale wing.

vale wing
#

With what

forest bramble
#

It's ffmpeg

vale wing
#

youtube_dl.utils.DownloadError

granite parcel
# vale wing With what

i am using dislash for drop down menus
and i want that when someone clicks in menu bot responds

vale wing
#

Ytdl related

vale wing
granite parcel
vale wing
#

I think it was renamed to disnake which is the modern library but I am not sure about that

granite parcel
#

yeah it is renamed to disnake

forest bramble
#

And discord to nextcord

granite parcel
#

but there exists dislash too

forest bramble
#

idk

#

the old libraries are still there but useless

vale wing
forest bramble
#

as new cmds have come

vale wing
#

Dpy stays itself

#

Nextcord is a fork

#

Just like disnake

forest bramble
#

nextcord is better than discord

vale wing
#

Idk about it but disnake is better at slash commands implementation

vale wing
#

Is this in a cog

#

Then why do you have self

glad cradle
#

sure you don't want to use the replit database?

formal basin
#

Nvm

#

Don’t worry

granite parcel
vale wing
#

What have you got so far

dire folio
#

How would I do smth if the channel doesn't let people msg in it

glad cradle
#

this is in a cog file?

vale wing
#

Logic

dire folio
#

I mean like how would I check if the channel doesn't let people type in it

vale wing
#

Ah that

#

I don't remember correctly

#

!d discord.TextChannel

vale wing
unkempt canyonBOT
#

permissions_for(obj, /)```
Handles permission resolution for the [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member")
or [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role").

This function takes into consideration the following cases...
flint isle
#

TypeError: Embed.set_author() takes 1 positional argument but 2 positional arguments (and 2 keyword-only arguments) were given

    embed.set_author('name', url='Embed.Empty', icon_url='Embed.Empty')
vale wing
#

!d discord.Embed.set_author

unkempt canyonBOT
#

set_author(*, name, url=None, icon_url=None)```
Sets the author for the embed content.

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

All args are keyword-only @flint isle

flint isle
#

whats keywords

vale wing
#

function(kwarg=10)

flint isle
#

umm so how do i fix the embed code then? what part is wrong?

vale wing
#

You provided first arg as a positional one but it is keyword

#

Add name= before it

flint isle
#

oh

flint isle
#

this is my cog, what is wrong in it?

import disnake
from disnake.ext import commands
from colorama import Fore, Back, Style

class events(commands.Cog):
    """Useful Features for Bot Development."""


    def __init__(self, bot: commands.Bot):
        self.bot = bot
        print('Loading Events cog')


    @commands.Cog.listener()
    async def on_ready(self):
        print(Fore.GREEN + 'Connected!' + Fore.WHITE)
        print(Fore.GREEN + 'Bot is ready!' + Fore.WHITE)
        print(Fore.CYAN + 'Waiting For Commands' + Fore.WHITE)
        bot.get_guild(798726719573065749)
        channel = bot.get_channel(798726720181633047)
        await channel.send('Bot Online!')
        embed = disnake.Embed()
        embed.title = f"**Online**"
        embed.description = f"[`{datetime.datetime.now().strftime('%b-%d-%Y`] @ [`%I:%M:%S')}`]\n\n" \
                            f"- Bot account: `{bot.user.name}`\n" \
                            f"- Bot ID: `{bot.user.id}`\n" \
                            f"- Guilds: `{len(bot.guilds):,}`\n" \
                            f"- Users: `{len(list(bot.get_all_members()))}`\n" \
                            f"- Disnake Version: `{disnake.__version__}`\n" \
                            f"- Developer: `whiskeythefox$7339`\n" \
                embed.set_footer(text="Logging System")
        GUILD_ID = 798726719573065749
        CHANNEL_ID = 798726720181633047
        location = bot.get_guild(GUILD_ID).get_channel(CHANNEL_ID)
        await location.send(embed=embed)

        pass

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

cause it wont run that on ready

vale wing
#

What error do you get

#

And do print statements get executed

#

I suspect you have issue with sending a message to a channel

flint isle
# vale wing I suspect you have issue with sending a message to a channel

so i fogot to load it lol and now im getting this error


Developed by: David Powell 0.005
Starting Bot
Connecting to Discord API.
Please Wait
Loading Developer Features cog
Traceback (most recent call last):
  File "C:\Users\David Powell\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\common_bot_base.py", line 418, in _load_from_module_spec
    spec.loader.exec_module(lib)  # type: ignore
  File "<frozen importlib._bootstrap_external>", line 879, in exec_module
  File "<frozen importlib._bootstrap_external>", line 1017, in get_code
  File "<frozen importlib._bootstrap_external>", line 947, in source_to_code
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "C:\Users\David Powell\PycharmProjects\WhiskeyBotMain\cogs\events.py", line 31
    embed.set_footer(text="Logging System")
    ^^^^^
SyntaxError: invalid syntax

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

Traceback (most recent call last):
  File "C:\Users\David Powell\PycharmProjects\WhiskeyBotMain\wb.py", line 61, in <module>
    bot.load_extension('cogs.events')
  File "C:\Users\David Powell\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\common_bot_base.py", line 490, in load_extension
    self._load_from_module_spec(spec, name)
  File "C:\Users\David Powell\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\common_bot_base.py", line 421, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
disnake.ext.commands.errors.ExtensionFailed: Extension 'cogs.events' raised an error: SyntaxError: invalid syntax (events.py, line 31)

Process finished with exit code 1
flint isle
vale wing
#

Issue with another extension

flint isle
vale wing
#

To be certain indent issue

#

Your embed.set_footer is indented in a wrong way

#

Also what the hell is that string

#
"""
Use 
multiline 
string
please
"""```
flint isle
vale wing
#

See it's indented wrongly

#

It should be on the same level with those constants

flint isle
#

yeah i moved it to right under the title one and it works better now

vale wing
#

Also you should bring the constants out

flint isle
#
Loading Developer Features cog
Traceback (most recent call last):
  File "C:\Users\David Powell\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\common_bot_base.py", line 430, in _load_from_module_spec
    setup(self)
TypeError: setup() takes 0 positional arguments but 1 was given

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

Traceback (most recent call last):
  File "C:\Users\David Powell\PycharmProjects\WhiskeyBotMain\wb.py", line 61, in <module>
    bot.load_extension('cogs.events')
  File "C:\Users\David Powell\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\common_bot_base.py", line 490, in load_extension
    self._load_from_module_spec(spec, name)
  File "C:\Users\David Powell\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\common_bot_base.py", line 435, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
disnake.ext.commands.errors.ExtensionFailed: Extension 'cogs.events' raised an error: TypeError: setup() takes 0 positional arguments but 1 was given

Process finished with exit code 1
vale wing
#

It needs to have bot arg

#
def setup(bot):```
flint isle
#

it this what its talking about?

def setup():
    bot.add_cog(events)```
vale wing
#

Yes

#

Where would you bring that bot from

flint isle
#
Traceback (most recent call last):
  File "C:\Users\David Powell\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\common_bot_base.py", line 430, in _load_from_module_spec
    setup(self)
  File "C:\Users\David Powell\PycharmProjects\WhiskeyBotMain\cogs\events.py", line 42, in setup
    bot.add_cog(events)
  File "C:\Users\David Powell\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\common_bot_base.py", line 307, in add_cog
    raise TypeError("cogs must derive from Cog")
TypeError: cogs must derive from Cog

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

Traceback (most recent call last):
  File "C:\Users\David Powell\PycharmProjects\WhiskeyBotMain\wb.py", line 61, in <module>
    bot.load_extension('cogs.events')
  File "C:\Users\David Powell\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\common_bot_base.py", line 490, in load_extension
    self._load_from_module_spec(spec, name)
  File "C:\Users\David Powell\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\common_bot_base.py", line 435, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
disnake.ext.commands.errors.ExtensionFailed: Extension 'cogs.events' raised an error: TypeError: cogs must derive from Cog

dire folio
vale wing
#

You need class instance not a class itself

vale wing
flint isle
vale wing
#

Tbh this documentation is pretty easy to understand in relation to some others

vale wing
vale wing
#
def setup(bot):
    bot.add_cog(SomeCog(bot))```
#

SomeCog is just a class and SomeCog(bot) is an instance of class, iow an object

#

OOP 😀 👍

flint isle
#

hmm

Ignoring exception in on_ready
Traceback (most recent call last):
  File "C:\Users\David Powell\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\client.py", line 515, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\David Powell\PycharmProjects\WhiskeyBotMain\cogs\events.py", line 22, in on_ready
    await channel.send('Bot Online!')
AttributeError: 'NoneType' object has no attribute 'send'
#
    @commands.Cog.listener()
    async def on_ready(self):
        print(Fore.GREEN + 'Connected!' + Fore.WHITE)
        print(Fore.GREEN + 'Bot is ready!' + Fore.WHITE)
        print(Fore.CYAN + 'Waiting For Commands' + Fore.WHITE)
        bot.get_guild(798726719573065749)
        channel = bot.get_channel(798726720181633047)
        await channel.send('Bot Online!')```
#

thats the affected code

glad cradle
flint isle
glad cradle
flint isle
#

yep just had to add self infront of all the bot.

slate swan
#

imagine defining "bot" in the cog file again.

#

that's how it works in cogs

#

self.bot = bot

flint isle
#

well that code vanished

dire folio
#

yh i accidentally sent

#

i have this:

for channel in ctx.guild.channels:
  if channel.permissions_for(ctx.guild.default_role).send_messages==False:
    #stuff

and i'm getting this error:

Traceback (most recent call last):
  File "C:\Users\Asus User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\Asus User\Documents\Python Practice\Test Bot\test bot.py", line 15, in lock
    if channel.permissions_for(ctx.guild.default_role).send_messages==False:
  File "C:\Users\Asus User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\abc.py", line 495, in permissions_for
    roles = member._roles
AttributeError: 'Role' object has no attribute '_roles'

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

Traceback (most recent call last):
  File "C:\Users\Asus User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\Asus User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\Asus User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Role' object has no attribute '_roles'
unkempt canyonBOT
#

Hey @slate swan!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

stray carbon
#

string = 'got fined 696,696 again'
List = list(map(int, re.findall('\d+', string)))
await ctx.send(''.join(List))
dense swallow
#

which fork?

stray carbon
#

TypeError: sequence item 0: expected str instance, int found

slate swan
#

Can someone teach me how to make my own middlemanbot for my new middleman server? Plssssss

stray carbon
#

🤔

slate swan
#

Plss

slate swan
loud junco
slate swan
#

But

loud junco
#

...

slate swan
#

Idk codinggg

loud junco
#

@shrewd apex look at this legend

slate swan
#

Bruv

shrewd apex
#

yeah

loud junco
#

@slate swan in that case
u have 2 option

  1. just go to top.gg and invite the bot u want
  2. learn python fundamental
shrewd apex
slate swan
#

Ok

#

And do yk how much it will be?

lethal radish
#

Im a pro at discord bots I can certainly help you

loud junco
#

a pro that doesnt know how to reverse thing

#

🤣

lethal radish
loud junco
shrewd apex
lethal radish
loud junco
#

we all will help

lethal radish
#

Yes, ill probably be the most help here tbh

loud junco
#

but cant guarantee instant reply

slate swan
#

I can make u guys staff in server?

loud junco
#

sarth hunter sparky immit ashley can help

slate swan
#

Or co owner

loud junco
lethal radish
#

Sure np

slate swan
#

Dm me

dense swallow
#

i dont think u can add reactions to a msg invoked with slash commands

lethal radish
#

@loud junco @shrewd apex could you guys go back and help me solve my complex problem

shrewd apex
#

k

loud junco
maiden fable
#

What's even happening

#

Just do string = string[::-1] to reverse

lethal radish
#

Theres much more to that

loud junco
#

hunter is here

#

hihi hunter is my dad in python

maiden fable
#

Uh, no I'm not

lethal radish
maiden fable
#

I'm his dad who has gone to get some milk

loud junco
#

pure legend that no one can beat

lethal radish
#

I'm a pro at coding hunter like I have 12 years of experience

maiden fable
#

Oh cool

lethal radish
#

Yh I specialise in lots of things

#

I can teach you a thing or two if you wanted👍

dense swallow
#

!ot

unkempt canyonBOT
maiden fable
lethal radish
#

Alr

maiden fable
#

Hm I was thinking...

#

!e

import builtins
class String(str):
    def reverse(self):
        return self[::-1]
builtins.str = String
print(str("Hi").reverse()) 
unkempt canyonBOT
#

@maiden fable :white_check_mark: Your eval job has completed with return code 0.

iH
maiden fable
#

Oh works. Cool!

paper sluice
#

!e

from fishhook import hook

@hook(str)
def reverse(self):
    return self[::-1]

print('hello'.reverse())
unkempt canyonBOT
#

@paper sluice :white_check_mark: Your eval job has completed with return code 0.

olleh
dense swallow
#

is there a method to get a vc like bot.get_channel

#

maybe try to fetch the message id and then add reactions

slate swan
#

vc are channels too

#

so get_channel works for that.

dense swallow
#

that works?

stiff gorge
#
    @app_commands.command(name="test", description="Testing")
    @app_commands.guilds(discord.Object(id=845317571301081158))
    async def testreason_slash(self, interaction: Interaction, reason: str="Unspecified"):
slate swan
#

yep

dense swallow
#

oh ty

stiff gorge
#

is this correct ?

slate swan
#

^

stiff gorge
#

it dosent work for me i had added tht cmnd yesterday

slate swan
#

any errors?

stiff gorge
#

yes

slate swan
#

what is it

stiff gorge
#

it says cmnd not found

#

but tht cog is working

slate swan
#

uh-huh that's a slash command how do you get command not found error with that?

#

!d discord.app_commands.CommandNotFound

unkempt canyonBOT
#

exception discord.app_commands.CommandNotFound(name, parents, type=<AppCommandType.chat_input: 1>)```
An exception raised when an application command could not be found.

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

New in version 2.0.
loud junco
slate swan
#

hm maybe a command which appears on discord but not in the code? ...

slate swan
#

yeah that makes sense

nimble plume
#

hi

#

im a chat bot

loud junco
#

ashley going to !ot u again

slate swan
stiff gorge
#

i hv made tht command in a new cog so i need to wait 1 hr ?

loud junco
#

i see the passion
but wrong place

#

🤣

slate swan
#

that works for me

loud junco
#

someone trolls me and my discord crashes for 30 mins

slate swan
loud junco
#

yes

#

u have milk bucket?
lemme drink the milk
and remove this stupid bad omen

slate swan
loud junco
slate swan
#

no comments

loud junco
#

LOL

#

its like what i would say 3 years ago

slate swan
#

smh

loud junco
#

when idk whats programming language

slate swan
#

24-hour format 😭

loud junco
#

i can read it

#

the way we think in math is different ig

#

:/

slate swan
#

whats the relation....

#

anyways........ot

loud junco
#

ok

#

lets go ot

#

!ot

unkempt canyonBOT
slate swan
loud junco
#

me and asher is there

slate swan
#

i'd not just....going to random help channels

flint isle
#

how can i get a list of what cogs are loaded?

maiden fable
#

!d discord.ext.commands.Bot.cogs @flint isle

unkempt canyonBOT
slate swan
#

Bot.cogs gives you a mapping of cog names to Cog objects

flint isle
slate swan
#

Bot.cogs.keys()

flint isle
#

and how do i remove dict_keys( from the output lol

maiden fable
flint isle
shrewd harbor
flint isle
#

like this?```py

list(self.bot.cogs.keys())```

slate swan
#

Yea

flint isle
#

thanks

paper sluice
#

list(self.bot.cogs) also works

loud junco
loud junco
flint isle
#

they list the same thing

loud junco
#

one will list the variable name and one will list the variable value

slate swan
#

nope, that would be just the list of keys

loud junco
#

hmmm ok

slate swan
#

they earlier said they just want the name of the cogs so i suggested cogs.keys()

flint isle
#

from the one without keys: ['developerfeatures', 'events']
the one with keys: ['developerfeatures', 'events']

slate swan
#

thats the same :p

paper sluice
slate swan
#

how may i get my bots uptime?

loud junco
#

should i send him the uptimerobot

slate swan
#

no not that

loud junco
slate swan
#

like have a command to show uptime right

loud junco
#

huh

slate swan
#

shows how long the bot has been running

slate swan
unkempt canyonBOT
#

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

001 | A
002 | B
003 | A
004 | B
slate swan
# slate swan

setup a datetime when the bot starts
each time you want to get the uptime, you would have to subtract it from the current datetime

loud junco
slate swan
loud junco
#

oo

flint isle
# slate swan setup a datetime when the bot starts each time you want to get the uptime, you w...

i found this on stack overflow
would this work for that?

import discord, datetime, time
from discord.ext import commands
start_time = time.time()
@commands.command(pass_context=True)
async def uptime(self, ctx):
        current_time = time.time()
        difference = int(round(current_time - start_time))
        text = str(datetime.timedelta(seconds=difference))
        embed = discord.Embed(colour=0xc8dc6c)
        embed.add_field(name="Uptime", value=text)
        embed.set_footer(text="<bot name>")
        try:
            await ctx.send(embed=embed)
        except discord.HTTPException:
            await ctx.send("Current uptime: " + text)
slate swan
#

how did you define start_time

slate swan
#

value*

loud junco
flint isle
slate swan
slate swan
#

lemme show a quick example of how you would do the uptime

#
from datetime import datetime

bot = ...
bot.start_time = datetime.now()
``` now whenever you want to get the uptime you can do datetime.now() - bot.start_time
small sentinel
#

Is it okay to have 50+ 1 second-loops editing files on the host's computer every second ?

#

this means 50 file edits every second

#

won't this make the bot lag alot ?

slate swan
#

yea~

#

Depends on your hosts memory

small sentinel
#

Does the lag amout scale with the size of the file edition ?

slate swan
#

ofcourse, larger the data the more resource usage

nimble plume
#

hi how do i print bots

#

guild

#

only 1

slate swan
#

bot.guilds

nimble plume
#

yes

#

everything

#

ok

#

everything

#

its discord.ui.Select

#

not Select

slate swan
#

error?

#

um

#

try changing the emoji like one above

#

@slate swan

#

do you get any errors?

slate swan
slate swan
#

hm, try using the unicode form of emoji \🛠️

#

And does all other option appear?

#

ye ig

slate swan
#

mobile?

#

uh

flint isle
#

i just realized what was missing lmao

slate swan
slate swan
#

yert install emoji extensions or whatever its just a 🛠️ emoji in unicode form

flint isle
slate swan
#

ye i copy paste in discord chat it show me 🛠️

slate swan
#

tias

flint isle
flint isle
slate swan
#

@slate swan works?

#

np

vale wing
#

1 second loops are bad

#

Generally

#

Unless you make them better

slate swan
vale wing
#

Min time I use is 30 seconds

slate swan
#

imagine 30 sec late giveaway

vale wing
#

1 second loop has a high chance of getting stuck

slate swan
#

ye

vale wing
#

Before it is able to execute again

flint isle
vale wing
unkempt canyonBOT
#

datetime.strftime(format)```
Return a string representing the date and time, controlled by an explicit format string. For a complete list of formatting directives, see [strftime() and strptime() Behavior](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior).
vale wing
#

Just make embed object

#

Holy cow I see "open_account" again

#

Who's the author of that tutorial

#

It's weird af

nimble plume
#

me

vale wing
#

Man

#

Why not use OOP

#

And make nice looking classes for operating with data

nimble plume
#

i dont know whats oop(object oriented proggraming)

small sentinel
rare saddle
#

Why are custom emojis shown on the server where these emojis were uploaded, but not on other servers?

vale wing
slate swan
#

what code to use to get the description of a command by a command

fading marlin
slate swan
#

yeah ik but like lets say i have a custom help command where i wanna the user to do !Help <command> and it gets this commands description as well

vale wing
unkempt canyonBOT
#

get_command(name, /)```
Get a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") from the internal list
of commands.

This could also be used as a way to get aliases.

The name could be fully qualified (e.g. `'foo bar'`) will get
the subcommand `bar` of the group command `foo`. If a
subcommand is not found then `None` is returned just as usual...
small sentinel
rare saddle
slate swan
vale wing
minor totem
small sentinel
#

what timer ?

#

what function ?

slate swan
#

@vale wing i tried as well but i got no idea how to use it as well

#

it is bot.get_command nvm let me try again

minor totem
minor totem
small sentinel
#

oh

slate swan
#

await ctx.message.delete()
AttributeError: 'str' object has no attribute 'message'

#

it works but doesn't get the description of the command as well which is not what i need

minor totem
small sentinel
#

well I want a 1 hour timer that does stuff at the end of that hour

minor totem
slate swan
#

im not tho thats why im confused

glad cradle
slate swan
#

and its deleting the message but still sending the error

#
@bot.command()
@commands.cooldown(1, 5, commands.BucketType.user)
async def monkey(ctx, banana):
    await ctx.message.delete()
    await dh(f"{ctx.author} ran monkey command!", f"banana: `{banana}`")
    await monkey(banana, ctx.author)
#
Unhandled exception in internal background task 'timer'.
Traceback (most recent call last):
  File "C:\Users\hp\AppData\Local\Programs\Python\Python38\lib\site-packages\disnake\ext\tasks\__init__.py", line 157, in _loop
    await self.coro(*args, **kwargs)
  File "c:\Users\hp\Desktop\bot\giveaway.py", line 71, in timer
    for keys in logs2.keys():
RuntimeError: dictionary changed size during iteration

..

    @tasks.loop(seconds=10)
    async def timer(self):
         with open("giveawaytime.json") as f:
          logs2 = json.load(f)
          for keys in logs2.keys():

😐

minor totem
minor totem
minor totem
slate swan
#

ok i fixed it, i had a function called the same as the command

slate swan
slate swan
slate swan
#

so

    @tasks.loop(seconds=5)
    async def timer(self):
         with open("giveawaytime.json") as f:
          logs2 = json.load(f)
          for keys in logs2.keys():
            a = logs2[keys]
            b = datetime.fromisoformat(a[0])
            if b <= datetime.now():
                a1 = a[1]
                a2 = a[2]
                await self.endgiv(int(keys),int(a1),int(a2))
                del logs2[keys]
                with open("giveawaytime.json","w") as s:
                 json.dump(logs2,s)
minor totem
minor totem
slate swan
#

del ?

#

..

minor totem
#

Yeah, that modifies the dictionary

slate swan
#

ill suggest to clone the dictionary and use it for iteration

minor totem
#

You should do the opposite: create a new dictionary with only the keys you wish to keep

slate swan
#

okay

#

@minor totem thanks so much

#

sparky: the message logs spammer.

#

lol

slate swan
#

im confused

slate swan
#

but i want to compare the time

#

use that dict only for the for loop checker?

hollow edge
#

how can I send a message in chat off a slash command without it being counted as a reply?

slate swan
#

!d discord.Interaction.channel

unkempt canyonBOT
slate swan
#

and use the send method on this

hollow edge
#

thanks

stiff gorge
slate swan
stiff gorge
#

yes i made tht cmnd yesterday and restarted today

slate swan
#

like it doesnt show up or what

pseudo dawn
#
colors = ["yellow","red", "blue"]
@bot.command()
async def delete_role(message):
    userrole = message.author.roles
    user = message.author
    for x in colors:
        if x in userrole:
            role = discord.utils.get(user.guild.roles, name=x)
            await message.author.remove_roles(role)
            await message.reply("role deleted")
        else:
            await message.reply("i cant find any role")
            return```
#

i want to code something that deletes the every role user have in the colors list

#

but bot always says i cant find any role

#

can somebody explain me why?

supple thorn
#

!d discord.Member.roles

unkempt canyonBOT
#

property roles```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that the member belongs to. Note
that the first element of this list is always the default [‘@everyone](mailto:'%40everyone)’
role.

These roles are sorted by their position in the role hierarchy.
supple thorn
#

Which would never be true so it triggers the else block

stiff gorge
slate swan
supple thorn
#

Also hi ashley

slate swan
supple thorn
gaunt ice
#

higuys

#

howyalldoing

#

myspacebarded

paper sluice
#

rip

slate swan
paper sluice
supple thorn
#

It was fun

#

I got absolutely rekt

#

I was getting bullied

paper sluice
#

oh, cool

small sentinel
#

is there a way to execute a bot command through code ?

supple thorn
#

Well

formal basin
#

What does this error mean second image is my json

supple thorn
oak warren
#

i am having problem with easy pil
when i call Font().popins(size=30) it gives me an error TypeError: __init__() missing 1 required positional argument: 'path'
i am trying to use the static method of the class i tried multiple ways but no luck
its not letting me send a rank card

small sentinel
#

even though the user didn't type in /show_help_embed nor did he type /admin_call_help command

supple thorn
#

Wait does it exist

paper sluice
#

i mean u can import the function and edit it a little bit 🤷‍♂️

supple thorn
#

!d discord.ext.commands.Context hold on lemme just search the docs

unkempt canyonBOT
#
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.

This class contains a lot of meta data to help you understand more about
the invocation context. This class is not created manually and is instead
passed around to commands as the first parameter.

This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable "discord.abc.Messageable") ABC.
small sentinel
#

I think it's the "outdated" one

#

the one that doesn't get updates anymore

slate swan
#

idk then, generally i'd just get the .callback of the slash command object and pass in the interaction to it

supple thorn
unkempt canyonBOT
#

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

Calls a command with the arguments given.

This is useful if you want to just call the callback that a
[`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") holds internally...
supple thorn
#

@paper sluice

small sentinel
#

woah huge

slate swan
#

Slash comamnds dont work on context.

small sentinel
#

thanks @supple thorn

supple thorn
#

Oh is it slash commands?

paper sluice
supple thorn
slate swan
paper sluice
supple thorn
slate swan
#

unless they have / as their prefix

supple thorn
#

@small sentinel is / your prefix?

small sentinel
#

no

#

it was an example

#

I use > as a prefix

supple thorn
#

Then you can do it

slate swan
#

ah , the just use bot.get_command("command name").invoke()

small sentinel
#

yup thanks

supple thorn
#

Damn my brain working overtime

slate swan
#

Context.invoke will just invoke the main command

supple thorn
#

I was gonna check discord.ext.commands but i went with context instead

slate swan
#

unless the command is passed

supple thorn
#

Cause it seemed right

rare saddle
#

Can you please tell me which intents should be called separately for PRESENCE INTENT or SERVER MEMBERS INTENT or both?

slate swan
#

!intents

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

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

from discord import Intents
from discord.ext import commands

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

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

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

slate swan
#

do it this way

#

for member intents, intents.members=True , for presence intents.presence =True

zealous jay
#

How do I activate members.intent?

class client(commands.Bot):
    def __init__(self):
        super().__init__(
            command_prefix='.',
            intents = discord.Intents.default(),
            application_id = 770696433573036054)
        self.synced = False
    
    async def setup_hook(self) -> None:
        self.session = aiohttp.ClientSession()

        folders = []
        files = []

        target_dir = Path.cwd() / "cogs"

        for file in target_dir.rglob("*.py"):
            folders.append(file.parent.name)
            files.append(file)

        print(folders)
        print(files)

        for ext in folders:
            for num in files:
                try:
                    await self.load_extension(f"cogs.{ext}.{num.stem}")
                except:
                    pass

        await cltree.sync(guild = discord.Object(864993787835056138))
        self.synced = True

    async def on_ready(self):
        await self.wait_until_ready()
        print(f"Logged in as {self.user}")

aclient = client()
cltree = aclient.tree

aclient.run(os.getenv("TOKEN"))            
slate swan
zealous jay
#

discord.Intents.all()?

slate swan
zealous jay
#

if I do that i get an error saying I didn't activate them on the discord devs

#

but I did

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

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

from discord import Intents
from discord.ext import commands

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

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

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

slate swan
#
           intents=(
                hikari.Intents.ALL_UNPRIVILEGED
                | hikari.Intents.GUILD_MEMBERS
                | hikari.Intents.GUILD_PRESENCES
            ),``` my intents
rare saddle
#

@slate swan

slate swan
slate swan
slate swan
slate swan
zealous jay
#

every time i turn this intent on after I reload the website it deactivates suffer

slate swan
rare saddle
zealous jay
#

that's why I cant do discord.Intents.all()

slate swan
#

💀 perks of using lightbulb.

rare saddle
#

@slate swanNow everything is correct, why the error?

slate swan
#

make sure its the right bot.

rare saddle
small sentinel
#

Is there a simple way to prevent a list turning into NoneType when its last value gets removed ?
because right now I have a list, and when I remove the last element of that list, it turns into a NoneType object

small sentinel
#

I use .remove to remove elements of that list

strong vector
#

what the hack?

>>> 968269079339216960 == 968269079339216960
True
    async def webhookHandler(self,webhookobj,message):
        o = webhookobj.data.data["obj"]
        chid = o.webhook.hook.data.data["channel_id"]
        d = o.webhook.hook.data.data
        print(d)
        print(message.channel.id == chid,end=f": {message.channel.id} == {chid}\n")

        if message.channel.id == chid: return await o.process_command(message,message.content,message.channel)

output

False: 968269079339216960 == 968269079339216960

that doesn't make any sense

slate swan
strong vector
supple thorn
#

Of the webhook

strong vector
strong vector
supple thorn
slate swan
#

well his error was saying his class didnt have an attr of message lol

maiden fable
#

Yea

native wedge
#

https://paste.pythondiscord.com/yemoloreti

  File "C:\Users\a\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ui\view.py", line 370, in _scheduled_task
    await item.callback(interaction)
  File "c:\Users\a\Desktop\GD Verify\bot.py", line 25, in first_button
    account_id = response.json()[accountID]
KeyError: 0```
#

i do not understand why this returns keyerror: 0

slate swan
#

no such key

#

accountID is literal to 0

#

so its value is 0

#

and theres no such key lol

native wedge
#

hm

#

i have a question, in my code

slate swan
#

!e

key = 0
d = {1: 2}
print(d[key])
unkempt canyonBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 3, in <module>
003 | KeyError: 0
slate swan
native wedge
#

?

slate swan
#

well it depends on your code you can yes with f strings

native wedge
#

if yes, then the code thinks accountID is 0?

slate swan
#

and its never been mutated

native wedge
#

oh wtf

#

i didnt notice that

slate swan
#

and here you should make username a kwarg

#
inter, *, username: str
#

so it would take all text after the slash

native wedge
#

forgot about that trick lol

native wedge
#

ohh wait

#

nvm

slate swan
#

i recommend you print the payload and then index it correctly

native wedge
#

this is what happens when you dont do python for a while
i figured it out

#

ty for the help

#

@slate swan

slate swan
#

youre welcome!

autumn surge
#

how does a member enter the bot cache

slate swan
#

Why am I getting this error

    bot = commands.Bot(command_prefix=".")
AttributeError: module 'discord.ext.commands' has no attribute 'Bot'
slate swan
slate swan
#

I used to but I uninstalled it using pip uninstall py-cord

autumn surge
slate swan
#

I don't want to use pycord anymore, just discord.py

supple thorn
#

Purposefully?

autumn surge
#

yes

slate swan
#

Wdym

supple thorn
#

Wdym by purposefully

autumn surge
#

as in I want to get a member in the cache without using fetch_member

supple thorn
#

Do you mean intentionally?

slate swan
autumn surge
slate swan
#

member

autumn surge
#

if you use get it searches the cache

slate swan
#

i think they ment add the member or get it?

supple thorn
#

!d discord.ext.commands.Bot.get_user

unkempt canyonBOT
supple thorn
#

@autumn surge

#

This gets it from the internal cache

autumn surge
supple thorn
#

Then fetch

#

Literally what you're asking sounds impossible

autumn surge
#

well how does a member get added to the cache

supple thorn
#

Somehow getting a member from the cache without the member actually being in the cache and not fetching the user

supple thorn
#

Fetching the user using fetch_user

#

Also puts the member in the cache

autumn surge
#

I mean if the user interacts with the bot and somehow gets added to the cache that would do great

supple thorn
#

So you can get the member by get_user

slate swan
unkempt canyonBOT
#

discord/state.py lines 333 to 342

def store_user(self, data: Union[UserPayload, PartialUserPayload]) -> User:
    # this way is 300% faster than `​dict.setdefault`​.
    user_id = int(data['id'])
    try:
        return self._users[user_id]
    except KeyError:
        user = User(state=self, data=data)
        if user.discriminator != '0000':
            self._users[user_id] = user
        return user```
slate swan
#

dpy first parses the user in another method and then they use this to save the parsed user

autumn surge
slate swan
autumn surge
#

alright I'll have a look ty

slate swan
#

let me give you an example

pure crypt
#

how can i check if a user snd the bot a dm?

zealous jay
#

This should do it?

#
@cltree.command(guild = discord.Object(864993787835056138), name="testing_command", description="Comando para pruebas.")
async def test(interaction: discord.Interaction):
    await interaction.response.defer(thinking=True)
    for user in interaction.guild.members:
        print(user.name)
#

Im trying to get all the members in a server

#

But only get one and it's the bot itself

slate swan
#

the method _add_user() os more suiting in this case

slate swan
#
if not ctx.guild:
    ...
autumn surge
slate swan
#

youre welcome!

slate swan
slate swan
unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

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

from discord import Intents
from discord.ext import commands

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

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

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

zealous jay
#

class client(commands.Bot):
    def __init__(self):
        super().__init__(
            command_prefix='.',
            intents = discord.Intents.default(),
            application_id = 770696433573036054)
        self.synced = False
        self.intents.members=True
slate swan
#

well do you have them active in the portal?

zealous jay
#

yeah

slate swan
#

How can I set the author embed have user avatar?

#

!d discord.Interaction.guild

unkempt canyonBOT
zealous jay
#

member count works

slate swan
#

was it in a dm?

zealous jay
#

nope

slate swan
#

because the property can return None if its in a dm but i doubt it because you would get a Nonetype error

#

tbh i dont really know whats your problem everything looks fine to me

#

Hi

slate swan
#

I want to make a welcome bot with pyrhon

zealous jay
slate swan
#

im a bit confused on the wording

#

yes

#

Does someone wanna help me making welcome bot with python

slate swan
slate swan
slate swan
#

pretty sure this is against tos

slate swan
slate swan
slate swan
slate swan
slate swan
slate swan
# slate swan spamming?

Well, it's not in a public discord.
I'm the only one in it, I just want to check vanity urls.

slate swan
slate swan
slate swan
slate swan
slate swan
zealous jay
#

What about this

slate swan
#

??

zealous jay
#

TypeError: fetch_guild() missing 1 required positional argument: 'guild_id'

slate swan
unkempt canyonBOT
#

set_author(*, name, url=None, icon_url=None)```
Sets the author for the embed content.

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

im a bit confused on what you want sorry😅

slate swan
slate swan
torn sail
slate swan
#

ctx.author.avatar.url

#

If on icon

slate swan
#

I think I got it

zealous jay
#

so...

slate swan
#

Just icon_url=ctx.author.avatar_url

zealous jay
#

what am i doing wrong in here?

await client.fetch_guild(864993787835056138)
slate swan
#

Show Full error

#

Or

#

Name it like guild_id =

#

Maybe

zealous jay
#

discord.app_commands.errors.CommandInvokeError: Command 'testing_command' raised an exception: TypeError: fetch_guild() missing 1 required positional argument: 'guild_id'

zealous jay
# slate swan Name it like guild_id =

Tried that and got this
discord.app_commands.errors.CommandInvokeError: Command 'testing_command' raised an exception: TypeError: fetch_guild() got some positional-only arguments passed as keyword arguments: 'guild_id'

slate swan
#

Can u send ss

#

Of the code

zealous jay
#

sure

#

This is my command

#

I could do interaction.guild.members but If I do that for some reason I get only one member and it's the bot itself

torn sail
#

Show where u define client

zealous jay
slate swan
#

No

slate swan
torn sail
slate swan
#

bot = Client()

zealous jay
#

oh sorry

torn sail
#

Also you should make class names PascalCase so it isn’t the same as variable names

zealous jay
#

oh so it should be aclient.fetch (?

torn sail
#

Oh ok use await aclient.fetch

#

Yes that’s right

zealous jay
#

worked

#

the list was empty tho, i'll get back to it later

torn sail
#

U may need member intents enabled

#

!intents

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

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

from discord import Intents
from discord.ext import commands

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

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

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

mellow mountain
#
@bot.command()
@commands.cooldown(1, 86400, commands.BucketType.user)
async def daily(ctx):
# Daily stuff


#####

bot.event()
async def reset_daily():
    now = datetime.now()
    reset = datetime.strptime('23:59', '%H:%M')
    if now == reset:
        daily.reset_cooldown()

Is this correct somehow? And how do i reset the cooldown for everyone from the server?

I want the daily command reset every day at 23:59 or 12pm like that

#

Not sure about the cooldown stuff

zealous jay
#

I have this

#

it's kinda weird

slate swan
#

enabled from the discord developer site too?

zealous jay
#

yup

slate swan
#

damn that's weird

empty kernel
#

Yesterday, I had asked about manually triggering an event (in my case, I'm looking to trigger the on_member_join event. So they suggested:

Bot.dispatch("member_join", Member)

But I can't seem to quite figure out what the second parameter Member needs to be. I tried to create an instance of Member:

test_member = discord.Member()
bot.dispatch("member_join", test_member)

But that wasn't right.
So then I tried:

bot.dispatch("member_join", discord.Member)

And that seems to half work? It doesn't error, but I get odd results.
Just wondering if someone can help me figure out how to set Member correctly.

slate swan
#

!d discord.Guild.get_member

unkempt canyonBOT
#

get_member(user_id, /)```
Returns a member with the given ID.

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

Use this to get the Member object

empty kernel
#

Thanks! I'll give that a try!

slate swan
#

yeah and make sure you have member intents enabled

#

do !intents here if you dont know what it is

#

!intents

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

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

from discord import Intents
from discord.ext import commands

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

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

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

empty kernel
#

yep! I've got it set on the gateway as well as in the code. I think I have that bit working, but good call!

#

so I'm doing this in my "on_ready" and when I provide my own user_id

test_member = discord.Guild.get_member(user_id=user_id_int)

I get an error about missing a positional argument:
TypeError: Guild.get_member() missing 1 required positional argument: 'self'

#

do I need to get the guild first?

slate swan
#

you would need an instance of a Guild object yes

#

!d discord.ext.commands.Context.guild

unkempt canyonBOT
slate swan
#

if youre using a command with context then you can return an instance of a guild object with the guild attribute

empty kernel
#

ok, let me fight with this some more. Thanks! 🙂

slate swan
#

youre welcome

zealous jay
#

Well, still can't figure out why I can't get all memers from the server and only the bot itself

#
class client(commands.Bot):
    def __init__(self):
        super().__init__(
            command_prefix='.',
            intents = discord.Intents.default(),
            application_id = 770696433573036054)
        self.synced = False
        self.intents.members= True
    
    async def setup_hook(self) -> None:
        self.session = aiohttp.ClientSession()

        folders = []
        files = []

        target_dir = Path.cwd() / "cogs"

        for file in target_dir.rglob("*.py"):
            folders.append(file.parent.name)
            files.append(file)

        print(folders)
        print(files)

        for ext in folders:
            for num in files:
                try:
                    await self.load_extension(f"cogs.{ext}.{num.stem}")
                except:
                    pass

        await cltree.sync(guild = discord.Object(864993787835056138))
        self.synced = True

    async def on_ready(self):
        await self.wait_until_ready()
        print(f"Logged in as {self.user}")

aclient = client()
cltree = aclient.tree

@cltree.command(guild = discord.Object(864993787835056138), name="testing_command", description="Comando para pruebas.")
async def test(interaction: discord.Interaction):
    await interaction.response.defer(thinking=True, ephemeral=True)
    print(interaction.guild._members)

aclient.run(os.getenv("TOKEN"))          
#

This is my full code

rare saddle
#

How to send an image to discord using pillow without saving the image

slate swan
#

Can anyone help me building a welcome message bot if so then dm me

dull terrace
dull terrace
rare saddle
slate swan
#

Can someone send me begging of index.js

dull terrace
#

no worries, i ran into the same issue with mine

dull terrace
slate swan
#

Do u have js server?

livid hinge
#

speakjs is one

empty kernel
#

I still don't seem to be getting it

current_guild = commands.Context.guild # This is a cached_property, and has no get_member()
test_member = current_guild.get_member(user_id=user_id_int)
bot.dispatch("member_join", test_member)

So commands.Context.guild is a cached_property and therefore doesn't seem to have a get_member() attribute:

    test_member = current_guild.get_member(user_id=user_id_int)
AttributeError: 'cached_property' object has no attribute 'get_member'

I'm not sure what I'm doing wrong (obviously I'm not understanding something). I should also mention the function are async in case that matters? I had been seeing things on StackOverflow talking about an async branch of discord.py being different, but they were a little older so I wasn't sure if that was still relavant?

quaint epoch
#

!d disnake.Interaction

unkempt canyonBOT
#

class disnake.Interaction```
A base class representing a user-initiated Discord interaction.

An interaction happens when a user performs an action that the client needs to be notified of. Current examples are application commands and components.

New in version 2.0.
rain salmon
#

hey ive been running into this error
Traceback (most recent call last):
File "/home/toasty/.local/lib/python3.10/site-packages/interactions/api/http/request.py", line 171, in request
raise HTTPException(data["code"], message=data["message"])
interactions.api.error.HTTPException: Invalid Form Body Error code: 50035
@bot.command(
name="minions",
description="Information about Slayers",
options=[
interactions.Option(
name="username",
description="Minecraft username",
type=interactions.OptionType.STRING,
required=True,
options=[
interactions.Option(
name="profile",
description='profile name',
type=interactions.OptionType.STRING,
requered=True), ], ), ], )
the last options is the error
it does not crash when i remove it but i need it
how do i stop it from crasing

unkempt canyonBOT
#

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.

brave forge
#

what is the best module for buttons in discord.py ?

quaint epoch
rain salmon
#
@bot.command(
    name="minions",
    description="Information about Slayers",
    options=[
        interactions.Option(
            name="username",
            description="Minecraft username",
            type=interactions.OptionType.STRING,
            required=True,
            options=[
                interactions.Option(
                    name="profile",
                    description='profile name',
                    type=interactions.OptionType.STRING,
                    requered=True), ], ), ], 



Traceback (most recent call last):
  File "/home/toasty/.local/lib/python3.10/site-packages/interactions/api/http/request.py", line 171, in request
    raise HTTPException(data["code"], message=data["message"])
interactions.api.error.HTTPException: Invalid Form Body Error code: 50035



brave forge
quaint epoch
#

what lib are you using

#

sighhhhh

#

dammit

brave forge
#

@quaint epoch just import button

quaint epoch
#

no

brave forge
quaint epoch
#

for example ```py
import discord
class view(discord.View):

@discord.ui.button(label="button", style=discord.Style.green)
async def callback(self, button: discord.Button, interaction:discord.Interaction):
# do stuff
@bot.command()
async def foo(ctx):
await ctx.send(view=view())```

brave forge
#

@quaint epoch just don't give me the documentation site from discord.py

unkempt canyonBOT
#

discord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)```
A decorator that attaches a button to a component.

The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.ui.View "discord.ui.View"), the [`discord.Interaction`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.Interaction "discord.Interaction") you receive and the [`discord.ui.Button`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.ui.Button "discord.ui.Button") being pressed.

Note

Buttons with a URL cannot be created with this function. Consider creating a [`Button`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.ui.Button "discord.ui.Button") manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.
quaint epoch
#

!d discord.Button

unkempt canyonBOT
#

class discord.Button```
Represents a button from the Discord Bot UI Kit.

This inherits from [`Component`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.Component "discord.Component").

Note

The user constructible and usable type to create a button is [`discord.ui.Button`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.ui.Button "discord.ui.Button") not this one.

New in version 2.0.
quaint epoch
#

couldn't you just check the docs yourself?

brave forge
#

@quaint epoch no!! don 't do this !!!

quaint epoch
#

it's quite easy

#

what?

#

and also don't ping me that much

brave forge
#

@quaint epoch this site pisses me off

quaint epoch
#

what?

#

i don't even understand

brave forge
#

don't like the site

quaint epoch
#

which site?

brave forge
#

it's not my fault that there are so few synonyms for words in English

quaint epoch
#

okay it doesn't seem related to your question

brave forge
quaint epoch
#

oh you said don't

#

well, i also provided an example

#

!rule 4

unkempt canyonBOT
#

4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.

brave forge
#

@quaint epoch I know!!!

#

@quaint epoch I know!!!

quaint epoch
#

okay?

dull terrace
#

If i change dictionary_name size while looping through enumerate(dictionary_name): will it throw an error or is it creating a new object

quaint epoch
#

!e dict = {"hello": "hello", "there":"there"}
for i in enumerate(dict):
dict["world"] = "world"

unkempt canyonBOT
#

@quaint epoch :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | RuntimeError: dictionary changed size during iteration
quaint epoch
#

aha, error

#

so, what exactly are you trying to do?

dull terrace
#

!e

dict = {"hello": "hello", "there": "there"}
for i in list(enumerate(dict)):
    dict["world"] = "world"
unkempt canyonBOT
#

@dull terrace :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | NameError: name 'python' is not defined
dull terrace
#

!e

dict = {"hello": "hello", "there": "there"}
for i in list(enumerate(dict)):
    dict["world"] = "world"
unkempt canyonBOT
#

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

[No output]
quaint epoch
#

oh, so you need to create a new object

#

there's that

#

now im gonna go brush me teeth, cya

#

and gn

dull terrace
#

gn

#

!e

dict = {"hello": "hello", "there": "there"}
for count, i in list(enumerate(dict)):
    print(count, i)
for count, i in enumerate(dict):
    print(count, i)```
unkempt canyonBOT
#

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

001 | 0 hello
002 | 1 there
003 | 0 hello
004 | 1 there
tawdry perch
#

The docs aren't "shitty" tho, they work quite well

brave forge
tawdry perch
#

Eh...

#

I'm not? Edit: reply to message where you said something along the lines of "don't change your mind"

silent ermine
#

Is there a way to specify how many servers per shard?

brave forge
brave forge
tawdry perch
#

. . .

#

The rules exist for reason(s)

tawdry perch
brave forge
dull terrace
#

holy mother of god i've made this piece of code messy

#
if player.guild not in guild_gen_rank:
        guild_gen_rank[player.guild] = {player.id: (player.username, player.generated)}
else:
    temp_ggr = list(guild_gen_rank[player.guild].items())
    for count, tup in list(enumerate(temp_ggr)):
        generated = tup[1][1]
        if player.generated > generated:
            temp_ggr.insert(count, (player.id, (player.username, player.generated)))
            count += 1
            for count_two, data in list(enumerate(temp_ggr[count:])):
                ind = count + count_two
                if data[0] == player.id:
                    del temp_ggr[ind]
                    break
            guild_gen_rank[player.guild] = dict(temp_ggr[:3])
            break```
#

trying to keep only the top 3 people in the dictionary who have the highest player.generated

tawdry perch
brave forge
tawdry perch
#

why...?

#

!ot btw, this is far a way from the topic (sorry)

unkempt canyonBOT
brave forge
tawdry perch
#

off-topic, and not related to me

silver agate
#

Is there a way to make a command to get all discord member, example:

This Server has (member count) user

silent ermine
#

i think its len(bot.users)

#

I think you need the members/users intent though

silver agate
#

with discord py btw.

#

ok ok

unkempt canyonBOT
#

property member_count```
Returns the member count if available.

Warning

Due to a Discord limitation, in order for this attribute to remain up-to-date and
accurate, it requires [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be specified...
slate swan
#

guild.member_count where guild should be a Guild object

torn sail
pseudo dawn
#

list = [apple, banana, orange]

i need to make list look like that without making them string, how can i make it?

torn sail
#

Maybe use str then .replace(“‘“, “”)

pseudo dawn
#
colors = ["yellow", "red", "blue"]
@bot.command()
async def delete_role(message):
    userrole = message.author.roles
    user = message.author
    for x in colors:
        if x in userrole:
            role = discord.utils.get(user.guild.roles, name=x)
            await message.author.remove_roles(role)
            await message.reply("role deleted")
        else:
            await message.reply("i cant find any role")
            return```
sick birch
pseudo dawn
#

i want to use it on that code

pseudo dawn
pseudo dawn
sick birch
#

!e

mylist = ["apple", "banana", "orange"]
print(str(mylist))
unkempt canyonBOT
#

@sick birch :white_check_mark: Your eval job has completed with return code 0.

['apple', 'banana', 'orange']
sick birch
#

Like that without the quotes, you say?

#

!e

mylist = ["apple", "banana", "orange"]
print(f"[{', '.join(mylist)}]")
unkempt canyonBOT
#

@sick birch :white_check_mark: Your eval job has completed with return code 0.

[apple, banana, orange]
sick birch
#

like that?

pseudo dawn
#

yay

pseudo dawn
pseudo dawn
#

name=', '.join(colors))

slate swan
#

😭

sick birch
pseudo dawn
#

it didnt work

sick birch
pseudo dawn
#

it sent i cant find any role

pseudo dawn
#

i dont know much about coding

torn sail
slate swan
pseudo dawn
#

sorry

gaunt mortar
#

Hi guys, is there any way to do this kind of things using a python library ? I'm using discord.py & discord_components for Button & so but I can't find any library that allows me to do this

sick birch
#
  1. commands take ctx as the first argument, not message
  2. if x in userrole you're checking if a string is inside an iterable of discord.Role objects
sick birch
#

I'd suggest not using discord_components

torn sail
pseudo dawn
gaunt mortar
sick birch
#

You can use a list comp to map role objects to strings

#

[role.name for role in user.roles]

pseudo dawn
#

can you send an example please

#

i really cant understand properly

#

sorry lemon_angrysad

sick birch
#
if "role name" in [role.name for role in user.roles]:
  # user has the role
pseudo dawn
#

im stupid lol

pseudo dawn
#

after and after

sick birch
#

Not really, it can be x in your case

pseudo dawn
#

if "role name" in [role.name for role in user.roles]:
stuff
elif "differen role name" in [role.name for role in user.roles]:
stuff
elif "differen role name" in [role.name for role in user.roles]:

sick birch
#
colors = ["yellow", "red", "blue"]
for color in colors:
  if color in [role.name for role in user.roles]:
    # user has color role
torn sail
#

Would be better to only do the list comp once I think

sick birch
#

Fair point

pseudo dawn
sick birch
#
@bot.command()
async def my_command(ctx: commands.Context, ...):
  role_names = [role.name for role in ctx.author.roles]
sick birch
torn sail
#

It’s like dynamically creating a list

sick birch
#

!e

fruits = ["apple", "banana", "orange"]
print([fruit[0] for fruit in fruits])
unkempt canyonBOT
#

@sick birch :white_check_mark: Your eval job has completed with return code 0.

['a', 'b', 'o']
sick birch
#

for example

pseudo dawn
#

it's getting too complicated

sick birch
#

It's like map(), but faster

pseudo dawn
sick birch
#

You don't, it was an example to demonstrate list comps

pseudo dawn
#

oh

pliant gulch
#

You could optimise it even more with sets, ```py
colors = {"yellow", "red", "blue"}
names = {r.name for r in roles}

if names.intersection(colors):
# has

sick birch
#

In your case, instead of getting the first letter of each item in a list, you want to access a certain attribute of each item in a list (role.name)

pliant gulch
#

Beauty of hashes

sick birch
pseudo dawn
#

cant you guys explain it like im 10

sick birch
#
colors = {"yellow", "red", "blue"}
names = {r.name for r in roles}

if names & colors:
  # user has role

doesn't change much but looks nicer imo

pseudo dawn
#

cuz im new to python and i cant get every part of your words

sick birch
#

Okay, what are you confused on?

pseudo dawn
#

role_names = [role.name for role in ctx.author.roles]

#

that part

sick birch
#

Okay, let's take that apart part by part

#

look at this part first:
for role in ctx.author.roles

#

That's basically going to go through each item inside ctx.author.roles (which is a list, btw), and assign that to the role variable

#

Next part is the first part: role.name for ...

#

Basically that says: "take each item in the list, get the .name property of it, and put it inside a new list"

pseudo dawn
#

and that new list is role_names

#

thank you

sick birch
#

yup

#

role_names would be a list of role names, instead of discord.Role objects

pseudo dawn
#
@bot.command()
async def delete_role(message):
    user = message.author
    colors = ["yellow", "red", "blue"]
    for color in colors:
      if color in [role.name for role in user.roles]:
        role = discord.utils.get(user.guild.roles, name=', '.join(colors))
        await message.author.remove_roles(role)
        await message.reply("role deleted")
    else:
        await message.reply("i cant find any role")
        return```
#

code looks like that

#

and i got that error

#

theres nothing like "id"

#

did i miss something

sick birch
#

Full traceback please?

pliant gulch
# pliant gulch You could optimise it even more with sets, ```py colors = {"yellow", "red", "blu...
In [1]: def foo() -> None:
   ...:     Role = type("Role", (), {"name": "blue"})
   ...: 
   ...:     names = {r.name for r in [Role() for _ in range(100)]}
   ...:     colours = {"yellow", "red", "blue"}
   ...: 
   ...:     if names.intersection(colours):
   ...:         ...
   ...: 

In [2]: def bar() -> None:
   ...:     Role = type("Role", (), {"name": "blue"})
   ...: 
   ...:     names = [r.name for r in [Role() for _ in range(100)]]
   ...:     colours = ["yellow", "red", "blue"]
   ...: 
   ...:     for colour in colours:
   ...:         if colour in names:
   ...:             ...
   ...: 

In [3]: %timeit foo()
12.6 µs ± 231 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)

In [4]: %timeit bar()
14 µs ± 262 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)
pseudo dawn
sick birch
#

You're sure that's 100% everything?

pseudo dawn
#

thats all

torn sail
#

The role is None so get couldn’t find the role with the name

pseudo dawn
#

how can it be possible

paper bane
#

the issue is that you're passing all the role names separated by "," when trying to get the current match. Instead of say, looking for "yellow", it'd look for "yellow, red, blue"

slate swan
paper bane
#

change ", ".join(colors) to just color

pseudo dawn
#

ohh

#

im so stupid

#

lol

pliant gulch
#

Why even use the name? Why not just use IDs

#

With that you'd be able to use get_role as well, which is faster than utils.get

#

Just need to change the colors list to a list of role IDs, corresponding to the colour of course. Then just change the list comp to use role.id instead of role.name, then just do Guild.get_role(color)

summer zephyr
#

Hey hello

#

anyone knows why this happens every time I turn on my bot?

TypeError: 'type' object is not subscriptable

pseudo dawn
#

so please

#

dont do it