#discord-bots

1 messages · Page 715 of 1

slate swan
#

I forgot the bot object ;-;

#

kk thx

#

its still possible to make a economy bot right?

slate swan
#

alright

slate swan
#

dont use json tho

#

or im going to go crazy

#

haha alright

slate swan
#

its pretty easy

modern fiber
#

Hello! I need someone to help me with this command.
So basically, you run !trade command. And then the bot sends you two questions in DM; what you wanna trade, and what are you trading for.

So when you fill those up,
the bot sends return message in the channel choosed.
For example it says;
@amber beacon want to trade!
Trading: message 1
For: message 2

slate swan
#

since youll need a db

slate swan
slate swan
#

what is sql? so ik

slate swan
modern fiber
slate swan
#

lmfao

modern fiber
slate swan
#

my brain is hurting rn

slate swan
modern fiber
#

Can I explain you?

slate swan
slate swan
slate swan
#

thats the language youll need a db tho

#

thats async

tough lance
#

SQL is easy although the schema is tough

slate swan
#

Oh how fun

#

!pypi aiosqlite

unkempt canyonBOT
slate swan
#

im looking forward to this

slate swan
slate swan
#

just lying to myself i can feel the pain coming

#

i will jump to sql when i finish my 300functionspithink

slate swan
tough lance
slate swan
#

im about to do the same

#

maybe just to making wrappers

modern fiber
#

@slate swan DMs bud

slate swan
#

looks easy

slate swan
tough lance
#

I just randomly stroll here help someone and go back

slate swan
#

Lol same

#
    if 'afk check' in message.content:
        print('i have been summoned')
        await message.channel.send('Hello')
    else:
        pass
``` is this correct?
#

Depends

tough lance
#

Syntax is by far correct

slate swan
#

TypeError: on_ready() missing 1 required positional argument: 'message'

tough lance
#

on_ready doesn't take any params

final pumice
#

Does SQLite work with discord bots

#

Is it asynchronous

tough lance
final pumice
#

Ok thanks

tough lance
#

I think it has something to do with discord

slate swan
#

would anyone like to also code with me on this discord bot:D

soft narwhal
#

how do i make spaces in an embed(new lines)

slate swan
soft narwhal
slate swan
#

makes a new line

slate swan
#

imma start making economy

tough lance
#

Bro on_afkcheck isn't an event

slate swan
slate swan
slate swan
tough lance
#

You have to use on_message

slate swan
tough lance
#

Also you can use SQL if your bot is supposed to be a small one. Otherwise you will need to use PostgreSQL

#

Postgre is a beast

slate swan
#

sql isnt a db its a language

tough lance
slate swan
#

ofc it will lol

slate swan
#

as a db

tough lance
slate swan
#

i have to finish my 300functions first tho😔

daring valley
#
embed.set_image(guild.icon_url)

TypeError: set_image() takes 1 positional argument but 2 were given
how is this 2 arguements 😔

unkempt canyonBOT
#

set_image(*, url)```
Sets the image for the embed content.

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

