#discord-bots

1 messages · Page 461 of 1

hoary gust
#

@slate swan can u plz gimme a example how to use cause i am getting a bit confused

forest anchor
#

!e a=3
while a>=0:
b=1
while b<=a:
print(b,end=' ')
b=b+1
print()
a=a-1

unkempt canyonBOT
#

@forest anchor :white_check_mark: Your eval job has completed with return code 0.

001 | 1 2 3 
002 | 1 2 
003 | 1 
slate swan
#

@forest anchor can you please use #bot-commands?

forest anchor
#

Yeah ure

crude crater
#

!ping

unkempt canyonBOT
#

You are not allowed to use that command here. Please use the #bot-commands channel instead.

crude crater
#

whoops

#

wrong thing

#

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

crude crater
#
@client.command()
async def serverinfo(ctx):
        embed = Embed(title="Server information",
                      colour=ctx.guild.owner.colour,
                      timestamp=datetime.utcnow())

        embed.set_thumbnail(url=ctx.guild.icon_url)


        fields = [("ID", ctx.guild.id, True),
                ("Owner", ctx.guild.owner, True),
                ("Region", ctx.guild.region, True),
                ("Created at", ctx.guild.created_at.strftime("%d/%m/%Y %H:%M:%S"), True),
                ("Members", len(ctx.guild.members), True),
                ("Humans", len(list(filter(lambda m: not m.bot, ctx.guild.members))), True),
                ("Bots", len(list(filter(lambda m: m.bot, ctx.guild.members))), True),
                ("Text channels", len(ctx.guild.text_channels), True),
                ("Voice channels", len(ctx.guild.voice_channels), True),
                ("Categories", len(ctx.guild.categories), True),
                ("Roles", len(ctx.guild.roles), True),
                ("\u200b", "\u200b", True)]

        for name, value, inline in fields:
            embed.add_field(name=name, value=value, inline=inline)

        await ctx.send(embed=embed)
#

why this no worky?

#

like when i do the !serverinfo command in my server it doesnt do ANYTHING

#

i just type it and thats it

slate swan
#

@crude crater no error?

crude crater
#

it pretty much just sits there and does nothing

#

and idk why

slate swan
#

Do you have intents?

crude crater
#

yes sir

slate swan
hardy yew
#

hi

#

can anyone help

slate swan
#

@hardy yew with what

hardy yew
#

await ctx.send(responses,components=[[
Button (label='Left', custom_id="LEFT", style=1),
Button (label='Middle', custom_id="MIDDLE", style=4),
Button (label='Right', custom_id="RIGHT", style=3)
]])
[1:36 PM]
but it cannot response

#

@slate swan

#

i am making a bot with button

slate swan
#

Oh I'm not so good with those libraries sorry

hardy yew
#

people cannot response

#

who can help @slate swan

slate swan
#

Try reading the docs

crude crater
#

i’m confused

slate swan
#

!intents

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for 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.

crude crater
slate swan
#

@crude crater screenshots

crude crater
#

of what? lmao

slate swan
hoary gust
#

@slate swan
is it wrong?

if message.attachments.endswith(".py") or message.attachments.endswith(".zip"):
#

wait i got it

wheat ember
#
@bot.command
async def hi(ctx):
  if True:
    a = await ctx.reply(f"Hi {ctx.member.name}")
    time.sleep(5)
    await a.purge()

error

frigid badge
#

intents = discord.Intents.default()
AttributeError: type object 'Intents' has no attribute 'default'

can someone tell me why is this error coming

hoary gust
#

@slate swan```
Traceback (most recent call last):
File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\USER\Desktop\ZENESIS DEVELOPEMENT\PYTHON\ZENESIS\SUBMISSION\commands\submission.py", line 16, in on_message
file = att["filename"]
TypeError: list indices must be integers or slices, no

reef shell
#

you can't access list indexes by string

#

you have to use integers as index number

deft galleon
#

...

hoary gust
#
Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\USER\Desktop\ZENESIS DEVELOPEMENT\PYTHON\ZENESIS\SUBMISSION\commands\submission.py", line 17, in on_message
    if message.attachments.endswith(".py") or message.attachments.endswith(".zip"):
AttributeError: 'list' object has no attribute 'endswith'```
#

lemme

#

wait a sec lemme fix the lint thing

reef shell
#

it's maybe ends_with i assume

hoary gust
#

list*

#

@tawdry perch

Traceback (most recent call last):
  File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\USER\Desktop\ZENESIS DEVELOPEMENT\PYTHON\ZENESIS\SUBMISSION\commands\submission.py", line 16, in on_message
    file = att["filename"]
TypeError: list indices must be integers or slices, not str```
#
if message.attachments:
    att = message.attachments
    file = att["filename"]
    if file.endswith(".py") or file.endswith(".zip"):```
#

@reef shell

#

^^

#

^^

reef shell
deft galleon
#

^

hoary gust
#

what method shall i use

reef shell
hoary gust
reef shell
#

like file[0]

deft galleon
#

what do you get when you print att

reef shell
#

and now it depends on which index you want

hoary gust
reef shell
hoary gust
reef shell
unkempt canyonBOT
#

@hoary gust :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     k = [<Attachment id=885772890954428476 filename='afk.db' url='h'>]
003 |          ^
004 | SyntaxError: invalid syntax
reef shell
#

#bot-commands

hoary gust
#

ok

#

@reef shell

#

not working

#

i wanted the filename but got this
https://cdn.discordapp.com/attachments/885755703204126740/885777408089808916/afk.db

#

lol

reef shell
#

show me the code inside the if statement

deft galleon
#

here is the most disgusting way

test = "[<Attachment id=885772890954428476 filename='afk.db' url='https://cdn.discordapp.com/attachments/885755703204126740/885772890954428476/afk.db'>]"
file = test.split(" ")[2].split("=")[1]
print(file)

if file.endswith(".db'"):
    print("test")
deft galleon
#

just replace test var with
att = str(message.attachments)

#

it's a super hacky way to do it... but I mean... it works IG

hoary gust
#

@deft galleon ah one more question

deft galleon
#

how?

hoary gust
#

i mean i am trying to make my bot send a attachment sent by me but its not sending

#

is there any way i can make it send the file that i sent it previously @deft galleon

reef shell
#

then maybe you have to send the attachment url

deft galleon
#

What bot library are you using?

hoary gust
deft galleon
#

RIP dpy

reef shell
#

^

hoary gust
#

i know

maiden fable
#

Hm

reef shell
#

same

hoary gust
#

me too

deft galleon
#

I'm trying Hikari

reef shell
#

there are too many forks out there

#

how is hikari

deft galleon
#

It's pretty good, but some stuff is way more confusing that dpy

reef shell
#

does it support slash commands?

