#discord-bots

1 messages · Page 574 of 1

dense swallow
jade tartan
#

member = discord.utils.get(message.guild.members, name='Foo') so its this?

#

then

dense swallow
#

Yeah

dense swallow
#

Can u explain what ur trying to do? Are u like trying to do something like making an embed and then reacting to that embed with emoji?

jade tartan
#

yes and also having the emoji inside the embed for example ♂️ - Male

#

♂️ - Male that will be inside the embed

dense swallow
#

U can put this character before the emoji and then directly copy paste it \

#

It gives u a Unicode form of the emoji

jade tartan
#

Unicode is kinda like the id of the emoji?

fleet axle
#

@slate swan hey finally buttons are now working

#

Thankyou for help

jade tartan
#

well it gives me the emoji symbol

dense swallow
jade tartan
#

bro

dense swallow
fleet axle
dense swallow
#

!code

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.

dense swallow
#

This makes it easier to read code, so pls use this format

urban sphinx
#

I just want a cute little femboy to please all my sexual needs, I would smash his boy pussy whusy and he would be like "Nwooo you boy cwant jwust boy cum in my boy pwussie sussie boy whussie", then I would be all like "YEEEEEEAH😎😎😎😎", then, when we are doing 69 (funny number big chungus), he would fart in my face accidentally, but then it wouldn...

fossil goblet
#

Why doesn't my button command works?

fossil goblet
jade tartan
dense swallow
#

Yeah

#

For longer codes

#

Discord has character limits..

jade tartan
jade tartan
fossil goblet
dense swallow
#

Use ctx.send not client.send