Changed in version 1.4: Passing [`Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty") removes the image.
slate swan
#

is sublime text good?

slate swan
daring valley
slate swan
#

replit

#

lmao

slate swan
slate swan
slate swan
#

i only use json to hide my token

#

vsc is good

#

i use vsc

slate swan
#

dont use pycharm tho

daring valley
soft narwhal
#

why is the bracket red? @slate swan

slate swan
#

pycharm takes 1gb of ram for me

slate swan
slate swan
soft narwhal
slate swan
#

what should i use instead of json

#

.json*

slate swan
soft narwhal
slate swan
#

economy bot

slate swan
slate swan
#

has said on top

daring valley
tough lance
slate swan
#

you have to make a on ready event

soft narwhal
slate swan
#
@client.event
async def on_ready():
    ctypes.windll.kernel32.SetConsoleTitleW(f"Anti AFK • Ready as {client.user}")
    print(f'Logged in as {client.user}')

print(f'Logged in as {client.user}') isn't printing out anything kekw

slate swan
soft narwhal
#

im not sure im new to coding

slate swan
#
@bot.event
async def on_ready():
    print("bot is online")
#

add it to the top

tough lance
soft narwhal
# slate swan yes

Error:

Traceback (most recent call last):
  File "C:\Users\W 10\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\W 10\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\W 10\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: 'str' object has no attribute 'to_dict'```

Code:
```py
import discord
from discord import colour
from discord.ext import commands  # This is the part of discord.py that helps us build bots

token = ''

bot = commands.Bot(command_prefix="-")


@bot.command(name="hello")
async def hello_world(ctx: commands.Context):
    await ctx.send(embed=discord.Embed(description = "hello", title = "Test yay!", footer = "ok!"))


@bot.command(name="ping")
async def ping(ctx: commands.Context):
    await ctx.send(embed = discord.Embed(description=f"Pong! {round(bot.latency * 1000)}ms", colour=0x2f3136))

emb = 'discord.Embed(title = **__Level Rewards__** :giveaway:,description = > test \n ok, colour=0x2f3136)'

@bot.command(name="level")
async def ping(ctx: commands.Context):
    await ctx.send(embed =emb)


bot.run(token)
print("online!")```
slate swan
soft narwhal
slate swan
tough lance
unkempt canyonBOT
#
Resources

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

tough lance
#

Look at these first

slate swan
slate swan
slate swan
daring valley
slate swan
daring valley
slate swan
#

why would you set an img if your not gonna send one?

#

hurts my brain

soft narwhal
slate swan
slate swan
tough lance
daring valley
slate swan
slate swan
unkempt canyonBOT
#

set_image(*, url)```
Sets the image for the embed content.

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

Changed in version 1.4: Passing [`Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty") removes the image.
slate swan
#

basic py lol

#

no comments

#

why even set an img with the embed var and not the embed constructor

slate swan
slate swan
tough lance
soft narwhal
#

how do i restart my vsc code

#

i cant seem to find it

tough lance
#

!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.
slate swan
soft narwhal
soft narwhal
slate swan
tough lance
#

ARG means argument and jwargean keyword argument

soft narwhal
soft narwhal
tough lance
slate swan
#

kid wyd

slate swan
slate swan
slate swan
slate swan
#

more clean

slate swan
soft narwhal
slate swan
soft narwhal
slate swan
slate swan
#

i really should

#

😔

tough lance
#

How many time has that message been mentioned 🤣

slate swan
slate swan
tough lance
#

Lol

slate swan
#
afk_check_messages = ['Afk check', 'afk check', 'AFK CHECK']

how do i make a function so it goes through every single string in the list?

tough lance
#

Or any()

slate swan
#

no

tough lance
#

Well for loop is better here

slate swan
#

yes

daring valley
slate swan
#
for iterable in afk_check_messages:
tough lance
slate swan
slate swan
slate swan
slate swan
slate swan
#

message.channel.guild?

#

!d str.split

unkempt canyonBOT
#

str.split(sep=None, maxsplit=- 1)```
Return a list of the words in the string, using *sep* as the delimiter string. If *maxsplit* is given, at most *maxsplit* splits are done (thus, the list will have at most `maxsplit+1` elements). If *maxsplit* is not specified or `-1`, then there is no limit on the number of splits (all possible splits are made).

If *sep* is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, `'1,,2'.split(',')` returns `['1', '', '2']`). The *sep* argument may consist of multiple characters (for example, `'1<>2<>3'.split('<>')` returns `['1', '2', '3']`). Splitting an empty string with a specified separator returns `['']`.

For example:
soft narwhal
#

i thought it was message.content.split(“::”)

slate swan
#

it is?

#

your splitting the msg on a certain point with split

tough lance
#

Ye it's the side effects of a tutorial

slate swan
#

💀

#

how do i grab the guild from message?

#

@slate swan im not even done yet

#

anyone know why user is underlined?

#

my small brain needs assistance

slate swan
#

oh.

#

users as you set in the var

#

yeah

soft narwhal
tough lance
#

You defined users instead of user lol

slate swan
#

LMAO

shy roost
slate swan
#

how do i grab the guild from message?

slate swan
shy roost
tough lance
unkempt canyonBOT
slate swan
#

typo again?

shy roost
soft narwhal
slate swan
#

fuck

#

fixed it

#

was just another typo 💀

shy roost
# slate swan typo again?

check the place where you are referencing the object, could most likely be a misreference or a typo

slate swan
shy roost
#

anyone here have anything more advanced to add to a moderation bot?

slate swan
#

just closed my bot and it was playing relaxing music

shy roost
#

i need something challenging to keep my interest

slate swan
#
                            reason = ""
                            while reason == "":
                                if reaction.emoji == "0️⃣":
                                    reason = "Other" 
                                    break
                                elif reaction.emoji == "1️⃣":
                                    reason = "Too short application \ poorly explained"
                                    break
                                elif reaction.emoji == "2️⃣":
                                    reason = "Lack of hours on Unturned \ inexperienced"
                                    break
                                elif reaction.emoji == "3️⃣":
                                    reason = "Bad english \ grammar"
                                elif reaction.emoji == "4️⃣":
                                    reason = "Inactivity \ Lack of hours on ICE RP"
                                elif reaction.emoji == "5️⃣":
                                    reason = "Too many incorrect answers"
                                elif reaction.emoji == "6️⃣":
                                    reason = "Lack of developer skills"
                                elif reaction.emoji == "7️⃣":
                                    reason = "Cannot be trusted \ too many bans"
                                elif reaction.emoji == "8️⃣":
                                    reason = "Troll application"
                            embed.add_field(name="Reason for denial", value=reason, inline=True)
                            await chl2.send(content=None, embed=embed)

discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed.fields.0.value: This field is required

#

woah

soft narwhal
shy roost
#

not very pythonic if you ask me

slate swan
#

no

shy roost
slate swan
#

cant use buttons here

#

how

#

cuz it needs to send a message to another channel

slate swan
wispy spade
slate swan
#

and interactions are autistic

slate swan
slate swan
slate swan
tough lance
#

Why not create a dict?

slate swan
soft narwhal
#

@slate swan

wispy spade
#

there's no variable called message anywhere

soft narwhal
shy roost
# slate swan and interactions are autistic

that's an interesting way to describe something that's related with computers, and secondly, interacting with the channel that the message should be sent to should be a better way than to use about 7 elif checks. That's just not very pythonic.

slate swan
slate swan
shy roost
#

never heard of such a term as "snipe" when it comes to past messages

slate swan
#

well fuck him then

tough lance
slate swan
#

idc not gonna remake this

shy roost
slate swan
#

even after an edit it logs it to

soft narwhal
#

@wispy spade will discord.Message work?

wispy spade
slate swan
#
afk_check_messages = ['Afk check', 'afk check', 'AFK CHECK']

@client.event
async def on_message(message):
    for i in afk_check_messages:
        if i in message.content:
            print(f'[{get_time()}] -> Prevented AFK check from: {message.author}!')
            await message.channel.send(random.choice(sentences))
        else:
            pass
``` when someone does say something in `afk_check_messages` it sends it 3 times
tough lance
#

With the rise of NFTs there are many self bots now

shy roost
wispy spade
slate swan
#

but it has to be for moderation as you cant log a msg for no reason since its against tos

shy roost
shy roost
slate swan
#

he was owner of discord interactions discord

slate swan
#

and thats the reason

tough lance
shy roost
thin kelp
shy roost
soft narwhal
#

@slate swan

File "C:\Users\W 10\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: 'member_descriptor' object has no attribute 'split'      ```
tough lance
#

I just realized levi

soft narwhal
#

more errorrs

shy roost
slate swan
#

@slate swan i dont think i can make a economy bot.😅

shy roost
tough lance
shy roost
slate swan
#

i tried making a comand just for beg

tough lance
#

!resources

unkempt canyonBOT
#
Resources

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

shy roost
slate swan
#

sql has no attribute to load so what do i do?

slate swan
thin kelp
shy roost
# slate swan make a auto mute on a msg burst

tried that before, was a pain. I want something that's more related to databases, which in this case might be an economy system, where a user can buy certain colors for their roles?

slate swan
#

anyone has repos i can contribute to im kinda bored

shy roost
slate swan
#

i sure do!

tough lance
#

I have some game suggestions

slate swan
#

have repos*

tough lance
#

Minesweeper

#

Sokoban

slate swan
shy roost
slate swan
shy roost
slate swan
slate swan
shy roost
# slate swan a marketplace

yeah maybe where the amount of messages you send in the server, the more 'currency' you get, and you can buy color roles or certain features?

slate swan
thin kelp
#

And make it spam proof

#

So people don't spam for money

soft narwhal
tough lance
#

Dude

soft narwhal
#
message = discord.Message
@bot.command(name="repeat")
async def repeat(ctx: commands.Context):
    await ctx.send("You sent:" + message)```
wispy spade
#

uh wot?

#

discord.Message is really just a class not a message or anything

shy roost
thin kelp
#

You are defining message before the command

shy roost
#

that's a good suggestion

wispy spade
shy roost
soft narwhal
wispy spade
#

again, you are probably looking for ctx.message or something

slate swan
#

                            reason = [""]
                            while len(str(reason)) < 1:
                                if reason.emoji == "9️⃣":
                                    break
                                if reaction.emoji == "0️⃣":
                                    reason.append("Other")
                                if reaction.emoji == "1️⃣":
                                    reason.append("Too short application \ poorly explained")
                                if reaction.emoji == "2️⃣":
                                    reason.append("Lack of hours on Unturned \ inexperienced")
                                if reaction.emoji == "3️⃣":
                                    reason.append("Bad english \ grammar")
                                if reaction.emoji == "4️⃣":
                                    reason.append("Inactivity \ Lack of hours on ICE RP")
                                if reaction.emoji == "5️⃣":
                                    reason.append("Too many incorrect answers")
                                if reaction.emoji == "6️⃣":
                                    reason.append("Lack of developer skills")
                                if reaction.emoji == "7️⃣":
                                    reason.append("Cannot be trusted \ too many bans")
                                if reaction.emoji == "8️⃣":
                                    reason.append("Troll application")
                            embed.add_field(name="Reason for denial", value=str(reason), inline=True)
                            await chl2.send(embed=embed)

discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed.fields.0.value: This field is required

#

just say if there is smthing wrong dont comment on the reaction or button shit

#

please

#

im getting cancer from this shit fr

soft narwhal
wispy spade
#

you want to access the content

soft narwhal
thin kelp
#

Can it be because you named your embed "embed"?

shrewd pasture
#

how do you make your bot copy an emoji and put it on your server. Example

I write: !emoji Python
The Bot copies that emoji and makes it a server emoji
Please help me out thank you!

slate swan
#

anyone know fix?

slate swan
shrewd pasture
thin kelp
slate swan
#

that wont matter

wispy spade
slate swan
#

its cuz one of the fields is invalid

wispy spade
#

So check the str(reason) thingie

slate swan
#

but none of them are

#

while len(str(reason)) < 1:

slate swan
#

so it shouldn't continue before its valid

soft narwhal
wispy spade
slate swan
#

hm

#

well for some reason reason = [""]

#

so while len(str(reason)) < 1:

thin kelp
#

Is it because of the emojis

wispy spade
slate swan
#

doesn't work

slate swan
soft narwhal
slate swan
#

why might this not work ?

                        while len(str(reason)) < 1:
thin kelp
#

Nvm I am dunb

slate swan
soft narwhal
wispy spade
wispy spade
slate swan
#

well how do I check if reason is empty

wispy spade
#

just do len(reason) instead of converting reason

soft narwhal
slate swan
#

what did i do wrong?

wispy spade
slate swan
thin kelp
slate swan
#

one of them works fine and other

thin kelp
#

you are missing a closing bracket

#

After datetime.datetime.utcnow()

wispy spade
# slate swan

forgot to close parenthesis in both embed variables

slate swan
#

ah

#

i see

#

got it thanks

soft narwhal
#

@slate swan help mee

slate swan
#

reason = []
while not reason:

#

doesn't work either

slate swan
thin kelp
soft narwhal
wispy spade
slate swan
#

coinflip command works thanks guys :D<3

wispy spade
slate swan
#

it just doesn't work

#

@soft narwhal

@bot.command()
async def repeat(ctx,*,say):
    await ctx.send(say)
#

wtf is wrong with this shit

#

it just skips

#

the while loop

#

like it never was there

wispy spade
#

well it shouldn't cause not [] would be True

#

when an item is there it should become False

slate swan
#

while len(reason)!=0:

#

doesn't work either

wispy spade
slate swan
#

yes

#

and the error is cuz reason is invalid

#

and reason shouldn't be invalid

#

if it went thru while

#

while reason:

#

doesn't work either

thin kelp
#

Same error?

slate swan
#

bro

slate swan
#

python < javascript from now on

thin kelp
#

If you are using a list, did you change the str(reason)

slate swan
#

read the code dude

wispy spade
slate swan
#

yes

wispy spade
#

are there any other fields apart from that one?

slate swan
#

shouldn't matter

#

the list is empty

#

but here

#
                            embed = discord.Embed(title="Application denied", color=0xFF0000)
                            embed.add_field(name="Applicant", value=reaction.message.content, inline=False)
                            embed.add_field(name="Denied by", value=user, inline=False)```
thin kelp
#

Are you sure the while loop is not running

slate swan
#
                                if reaction.emoji == "9️⃣":
                                    break
                                if reaction.emoji == "0️⃣":
                                    reason.append("Other")
                                if reaction.emoji == "1️⃣":
                                    reason.append("Too short application \ poorly explained")
                                if reaction.emoji == "2️⃣":
                                    reason.append("Lack of hours on Unturned \ inexperienced")
                                if reaction.emoji == "3️⃣":
                                    reason.append("Bad english \ grammar")
                                if reaction.emoji == "4️⃣":
                                    reason.append("Inactivity \ Lack of hours on ICE RP")
                                if reaction.emoji == "5️⃣":
                                    reason.append("Too many incorrect answers")
                                if reaction.emoji == "6️⃣":
                                    reason.append("Lack of developer skills")
                                if reaction.emoji == "7️⃣":
                                    reason.append("Cannot be trusted \ too many bans")
                                if reaction.emoji == "8️⃣":
                                    reason.append("Troll application")```
#

this is the while loop

#

nvm the error was from something else but the loop still is not running

shy roost
#

what are some ways to make a embed look fancier?

wispy spade
#

if the reaction is 9️⃣, then i'd just break and not add it to the list

#

so that could be a reason

soft narwhal
#

how do i add aliases?

#

or should i make a whole new cmd

slate swan
shy roost
shy roost
slate swan
wispy spade
#

is reason empty?

#

what's reason?

#

i know it's a list but what are the contents?

#

if it's not running it likely means there's something in the list already

#

(assuming there's no other ifs or conditions that could cause it not to run)

slate swan
#

I have print on that too

thin kelp
#

What's the while statement

slate swan
#

...

shy roost
#

does anyone know the reference I can use to find the name of the server the bot is in?

slate swan
thin kelp
#

No

#

The

slate swan
#

while reason:

#

reason = [

#

]

wispy spade
#

so it's now while reason?

blazing coral
#

Is there a way I can restart my bot etc from discord

slate swan
#

yes.

blazing coral
#

Lol 😂 how would I go about doing that

quaint epoch
#

So, my bot just stopped, i tried to purge the entire channel using a command -

thin kelp
#

Bruv

blazing coral
#

There is so much there

#

I don’t know what to look at

thin kelp
quaint epoch
# thin kelp Bruv

i tried to do py await ctx.channel.purge(limit=9999999999999) but it had the same result

blazing coral
#

Just do a clear command

#

Like to clear a message

quaint epoch
blazing coral
#

And just run the number up to some outrageous number

blazing coral
#

That’s what I do

quaint epoch
#

alr

blazing coral
#

Works fine

#

But I’m sure there is a better way of doing it

sage otter
#

There is

quaint epoch
blazing coral
#

See

wispy spade
wispy spade
sage otter
#

Clone the channel and delete the old copy with all the messages in it

quaint epoch
#

instead of fetching all the messages and deleting them

wispy spade
quaint epoch
#

how would you do that with a bot?

sage otter
#

!d discord.TextChannel.clone

unkempt canyonBOT
#

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

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

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

New in version 1.1.
quaint epoch
#
channel.clone()```
blazing coral
#

!normally just do ! Clear then 10000000000000000

quaint epoch
#

oh you CAN do that, huh

sage otter
#

Yeah, clone it so all the perms copy over

blazing coral
#

And that clears the thing but what ever the clone thing will work

sage otter
#

I mean it would probably be faster and less work intensive for your bot as well.

#

Clone channel then delete the old one.

daring olive
#

english please, @spark sleet

slate swan
daring olive
#

👋 hi

slate swan
daring olive
#

pretty good :) you?