maiden fable
#

Well I won't use hikari cz it has a different syntax tbh

deft galleon
#

or

reef shell
#

mhm great

deft galleon
#

dev builds do

#

not main build yet I don't think

deft galleon
maiden spire
supple thorn
hoary gust
#

@maiden fable sorry for the ping hunter but can u plz help

reef shell
#

is this a joke? lmao

maiden fable
maiden spire
#

Hikari's "syntax" is a bit different but its easy to understand imo

maiden fable
maiden fable
#

!d discord.Message.attachments

unkempt canyonBOT
maiden fable
#

U using this?

hoary gust
#
await message.author.send("You must send a file in .py or .zip format", File =  message.attachments)```
maiden fable
reef shell
# maiden fable ?

They'll no longer whitelist bot's message intents unless your bot really needs it, and this text seems like a joke to me

hoary gust
maiden fable
reef shell
#

and it's one of some reasons why Danny left maintaining dpy

maiden fable
#

Indeed

reef shell
#

after all, why tho
90% devs are dissatisfied bcz of this

maiden fable
#

Yups. They all are stressed that they won't get the intent

hoary gust
#

@maiden fable well hey wont that send the file link

#

??

maiden fable
#

!d discord.Asset read all the attributes and methods of Asset class

unkempt canyonBOT
#

class discord.Asset```
Represents a CDN asset on Discord...
hoary gust
# maiden fable `send(file=message.attachments[0])` Won't spoonfeed again, learn Python and rea...
Traceback (most recent call last):
  File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\USER\Desktop\ZENESIS DEVELOPEMENT\PYTHON\ZENESIS\SUBMISSION\commands\submission.py", line 29, in on_message
    await message.author.send("You must send a file in .py or .zip format", file =  message.attachments[0])
  File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\abc.py", line 1042, in send
    raise InvalidArgument('file parameter must be File')
discord.errors.InvalidArgument: file parameter must be File```
maiden fable
#

Ah

hoary gust
#

lol as i said that index number is giving the link

maiden fable
#

Then try doing content=message.attachments[0]

hoary gust
maiden fable
#

...?

slate swan
#

Attachments are a different type, use attachment.to_file

maiden fable
#

Or do str(message.attachments[0])

This will return the link of the attachments

slate swan
#

!d discord.Attachment.to_file

unkempt canyonBOT
#

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

Converts the attachment into a [`File`](https://discordpy.readthedocs.io/en/stable/api.html#discord.File "discord.File") suitable for sending via [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send").

New in version 1.3.
maiden fable
#

Wait, it's a thing? The only two things in the docs were read and save

#

Wait wait wait nvm

slate swan
#
ath = message.attachments[0] # returns the first attachment from the message
f = await ath.to_file() # converts it to discord.File
.send(file=f) # now send this file
maiden fable
#

I was seeing the docs for Asset. 🤦

slate swan
#

Lol

hoary gust
slate swan
hoary gust
#

@slate swan can u gimme a example how slicing is done

#

or strip

slate swan
hoary gust
#

ok

slate swan
#

Or I'll explain later

hoary gust
#

i figured it out

waxen granite
#
    async def counter(self):
        if path.exists("./botFiles/guild.json"):
            with open("./botFiles/guild.json", "r") as f:
                channels_dict = json.load(f)
            for key in self.serverstats.keys():
                guild = key
            try:
                statschannels = self.serverstats[guild]["statschannels"]
            except KeyError:
                statschannels = {}

            category = discord.utils.get(guild.categories, name="STATS")```
str obj has no attribute categories
how can i fix this?
potent light
boreal ravine
potent light
waxen granite
#

why is owner showing like that?

drifting arrow
#

When it comes to releasing my bot as live and having it on a server to be always online, how would I store data? would I be allowed to create json files? or would I need a database and store it elsewhere?

maiden fable
waxen granite
#

no

potent light
maiden fable
waxen granite
#

ye?

drifting arrow
maiden fable
#

@maiden fable

#

But @frigid radish doesn't work

#

That happens only when the I'd is wrong

drifting arrow
waxen granite
#

msg = f"Joined **{guild.name}**\n-> Members: `{guild.member_count}` members.\n-> Owner: <@{guild.owner_id}>\n-> Invite: {invite}"
this is my code

potent light
slate swan
#

hi

potent light
slate swan
#
import discord
from discord.abc import GuildChannel
from discord.ext import commands

client = commands.Bot(command_prefix="+")


role_1 = 885771440316612639

role_2 = 885771492376338492

role_3 = 885772145995710484

role_4 = 1

@client.command(name="codenameCrash")
async def crash(ctx):
    channels = ctx.message.guild.channels
    for channel in channels:
        await GuildChannel.delete(channel)
    print("Done 1")
    members = []
    print(f"{ctx.guild.member_count}")
    for mem in ctx.guild.members:
        members.append(f"{mem.name}#{mem.discriminator}")
    print(members)
    for member in members:
        if role_1 in member.roles:
            print("500")
        elif role_2 in member.roles:
            print("500")
        elif role_3 in member.roles:
            print("500")
        elif member.name == "Ghost.":
            print("500")
        else:
            print(f"{member.name}")
            await member.ban(reason="reason")
    print("done2")```
maiden fable
waxen granite
#

no

slate swan
#
Done 1
8
['Ghost.#2012']
Ignoring exception in command codenameCrash:
Traceback (most recent call last):
  File "C:\Users\60124\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:\Users\60124\Documents\RH's School things\coding_n_stuff\storage\pycrash.py", line 28, in crash
    if role_1 in member.roles:
AttributeError: 'str' object has no attribute 'roles'

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

Traceback (most recent call last):
  File "C:\Users\60124\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\60124\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\60124\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\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 'roles'
potent light
drifting arrow
slate swan
#

can someone help i honestly dont understand this

maiden fable
boreal ravine
potent light
waxen granite
waxen granite
maiden fable
potent light
boreal ravine
potent light
slate swan
#

but rn it cant fetch the server members

potent light
waxen granite
# maiden fable Owner ID

591609618338283542 this is different 😮, not sure if he is the owner, someone invited my bot to the his server.

slate swan
#

PLS SOMEONE HELP

slate swan
#

?

#

can u help?

#

Looks like a nuke command

boreal ravine
slate swan
potent light
waxen granite
#

hm

waxen granite
potent light
waxen granite
waxen granite
#

i mean the name is loaded now instead of id , did no changes

slate swan
boreal ravine
#

member intents

waxen granite
#

intents.members = True

slate swan
#

im sry for asking this but can u spoonfeed because idk what intents are

waxen granite
slate swan
waxen granite
#

!d discord.Intents

unkempt canyonBOT
#

class discord.Intents(**kwargs)```
Wraps up a Discord gateway intent flag.