jade tartan
# dense swallow Any error?
    member = discord.utils.get(message.guild.members, name='Male'
                                                           ^^^^^^
SyntaxError: invalid syntax. Perhaps you forgot a comma?```
tawdry perch
urban sphinx
#

no workie

dense swallow
#

Hmm

dense swallow
jade tartan
#

oops

fossil goblet
# tawdry perch that is quite a hard question, there are so many possibilities.. Instead you cou...
@bot.command()
async def button(ctx):
    await ctx.send("Buttons!", components=[Button(label="Button", custom_id="button1")])
    interaction = await bot.wait_for(
        "button_click", check=lambda inter: inter.custom_id == "button1"
    )
    await interaction.send(content="Button Clicked")
from discord_components import Button, Select, SelectOption, ComponentsBot, ButtonStyle
from discord_components import DiscordComponents
from discord.ext.commands import Bot
#

Here's the code

fleet axle
#

yep

#

Interactions has been removed from the library

fossil goblet
#

??

fleet axle
#

so import this

from discord_components import DiscordComponents```
jade tartan
dense swallow
#

Put \ infront of any emoji

jade tartan
#

ohh so i wouldnt need that? so then get the emoji when the embed is send

fossil goblet
#

Than you get this \👍not 👍

jade tartan
#

or what

#

but then i would need that inside of the embed

fossil goblet
#

yea

#

puy \👍 in your embed

dense swallow
fossil goblet
#

or try to use :tada:

#

I guess it will work too

jade tartan
fossil goblet
jade tartan
#

member = discord.utils.get(message.guild.members, name='/Female'

#

🤞

#

RIght?

#

:male:

fleet axle
#

yep

fossil goblet
fleet axle
#

it will work and u need to add wait a min

fossil goblet
jade tartan
#

i mean ♂️

fossil goblet
#

:male_sign:

fleet axle
jade tartan
#

yes i know

fossil goblet
fossil goblet
jade tartan
#

it wont do the unicode

#

it just shows the symbol

fleet axle
fossil goblet
#

\♂️ here is it

jade tartan
#

yes that one

#

wouldnt i need the code

fossil goblet
#

you need \ infront of emogi

jade tartan
#

for it

#

`\♂️

#

ohh wait

fossil goblet
#

Like for example
await ctx.send(":male_sign:") is same with
await ctx.send("♂️")

fossil goblet
jade tartan
#

this whole time i was using this

#

member = discord.utils.get(message.guild.members, name='/:Female:',

fossil goblet
#

hmm

fleet axle
# fossil goblet and no import???

you need to import these things

from discord_components import Button, Select, SelectOption, ComponentsBot, ButtonStyle
from discord_components import DiscordComponents

jade tartan
#

i have dyslexic sometimes

fossil goblet
#

Your friends name is ♂️???
I don't know if it will work

jade tartan
#

umm my code is very weird

#
async def embed(ctx):
    Myembed = Embed(title= f"Please pick your gender role by reacting to the emoji", color=0x24045b,
    description=f"Gender role")
    await ctx.send(":male_sign:")
    await ctx.send(embed=Myembed)```
#

its replying with

fleet axle
fossil goblet
#
@client.command(pass_context=True)
async def embed(ctx):
    Myembed = discord.Embed(title= f"Please pick your gender role by reacting to the emoji", color=0x24045b,
    description=f"Gender role")
    await ctx.send(":male_sign:")
    await ctx.send(embed=Myembed)
fossil goblet
#

I don't know if it will work

#

But I don't know how that command became sending Hi

jade tartan
#

Yeah i dont have any command with Hi

fossil goblet
#

Hmm

jade tartan
#

i tried restarting my code

#

still the same

fossil goblet
#

maybe try Myembed = discord.Embed(title= f"Please pick your gender role by reacting to the emoji", color=0x24045b, description=f"Gender role") you need **discord.**Embed

#

!d discord.Embed

unkempt canyonBOT
#

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

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

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

New in version 2.0.

Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty").

For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
fossil goblet
#

It may work

jade tartan
#

or maybe i need to change my token hold on a sec

fossil goblet
#

orrr maybe there is error on athor commands... ||(It sometimes happens to me... only me?)||

jade tartan
#

let me try this first

fossil goblet
#

Kk

jade tartan
#

no too sure

fossil goblet
#

Good luck to you and your bot!

jade tartan
#

Now its doing this

fossil goblet
#

Nice!

jade tartan
#

I need the emoji inside the embed

#

not outside

fossil goblet
#
@client.command(pass_context=True)
async def embed(ctx):
    Myembed = discord.Embed(title= f":male_sign: Please pick your gender role by reacting to the emoji", color=0x24045b,
    description=f"Gender role")
    await ctx.send(embed=Myembed)

Maybe like this

#

Just put :male_sign: in title or description. or ♂️

jade tartan
#

ok

slate swan
boreal ravine
boreal ravine
fossil goblet
#

Just I didn't edited form the original code
I gotta go bye

jade tartan
#

One more thing

#

plz

#

How do you make the emoji inline?

#

is it inline=true?

boreal ravine
#

what u mean emoji inline

slate swan
jade tartan
#

like a new paragraph

boreal ravine
#

ah

#

\n is used to make a new line

#

!e

print("hi\nok")
unkempt canyonBOT
#

@boreal ravine :white_check_mark: Your eval job has completed with return code 0.

001 | hi
002 | ok
boreal ravine
jade tartan
tough mirage
#

hello, how would I use this in cogs? ```py
@tasks.loop()
async def live_status(seconds=75):
pcount = pc()
Dis = client.get_guild(876471014043815966) #Int

    activity = discord.Activity(type=discord.ActivityType.watching, name=f'🐌 {pcount}')
    await client.change_presence(activity=activity)
    await asyncio.sleep(15)

    activity = discord.Activity(type=discord.ActivityType.watching, name=f'👥 {Dis.member_count}')
    await client.change_presence(activity=activity)
    await asyncio.sleep(15)

    activity = discord.Activity(type=discord.ActivityType.watching, name=f'NOT lowkey#0669')
    await client.change_presence(activity=activity)
    await asyncio.sleep(15)

    activity = discord.Activity(type=discord.ActivityType.watching, name=f'City of lights')
    await client.change_presence(activity=activity)
    await asyncio.sleep(15)

    activity = discord.Activity(type=discord.ActivityType.watching, name=f'')
    await client.change_presence(activity=activity)
    await asyncio.sleep(15)```
agile thicket
#

{'-MnUSfSTI4t54I-8gLag': {'tagname': 'name here', 'tagvalue': 'value here'}}

I want to print only the tagvalue part

#

how to do that

agile thicket
#

?

boreal ravine
urban shell
#

hey, so I am trying to build a bot which checks if a user has joined a particular vc, and then creates a new vc and moves the user,
this is my code so far -

async def on_voice_state_update(self, member, before, after):
        channel_id = client.get_channel(904997311283884063)
        if after.channel.id == channel_id:
            print('success')
            guild = discord.utils.find(lambda g : g.id == guild_id, client.guilds)
            a = str(message.author.name) + "'s Channel"
            await guild.create_voice_channel(name=a)
jade tartan
#

is there a better way to when u run a command it doesnt get send multiple times?

tough mirage
#
Traceback (most recent call last):
  File "C:\Users\bill\COLRP\status bot\main.py", line 2, in <module>
    import discord
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\__init__.py", line 25, in <module>
    from .client import Client
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 53, in <module>
    from .webhook import Webhook
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\__init__.py", line 12, in <module>
    from .async_ import *
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 47, in <module>
    from ..channel import PartialMessageable
ImportError: cannot import name 'PartialMessageable' from 'discord.channel' (C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\channel.py)``` what is this error?
jade tartan
#

cuz everytime i do !embed which sends the emoji embed it sends 3 or 4 times

urban shell
#

I'm getting an Attribute Error -
if after.channel.id == channel_id: AttributeError: 'NoneType' object has no attribute 'id'

tough mirage
jade tartan
jade tartan
#

nvm

boreal ravine
jade tartan
urban shell
final shard
#

How will I delete slash commands

boreal ravine
#

wdym

final shard
#

After I remove from the code the slash still stays in the list

boreal ravine
#

probably a client side error it wont affect ur bot

#

visual error*

final shard
#

Will it get removed soon?

boreal ravine
#

yes

final shard
#

I realized after a while that I hadn't enabled sync commands.

#

Maybe that's why.

agile thicket
#
    print(result)
    print(result["-MnUSfSTI4t54I-8gLag"]["tagvalue"])```

in this code everything is fine except that unique id ```-MnUSfSTI4t54I-8gLag``` always doesnt remain same in all cases.

how can i solve this?
boreal ravine
#

hm

agile thicket
#

the id isdifferent for different data

jade tartan
#

await discordBot.delete_message(message) is that what makes the bot delete a message ? and also if i want it to delete after a certain time?

unkempt canyonBOT
#

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

Deletes the message.

Your own messages could be deleted without any proper permissions. However to delete other people’s messages, you need the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission.

Changed in version 1.1: Added the new `delay` keyword-only parameter.
boreal ravine
#

delay kwarg

#

also that isnt how a bot deletes a message

jade tartan
#

well thats what i found on

urban shell
jade tartan
jade tartan
urban shell
agile thicket
tough wagon
#

but not related to bots

agile thicket
#

ok then where should i ask?

tough wagon
#

I'm not sure but as I see it is database problem, so #databases

#

if there aren't any channel with name related to your problem in TOPICAL CHAT/HELP category then ask in #python-discussion

tough wagon
#

you don't know how to move member?

urban shell
#

so now I updated the code -

if after is not None and after.voice.channel.id == channel_id:
tough wagon
#

yes

#

oh no

#

after.channel is not None

#

not after

urban shell
#

oh ty

#

but

jade tartan
#
async def purge(ctx, amount=1000):
    if(not ctx.author.guild_permissions.manage_messages):
        await ctx.send('Cannot run command! Requires: ``Manage Messages``')
        return
    amount = amount+1
    if amount > 101:
        await ctx.send('I can\'t delete more than 100 messages at a time!')
    else:
        await ctx.channel.purge(limit=amount)
        await ctx.send(f'Sucessfully deleted {amount} messages!')
        await delete(*, delay=None)```
urban shell
# tough wagon not `after`

I'm getting yet another Attribute Error 😔 -
AttributeError: 'VoiceState' object has no attribute 'voice'

jade tartan
#
    await delete(*, delay=None)
                  ^
SyntaxError: invalid syntax```
tough wagon
jade tartan
shy schooner
#

hi, I want to load multiple cogs in multiple folders, the img below is my directory tree

tough wagon
#

if you want to delete message Successfully deleted... after some time the delete(delay=) is bad way, just do await ctx.send(..., delete_after=5)

shy schooner
#

but i got this error and dont know why i cant load the test cog

  File "d:\Coding\Python\Discord.py\Lenny Bot\main.py", line 180, in <module>
    client.load_extension(f"cogs.{file_name[:-3]}")
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 618, in load_extension
    raise discord.ExtensionNotFound(name)
discord.errors.ExtensionNotFound: Extension 'cogs.test' could not be found.
Exception ignored in: <function ClientSession.__del__ at 0x0000022508726160>
tough wagon
#

in send there is delete_after

tough wagon
#

change folder cooldude

shy schooner
#

ok tysm, my bad 🙂

tough wagon
jade tartan
#

ok it worked but when i run the cmd it replies this to me

#

Ellipsis

tough wagon
#

show purge command code, and do you have any on_message event?

jade tartan
#
async def purge(ctx, amount=1000):
    if(not ctx.author.guild_permissions.manage_messages):
        await ctx.send('Cannot run command! Requires: ``Manage Messages``')
        return
    amount = amount+1
    if amount > 1000:
        await ctx.send('I can\'t delete more than 1000 messages at a time!')
    else:
        await ctx.channel.purge(limit=amount)
        await ctx.send(f'Sucessfully deleted {amount} messages!')
        await ctx.send(..., delete_after=5)
tough wagon
#

Do not just copy and paste

#

you did await ctx.send(f'Sucessfully deleted {amount} messages!'), there is delete_after attr for send function, so you should do py await ctx.send(f'Sucessfully deleted {amount} messages!', delete_after=5)

jade tartan
#

ok done that still says that

#

elipsis thing

jade tartan
#

@tough wagon

tough wagon
#

idk maybe you have on_message event

jade tartan
boreal ravine
#

find elipsis in your code

merry pewter
#

!d help

jade tartan
#

myEmbed = discord.Embed(title = f"Welcome {mention.member}") Is this how to mention the member?

tawdry perch
#

not sure if it will work at all

#

but the format to mention someone is correct

jade tartan
#
color=0x0ff00)

             ^
SyntaxError: unmatched ')'```
tawdry perch
#

share the whole embed?

jade tartan
#

let me see if i can fix this first

tawdry perch
#

you maybe want to add ,to use multi line

wanton cipher
tawdry perch
#

oh they had it that way 😅

#

I miss read itt

jade tartan
#

ok yeah it wont mention the member in the embed but can it maybe do outside of the embed?

jade tartan
jade tartan
wanton cipher
wanton cipher
jade tartan
#

Should i do member = {member.mention}?

#

I dont think that would work

jade tartan
wanton cipher
wanton cipher
#

hence, you can do this:```py
@bot.command(name="ping")
async def ping(ctx):
mention = ctx.author.mention
await ctx.send(f"Hello {mention}")

jade tartan
#

Itll look more fancier

#

On the server

wanton cipher
jade tartan
#

Just that ?

wanton cipher
#

you can change it and add and all sorts, that's just the bare bones so you get an idea :)

jade tartan
#

Am sorry if am asking too much ?

#

But can a bot add multiple autoroles when a member joins?

wanton cipher
boreal ravine
#

lists exists for a reason

jade tartan
#
    await member.channel.send(f"OMG! {member.mention} just joined!")
AttributeError: 'Member' object has no attribute 'channel'```
boreal ravine
#

ah it doesn't

wanton cipher
#

!d discord.Member.add_roles

dense swallow
unkempt canyonBOT
#

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

Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s.

You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
tawdry perch
boreal ravine
#

^

tawdry perch
#

and no it does not exists*

boreal ravine
#

think about it

wanton cipher
#

oops, mb, lemme change it rq

boreal ravine
#

"members" dont have special channels therefore theres no attr for that

#

¯_(ツ)_/¯

tawdry perch
#

this .

jade tartan
#

so

boreal ravine
#

meaning?

#

!d discord.ext.commands.Bot.get_channel use this

unkempt canyonBOT
tawdry perch
jade tartan
#

sorry i mean when they join they only have one channel where they go and react to the message to gain full access to the server

#

and by that theyre giive a specified role

#

to see that channel

dense swallow
#

Reaction roles?

jade tartan
#

yes

dense swallow
#

Those are complicated stuffs.

jade tartan
#

Wdym its simple

dense swallow
#

Its using on_raw_reaction_add event

jade tartan
#

yes

#

well its using this

#

hold up

tawdry perch
jade tartan
#
        await member.add_roles(autorole)```
dense swallow
jade tartan
#

by that they will see only one channel called rules and thats where they have to react to the emoji to gain a member role

#

after that have react to the emoji

#

if that make sense

tawdry perch
boreal ravine
#

why spoonfeed

dense swallow
#

Yeah that works too

wanton cipher
tawdry perch
#

but it has timeout so it technically should be only used in DMs

jade tartan
dense swallow
#

I haven't worked with autorole/reaction roles.. so irdk

tawdry perch
dense swallow
#

u need to use the payload and smth

jade tartan
#
async def on_raw_reaction_add(payload):
    ourMessageID = 903210158803537970

    if ourMessageID == 903210158803537970:
        member = payload.member
        guild = member.guild

        emoji = payload.emoji.name
        if emoji == '✅':
            role = discord.utils.get(guild.roles, name="Member")
            await member.add_roles(role)

@client.event
async def on_raw_reaction_add(payload):
    if payload.member.bot:
        pass

    else:
        with open('reactrole.json') as react_file:
            data = json.load(react_file)
            for x in data:
                if x['emoji'] == payload.emoji.name:
                    role = discord.utils.get(client.get_guild(
                        payload.guild_id).roles, id=x['role_id'])

                    await payload.member.add_roles(role)
dense swallow
#

!d discord.on_raw_reaction_add

unkempt canyonBOT
#

discord.on_raw_reaction_add(payload)```
Called when a message has a reaction added. Unlike [`on_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_reaction_add "discord.on_reaction_add"), this is called regardless of the state of the internal message cache.

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