slate swan
#

thats good to hear,im goodpithink

#

welp i gtg do 205 more functions had a great talk with you

daring olive
#

haha gl!

slate swan
#

thank youpithink

undone wyvern
#

Wait I keep seeing you say you have to do 300 functions, but why?

slate swan
#

project im doing lol

#
    for channel_id in channel_list:
        channel = bot.get_channel(int(channel_id))
        embed = discord.Embed(title="> __Channel inactive__", color=0xFF0000)
        await asyncio.sleep(3)
        await channel.send(embed=embed)
#

doesn't work

#

channel = bot.get_channel(int(channel_id))

#

doesn't apprenlty get the channel rly

#

the channel object

#

bro

#

anime rly

#

your enemy

#

is here @slate swan

ebon island
#

What's the practical difference between message and ctx?

cloud dawn
ebon island
#

Got you 🙂 I will have to look at the docs later to understand better but appreciate that overview!

slate swan
#

how do I get channel object

#

using id of the channel

pliant gulch
#

Context is just message with a chance of being valid, that is valid meaning there is a command behind it

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

Ok

cloud dawn
slate swan
#

it needs to send it on every channel that I have listed

#

any1 know how to make a channel what says Bot Online when it comes on and when its gone off it says bot offline?

ebon island
#

Have it send a message to a channel?