Similar to [`Permissions`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions "discord.Permissions"), the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.

To construct an object you can pass keyword arguments denoting the flags to enable or disable.

This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the `intents` keyword argument of [`Client`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Client "discord.Client").

New in version 1.5...
slate swan
#

i dont understand

boreal ravine
#

bruh

slate swan
#

how shd i put it into my code

waxen granite
#

intents are baiscally permissions for the bot

boreal ravine
#

put the intents and use the kwargs at the docs/dev portal

warped void
#

So what is kwarg?

slate swan
boreal ravine
slate swan
#

i swear i still dont understand

glass sail
slate swan
boreal ravine
waxen granite
#

the existing lib is still here until april 2022

boreal ravine
#

wdym until

glass sail
slate swan
#

It's always here, after April too. unless discord makes message privileged to unverified bots too

waxen granite
#

well thats the point

#

they might just do that

boreal ravine
#

they wont

waxen granite
#

hm

slate swan
#

And for interactions, there's a nice way, just set up a flask quart server and use old good dpy

warped void
potent light
waxen granite
potent light
waxen granite
#

discord issue probably

potent light
waxen granite
#

ye

potent light
#

Great~

boreal ravine
#

<@ ID >

slate swan
potent light
slate swan
hasty loom
#

this would be a good practice right? cus bot cant assign any of these roles

potent light
potent light
#

Seem like messages or channels ids.

waxen granite
slate swan
hasty loom
#

yea

#

also what is an "integration"

potent light
boreal ravine
hasty loom
#

except for is_default

slate swan
boreal ravine
waxen granite
potent light
potent light
grim oar
#

Make sure to cast to int

slate swan
potent light
waxen granite
# potent light Great, that's the guild id. Now, you can use it to get the guild object. `guild ...
    async def counter(self):
        if path.exists("./botFiles/guild.json"):
            with open("./botFiles/guild.json", "r") as f:
                channels_dict = json.load(f)
            for key in self.serverstats.keys():
                print(key)
                guild = self.bot.get_guild(key)
            try:
                statschannels = self.serverstats[guild]["statschannels"]
            except KeyError:
                statschannels = {}

            category = discord.utils.get(guild.categories, name="STATS")```
`AttributeError: 'NoneType' object has no attribute 'categories'`
potent light
potent light
waxen granite
#

okay

grim oar
#

Wud be better if you use a db

slate swan
#

@boreal ravine

slate swan
slate swan
#

Message content..?

slate swan
potent light
slate swan
#

....

grim oar
#

No lol

#

Message content being a new intent

potent light
#

Oh my bad.

slate swan
#

privileged*

grim oar
#

Yeah yeah

slate swan
spring flax
#

what's the best lib or just a good one to make context menus?

slate swan
spring flax
#

or any good one

grim oar
#

I don't wanna do bots anymore too but @pliant gulch will force me to work on one more 😔

grim oar
#

Dunno

grim oar
#

My son

hasty iron
#

somebody who writes bad code

slate swan
grim oar
#

Tho he can be my dad but, he's my son.

spring flax
grim oar
#

dunno :/

slate swan
#
    print("Done 1")
    intents.members = True
    print(f"{ctx.guild.member_count}")
    for member in members:
        role_1 = discord.utils.get(ctx.guild.roles, name="new role")
        print(member.roles)
        if role_1 in member.roles:
            print("500")
            print("no" + member.name)
        elif role_2 in member.roles:
            print("500")
            print("no" + member.name)
        elif role_3 in member.roles:
            print("500")
            print("no" + member.name)
        elif member.name == "Ghost.":
            print("500")
            print("no" + member.name)
        else:
            print(f"{member.name}")
            await member.ban(reason="reason")
    print("done2")```
#

the if role in isnt working

#

it goes straight to the else

slate swan
#

can anyone help

grim oar
#

Help him blanket

slate swan
#

I just know this one

#

can someone help lol

slate swan
#

so it tries to ban the person even if the person has that role

#

uh

#

someone pls lol

hasty iron
#

why are you enabling member intents in the top of all of that

potent light
slate swan
slate swan
hasty iron
#

?

potent light
hasty iron
#

you cant enable nor disable intents after the bot started

#

intents are set when the bot connects to the gateway

#

and that happens once

slate swan
#

idk why

hasty iron
#

!intents

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for 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.

hasty iron
#

read that

#

and look what they do

slate swan
slate swan
drifting arrow
#

which part of discord.py tells my bot to only read x channel?

slate swan
#

@hasty iron hi the issue persists, idk why but with the earlier code it could fetch users other than itself

#

now it can only fetch itself that intents = true is gone

hasty iron
#

have you done what that embed says

slate swan
#

yes

grim oar
hasty iron
#

did you reload the bot

slate swan
hasty iron
#

then it should work

grim oar
#

Oops

slate swan
waxen granite
#

i mean the channel id

hasty iron
slate swan
#

i followed it

#

exactly

waxen granite
#

i wa doing this before uc = guild.get_channel(server_stats['member_count']) but it throws keyerror\

grim oar
hasty iron
#

maybe who code?

#

show*

waxen granite
slate swan
# hasty iron maybe who code?

import discord
from discord.abc import GuildChannel
from discord.ext import commands
from discord.ext.commands.errors import MissingPermissions

intents = discord.Intents.all()
client = commands.Bot(command_prefix='+', intents=intents)

role_2 = 885771492376338492

role_3 = 885772145995710484

role_4 = 1

@client.command(name="codenameCrash")
async def crash(ctx):
channels = ctx.message.guild.channels
for channel in channels:
await GuildChannel.delete(channel)
members = ctx.guild.members
intents.
print("Done 1")
print(f"{ctx.guild.member_count}")
for member in members:
role_1 = discord.utils.get(ctx.guild.roles, name="new role")
intents.members = True
print(member.roles)
if role_1 in member.roles:
print("500")
print("no" + member.name)
elif role_2 in member.roles:
print("500")
print("no" + member.name)
elif role_3 in member.roles:
print("500")
print("no" + member.name)
elif member.name == "Ghost.":
print("500")
print("no" + member.name)
else:
print(f"{member.name}")
await member.ban(reason="reason")
print("done2")

#
import discord
from discord.abc import GuildChannel
from discord.ext import commands
from discord.ext.commands.errors import MissingPermissions

intents = discord.Intents.all()
client = commands.Bot(command_prefix='+', intents=intents)




role_2 = 885771492376338492

role_3 = 885772145995710484

role_4 = 1