And yes i have that sorted

#

Sorry what was the multiple auto roles?

#

tht ive asked about

#

i mean everyone has their preference in designing their own server

#

so

dense swallow
#

Autoroles means giving user role automatically when they join

tawdry perch
#

what is the server design related to this?

jade tartan
#

true yes

jade tartan
#

etc

#

basically being ur own discord admin server

slate swan
#

how to make the command can be used only by the owner of the server?

#

How to create a decorator when used check if a user is in a list

tawdry perch
boreal ravine
slate swan
unkempt canyonBOT
#

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

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

This check raises a special exception, [`NotOwner`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NotOwner "discord.ext.commands.NotOwner") that is derived from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
slate swan
tawdry perch
slate swan
boreal ravine
#

isnt he the bot/guild owner though

slate swan
tawdry perch
#

Bot owner != server owner

#

Always*

boreal ravine
#

technically if its his server it shouldnt mind

slate swan
boreal ravine
#
a = [656073353215344650, 512354988157173763]

def check(ctx):
  return ctx.author.id in a
#

👀

slate swan
#

Does it works a decerator

#

@boreal ravine

slate swan
#

Ok

#

there, theyve already provided the check for you

merry pewter
#

Pls Script Invite Tracker..

boreal ravine
#

no

#

we no spoonfeed here

maiden fable
#

!d discord.Guild.invites

unkempt canyonBOT
#

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

Returns a list of all active instant invites from the guild.