slate swan
#

just help me aight?

#

cmon

quaint epoch
#

if i get roles like this, do i need to do role = await ctx.guild.get_role(role_id)?

slate swan
rich brook
slate swan
#

anyone know why??

quaint epoch
final iron
rich brook
final iron
slate swan
quaint epoch
#

is it possible to fetch a single role, bc i can only get_role not fetch_role using ctx.guild

rich brook
ebon island
#

Does commands.HelpCommand not pass client the same way commands.Cog does?

glacial kernel
#

How do I keep my bot online everytime?

sick birch
dire folio
#

i have this:

unranked = bot.get_channel(760103928393629716)
await unranked.send(embed=emb)

i get this error:

Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 299, in uhc
    await unranked.send(embed=emb)
AttributeError: 'NoneType' object has no attribute 'send'

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

Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/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: 'NoneType' object has no attribute 'send'
sick birch
#

get_role and fetch_role do the same thing, get_* functions return it form the cache, while fetch_* functions do an API call, hence the coro

slate swan
#

!.join

unkempt canyonBOT
#

Joining Iterables

If you want to display a list (or some other iterable), you can write:

colors = ['red', 'green', 'blue', 'yellow']
output = ""
separator = ", "
for color in colors:
    output += color + separator
print(output)
# Prints 'red, green, blue, yellow, '

However, the separator is still added to the last element, and it is relatively slow.

A better solution is to use str.join.

colors = ['red', 'green', 'blue', 'yellow']
separator = ", "
print(separator.join(colors))
# Prints 'red, green, blue, yellow'

An important thing to note is that you can only str.join strings. For a list of ints,
you must convert each element to a string before joining.

integers = [1, 3, 6, 10, 15]
print(", ".join(str(e) for e in integers))
# Prints '1, 3, 6, 10, 15'
slate swan
#

ah

ebon island
#

How do I get ctx from a get_destination messageable in my help function?

quaint epoch
quaint epoch
slate swan
#

nvmjust made it better

sick birch
quaint epoch
sick birch
#

Hmm

#

Oh right

final iron
quaint epoch
#

for me, client.fetch_role and ctx.guild.fetch_role don't exist

sick birch
#

Yeah oddly discord only lets you request ALL roles

quaint epoch
sick birch
#

you can fetch_roles

quaint epoch
sick birch
#

You can get_role() though

#

Does that not work for you?

final iron
quaint epoch
sick birch
#

Self hosting with, say, a raspberry pi isn't all that bad

quaint epoch
sick birch
#

Yes

#

And the electrical costs for a raspberry pi can rival VPS

quaint epoch
#

aw, i hope discord updates support for role fetching and disnake adds it

sick birch
#

Though of course it's not very powerful nor scalable and you'll have issues once your bot gets bigger but yes

sick birch
quaint epoch
#

anyway

#

gtg

sick birch
#

I suppose it's quite easy to fetch a single role though, just combine fetch_roles() with utils.get

final iron
quaint epoch
#

or not, is there a diff way to use utils.get bc i've never used it before

#

do you have to await discord.utils.get or not?

wanton veldt
#

Hi why i get this error

Code

    @commands.command(pass_context=True) 
    async def color(self, ctx): 
        await ctx.send("#{:06x}".format(random.randint(0, 0xFFFFFF)))
#

the command is working but i still get this error

slender perch
#

lets say i wanted to make a python discord bot, but i wanted to be able to change settings through a website, how would i make that?

#

or does someone have a git source for something like that

#

or a video tut

shrewd pasture
#

can someone please send me an example command using buttons for discord.py
I have never used them before but want to start now

slate swan
shrewd pasture
#