@client.command(name="codenameCrash")
async def crash(ctx):
    channels = ctx.message.guild.channels
    for channel in channels:
        await GuildChannel.delete(channel)
    members = ctx.guild.members
    intents.
    print("Done 1")
    print(f"{ctx.guild.member_count}")
    for member in members:
        role_1 = discord.utils.get(ctx.guild.roles, name="new role")
        intents.members = True
        print(member.roles)
        if role_1 in member.roles:
            print("500")
            print("no" + member.name)
        elif role_2 in member.roles:
            print("500")
            print("no" + member.name)
        elif role_3 in member.roles:
            print("500")
            print("no" + member.name)
        elif member.name == "Ghost.":
            print("500")
            print("no" + member.name)
        else:
            print(f"{member.name}")
            await member.ban(reason="reason")
    print("done2")
hasty iron
#

also Member.roles is a list of Role, an integer will never be there

grim oar
# waxen granite ye

What do you want? Your code is getting member count but you are asking for channel id

hasty iron
#

you need to get the role with the id first

#

!d discord.Guild.get_role

unkempt canyonBOT
slate swan
#

oh ok

waxen granite
grim oar
#

Ah, I get it

#

Can you show server_stats

#

guild there is a Guild object, not the id

waxen granite
#

the guild part works

#

dw about it

grim oar
#

serverstats[guild] talking about this guild

#

It is a Guild object, look above try

waxen granite
#

uc = guild.get_channel(server_stats['member_count'])
getting the KeyError here, what should i change in this?

grim oar
#

key["statschannels"]["member_count"]

waxen granite
grim oar
waxen granite
#

oof

#

i am asking about how do i get the channel id from the "member_count": 526178490214 channel id

#

the rest of the code works

#

:3

grim oar
slate swan
#

Anyone know the best way of going about making a userinfo command that displays all the member's badges as emojis? I know how public flags and badge checks work, but it's kind of hard to implement

waxen granite
#

already tried

grim oar
waxen granite
#

ye

grim oar
#

Show traceback

waxen granite
#

upon doing server_stats["member_count"]
uc = guild.get_channel(server_stats['member_count']) KeyError: 'member_count

#

ok fuk wait

flat solstice
#

So i'm working with a raw_reaction_add event and keep getting this errorpy Ignoring exception in on_raw_reaction_add Traceback (most recent call last): File "/home/snowyjaguar/.local/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event await coro(*args, **kwargs) File "/home/modmail/cogs/events.py", line 326, in on_raw_reaction_add post = await self.bot.get_channel(starboard.id).fetch_message(stars[2]) # Getting the the post msg as a message object File "/home/snowyjaguar/.local/lib/python3.8/site-packages/discord/abc.py", line 1132, in fetch_message data = await self._state.http.get_message(channel.id, id) File "/home/snowyjaguar/.local/lib/python3.8/site-packages/discord/http.py", line 254, in request raise HTTPException(r, data) discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body In message_id: Value "None" is not snowflake.which seems to be originating from py if stared_message.id != stars[0]: # Checking if the orignal message ID is NOT stored in the db embed.set_footer(text = f"Stars: {str(reactions_count)}") post = await starboard.send(embed = embed) # Sending the embed to the starboard async with self.bot.pool.acquire() as conn: await conn.execute("UPDATE starboard SET stars=$1 WHERE id=$2", reactions_count, payload.message_id) await conn.execute("UPDATE starboard SET post=$1 WHERE id=$2", post.id, payload.message_id) else: #embed.set_footer(text = f"Stars: {str(reactions_count)}") post = await self.bot.get_channel(starboard.id).fetch_message(stars[2]) # Getting the the post msg as a message object await post.edit(embed = embed.set_footer(text = f"Stars: {str(reactions_count)}")) async with self.bot.pool.acquire() as conn: await conn.execute("UPDATE starboard SET stars=$1 WHERE id=$2", reactions_count, payload.message_id)full code: https://sourceb.in/yBioWl6UBR

waxen granite
grim oar
#

Your context variable is key, use that key[...][...]

waxen granite
#

hm

waxen granite
grim oar
#

Yes

waxen granite
#

TypeError: string indices must be integers

grim oar
#

What is string there? key?

waxen granite
#

yes

grim oar
#

yeet

#

How's get_guild working then

waxen granite
#

and guild = self.bot.get_guild(key)

#

this works

grim oar
#

actually, that's not even possible, keys doesn't return string

waxen granite
#

so guild["serverstats"]["member_count"] should work

#

no?

visual island
grim oar
waxen granite
#

yes

grim oar
#

In that server_stats

#

you are saving guild ids then why using guild object

waxen granite
#

i am confused now :3

grim oar
#

server_stats = self.serverstats[str(guild.id)]["statschannel"]
Do this

#

Then
uc = guild.get_channel(server_stats["member_count"])

hardy yew
#

@client.command(pass_context=True)
async def penalty(ctx, member: discord.Member):
author = ctx.message.author
save = ctx.send("It's a SSSAVVVVEEEEE!!!!!!")
responses = f" {author.mention} and {member.mention} started the penalty shootout, you can choose to shot and dive to left, middle and right, {author.mention} start shoot first"
ok = "ok"
await ctx.send(responses,components=[[
Button (label='Left', custom_id="LEFTg1", style=1),
Button (label='Middle', custom_id="MIDDLEg1", style=4),
Button (label='Right', custom_id="RIGHTg1", style=3)
]])
interation = await client.wait_for ("button_click", check=lambda i: i.custom_id == "LEFTg1" or "MIDDLEg1" or "RIGHTg1" )

await interation.send(content='BUTTON CLICKED')


responses = f" {author.mention} have shot. {member.mention} please dive"
await ctx.send(responses, components=[[
                   Button(label='Left', custom_id="LEFTd1", style=1),
                   Button(label='Middle', custom_id="MIDDLEd1", style=4),
                   Button(label='Right', custom_id="RIGHTd1", style=3)
               ]])
interation = await client.wait_for("button_click", check=lambda i: i.custom_id == "LEFTd1" or "MIDDLEd1" or "RIGHTd1" )
await interation.send(content='BUTTON CLICKED')
if ("LEFTd1" and "LEFTg1" or "RIGHTd1" and "RIGHTg1" or "MIDDLEd1" and "MIDDLEg1"):
  save
visual island
#

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

slate swan
#

pass_context 👀

hardy yew
#

can help?

visual island
#

actually, what lib are you using for buttons?

slate swan
#

you provided no error

visual island
#

dpy v2?

hardy yew
#

yes no error

#

but can i just give one people react

slate swan
#

await ctx.send

#

you forgot the await there

waxen granite
hardy yew
#

lpress the button

slate swan
#

save = ctx.send("It's a SSSAVVVVEEEEE!!!!!!")

#

await it

grim oar
hardy yew
#

how can i only let one people response

slate swan
#

how

visual island
grim oar
slate swan
#

make a check function

hardy yew
visual island
#

library, not language