You must have the [`manage_guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_guild "discord.Permissions.manage_guild") permission to get this information.
maiden fable
#

!d discord.on_invite_create

unkempt canyonBOT
#

discord.on_invite_create(invite)```
Called when an [`Invite`](https://discordpy.readthedocs.io/en/master/api.html#discord.Invite "discord.Invite") is created. You must have the [`manage_channels`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to receive this.

New in version 1.3.

Note

There is a rare possibility that the [`Invite.guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Invite.guild "discord.Invite.guild") and [`Invite.channel`](https://discordpy.readthedocs.io/en/master/api.html#discord.Invite.channel "discord.Invite.channel") attributes will be of [`Object`](https://discordpy.readthedocs.io/en/master/api.html#discord.Object "discord.Object") rather than the respective models.

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

!d discord.on_invite_delete

unkempt canyonBOT
#

discord.on_invite_delete(invite)```
Called when an [`Invite`](https://discordpy.readthedocs.io/en/master/api.html#discord.Invite "discord.Invite") is deleted. You must have the [`manage_channels`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to receive this.

New in version 1.3.

Note

There is a rare possibility that the [`Invite.guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Invite.guild "discord.Invite.guild") and [`Invite.channel`](https://discordpy.readthedocs.io/en/master/api.html#discord.Invite.channel "discord.Invite.channel") attributes will be of [`Object`](https://discordpy.readthedocs.io/en/master/api.html#discord.Object "discord.Object") rather than the respective models.

Outside of those two attributes, the only other attribute guaranteed to be filled by the Discord gateway for this event is [`Invite.code`](https://discordpy.readthedocs.io/en/master/api.html#discord.Invite.code "discord.Invite.code").

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

Use these things @merry pewter

spiral frigate
#

even I forgot how to get out of one folder to another
like I have a bot folder and a cog folder and I want to get from the cog folder to the bot folder without specifying the full path

lament mesa
#

Use the relative path

spiral frigate
#

like I have a bot folder in it the cog and resources folders I want to get from the cog folder to the resources folder

devout iris
#

How can i see bot's uptime?

#

Codes

boreal ravine
#

How do i get a command group?

undone wyvern
boreal ravine
#

like getting a cog

#

!d discord.ext.commands.Group like getting this

unkempt canyonBOT
#

class discord.ext.commands.Group(*args, **kwargs)```
A class that implements a grouping protocol for commands to be executed as subcommands.

This class is a subclass of [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") and thus all options valid in [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") are valid in here as well.
boreal ravine
#

!d discord.ext.commands.Bot.get_cog using smth like this

unkempt canyonBOT
slate swan
#

../ returns to the previous folder

#

So if your folder structure is like

src (folder)
-> image.png  (file)
-> public (folder)
   -> data  (folder)

So if you want to access image.png from the data folder you'd need to use ../data.png

spiral frigate
#
  File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "O:\Suzuki\cogs\utilities.py", line 75, in monetka
    await ctx.reply(f"`{choice}` да? Посмотрим... А у нас тут `{result}` Жаль! :tired_face:", file=discord.File(r'../coin-flip.gif'))
  File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\file.py", line 73, in __init__
    self.fp = open(fp, 'rb')
FileNotFoundError: [Errno 2] No such file or directory: '../coin-flip.gif'

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

Traceback (most recent call last):
  File "C:\Users\Baraban4ik\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\Baraban4ik\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\Baraban4ik\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: FileNotFoundError: [Errno 2] No such file or directory: '../coin-flip.gif'
maiden fable
#

Print your cwd

#

!d os.getcwd

unkempt canyonBOT
#

os.getcwd()```
Return a string representing the current working directory.
maiden fable
#

@spiral frigate

spiral frigate
#
        elif isinstance(choice, str):
            if choice in ("орёл", "решка"):
                result = random.choice(["орёл", "решка"])

                if result == "орёл" and choice == "орёл":
                    await ctx.reply(f"`{choice}` да? Посмотрим... О, `{result}`! Милашка выиграла! :tada:")
                    await ctx.send(file=discord.File(r'../coin-flip.gif'))
                if result == "решка" and choice == "решка":
                    await ctx.reply(f"`{choice}` да? Посмотрим... О, `{result}`! Милашка выиграла! :tada:", file=discord.File(r'../coin-flip.gif'))
                if result != choice:
                    await ctx.reply(f"`{choice}` да? Посмотрим... А у нас тут `{result}` Жаль! :tired_face:", file=discord.File(r'../coin-flip.gif'))
            elif choice != "орёл" or "решка":
                embed = discord.Embed (
                    title = 'Команда `s~монетка`',
                    description = 'Это `монетка` ты должен выбрать сторону `орёл` или `решка`. \n Потом я бросаю монетку, и если ты выбрал `орёл`, а выпала `решка` то ты проиграл.',
                    colour = 0x694c5f
                )
                embed.add_field(name= "Использование:", value= "> `s~монетка` `(орёл/решка)`", inline= False)
                embed.add_field(name= "Параметры:", value= ">>> <> - Необязательный параметр \n () - Обязательный параметр", inline= False)
                embed.add_field(name= "Пример:", value= ">>> `s~монетка` `орёл` \n ⮩ Ты выбираешь `орёл` и я подкидываю монетку", inline= False)

                await ctx.reply(embed = embed, delete_after= 15)
#

code

maiden fable
#

Bro

#

Can u please do print(os.getcwd()) after importing os?

fossil goblet
spiral frigate
dusk pumice
#

I think there's something when hunter says
I'm gonna try it too

fossil goblet
dusk pumice
maiden fable
#

Current Working Directory

#

😐 Python short forms istg

dusk pumice
maiden fable
#

Oops, u gotta call it since it's a function

dusk pumice
maiden fable
#

Edited it, thanks for pointing it out

#

() after cwd

#

Its a function

#

getcwd is a function, you gotta call it

dusk pumice
#

Okayy

strong matrix
#

Cwd = current working directory

dusk pumice
maiden fable
dusk pumice
maiden fable
#

That's the path where your console is rn. Suppose u have a file named image.png in a folder named data, then u gotta do .data/image.png instead of just .image.png .

The second one is gonna raise a FileNotFoundError

#

Haha ik it's confusing

dusk pumice
maiden fable
#

For now, you can think thT it's mainly used for debugging purposes haha

dusk pumice
#

Okaylemon_thinking

maiden fable
#

I hope you know what's debugging now

dusk pumice
#

Yep. Now I can know little bit of it.

#

Thanks

maiden fable
#

Phew

dusk pumice
maiden fable
#

Eh I told him to print that, he didn't sooo I can't really do anything 🤷‍♂️

dusk pumice
slate swan
#

What's the command for dms to lazy to go to the api reference on mobile

maiden fable
slate swan
#

To send a dm to users

maiden fable
#

!d discord.User.send

unkempt canyonBOT
#

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

Sends a message to the destination with the content given.

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

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

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
dusk pumice
maiden fable
#

Hm?

slate swan
maiden fable
dusk pumice
#

Howw

maiden fable
#

There, was finding that

#

@dusk pumice ^^^

dusk pumice
#

Thanks

maiden fable
#

(:

dusk pumice
#

No?

maiden fable
dusk pumice
#

Kk

#

Hmm

#

Hunter do you know why my button doesn't work?

#

It worked yesterday.. lemon_grumpy

maiden fable
#

How would I know without seeing your code pithink

dusk pumice
#

Ohh

#

I thought I sendt the code sry

maiden fable
#

It's fine

dusk pumice
#

Import codes:

from discord_components import Button, Select, SelectOption, ComponentsBot, ButtonStyle
from discord_components import DiscordComponents
from discord.ext.commands import Bot

The codes:

#TEST
@bot.command()
async def button(ctx):
    await ctx.send("Buttons!", components=[Button(label="Button", custom_id="button1")])
    interaction = await bot.wait_for(
        "button_click", check=lambda inter: inter.custom_id == "button1"
    )
    await interaction.send(content="Button Clicked")
NOT WORKING ):

||): is weird to me.||

maiden fable
#

Why not use dpy 2.0 for buttons 😐

dusk pumice
maiden fable
#

Welp gtg rn. If you want, u can DM me the code and gonna reply to u ASAP. Cya

slate swan
dusk pumice
#

I didn't ment it was bad. Sorry hunter

slate swan
#

Nah im not saying irs bad im just saying people do it that for that reason

#

hello guys help

#

But if he likes it like that well i have no problem

dusk pumice
#

kk

slate swan
#

see i want my discord bot to get some permisiions when we are adding to a server

slate swan
dusk pumice
slate swan
#

see i want my discord bot to get some permisiions when we are adding to a server

dusk pumice
slate swan
#

see i want my discord bot to get some permisiions when we are adding to a server

slate swan
#

please help guys

slate swan
dusk pumice
slate swan
#

i am not getting

dusk pumice
slate swan
slate swan
slate swan
#

Use this

slate swan
dusk pumice
slate swan
#

when i try in bot section

#

nothing happen\

slate swan
#

when i do something in ouath

boreal ravine
dusk pumice
slate swan
#

Np

#

How to implement check in cogs

#

it's same as in Normal commands

#

It doesn't include stuff like components , threads and stuff , so no

#

Ok but am i up to date the other stuff are forks?

dapper cobalt
#

!pypi disnake is a really great and up-to-date fork.

unkempt canyonBOT
slate swan
#

Ok

#

true , it's far better than most of the forks

slate swan
#

Whats the difference tho?

dapper cobalt
#

It has the same context, too. All you have to do is change discord everywhere in your code to disnake.

slate swan
dapper cobalt
slate swan
#

And ill check them out

#

Decent repo , it's great for a person who just started with dpy

slate swan
#

pull reqs exist

tawdry perch
#

I suck at them :D

#

it took me 90 minutes to make a single pr

slate swan
#

☠️ git installation issues?

tawdry perch
#

no, I never made pr before to @lament depot

slate swan
#

you can make pull reqs in visual studio code very easily

dapper cobalt
kindred hedge
#

I assume this is an appropriate channel to ask for help with this.

How do I make specific text, in t his case "Master", "Diamond, "Platinum", have their own color, ex. Master being red, Diamond blue, and so on

tawdry perch
urban shell
#

hey, is there a way to fetch the ids of the members in a particular vc

slate swan
dapper cobalt
dapper cobalt
#

Though, you can use code blocks.

kindred hedge
#

Oh, can I ping roles as the name of the embed instead and give those roles colours then?

slate swan
#

Or title/author/footer

dapper cobalt
#

You can't ping in fields' name, embed title, nor author name.

kindred hedge
#

How was this done then

dapper cobalt
slate swan
kindred epoch
#

Bruh that's literally a role pinged

slate swan
kindred hedge
#

Oh, so the value?

slate swan
dapper cobalt
#

!d discord.Embed.description

kindred hedge
#

oo, i see

tawdry perch
#

@dapper cobalt , am I allowed to use the repo. It has no license which means it is like "non copyable" aka copyright

unkempt canyonBOT
kindred hedge
#

Can you set colors in description, or is that not a thing either

tawdry perch
#

but missing license for it :/

kindred epoch
dapper cobalt
kindred epoch
#

Only way Is to ping the role which had the color

tawdry perch
#

does disnake has the same syntax as dpy?

slate swan
tawdry perch
#

Because I need to add ```py
except discord.Forbidden

slate swan
#

It's a fork , so sure

tawdry perch
#

so it would not be ```
except disnake.Forbidde

visual island
#

!d discord.errors.Forbidden

unkempt canyonBOT
#

exception discord.Forbidden(response, message)```
Exception that’s raised for when status code 403 occurs.

Subclass of [`HTTPException`](https://discordpy.readthedocs.io/en/master/api.html#discord.HTTPException "discord.HTTPException")
dapper cobalt
#

I thought it looks for queries everywhere on rtd.

tawdry perch
#

I need to be sure of the error

dapper cobalt
#

It has it.

slate swan
dapper cobalt
slate swan
#

I'm on phone so cannot check it , if it's wrong anyone pls do correct it

tawdry perch
#

so instead of discord I use disnake?

slate swan
#

Disnake can install itself as discord iirc

tawdry perch
#

@dapper cobalt did you install as discord?

visual island
#

installing disnake allows you to use discord or disnake

tawdry perch
#

oh good to know

dapper cobalt
tawdry perch
#

well I write them as discord to now confuse myself 😅

slate swan
#

or make an init.py and import disnake as discord

may work?

dapper cobalt
#

Someone like me would've forgotten about the import ... as ... and do

import disnake
discord = disnake
tawdry perch
#

well if this is correct, then all good ```py
except disnake.Forbidden:

twilit scarab
#

Why did my bot not react to the message?

async def add_reaction(reaction, message):
  msg = client.get_message(905012238727921676)
  emoji = '\N{THUMBS UP SIGN}'
  await msg.add_reaction(emoji)

TY for any help ❣️

slate swan
#

what's the difference between on_ready and on_connect

visual island
visual island
#

Disnake has Client.get_message while discord.py dont

dim wing
#

does bot like Koya uses a website to get their nsfw pictures?

twilit scarab
#

Oh okay good to know

visual island
#

?

dim wing
boreal ravine
dim wing
twilit scarab
#

What else could i use @visual island ?

boreal ravine
visual island
#

you need to fetch

slate swan
#
    if ctx.author.discord.Status == discord.Status.dnd:
    #do something```
is this not a thing?
visual island
#

Client._connection._get_message() is read only

twilit scarab
#

client.fetch_message ? Can i look this up somewhere ( the available commands )

visual island
#

no

#

abc.Messageable.fetch_message

#

!d discord.Status

unkempt canyonBOT
#

class discord.Status```
Specifies a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") ‘s status.
slate swan
visual island
#

no

slate swan
#

how would i get that

visual island
#

ctx.author.status

slate swan
#

thanks

twilit scarab
twilit scarab
slate swan
#
@bot.command()
async def st(ctx):
    if ctx.author.status == 'dnd':
        await ctx.send('yes')```
so this doesnt work
#

and neither does

@bot.command()
async def st(ctx):
    if ctx.author.status == discord.Status.dnd:
        await ctx.send('yes')```
visual island
# twilit scarab 😵‍💫 whaaat

a GuildChannel instance is inherited from abc.Messageable. the classes that inherited GuildChannel are: TextChannel, VoiceChannel, StoreChannel, StageChannel. You can get them by doing something.channel or bot.get_channel

visual island
slate swan
#

yes

twilit scarab
visual island
#

you need the channel's ID also sadly

#

but anyways you can get the channel's ID from the message id by using ._connection._get_message() method

visual island
twilit scarab
slate swan
#

im dnd...

visual island
#

you're intents are not set up correctly

slate swan
#

weird

#

ill double check that ty

#

can that be done manually via the source code

#

or do i need to go back into the developer panel

twilit scarab
#

just tick the boxes

visual island
visual island
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 the Members and Presences intents, which are needed for events such as on_member 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.

visual island
#

both

slate swan
#

is there any way i can inable all intents with source?

#

like intents = intents.all()

slate swan
#

nevermind

#

i already have

intents = discord.Intents.all()
intents.members = True
bot = discord.Client(intents=intents)```
visual island
slate swan
#

yeah i get that

visual island
#

you're using discord.Client?

slate swan
#

what should i use..

visual island
#

they doesn't have commands extension

#

commands.Bot

slate swan
#

oh

#

i use @bot.command

visual island
#

your bot variable is currently discord.Client instance which doesnt have anything to do with commands

#

you can just change it to be commands.Bot

slate swan
#

ohh

#

u mean

#

bot = commands.Bot(command_prefix=commands.when_mentioned_or('^'))

visual island
#

sure

#

and pass your intents there

slate swan
#

so bot = commands.Bot(command_prefix=commands.when_mentioned_or('^')(intents=intents))

visual island
#

no

#
bot = commands.Bot(command_prefix=commands.when_mentioned_or('^'), intents=intents)
#

better

slate swan
#

ty

#

uhhh that caused a loop

visual island
#

a loop?

slate swan
#

¯_(ツ)_/¯

#

Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead. Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x0000000003863040>

visual island
#

what loop

#

you haven't enabled intents in the developer portal

slate swan
#

ohh so tell then that wont work

#

ok makes sense

slate swan
#

how can i define things like <PublicUserFlags value=256> and <PublicUserFlags value=64> as emojis?

twilit scarab
#

ah sorry client.get_message isn't working

maiden fable
maiden fable
boreal ravine
#

!d discord.Member.public_flags use this and check if a user has a certain flag

unkempt canyonBOT
#

property public_flags```
Equivalent to [`User.public_flags`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.public_flags "discord.User.public_flags")
boreal ravine
#

which part

slate swan
#

<PublicUserFlags value=256>

#

im trying to define the value as an emoji

twilit scarab
boreal ravine
#

i mean your just sending the member flag attr and not checking for anything

slate swan
#

should i just define the value?

maiden fable
slate swan
#

something like 256 = Balance

boreal ravine
maiden fable
#

!d discord.PublicUserFlags

unkempt canyonBOT
#

class discord.PublicUserFlags```
Wraps up the Discord User Public flags.

x == y Checks if two PublicUserFlags are equal.

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

hash(x) Return the flag’s hash.

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

New in version 1.4.
maiden fable
#

Just use iter() to create a pair of those

slate swan
#

okay ty

maiden fable
#

iter(discord.Member.public_flags)

Just like dict.items

twilit scarab
#

Looks not correct for me at all 😄

msg = client.abc.Messageable.fetch_message(905012238727921676)
maiden fable
#

!d discord.Client.get_channel

unkempt canyonBOT
boreal ravine
twilit scarab
#

Idk, i thought it would be client.fecht_message(msgid) ?
and thats the channel ```py
channel = client.fetch_channel(686471829074083860)
msg = client.fetch_message(905012238727921676) in channel

?
boreal ravine
#

and remove in channel

twilit scarab
#

So ```py
channel = client.fetch_channel(686471829074083860)
msg = channel.fetch_message(905012238727921676)

boreal ravine
#

yes

twilit scarab
#

No errorcode but the bot isn't reacting

boreal ravine
#

hm

slate swan
boreal ravine
#

huh

#

oh yeah

#

he didnt await it

#

!d discord.Client.fetch_channel

unkempt canyonBOT
#

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

Retrieves a [`abc.GuildChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.GuildChannel "discord.abc.GuildChannel"), [`abc.PrivateChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.PrivateChannel "discord.abc.PrivateChannel"), or [`Thread`](https://discordpy.readthedocs.io/en/master/api.html#discord.Thread "discord.Thread") with the specified ID.

Note

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

New in version 1.2.
slate swan
twilit scarab
#

Await is await msg.add_reaction(emoji)

devout iris
#

How can I make different colors for different console errors?

waxen torrent
#

Is there any way to stop/break/cancel asyncio.sleep mid way inside an async function..?

visual island
visual island
unkempt canyonBOT
#

coroutine asyncio.wait_for(aw, timeout)```
Wait for the *aw* [awaitable](https://docs.python.org/3/library/asyncio-task.html#asyncio-awaitables) to complete with a timeout.

If *aw* is a coroutine it is automatically scheduled as a Task.

*timeout* can either be `None` or a float or int number of seconds to wait for. If *timeout* is `None`, block until the future completes.

If a timeout occurs, it cancels the task and raises [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "asyncio.TimeoutError").

To avoid the task [`cancellation`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.cancel "asyncio.Task.cancel"), wrap it in [`shield()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.shield "asyncio.shield").

The function will wait until the future is actually cancelled, so the total wait time may exceed the *timeout*. If an exception happens during cancellation, it is propagated...
visual island
#

but this only works to a planned cancel

#

!d asyncio.Task.cancel this is probably a better way though

unkempt canyonBOT
#

cancel(msg=None)```
Request the Task to be cancelled.

This arranges for a [`CancelledError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.CancelledError "asyncio.CancelledError") exception to be thrown into the wrapped coroutine on the next cycle of the event loop.

The coroutine then has a chance to clean up or even deny the request by suppressing the exception with a [`try`](https://docs.python.org/3/reference/compound_stmts.html#try) … … `except CancelledError` … [`finally`](https://docs.python.org/3/reference/compound_stmts.html#finally) block. Therefore, unlike [`Future.cancel()`](https://docs.python.org/3/library/asyncio-future.html#asyncio.Future.cancel "asyncio.Future.cancel"), [`Task.cancel()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.cancel "asyncio.Task.cancel") does not guarantee that the Task will be cancelled, although suppressing cancellation completely is not common and is actively discouraged.

Changed in version 3.9: Added the `msg` parameter.

The following example illustrates how coroutines can intercept the cancellation request:
waxen torrent
#

Oh..Thanks will try .. 👍

visual island
dusk pumice
slate swan
#

ideas for a bot?

dusk pumice
#

8ball?

slate swan
dusk pumice
#

Yea

#

If it's fun bot...

#

It must be fun!

slate swan
#

idk

dusk pumice
#

LOL

#

Okay~~~

fossil goblet
slate swan
slate swan
dusk pumice
dusk pumice
fossil goblet
slate swan
dusk pumice
#

LOL

#

Supercars?

slate swan
#

yeah

dusk pumice
#

Haha okay. funny

slate swan
#

it searches a post for a keyword aka the carname

dusk pumice
#

How about games?

#

Like battleship

#

Ohh

#

I gotta go fast

#

bye

slate swan
#

later

slate swan
maiden fable
maiden fable
slate swan
#

is there a way to make command cooldowns different depending on the roles a user has?

e.g someone with the role 'booster' can use the command every 3 hours while someone with the role 'user' 6 hours

devout iris
#

i want to destroye bot's message in a few seconds how can i make it? i.e.

Me: !yb
Bot: "answer" (5 seconds later bot's message will be deleted)

tawdry perch
#

I could say so

tawdry perch
#

!custom-cooldown can be useful to start of by

unkempt canyonBOT
#

Cooldowns in discord.py

Cooldowns can be used in discord.py to rate-limit. In this example, we're using it in an on_message.

from discord.ext import commands

message_cooldown = commands.CooldownMapping.from_cooldown(1.0, 60.0, commands.BucketType.user)

@bot.event
async def on_message(message):
    bucket = message_cooldown.get_bucket(message)
    retry_after = bucket.update_rate_limit()
    if retry_after:
        await message.channel.send(f"Slow down! Try again in {retry_after} seconds.")
    else:
        await message.channel.send("Not ratelimited!")

from_cooldown takes the amount of update_rate_limit()s needed to trigger the cooldown, the time in which the cooldown is triggered, and a BucketType.

maiden fable
unkempt canyonBOT
#
Nuh-uh.

No documentation found for the requested symbol.

tawdry perch
#

then few check functions

maiden fable
#

!d discord.abc.Messageable.send

unkempt canyonBOT
#

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

Sends a message to the destination with the content given.

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

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

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

delete_after kwarg

tawdry perch
#

Hunter, have you used disnake?

maiden fable
tawdry perch
#

Great, does it have exactly the syntax of dpy in exceptions as well?

maiden fable
devout iris
tawdry perch
#

I just wanted to be sure about I'm making good pr to one repo```py
#dpy
discord.Forbidden
#disnake
disnake.Forbidden

maiden fable
tawdry perch
#

nvm, good that it's correct

devout iris
#

Ty

stiff nexus
#

how do i make the bot calculate numbers in a command?

stark hearth
#

So a calculator?

#

You’ll need to classify your argument as integers for examples we will use a and b

#

And all you need to do is a basic ctx.send with a and b combined

#

@client.command()
async def addition(ctx,a:int,b:int):
await ctx.send(f"{a} + {b} = {a+b}")

#

Sorry if my code looks weird I’m on phone

#

If you wanna do other operator like multiply and subtract into one command, you can do if statements

#

@stiff nexus

stiff nexus
devout iris
#
@bot.command(pass_context= True)
async def temizle(ctx, arg):
    await ctx.channel.purge(arg)
    await ctx.send(f"{arg} tane Mesaj başarıyla Silindi".format(arg), delete_after = 5
#

What is wrong?

stark hearth
#

Ahh so multiple

stark hearth
#

I have no time but make one argument and eval it

#

Gtg bye

boreal ravine
devout iris
#

How can i make it with arg?
i.e.
Me: i!temizle 15
Bot: delete 15 message

boreal ravine
#

like I said

#

!d discord.TextChannel.purge

unkempt canyonBOT
#

await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=False, bulk=True)```
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 the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own. The [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.

Examples

Deleting bot’s messages...
autumn dove
#

I just learned that the discord.py project is ended. This is very sad news. Is there any word on forks or of a new library?

boreal ravine
#

disnake, hikari, py-cord, nextcord & more

autumn dove
#

Thank you

slate swan
#

can someone help me handle this error? my error processor isn't working so i'm obviously doing it wrong

Traceback (most recent call last):
snip
discord.ext.commands.errors.MissingAnyRole: You are missing at least one of the required roles: 'Server Booster' or 'Queer'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\coolb\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 71, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\coolb\OneDrive\Documents\mootbot\cogs\Commands.py", line 235, in nitropartner_error
    nitropartner.reset_cooldown(ctx)
NameError: name 'nitropartner' is not defined```
#

    @nitropartner.error
    async def nitropartner_error(self,ctx, error):
        if isinstance(error, commands.CommandOnCooldown):
            await ctx.message.delete()
            await ctx.send(error, delete_after=5)
        if isinstance(error, commands.errors.MissingAnyRole):
            nitropartner.reset_cooldown(ctx)
            await ctx.send("Incorrect roles.")
        else:
            print("Unhandled error:",error)
#

this is how the command starts:


    @commands.command(name="nitropartner")
    @commands.has_any_role("Server Booster","Queer")
    @commands.cooldown(1, 10800, commands.BucketType.user)
    async def nitropartner(self,ctx,member: discord.Member=None):

urban shell
#

hey guys, so I have been trying to retrieve the member info using this command -
member = discord.utils.get(guild.members, name="KamiKaizen")
but I was wondering if I could do the same with the member id instead of the member name

slate swan
#

!d discord.Guild.get_member

unkempt canyonBOT
urban shell
#

I'm sure that the id is correct

slate swan
#

Then the user is not in cache

urban shell
#

I defined guild as message.guild

slate swan
#

Use ...get_member(id) or await ...fetch_member(id)

urban shell
#

aight

#

I'll try await fetch_member(id)

slate swan
#

No

slate swan
#

Not just fetch_member

#

Always making an API call is bad

devout iris
#

how can i see the channel where a command is used in console?

quasi pawn
#

How to avoid @invalid-user?

manic wing
#

!d discord.ext.commands.Bot.after_invoke

unkempt canyonBOT
#

@after_invoke```
A decorator that registers a coroutine as a post-invoke hook.

A post-invoke hook is called directly after the command is called. This makes it a useful function to clean-up database connections or any type of clean up required.

This post-invoke hook takes a sole parameter, a [`Context`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context").

Note

Similar to [`before_invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.before_invoke "discord.ext.commands.Bot.before_invoke"), this is not called unless checks and argument parsing procedures succeed. This hook is, however, **always** called regardless of the internal command callback raising an error (i.e. [`CommandInvokeError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandInvokeError "discord.ext.commands.CommandInvokeError")). This makes it ideal for clean-up scenarios.
devout iris
#

Thx

slate swan
#

I'd rather use the accurate event

#

Then you can use like any ctx object, ctx.channel

manic wing
slate swan
manic wing
#

there is no difference

devout iris
slate swan
river hollow
#

hello whats wrong with this ```bot = commands.Bot(command_prefix='!')

message_id = 900079962903659123
channel = 900079092014388275

message = channel.fetch_message(message_id)
emoji = '\N{THUMBS UP SIGN}'
message.add_reaction(emoji)

bot.run('mytoken')```

#

i want that i start my bot and it direcly reacts to the message

vapid trellis
#

not channel.fetch_channel

river hollow
#

will try it

vapid trellis
#

channel is just an int containing the id over here, so its not working

slate swan
#

Your code won't work anyways

vapid trellis
#

yes

river hollow
vapid trellis
#

u need to keep it in a on_ready event

river hollow
#

ok

#

wait

steady flume
#

guys, help please, how to make cmd spoiler like Dank memer? when bot put puts every letter in spoiler form (||h||||e||||l||||p|| - like this) ?

river hollow
vapid trellis
river hollow
#

will add it

urban shell
#

hey guys, so I have been trying to retrieve the member info using this command -
member = discord.utils.get(guild.members, name="KamiKaizen")
but I was wondering if I could do the same with the member id instead of the member name

river hollow
urban shell
#

or is there a way to retrieve the member name if the id is known

river hollow
#

as error

vapid trellis
#

oh sry, I forgot to say u need to await the fetch channel function. my bad

river hollow
#

like this

urban shell
#

message = await bot.fetch_channel...

vapid trellis
#

yes

river hollow
#

will try it

#

discord.errors.NotFound: 404 Not Found (error code: 10003): Unknown Channel

vapid trellis
urban shell
river hollow
urban shell
# river hollow yes

can you just send me the tutorial you are following cause I've come across this same code somewhere

urban shell
#

did you copy it from SO?

river hollow
#

thats why i ask here

#

i dont find one

vapid trellis
urban shell
#

ah fuck

#

yes

vapid trellis
#

they are not trying to fetching channel, they are trying to fetch msg. we guided wrong i think

urban shell
#

the channel id is needed if he wants to fetch the channel

river hollow
#

yes

vapid trellis
#

yes, but they want to fetch the message and add a reaction to it

river hollow
urban shell
#

aight

vapid trellis
#

!d discord TextChannel.fetch_message

unkempt canyonBOT
#

In order to work with the library and the Discord API in general, we must first create a Discord Bot account.

Creating a Bot account is a pretty straightforward process.

river hollow
#

so what should i add

urban shell
#

so try something like this -
channel = await bot.fetch_channel(channel_id) message = await channel.fetch_message(message_id)

vapid trellis
#

yes

#

!d discord.TextChannel.fetch_message

unkempt canyonBOT
#

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

Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") from the destination.
river hollow
#

thanks you so muck

#

and also thank you @vapid trellis

#

:)) its working

urban shell
#

you copied the code from Stack Overflow 💀

#

but anyways

river hollow
#

oh

urban shell
#

np

river hollow
#

i started with it a long time ago

urban shell
#

and next time try not to blindly copy the code

river hollow
#

and then never finsished bc no one was able to help me

river hollow
#

the bot send the message and then react to his own

steady flume
#

guys, help please, how to make cmd spoiler like Dank memer? when bot put puts every letter in spoiler form (||h||||e||||l||||p|| - like this) ?

slate swan
#

make it write ||hello||?

urban shell
#

like the part where you're creating an embed or building a string

steady flume
# urban shell can you send your code?
    async def spoiler_cmd(self, ctx, text=None):
        if text is None:
            await ctx.reply("What do you want me to say?", mention_author=True)
        else:
            parsed_args = "||".join(text)
            await ctx.send(f"{parsed_args}")
vapid trellis
urban shell
#

^

steady flume
#

lol

vapid trellis
urban shell
#

so something like -
||T||||E ||||S ||||T||?

steady flume
#

yes

urban shell
slate swan
#

not the whole text in one spoiler

#

one spoiler for every letter each

steady flume
#

||h||||e||||l||||p|| - like this

urban shell
#

so you gotta split your string first

slate swan
#
parsed_args = "||||".join(text)
await ctx.send(f"||{parsed_args}")
#

something like this

steady flume
#

wait

#

imma try

slate swan
#

but you would have to remove the last two ||

#

so this is glitchy

#

I'm also dumb

#

because you'd have to make text into arguments

#

join takes an iterable as parameter

#

parsed_args = "||||".join(letter for letter in text) maybe

#

and if text is a sentence it will not make letters but whole words to letter 😕

slate swan
#

no sh

#

What is he trying to do?send a spoiler message? ||like me||

#

yes, with every letter surrounded by || ||

vapid trellis
steady flume
slate swan
#

Ah i see

#

How could I get a list of every channel in a server

steady flume
#
    async def spoiler_cmd(self, ctx, *, text=None):
        if text is None:
            await ctx.reply("What do you want me to say?", mention_author=True)
        else:
            parsed_args = "||".join(text)
            await ctx.send(f"||{parsed_args}")

doesnt work

slate swan
#

So I could do

for channel in channels
Code

slate swan
unkempt canyonBOT
steady flume
slate swan
#

Yes every channel possible

vapid trellis
slate swan
#

every channel

slate swan
slate swan
#

Idrk

steady flume
slate swan
#

ok

#

Then what about roles

#

why would u

#

one line

steady flume
#

how to make cmd spoiler like Dank memer? when bot puts every letter in spoiler form (||h||||e||||l||||p|| - like this) ?

#

help

slate swan
#

channels = len(guild.channels)

vapid trellis
#

btw I have a question, how would I go about if I were to prevent one person from accessing my bot's commands??
Would it be efficient to go around with something like this??

@bot.event
async def on_ready():
    print("Bot Online")
    for cmd in bot.commands:
        @cmd.before_invoke()
        async def before_invoke(ctx):
            if ctx.author.id == <the user id>:
                raise "Sorry, but you are not allowed to use commands on this bot"
            else:
                pass

or is there a more efficient and faster method??

slate swan
#

Thank you

slate swan
slate swan
slate swan
vapid trellis
#

but that doesnt mean I want to prevent them from talking atall

slate swan
#

oh mhm

slate swan
#

store their id

#

make a custom check

#

use it on every command

#

How could I get a list of all roles

slate swan
slate swan
#

if it works, let it be

slate swan
vapid trellis
slate swan
#

if what you did works, let it be

vapid trellis
#

I have questions about the code I posted like will it work

slate swan
#

one smart move again

#

Still no

#

use on_message

slate swan
vapid trellis
slate swan
#

Nah id rather not

#

and only do process_commands() under specific circumstances

#

if statements

slate swan
#

Just how do you get a list of all roles in a server

#

!d discord.Guild.roles