thats a hex code

wanton veldt
#

generate a random hex code

slate swan
#

and i used redis pub/sub for sending the message from the server to the bot

wanton veldt
slender perch
#

ah alright thank you, is there some sort of documentation or video you would reccomend to look into first?

shrewd pasture
#

did you code that or find that online

slender perch
#

yea

wanton veldt
#

and i make a command with that

slate swan
#

i mean well it's quite simple. you can set up a redis server on your machine and go from there

shrewd pasture
#

interesting

#

well if its working i suggest you simply ignore it

slate swan
#

there are many many redis libraries, even for python. a simple google search would lead you to those options.

shrewd pasture
#

well

wanton veldt
slate swan
#

i wish i didn't have to turn you away to google but i programmed my bot and server in javascript

#

not sure how much that would help

shrewd pasture
slate swan
#

i'm happy to send code snippets however, if that will help you (again, it's in javascript)

shrewd pasture
#

use a hex color api

wanton veldt
fresh orchid
# shrewd pasture can someone please send me an example command using buttons for discord.py I ha...

This is the Ultimate Python Guide on Buttons with Discord.py or Pycord. In this video, I talk about how to create buttons in discord.py or pycord and how to respond to button clicks along with everything about Views. After watching this you'll know everything about Buttons and Views in discord.py or pycord.

This video might also apply to other...

▶ Play video
shrewd pasture
slate swan
fresh orchid
#

Oh you wanted an example

Sorry then

But I think this should help too

shrewd pasture
#

yeah no worries

shrewd pasture
#

isnt pycord simply a wrapper?

fresh orchid
shrewd pasture
#

so did they edit anything massive?

fresh orchid
#

Not really

shrewd pasture
#

to where my discord.py code would be massively effected?

fresh orchid
shrewd pasture
#

i see

shrewd pasture
slate swan
shrewd pasture
#

repl isnt great for hosting bots unless its only used to test

slate swan
#

the python repl

shrewd pasture
#

?

fresh orchid
#

Read pinned messages

#

There is a message with reasons Why repl isnt Good for hosting

slate swan
#

jesus yall

fresh orchid
#

Ok

slate swan
#

you don't have a clue what i'm talking about

shrewd pasture
#

what?

fresh orchid
#

Yes

shrewd pasture
#

i think we have a very big clue

slate swan
#

? just cause you come from discord.py and people have told you to stay away from repl.it doesn't mean you know what i'm talking about

shrewd pasture
#

what are you on about

slate swan
#

try typing python3 in a terminal

#

geez lol

#

that thing is called a python repl

shrewd pasture
#

REPL stands for Read Evaluate Print Loop, and is the name given to the interactive MicroPython prompt that is accessible on the Pycom devices. Using the REPL is by far the easiest way to test out Python code and run commands. You can use the REPL in addition to writing scripts in main.py .

#

that what youre talking ab??

slate swan
#

take a guess

wanton veldt
#