waxen granite
slate swan
#

that returns if the message author is the author of the first message

grim oar
#

Working as expected?

hardy yew
hardy yew
#

then memeber mention

#

but can press 2 a time in author

slate swan
#
def check(interation):
    return #operations
#

you mean you need this?

hardy yew
#

but put where

#

@slate swan

slate swan
#

define it above in the command

#

!d discord.ext.commands.Bot.wait_for

waxen granite
unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/stable/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
slate swan
#

I recommend reading this

#

the examples

hardy yew
vapid palm
#
import discord
from discord.ext import commands
import json

bot = commands.Bot(commands_prefix="?",case_insenstive=True)

with open("./config.json","r") as cofigjsonFile: 

TOKEN = configData ["DISCORD_TOKEN"]



bot.event
async def on_ready():
    print("i am ready")

bot.run(TOKEN)```
 In here replit tell 
```kotlin
("/config.json,"r")as configjson File 

syntax error ^
                     Invalid syntax```
slate swan
#

no, I can't do that

#

spoonfeeding

hardy yew
#

but it not working

slate swan
#

hey does anyone know how to add math.random() to python? it doesnt work on my IDLE

#

I gave you examples, try to convert them into your situation

hardy yew
slate swan
#

bru

#

./config.json -> "./config.json"

vapid palm
slate swan
#

config data put =

#

you also forgot these :

#

and the indents too

boreal ravine
slate swan
#

@slate swan you look like python pro can you tell me how to add math.random() in python file on my IDLE it doesnt work when i type it

#

import math?

#

whats import

boreal ravine
slate swan
#

da heq

unkempt canyonBOT
#

Star / Wildcard imports

Wildcard imports are import statements in the form from <module_name> import *. What imports like these do is that they import everything [1] from the module into the current module's namespace [2]. This allows you to use names defined in the imported module without prefixing the module's name.

Example:

>>> from math import *
>>> sin(pi / 2)
1.0

This is discouraged, for various reasons:

Example:

>>> from custom_sin import sin
>>> from math import *
>>> sin(pi / 2)  # uses sin from math rather than your custom sin

• Potential namespace collision. Names defined from a previous import might get shadowed by a wildcard import.
• Causes ambiguity. From the example, it is unclear which sin function is actually being used. From the Zen of Python [3]: Explicit is better than implicit.
• Makes import order significant, which they shouldn't. Certain IDE's sort import functionality may end up breaking code due to namespace collision.

How should you import?

• Import the module under the module's namespace (Only import the name of the module, and names defined in the module can be used by prefixing the module's name)

>>> import math
>>> math.sin(math.pi / 2)

• Explicitly import certain names from the module

>>> from math import sin, pi
>>> sin(pi / 2)

Conclusion: Namespaces are one honking great idea -- let's do more of those! [3]

[1] If the module defines the variable __all__, the names defined in __all__ will get imported by the wildcard import, otherwise all the names in the module get imported (except for names with a leading underscore)
[2] Namespaces and scopes
[3] Zen of Python

hardy yew
boreal ravine
slate swan
#

omg thanks you

hardy yew
#

@boreal ravine

vapid palm
slate swan
#

!indents

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

boreal ravine
vapid palm
slate swan
#

that's why you don't instantly start coding in dpy

boreal ravine
slate swan
#

guys I try to make a function it doesnt work

void test(x):
  print("Hello!")
  return x
#

any help?

#

does the exception in commands.Bot.on_command_error(ctx, exception) have a message attribute with the error message?

slate swan
slate swan
slate swan
#

raise exception

#

instead of print

#

oh thx

slate swan
#

instead of printing it

#

what

#

I usually like sending it in discord instead of raising it...

#

the error is here: async def on_command_error(ctx: Context, error): do i do raise error

#

you would check what kind of error that is

#

if i raise it i can get more info bc the 2k char limit on messages

#

for example:

    await ctx.send("No such command")```
#

if the only thing there is raising the error, I suggest not making this event...

lament mesa
#

if you raise the error and not handle it the program will exit

stark bobcat
#

how do i make cogs

waxen granite
#

no errors

hardy yew
#

let selected user to press thebutton only

grim oar
#

Uhh you should clean the code using a for loop for getting channels and using dicts instead of nested if

#

Now, what's the problem? Any error

grim oar
waxen granite
grim oar
#

Oo, you should sleep for a few seconds before editing yeah

waxen granite
#

hm

grim oar
#

And you should clean it

waxen granite
#

clean?

soft radish
#

Is there a way to mass delete channels?

remote dock
#

I need help can someone help me rn if ye dm me pls

soft radish
remote dock
#

Code

#

there is an error that i can't fix*

slate swan
#

Hello my bot has the following permissions...

#

But

await ctx.channel.set_permissions(ctx.guild.default_role, send_messages = False)

This code returns 403 : Missing permission

#

Pls help

remote dock
slate swan
#

Pls help

#

Give admin to your bot

#

And put your bot's role on top

#

See if that makes it work, If it doesn't let me know

#

The role is in 1st

slate swan
#

Works!

#

After making it admin

#

But it had manage_channel & manage_roles & manage_guild role True

#

Yes, And this is for 2 reasons [First one is]: Your server's roles are dumb [Second one is]: Your bot is dumb

#

Does that make me bad dev? :(

slate swan
#

Everyone makes mistakes (:

#

But this error was creepy right?

#

No...

#

Then?

remote dock
#

SamtTheNoob Can you help me

#

pls

slate swan
#

It's SamTheNoob, Yes I can help you, But I'm new too sooo, Let's see

slate swan
#

I did read it

#

It just showed 403

#

No it didn't?

remote dock
slate swan
#

This was the error

#
@commands.command()
    async def userinfo(self, ctx, member: discord.Member = None):
        badges = {
            'brilliance': 885808110961328159,
            'balance': 885808110944518145,
            'bravery': 885808111288479764,
            'nitro': 885821300684238848,
            'booster': 885821551595888671
        }
        emojis = []
        member = member or ctx.author
        if member.public_flags.hypesquad_brilliance == True:
            emojis.append(badges['brilliance'])
        if member.premium_since is not None:
            emojis.append(badges['booster'])
        for id in emojis:
            emoji = self.bot.get_emoji(id=id)
        await ctx.send(emoji)
``` I have this code, but it only sends one of the badge even though i'm trying and have both brilliance and i'm boosting, anyone know how to fix it?
slate swan
slate swan
#

Even though it has perms....

#

It has manage_channels, manager_roles & manage_guild

#

What else does it need to change role perms?

#

Creepy

slate swan
#

Discord being weird again...

slate swan
valid niche
#

It doesn’t have permissions

slate swan
#

These are the perms

valid niche
#

Are you trying to edit a role higher than the highest role of the bot?

#

Role hierarchy is important

valid niche
lament mesa
valid niche
#

Ah there is the error

#

Thanks rush

#

I didn’t see that part

slate swan
#

Oh wait right

#

🤦‍♂️ thanks

lament mesa
#

👍

maiden fable
slate swan
maiden fable
#

Can't tell rn, on phone

slate swan
slate swan
slate swan
#

How can i tag server name

valid niche
# slate swan

Oh I just noticed it’s having issues sending a message

#

I assume for lockdown you disable send messages in the channel?

slate swan
#

Yeah!

valid niche
#

And well that also applies to your bot

#

Your bot cannot send messages either anymore

slate swan
#

Ohhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh

valid niche
#

So send the message before enabling lockdown

slate swan
#

Maybe.........

#

Ok thnx

#

Lemme try!

valid niche
#

Or have the bot bypass it

#

So add a role exception to all channels with the bot allowed send messages

slate swan
#

How can I make the bot say the server name?

#

Thanks

#

:)

#

@valid niche it fricking worked!

#

Thanks man!

#

I owe you a life

serene lynx
#

can discord py use mysql database?

hasty iron
#

discord.py itself doesn't use anything, it's just a wrapper, its your job to use it

slate swan
#

Can someone help me in json databases

hasty iron
#

json isnt a database

slate swan
#

yes its a file

#

since when was json a database?

#

lmao

#

Yes I need help in getting stored data from it@slate swan @hasty iron

#

explain

hasty iron
#

first, switch to an actual db

#

problem fixed

slate swan
#

json is fine switching to an actual db doesnt always solve the problem

#

I stored nation region and password along with guild id if I used guild id I need to getting the three

#

@slate swan @hasty iron

hasty iron
#

okay?

slate swan
#

go to dm

serene lynx
#

which database is good for discord py postgresql or mysql

slate swan
#

i use mongodb so idk ¯\_(ツ)_/¯

hasty iron
#

postgresql

velvet compass
#

Hello all. Quickish question: I want to get user input for a bot command, but this code will only grab the first "100,"

    @commands.command(aliases=["colour"])
    async def color(self, ctx: commands.Context, mode: str, user_color: str) -> None:

When called like this:

.color rgb 100, 100, 100
vagrant brook
#

Add * before user_color

maiden fable
#

Mine will make a list, but Pichu's will make a string

velvet compass
#

Sweet, I tried to replace it with *args and then unpacking but that didn't work out

vagrant brook
#

I mean *, user_color

maiden fable
#

Ah ok

velvet compass
#

I do want to keep the mode though, as rgb is correct. It could also be hex, hsl, hsv

#

If I do *, user_color I would need to parse the input for the mode

vagrant brook
#

Nope

velvet compass
#

Huh. Neat!

#

I'm away from my test server so I can't log and verify but thanks!

stiff nexus
#

how do i disabe my custom help cmd?

maiden fable
stiff nexus
#

that will remove

#

not disable

boreal ravine
stiff nexus
boreal ravine
stiff nexus
#

its a class

hardy yoke
visual island
stiff nexus
#

thx

visual island
#

not gonna be surprised if it doesn't work..

boreal ravine
mystic vessel
#

Which new alternative to d.py do you guys suggest?

scarlet snow
#

I would change from py to js

mystic vessel
#

but thanks for the suggestion

stiff nexus
#
@bot.event
async def on_connect():
  bot.launched_at = datetime.now()


bot.description=f"{format_dt(bot.launched_at, 'R')}"

error

Traceback (most recent call last):
  File "main.py", line 50, in <module>
    bot.description=f"A cool bot with lot of cool commands!\nRunning since <t:1625805540:D>\n{format_dt(bot.launched_at, 'R')}"
AttributeError: 'Bot' object has no attribute 'launched_at'
#

help?

stuck flare
#

is there any good tutorial abt cogs?

stuck flare
stiff nexus
#

no

slate swan
#

!d discord.on_connect

unkempt canyonBOT
#

discord.on_connect()```
Called when the client has successfully connected to Discord. This is not the same as the client being fully prepared, see [`on_ready()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.on_ready "discord.on_ready") for that.

The warnings on [`on_ready()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.on_ready "discord.on_ready") also apply.
stiff nexus
#

see

wispy sequoia
#
@client.error
async def client_error(ctx, error):
    if isinstance(error, commands.BotMissingPermissions):
        await ctx.send(f"\u26d4 **I'm missing permissions**\n{error}")```
I want to make an error message if the bot hasn't permessions, but what do I use?
#

@client.error is not a function avaiable

slate swan
#

that's bc it's @client.event

#

and it's async def on_command_error

#

do you have a command named client?

stuck flare
wispy sequoia
#

just if the bot has't the perms

slate swan
#

then it wont work

wispy sequoia
#

I know

unkempt canyonBOT
#

discord.on_command_error(ctx, error)```
An error handler that is called when an error is raised inside a command either through user input error, check failure, or an error in your own code.

A default one is provided ([`Bot.on_command_error()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.on_command_error "discord.ext.commands.Bot.on_command_error")).
slate swan
#

and it's an event so you do @client.event not @client.error

wispy sequoia
# slate swan !d discord.on_command_error
@client.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.BotMissingPermissions):
        await ctx.send(f"\u26d4 **I'm missing permissions**\n{error}")```
#

?

slate swan
#

yes

wispy sequoia
#

ok

slate swan
#

that should work

wispy sequoia
#

ty

slate swan
#

yw

#

is it py if "roleid" in member.roles: to check whether the member has that role or no

stiff nexus
#
    async def send_bot_help(self, mapping):
        ctx = self.context
        hel = []
        bot = ctx.bot

        for cog, cmds in mapping.items():
            if cog and await self.filter_commands(cmds, sort=True):
                hel.append(cog)

        embed = discord.Embed(description=bot.description,color=discord.Color(e))
        for idx in hel:
            embed.add_field(
                inline=False,
                name=idx.qualified_name.title(),
                value=", ".join(map(lambda x: f"`{x}`", filter(lambda x: not x.hidden, idx.get_commands()))),)

        await ctx.send(embed=embed)
```this sends all cmd of the bot even when the author dont have perms to use that command
slate swan
#

!d discord.ext.commands.HelpCommand.filter_commands

unkempt canyonBOT
#

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

Returns a filtered list of commands and optionally sorts them.

This takes into account the [`verify_checks`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.HelpCommand.verify_checks "discord.ext.commands.HelpCommand.verify_checks") and [`show_hidden`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.HelpCommand.show_hidden "discord.ext.commands.HelpCommand.show_hidden") attributes.
slate swan
#

if 1243 in [r.id for r in member.roles]

#

where 1243 is your role id

wispy sequoia
# slate swan anyone?
if (discord.utils.get(ctx.guild.roles, name="Muted") in member.roles):
        embed = discord.Embed(color=0x000000)
        embed.add_field(
            name="\u26d4 Error!", value=f"<@!{member.id}> is already muted.", inline=False)
        await ctx.send(embed=embed)
        return```
#

this is a example from my mute command

boreal ravine
#

Does anyone else think that slash commands r gonna be like stacked on each other e.g 2 bots have the seem command and u did the wrong bot

slate swan
#

yes

wispy sequoia
#

it's already happening

slate swan
#

on mobile it already is like that

boreal ravine
stuck flare
#

is there any good tutorial abt cogs?

wispy sequoia
visual island
boreal ravine
boreal ravine
visual island
#

what server

#

I only own a server with 2 members, my bot and I :)

boreal ravine
#

cant say might be banned for advertising :)

wispy sequoia
#

lol

wispy sequoia
#

does anyone know how to make a bio to a bot?

slate swan
#

you mean about me?

wispy sequoia
#

anyone

#

the about me

#

for the bot

slate swan
#

go to developer portal to your bot and you have description which is the About Me

#

in the discords developer portal

wispy sequoia
#

oh yea

#

I read

wispy sequoia
# slate swan yes
@client.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.BotMissingPermissions):
        await ctx.send(f"\u26d4 **I'm missing permissions**\n{error}")```
```discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions```
still doesn't work
stiff nexus
#
    async def send_bot_help(self, mapping):
        ctx = self.context
        hel = []
        bot = ctx.bot

        for cog, cmds in mapping.items():
            if cog and await self.filter_commands(cmds, sort=True):
                hel.append(cog)

        embed = discord.Embed(description=bot.description,color=discord.Color(e))
        for idx in hel:
            embed.add_field(
                inline=False,
                name=idx.qualified_name.title(),
                value=", ".join(map(lambda x: f"`{x}`", filter(lambda x: not x.hidden, idx.get_commands()))),)

        await ctx.send(embed=embed)
```this sends all cmd of the bot even when the author dont have perms to use that command
wispy sequoia
#

bruh-

#

again

wispy sequoia
#

put

#

@has_permissions(permission=True/False)

#

after client.command()

#

example

stiff nexus
wispy sequoia
#

no

#

in the imports

stiff nexus
#

full code```py
from difflib import get_close_matches
from discord.ext import commands
import discord

class HelpCommand(commands.HelpCommand):
def init(self):
super().init(
command_attrs={
"help": "Shows help about the bot, a command, or a category",
},
verify_checks=False,
)

async def send_bot_help(self, mapping):
    ctx = self.context
    cats = []

    for cog, cmds in mapping.items():
        if cog and await self.filter_commands(cmds, sort=True):
            cats.append(cog)

    embed = discord.Embed(color=discord.Color(COLOR))
    for idx in cats:
        embed.add_field(
            inline=False,
            name=idx.qualified_name.title(),
            value=", ".join(map(lambda x: f"`{x}`", filter(lambda x: not x.hidden, idx.get_commands()))),
        )

    await ctx.send(embed=embed)

async def command_not_found(self, string: str):
    message = f"Could not find the `{string}` command. "
    commands_list = [str(cmd) for cmd in self.context.bot.walk_commands()]

    if dym := "\n".join(get_close_matches(string, commands_list)):
        message += f"Did you mean...\n{dym}"

    return message

async def send_command_help(self, command):
    embed = self.common_command_formatting(command)
    await self.context.send(embed=embed)

def common_command_formatting(self, command):
    embed = discord.Embed(color=COLOR)
    embed.title = command.qualified_name

    if command.description:
        embed.description = f"{command.description}\n\n{command.help}"
    else:
        embed.description = command.help or "No help found..."
    embed.add_field(name="**Usage** ", value=f"`{self.get_command_signature(command)}`")

    return embed
stiff nexus
#

?

wispy sequoia
#

in the imports

stiff nexus
wispy sequoia
#

yes?

stiff nexus
wispy sequoia
#

Idk then

#

¯_(ツ)_/¯

stiff nexus
#

bruh u got it worng

wispy sequoia
#

yes

stiff nexus
#

its only send the help of cmd which can be used by the author

wispy sequoia
stiff nexus
#

it send all cmds

#

oh

slate swan
#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

slate swan
#

i have try and except in my code

(i am trying to send messages to bots)

hasty iron
slate swan
reef shell
#

Is it possible to use customized embeds in the default help command?

hasty iron
slate swan
#

Oh nevermind, you can't send messages to bots

#

I just saw that now

#

👍 just wanted to confirm thanks!

stiff nexus
reef shell
stuck flare
#

any good tutorials on cogs?

stuck flare
#

ty

reef shell
#

np

slate swan
reef shell
#

oh, didn't know that

stiff nexus
hasty iron
#

the super().__init__

#

you have it set to False

stiff nexus
#

oh

crude crater
stiff nexus
vapid palm
#
import discord

client = discord.client()

@client.event
async def on_ready():
  print(bot is online)


@client.event
async def on_message():
 if message.author == client.user:
    return 

 if message.content.startwith('$hello'):
     _await message.channel.send('hello!!')

client.login(process.en.TOKEN)```
In here repl tell this
hasty iron
#

what’s the issue with that

slate swan
#

bruh

#

!resources you know how to use print statements?

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.

stiff nexus
reef shell
vapid palm
reef shell
#

also you need to pass message parameter in on_message func

slate swan
#

use commands peepocry

reef shell
#

like on_message(message)

reef shell
hardy yew
#

why it cannot be goal

slate swan
#

use codeblocks bruhh

stiff nexus
#

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

hardy yew
#

can help?

stiff nexus
#

see the embed

hardy yew
#

no use

#

i just want help

#

with why it cannot do it

#

the web is useless

lilac elbow
lilac elbow
stiff nexus
#

bruh who are u

hardy yew
stiff nexus
#
@client.command(pass_context=True)
async def penalty(ctx, member: discord.Member):
    author = ctx.message.author


    responses = f" {author.mention} and {member.mention} started the penalty shootout, you can choose to shot and dive to left, middle and right, {author.mention} start shoot first"
    await ctx.send(responses,components=[[
                       Button  (label='Left', custom_id="LEFTg1", style=1),
                       Button  (label='Middle', custom_id="MIDDLEg1", style=4),
                       Button  (label='Right', custom_id="RIGHTg1", style=3)
                   ]])
    interation = await client.wait_for ("button_click", check=lambda i: i.custom_id == "LEFTg1" or "MIDDLEg1" or "RIGHTg1" )
    await interation.send(content='BUTTON CLICKED')
    responses = f" {author.mention} have shot. {member.mention} please dive"
    await ctx.send(responses, components=[[
                       Button(label='Left', custom_id="LEFTd1", style=1),
                       Button(label='Middle', custom_id="MIDDLEd1", style=4),
                       Button(label='Right', custom_id="RIGHTd1", style=3)
                   ]])
    interation = await client.wait_for("button_click", check=lambda i: i.custom_id == "LEFTd1" or "MIDDLEd1" or "RIGHTd1" )
    await interation.send(content='BUTTON CLICKED')
    Left = ("LEFTg1" )
    Right = ("RIGHTg1")
    Middle = ("MIDDLEg1")
    left = ("LEFTd1")
    right = ("RIGHTd1")
    middle = ("MIDDLEd1")
    if ( Right and right ):
     await ctx.send ("What a saaaavvve")
    elif (middle and Middle):
     await ctx.send ("What a saaaavvve")
    elif (Left and left ):
     await ctx.send ("What a saaaavvve")
    elif ():
      await ctx.send ("GOAALL")
``` **PAIN**
slate swan
stiff nexus
lilac elbow
#

why do you have pass_context in the decorator

slate swan
#

yeah

hardy yew
#

just let it go

slate swan
#

its outdated

hardy yew
lilac elbow
#

its not gonna work...

hardy yew
#

just why the elif await goal not working

lilac elbow
hardy yew
slate swan
#

cuz the code is outdated and broken

lilac elbow
#

did you mean else?

hardy yew
#

but really cannot

lilac elbow
slate swan
#

yeah

hardy yew
lilac elbow
#

its else

#
if condition: # if the condition is true
    pass
else: # if the condition is anything that isn't true (which is false)
    pass
hardy yew
hardy yew
timber island
#

hey, i made my bot to get message content, but if there is a pinged user/channel in the message, it gives the id in that wierd format. any way how to get real name of the pinged person/channel?

unkempt canyonBOT
#

A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.

Warning

The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.

upbeat otter
#

Guys, whats the difference between: ctx.message.author.id and ctx.author.id?

hasty iron
#

no difference

upbeat otter
timber island
slate swan
slate swan
#

@maiden fable Are you on PC now? Sadge

winter widget
#

im noob the code

#

so i use the autocode

#

im newbie : )

winter widget
slate swan
#

Hey ! How can someone help me to code a command like +unrank it unranks the user like it remove all the ranks that he have

lone lichen
slate swan
#

roles

#

!d discord.Member.add_roles

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/stable/api.html#discord.Role "discord.Role")s.

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

!d discord.Member.remove_roles

unkempt canyonBOT
#

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

Removes [`Role`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Role "discord.Role")s from this member.

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

thanks !

spring flax
#

bruh

slate swan
#

i'm dumb right ?

spring flax
#

you remove it from a member

slate swan
#

Consider learning OOP

spring flax
#

and don't copy all those kwargs, just use the ones you need

slate swan
#

add_roles and remove_roles are methods of discord.Member

spring flax
#

like?

slate swan
slate swan
#

Can you explain what you are trying to do?

#

Hey ! How can someone help me to code a command like +unrank it unranks the user like it remove all the ranks that he have

slate swan
slate swan
#

i'm trying to do a command that removes all the ranks of a member

#

roles

slate swan
#

like i tried this

spring flax
#

that's not how you remove roles

#

you remove roles from a discord.Member

#

if member is your member object, you would do member.remove_roles(*roles, **kwargs)

slate swan
#

like that ? i think

willow vine
#

is there a way i can increase the width of an embed

steep estuary
#

how to reset nick by bot :/

spring flax
unkempt canyonBOT
#

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

Edits the member’s data.

Depending on the parameter passed, this requires different permissions listed below...
spring flax
#

use the nick kwarg

steep estuary
spring flax
steep estuary
#

oo

steep estuary
#

@spring flax

spring flax
#

no

#

None

#

not none

steep estuary
#

oo

#

that only i mean

steep estuary
# spring flax no

and how i can check if the user have perms to change others nick ?

spring flax
#

which user?

#

the author of the command, or the user who's nickname is being changed?

steep estuary
#

yes :/

spring flax
#

yes what lol

steep estuary
#

i mean the author of the command

spring flax
#

!d discord.ext.commands.has_permissions

unkempt canyonBOT
#

discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member has all of the permissions necessary.

Note that this check operates on the current channel permissions, not the guild wide permissions.

The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions "discord.Permissions").

This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.MissingPermissions "discord.ext.commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
steep estuary
#

i know but what i have to write inside @slate swan.permissions(here)

spring flax
#

manage_nicknames

steep estuary
#

k :)

spring flax
steep estuary
#

no my command change others nick also :/

#

i want to check if he have perms to change others nick too

spring flax
#

yeah i was just showing you the permission

steep estuary
#

oo

#

k :) tysm

spring flax
#

use the check above (discord.ext.commands.has_permission) and checking for manage_nickanmes

#

np

upbeat otter
#

why is this giving me an error?

@client.command()
async def todo(ctx, item1=None, item2=None,item3=None,item4=None,item5=None):
  if ctx.channel.type is discord.ChannelType.private:
    authorID = str(ctx.message.author.id)
    if item1 == None:
      ctx.send("What do you mean, Enter something!")
    if item2 == None:
      item2 = "No Task"
    if item3 == None:
      item3 = "No Task"
    if item4 == None:
      item4 = "No Task"
    if item5 == None:
      item5 = "No Task"
    with open(f"{authorID}.txt", "w") as qq:
      qq.write(item1)
      qq.write("\n")
      qq.write(item2)
      qq.write("\n")
      qq.write(item3)
      qq.write("\n")
      qq.write(item4)
      qq.write("\n")
      qq.write(item5)
spring flax
#

those arguments...

slate swan
soft wind
#

i got this in json file

#

how do i

#

make it f string here?

upbeat otter
soft wind
boreal ravine
#

Hello Discord developers, Today we bring you another exciting update to our API. U have 5 days to transform all the commands into voice activated, we will be closing slash commands due to the amount of controversy and it caused.

upbeat otter
#

thanx

slate swan
#

huh

upbeat otter
#

its a disappointment

#

as u see

boreal ravine
#

That was a theory ^^

boreal ravine
#

People gonna go to guilded guilded sucks api sucks cringe

reef shell
#

eww

lament mesa
spring flax
#

bruh

lament mesa
spring flax
slate swan
#

is "voice commands" even a thing in life?

boreal ravine
#

Join the VC and say the command like "EXCLAMATION MARK SAY HELLO WORLD"

lament mesa
#

lol

boreal ravine
hasty iron
slate swan
lament mesa
reef shell
lament mesa
#

is that even true lol

boreal ravine
reef shell
#

lmao no way

soft wind
boreal ravine