its possible after the hex color is generated to send a picture with the generated hex color?

    @commands.command(pass_context=True) 
    async def color(self, ctx): 
        await ctx.send("#{:06x}".format(random.randint(0, 0xFFFFFF)))
        ``` code
slate swan
#

try using pillow

wanton veldt
#

pillow?

slate swan
#

haven't used it personally so ask around for help

slate swan
#

actually i think its PIL

wanton veldt
#
slate swan
#

ah that

#

heard it's a royal pain in the ass to download

#

any1 know how to fix SyntaxError: 'await' outside function

#

hey guys

ebon island
#

Is there a good way to iterate through the keys and subsequently values in a list of dicts?

#

I will post this in general actually since it's not discord related

pliant gulch
#

You have the dict.values() method, and you have the dicts

#

So you can just do a list comp, E.g [dict.values() for dict in list_of_dicts]

#

Then you would iterate the newly created list

#

oh wait I read you wrong, you want the keys and the values

#

Thought you only said values

slate swan
#

i am trying use cogs, and its like thispy class Example... async def ex1(): ... @commands.command() async def ping(): await ex1() and i got error ex1 is not defined why?

#

SyntaxError: 'await' outside function for i in await ctx.guild.invites():

pliant gulch
#

You must access ex1 through the instance of your Cog, likewise this means all your methods need to have the first argument self which is the instance

#

Cogs are classes, thus follow the same rules as classes

#

Unless the method is a staticmethod or a classmethod

slate swan
grand shell
#

hey guys im trying to host my discord bot. my bot uses json and os. do i need to state this in the requirements?

slate swan
#

only stuff that you intalled via a package manager like pip should be added to the dependencies

grand shell
#

ah i see

slate swan
#

if you can, you should try to find a way to have your package manager automatically add the dependency for you

pliant gulch
#

Poetry is very good for stuff like that

slate swan
#

@pliant gulch should functions also have self as first arg?

pliant gulch
slate swan
#

any1 know how to fix

File "C:\Users\liamd\Documents\MainGen\MainGen\main.py", line 355
totalInvites = 0
^
IndentationError: expected an indented block after function definition on line 354

#

*you're

#

in your status

#

so you're the clown

unkempt canyonBOT
#

Indentation

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

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

Example

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

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

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

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

blazing lynx
#

i forgot. how do i make a on_member_join? im like really confused

heavy folio
#

!d discord.on_member_join

unkempt canyonBOT
#

discord.on_member_join(member)``````py

discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") leaves or joins a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").

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

Does anyone know how can I hide error discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction from console?

blazing lynx
#

Ignoring exception in on_member_join Traceback (most recent call last): File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event await coro(*args, **kwargs) File "main.py", line 16, in on_member_join embed.set_thumbnail('https://cdn.discordapp.com/avatars/836727600067117096/e597053a98959e69d77cc5d1762f56e4.webp?size=4096') TypeError: set_thumbnail() takes 1 positional argument but 2 were given

patent lark
#

set_thumbnail takes a url kwarg in which you didn’t pass

#

embed.set_thumbnail(url="your link")

#

@blazing lynx

blazing lynx
#

sup snow

#

i fixed it btw

ebon island
#

I'm a little bit confused, for some reason this command works fine when receiving an integer as input but when inputting something like letters it does nothing rather than getting a ValueError as expected:

@commands.command(name='turn_time', aliases=['turntime', 'time', 'turn'], help='sets server turn time')
    async def turn_time(self, ctx, turn_time=40):
        try:
            time_per_turn = int(turn_time)
blazing lynx
#

hey @patent lark how can i display the members name that joined inside the embed that it sends?

blazing lynx
#

thanks!

ebon island
#

I have a try except else for the method but it only ever hits the elf, when it receives a bad input it doesn't even enter the try block

desert heart
#

You can use function annotations to have arguments automatically converted to different types

#

I suggest you use that instead of manually converting, especially for trivial types like ints which are supported out of the box

#

turn_time: int = 40

ebon island
#

I was using the type casting so that it would trip a value error if a bad type was input eg string

#

and then I could handle the value error and send a message in response

desert heart
#

Discord.py will raise conversion errors and you can register an error handler if you want to output the error in a different way

ebon island
#

Could you give an example of a simple method and error handling for bad conversion?

ebon island
#

Is there any way to pass the args into the error?

#

My old error handler had the args they put in the message

#

so here is what I have at present

#
    @commands.command(name='turn_time', aliases=['turntime', 'time', 'turn'], help='sets server turn time')
    async def turn_time(self, ctx, turn_time: int = 40):
        try:
            curr_server = await self.get_local_server_object(ctx)
            channel_to_be_sent = ctx.channel
            time_per_turn = int(turn_time)
            if time_per_turn < 10:
                print('less tahn 10')
                message_to_be_sent = '**Turn Time too low! 10 seconds is the minimum value.**'
                await self.message_sender(channel_to_be_sent, message_to_be_sent, 1)
            elif time_per_turn > 120:
                print('greater than 120')
                message_to_be_sent = '**Turn time too high! 120 (2 minutes) is the maximum value.**'
                await self.message_sender(channel_to_be_sent, message_to_be_sent, 1)
            elif time_per_turn < curr_server.word_count:
                print('time per turn too low')
                message_to_be_sent = '**Turn time too low! Maximum word rate cannot exceed 1 per second.**'
                await self.message_sender(channel_to_be_sent, message_to_be_sent, 1)
            else:
                print('normal')
                curr_server.turn_time = time_per_turn
                message_to_be_sent = f'Successfully changed server turn time to **{time_per_turn}**'
                await self.message_sender(channel_to_be_sent, message_to_be_sent, 1)


    @turn_time.error
    async def turn_time_error(self, ctx, error):
        channel_to_be_sent = ctx.channel
        if isinstance(error, commands.ConversionError):
            message_to_be_sent = f'**{turn_time}** is not a valid input - please enter a valid integer'
            await self.message_sender(channel_to_be_sent, message_to_be_sent, 1)
#

but {turn_time} would not be a resolved reference since turn_time_error has no access to it

desert heart
#

I believe the default message generated by the exception already includes the original input

#

But you could get it from ctx.args or ctx.kwargs if you really wanted to customise it

#

I suggest you just try to use str(error) as the message because chances are you'll find it sufficient

ebon island
#

Cool, it is working now but the ctx.args didn't work as expected

#
        if isinstance(error, commands.BadArgument):
            message_to_be_sent = f'**{ctx.args}** is not a valid input - please enter a valid integer'
            await self.message_sender(channel_to_be_sent, message_to_be_sent, 1)

returned

[<cogs.barbot.BarBot object at 0x000001B4727DE470>, <discord.ext.commands.context.Context object at 0x000001B4729778E0>] is not a valid input - please enter a valid integer

#

so obviously it is returning a list with two objects

desert heart
#

I don't think it will work anyway cause it can't populate the args list due to converter failing

pliant gulch
#

Maybe ctx.kwargs then? But another way you could do it is; Just raise a custom error which extends Exception to take in your argument turn_time

ebon island
#

Where would I go about trying that Andy?

#

My old method was using an Exception converting the type of the string input

pliant gulch
#

You would start off by making a new class which inherits Exception, change the __init__ method to take another arg that being your turn_time. Then construct the super class, set the arg then raise it

#

You might not need to construct the super class but I would do so anyways

#

Then just isinstance to check if this error captured is your custom error, if it is access the custom attribute

desert heart
#

I disagree. If you really are unsatisified with the default message in BadArgument, then either

  1. Accept the arg as a string and manually convert and handle the error within your command, as you were originally doing
  2. Define a custom converter that will raise a custom exception which has the argument name as an attribute. This will give you a generic way to handle the error I suppose.
ebon island
#

I will give it a try, I will be testing things out throughout the night, is there any way to have a cog wide error Handler like how you can do Cog check to check 4 permissions?

desert heart
#

The default message is "Converting to int failed for parameter turn_time".

ebon island
#

Yeah, that is a little robotic as a response, my target audience is not exactly technical so it would be better to have something that avoid possible confusion so custom handling would be preferred

desert heart
pliant gulch
desert heart
#

Not sure. I thought they wanted the argument name

slate swan
#

@slate swan im done wih the 1k functions project happy,ill push it to pypi later or tomorrow 🙄

ebon island
#

No, I want the argument that they entered itself

pliant gulch
#

Ok yea so the value

ebon island
#

How would I access that from the given ctx? I think there was something like ctx.message iirc so I will test that

pliant gulch
#

That is true you could do that

#

You need to make sure you trim off the prefix and the command name itself

desert heart
#

But then you manually have to parse the message and it isn't necessarily trivial

pliant gulch
#

If you just get the length of that then just string slice

#

Then you get the value

desert heart
#

Unfortunately discord.py doesn't have the provisions for what you're trying to do. You'd either have to just do it the manual way, which works but is not very "scalable" (imagine doing that for 5 arguments, or for 20 commands), or you'd have to write a significant amount of custom code to get a better converter and error handling system

pliant gulch
desert heart
#

But how would you get ALL converters to raise that error?

pliant gulch
#

You'd have to make a custom converter like you said to raise the error

#

You could also just manually raise it

desert heart
#

But then you need a custom converter for every type you need

pliant gulch
#

Just make a generic converter

#

MaybeRaise[Type]

#

E.g foo: MaybeRaise[int]

desert heart
#

Good point. Unfortunately it still makes you work for it.

pliant gulch
desert heart
#

The sad thing is that it would've been trivial to include the parameter name and value as attributes on the exception

pliant gulch
#

BadArgument has no reason not to have properties for the argument raised

ebon island
#

That's absurd haha, yeah, the ctx.message from the error doesn't have the actual message

#

I figured it out anyway though 🙂

drifting arrow
#

Getting this error and I have no idea why

Traceback (most recent call last):
  File "c:\Users\MyName\Desktop\dubsbot\Discordbot.py", line 62, in <module>
    bot.load_extension(f'cogs.{filename[:-3]}')
  File "C:\Users\MyName\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\bot.py", line 730, in load_extension
    raise errors.ExtensionNotFound(name)
discord.ext.commands.errors.ExtensionNotFound: Extension 'cogs.adminlogs' could not be loaded.

I deleted adminlogs from my files since it was no longer necessary and even removed any mention to it. Why is it still being called and why is there an error?

#

Figured out the issue. I was going to the wrong path. ;D

potent spear
#

I'd also like to see the relevant code, so the for loop

drifting arrow
#
#Location of the COG files.
for filename in os.listdir('c:/Users/MyName/Desktop/dubsbot/cogs'):
    if filename.endswith('.py'):
            bot.load_extension(f'cogs.{filename[:-3]}')
#

@potent spear

#

I got an issue now that when I sent the code to my friend it doesnt work ;-;

potent spear
drifting arrow
#

I mean, he did change the filepath.

#

he's slightly smarter than me

potent spear
#

can you print this for me in the file pls

#
from pathlib import Path
print(Path(__file__))```
manic wing
#

@slate swan

#

where’s my pull request hm?

slate swan
visual island
#

@slate swan you finally created a repo?

slate swan
#

but ill do it tomorrow

#

im going to publish it to pypi and github tomorrow

slate swan
solid falcon
#

How can I incorporate asyncio into my bot so that when it makes requests it can respond to other commands before the request has finished?

solid falcon
#

the commands look like

@bot.command()
async def request():
  make_request_to_website()
#

but when it does that it can't also respond to the ping command

#

until it's finished with its request

torn sail
#

I think if you use aiohttp it won’t happen

slate swan
#

if you're using requests library or something , use aiohttp instead

slate swan
solid falcon
#

I'm not, it's actually using the openai library

solid falcon
#

since it's using that library it has to process whatever data is sent before it can be returned and while it's waiting for a response nothing else can be run

slate swan
solid falcon
red sundial
#

so then the command works simultaneously

#

across all the servers that have your bot

slate swan
solid falcon
#

I'll check that out, thanks!

pliant gulch
#

You could also just run in executor if that doesn't work

solid falcon
#

how would I do that?

pliant gulch
#

This should have examples

solid falcon
#

great great, thank you too

#

would either of these solutions be preferrable over the other for any reason?

slate swan
#

if the library works , its preferable
else run_in_executor exists

pliant gulch
#

Oh kek didn't realize you said run_in_executor alr

solid falcon
#

oh I thought those were different somehow

surreal sierra
#

Hey, it's very late and Im just very confused why Im getting this problem. I just copy/paste a code from another bot I have to another one, I dont see any reason why it shouldnt work and something weird is that the import discord is like greyed like Im not using anything from that package and Im getting an error saying this AttributeError: module 'discord.ext.commands.bot' has no attribute 'event'. I have probably just missed something small but I really cant think of anything rn

slate swan
#

you defined bot as commands.bot , which should be commands.Bot

#

discord.ext.commands.bot -> discord.ext.commands.Bot

red sundial
#

@surreal sierra

surreal sierra
#

yea........... thx, really dumb of me but thanks XD

slate swan
#

you're not the only one

slate swan
dreamy sluice
#

Is there a way I can execute some code before the bot goes to fulfil the command?
(For more context, I want to make a blacklist command, and I want the bot to check if the author is blacklisted before it executes the command)

manic wing
#

uh

#

well i wrote a really long paragraph before but idk how helpful this will be to you

#

---> Adding a check so only one person can run a command

This can be done in many ways
1) an if statement inside the functionpy @bot.command() async def command(ctx): if ctx.author.id != user_id: return
2) a dedicated check

@bot.check
async def user_check(ctx):
  if ctx.author.id != user_id: return False
  return True```
  **3)** a non-specific `check`
```py
@bot.command(hidden=True)
async def command(ctx):
  """whateve you want"""

@bot.check
async def user_check(ctx):
  if ctx.author.id != user_id and ctx.command.hidden: return False
  return True```
**4)** `owner` only, if this suits you
```py
bot = commands.Bot(owner_ids=[...], ...)

@bot.command()
@commands.is_owner()
async def command(ctx):
  """whatever you want"""```

​
#

!d discord.ext.commands.check || you're looking for a check

unkempt canyonBOT
#

@discord.ext.commands.check(predicate)```
A decorator that adds a check to the [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or its subclasses. These checks could be accessed via [`Command.checks`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command.checks "discord.ext.commands.Command.checks").

These checks should be predicates that take in a single parameter taking a [`Context`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context"). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure") exception is raised and sent to the [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") event.

If an exception should be thrown in the predicate then it should be a subclass of [`CommandError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError"). Any exception not subclassed from it will be propagated while those subclassed will be sent to [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error").
manic wing
#

so like method 2 but py if ctx.author.id in blacklisted_list: return False return True

#

i have a bunch of material that ive written just lying around

dreamy sluice
#

I see.

#

I wanted to make a dedicated check, thanks.

manic wing
#

awesome

dreamy sluice
#

but what does hidden=True do btw?

manic wing
#

means a command is hidden and most automatic help commands wont show them

dreamy sluice
#

Oh I see.

#

Thanks

manic wing
#

🙇

boreal ravine
#

nice

slate swan
#

Is helpful

manic wing
#

cheers :D

manic wing
#

wanna see some other crap?

boreal ravine
#

no

dreamy sluice
slate swan
#

Why not

slate swan
manic wing
#

---> Sending a quote on a timer

you're going to want to have 3 things:
a) a list of channel ids
b) a database to store the channel ids - it can just be a json file, but you probably want the bot to remember to send the quotes, even if you restart the bot.
c) a discord.ext.tasks.loop.
In this example I am going to show how you may want to do it, but I will not show it linked to a database. You can do that part yourself. My github project where I have done this is https://github.com/caedenph/jesterbot.

@tasks.loop()
async def quote(): 
  ### Get channel_ids from database here ###

  for chan_id in channel_ids:
      channel = bot.get_channel(chan_id)
      await channel.send(quote)

in this example there is channel_ids, which holds the channel ids, and tasks.loop which is discord.ext.tasks.loop

You can also link this to a command,

@bot.command()
async def setup_quote():
  #apend to database```
slate swan
manic wing
#

idk if this ones real helpful

#

---> Kick command

@bot.command()
async def kick(ctx, member:discord.Member):
  await member.kick(reason='get kicked')
  await ctx.send(f'{member} got kicked')

: ctx is a default argument. ctx -> discord.Context. ctx.send sends it to the channel it was invoked in.
: member is a member, like @manic wing . This is an instance of discord.Member. You can get information from discord.Member like .name, .discriminator (the numbers after the #), .created_at (when you created the account)
: by TypeHinting member to discord.Member, it means you can do stuff like ?kick @Caeden#7205

​​​​

boreal ravine
#

bruh.

manic wing
#

hm?

slate swan
#

You should make a GitHub repo with all these things lmao

slate swan
manic wing
#

i have a budget of only one python repo :(

manic wing
slate swan
slate swan
slate swan
#

else , just deal with the error with a handler

slate swan
#

ic

#

no a arg for the reason kwarg?

slate swan
slate swan
#

understandable

slate swan
ocean leaf
#

My commands are working slow. I tried to comment half of the imports and it works faster. Is there any way to make the command called by the user automatically import it's required import without importing everything at once even if it doesn't need it?

drifting arrow
#

I am trying to upload my bot to a hosting service.
The module is found in:
.local/lib/python3.8/site-packages/discord/

Do I need to change the 'import' in my code?

slate swan
ocean leaf
#

I have multiple commands in 1 cog btw (like all moderation commands in a cog called "moderation" and all that)

slate swan
drifting arrow
#

I'll try regular discord

ocean leaf
#

to make the command call it's required import

boreal ravine
ocean leaf
#

instead of importing everything at once

slate swan
drifting arrow
boreal ravine
drifting arrow
patent lark
loud junco
#
@bot.command(aliases = ['cooldown'])
@commands.cooldown(1, 1, commands.BucketType.user)
async def cd(ctx):
  names = ['hunt', 'mine', 'boss','daily']
  res = ''
  for name in names:
    name = bot.get_command(name)
    seccd = round(name.get_cooldown_retry_after(ctx))
    mincd = 0
    hrcd = 0
    rseccd = 0
    rmincd = 0

    if seccd > 59:
      rseccd = seccd % 60
      mincd = (seccd - rseccd) / 60

    elif mincd > 59:
      rmincd = mincd % 60
      hrcd = (mincd - rmincd) / 60

    if rseccd == 0 and rmincd == 0 and hrcd == 0:
      res += f':white_check_mark: {name}\n' 
    else:
      res += f':spinning_clock: {name}: **{hrcd}h {rmincd}m {rseccd}s**\n'

  embed = discord.Embed(
    description= res,
    color = discord.Color.blue())
  embed.set_author(name= f"{ctx.author.display_name}'s cooldown", 
  icon_url = ctx.author.avatar_url)
  await ctx.send(embed=embed)
#

the logic isnt working ;-;

#

the operator part

drifting arrow
slate swan
# slate swan and?

why would you show a command that can be easily made better as an example

slate swan
loud junco
#

u wont wan pepo to spam rpm cd to break ur bot

slate swan
slate swan
boreal ravine
loud junco
#
  names = ['hunt', 'mine', 'boss','daily']
  res = ''
  for name in names:
    name = bot.get_command(name)
    seccd = round(name.get_cooldown_retry_after(ctx))
    mincd = 0
    hrcd = 0
    rseccd = 0
    rmincd = 0

    if seccd > 59:
      rseccd = seccd % 60
      mincd = (seccd - rseccd) / 60

    elif mincd > 59:
      rmincd = mincd % 60
      hrcd = (mincd - rmincd) / 60

    if rseccd == 0 and rmincd == 0 and hrcd == 0:
      res += f':white_check_mark: {name}\n' 
    else:
      res += f':spinning_clock: {name}: **{hrcd}h {rmincd}m {rseccd}s**\n'
#

help ;-;

drifting arrow
#

Requirements file```txt
discord.py==1.7.3
requests==2.25.1
validators==0.18.2
discord==1.7.3

Import list on bot.py```python
import discord, asyncio, os
from discord.ext import commands
import discord.utils
#

@slate swan

loud junco
#

seccd is in seconds
but some cd has 10k+ sec so im trying to change it to mins and hr

patent lark
boreal ravine
slate swan
boreal ravine
visual island
ocean leaf
drifting arrow
loud junco
#

:/

drifting arrow
boreal ravine
drifting arrow
#

Ty sarthak. I'd kiss you but my doctor says it's a bad idea.

patent lark
#

unused imports have a trivial impact on the compiler, but there are no imports in the byte code or at runtime. unused objects can be optimised.

shrewd pasture
#

i was hoping someone can help my with a blackjack command for my bot. I am trying to add buttons and make them work forever like so:

@bot.command():
async def blackjack(ctx):
  msg = await ctx.send("Hit or Stand")  
  
  #Adds buttons

  #checks which button is pressed

  if button_pressed = "Hit":
    #Do math then continue with the code if its not over 21
  else:
    #i can code the outcome stuff ofc

All i need help with is the button setup please help me out thanks!

drifting arrow
shrewd pasture
shrewd pasture
#

just a placement i put

slate swan
shrewd pasture
#

to show what im trying to get

loud junco
#

:/

boreal ravine
shrewd pasture
#

i have no clue how to use buttons

boreal ravine
#

he doesnt have it anywhere in his code

shrewd pasture
boreal ravine
#

thats why i asked

loud junco
#

#Adds buttons

shrewd pasture
#

its just a place holder to show

loud junco
#

LOL

slate swan
shrewd pasture
shrewd pasture
#

the pycord discord is made with a bunch wannabes and are stupid

#

they shouldnt even be verified discord

loud junco
#
    seccd = round(name.get_cooldown_retry_after(ctx))
    mincd = 0
    hrcd = 0
    rseccd = 0
    rmincd = 0

    if seccd > 59:
      rseccd = seccd % 60
      mincd = (seccd - rseccd) / 60

    elif mincd > 59:
      rmincd = mincd % 60
      hrcd = (mincd - rmincd) / 60

    if rseccd == 0 and rmincd == 0 and hrcd == 0:
      res += f':white_check_mark: {name}\n' 
    else:
      res += f':spinning_clock: {name}: **{hrcd}h {rmincd}m {rseccd}s**\n'
```help me
#

whats wrong here

#

its not an error
just my brain logic having error

loud junco
#

why is everyone gone within a sec

#

=.=

drifting arrow
#

Im reading your code

loud junco
#

oo ok

drifting arrow
#

you dont have a seccd <59 and set your first if to >= 59

#

What happens if seccd is <59?

boreal ravine
loud junco
#

:/

shrewd pasture
#

and thank you

boreal ravine
patent lark
#

logic doesn’t make sense, but okay.

loud junco
#

:/