#discord-bots

1 messages · Page 518 of 1

blazing vapor
#

the price there is giving a error

boreal ravine
#

hm

maiden fable
#

What's the error?

blazing vapor
maiden fable
#

Nvm, I gotta go. @patent lark do u mind helping them?

patent lark
#

what data type does price have?

blazing vapor
#

int

winged mural
patent lark
#

can i see the full code?

patent lark
blazing vapor
# patent lark can i see the full code?

sure

    @commands.command()
    async def buy(self,ctx,item_name,amount = 1):
        data = loadf('databases/shop1.json')
        item_name = item_name.lower()
        name_ = None
        for item in data["content"]:
            name = item['id'].lower()
            if name == item_name:
                name_ = name
                for item_pos, item in enumerate(data['content']):
                    if item_name == data['content'][item_pos]['id'].lower():
                        price = item['price']
                        print(price)
                        buyer_money = user_balance.find_one({'_id': ctx.author.id})
        
        buyer_cash = buyer_money['balance']['cash']
        if price > buyer_cash['balance']['cash']:
            await ctx.send('You Don\'t Even Have That Much Money Idiot 😛')
            return
        else:
            user_balance.update_one(buyer_cash, {"$inc": {
                    'balance.cash': -price}})
            user_inventory.insert_one({'_id': ctx.author.id, 'items': {
            name_: amount
            }})
            await ctx.send(f'You have successfully bought {amount} {name_}')```
somber musk
#

Solo?

winged mural
pliant gulch
#

Is there a reason you do ["cash"] when ["balance"] already returns an int?

#

Just remove that part and compare it to the price

glass sail
#

how do i make a developer only command

pliant gulch
#

ok

blazing vapor
pliant gulch
#

Somehow, somewhere you you turned balance into an int rather then a dictionary ¯_(ツ)_/¯

#

I'm only going off what the error says

#

Oh, wait

blazing vapor
#

is it fine?

pliant gulch
#

Well, you overwritten your original dictionary with an int

#

Doesn't seem like you use the dictionary again after accessing the cash the user has so

blazing vapor
#

ye?

pliant gulch
#

Ye, what?

blazing vapor
#

idk im dumb asf

pliant gulch
#

I just showed you the problem

#

Just use the variable you assigned and compare to price, don't try to access anything on it as its an int now, not a dictionary

solemn grove
#

How to create a sticky message?

boreal ravine
bitter perch
#

what's more concerning here is how you managed to get your error to mention Int64

maiden fable
#

Ikr

solemn grove
# boreal ravine whats a sticky message?

bot will send any message you give it to the bottom of a channel meaning every time a message is sent in the channel the bot will send the sticky message in the channel the bot will also delete its last sticky message everytime it sends a new one

static topaz
#

silly question, how can iterate over a sqlite db query? I know I can use for row but I am unsure of what to do next. Trying to display 3 different columns as embeds

slate swan
#

what's the error?

#

has_permissions

#

you have a typo

glass sail
#

i have the id of a message
i want to get the instance of that message
how do i do that?

slate swan
slate swan
unkempt canyonBOT
#

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

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

the perm check

glass sail
solemn grove
dapper cobalt
#

Read the last line.

slate swan
#

ugh

#

show code

#

muted_roles variable is not defined

boreal ravine
#

installing packages gone wrong

#

THeres a typo in ur code

#
muted_role = ctx.guild.get_role(881206952460451920) #muted_role

await member.add_roles(muted_roles) #u did muted_roles here
slate swan
#

oh

boreal ravine
#

no problem

slate swan
boreal ravine
#

lol

slate swan
#

oh yeah discord.py , discord they are basically same

somber musk
#

Discord* stop*

boreal ravine
somber musk
boreal ravine
#

what

somber musk
#

I also use replit

boreal ravine
somber musk
#

Replit is op because it's free 24/7 bot

#

People ask how my bot is 24/7 and I tell them it's a secret lolll

slate swan
boreal ravine
somber musk
slate swan
dapper cobalt
#

It doesn't matter if it's a Discord bot or not. Defining a variable is a Python thing, and programming in general. If you don't have enough knowledge in Python, do not jump into Discord bot development too early. Have some time to earn experience first so you won't be confused.

#

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

somber musk
#

Use YouTube

slate swan
boreal ravine
somber musk
#

So if you have for EG: TOKEN, you can hide your token by writing the value TOKEN which = your actual token in the thing

slate swan
#

replit aint a hosting site.

dapper cobalt
sick talon
#

Ahhh bot down

boreal ravine
slate swan
dapper cobalt
sick talon
dapper cobalt
somber musk
dapper cobalt
#

Of course.

slate swan
#

how do i get the guilds vanity url(if there is one)

dapper cobalt
#

And safer as well.

somber musk
#

Ic

#

I'll check it out tom

dapper cobalt
#

They use https://pterodactyl.io as their game panel.

slate swan
#

ctx.guild.vanity_url ddint work

sick talon
# somber musk Replit is op because it's free 24/7 bot

You should not use Repl.it to host your bot.

While this may seem like a nice and free service, it has a lot more caveats than you might think, such as:

  • The machines are super underpowered.

    • This means your bot will lag a lot as it gets bigger.
  • You need to run a webserver alongside your bot to prevent it from being shut off.

    • This isn't a trivial task, and eats more of the machines power.
  • Repl.it uses an ephemeral file system.

    • This means any file you saved via your bot will be overwritten when you next launch.
  • They use a shared IP for everything running on the service.
    This one is important - if someone is running a user bot on their service and gets banned, everyone on that IP will be banned. Including you.

Please avoid using repl.it to host your bot. It's not worth the trouble.

slate swan
unkempt canyonBOT
#

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

Returns the guild’s special vanity invite.

The guild must have `VANITY_URL` in [`features`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.features "discord.Guild.features").

You must have the [`manage_guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_guild "discord.Permissions.manage_guild") permission to use this as well.
somber musk
slate swan
#

invite play

#

add python to path

sick talon
somber musk
slate swan
sick talon
somber musk
slate swan
#

replit wont provide more than 500mbs

sick talon
#

Yeah

somber musk
somber musk
#

This bot is replit so it's pog:D

pliant gulch
#

inb4 half of the time your bot is API banned due to repl.it

somber musk
pliant gulch
#

Private testing server doesn't change the fact that it will get API banned lol

#

i.e meaning your bot is banned for a certain amount of time

somber musk
#

Y'all gotta stop shitting on replit ik it sucks but it's really not bad for beginners

sick talon
pliant gulch
#

It was never meant to be hosting discord bots lol

somber musk
pliant gulch
#

This is totally out of scope for beginners anyhow

sick talon
slate phoenix
#

beginners should use a real ide to learn how it works instead of learning it later

slate swan
somber musk
slate swan
#

?ytdl

somber musk
sick talon
sick talon
somber musk
somber musk
somber musk
#

Anyways

#

Do I have to pay for vs code 24/7

pliant gulch
#

VS Code is an IDE, not a VPS

#

It does not host your projects

somber musk
#

Wha

pliant gulch
#

IDE =/= VPS

sick talon
pliant gulch
#

??????

somber musk
#

Ic

sick talon
somber musk
sick talon
sick talon
sick talon
# slate swan I saw somewhere

yeah, coz there are many tutorials on YT, telling how to make a discord bot by forking a reply and changing the token of the bot

sick talon
slate swan
slate swan
sick talon
pliant gulch
#

Whats the point of using external libraries to handle components for discord.py excluding slash commands

#

Just use v2.0

dapper cobalt
#

Or use a fork. Either work.

slate swan
#

Yea

pliant gulch
#

No point in a fork right now

dapper cobalt
#

Yeah, but why wait until you've got only one month left to change your whole code when you can do it from now?

slate phoenix
#

plus the forks are bad

dapper cobalt
pliant gulch
#

A months time is long enough for me to migrate if discord rolls any breaking changes

#

They will announce said changes anyhow so

dapper cobalt
#

I mean, if you're just starting then you can just start with a fork. Though, it's totally up to you.

#

Learning something new isn't that bad.

pliant gulch
#

Learning something new?

#

Its a fork lol, 95% of the code will be from discord.py

dapper cobalt
#

I'm not talking about forks when I said learning something new.

#

I didn't clear what I meant correctly, that's my bad.

#

I meant, using the API itself or making your own library from scratch, which I tried to do.

#

I seriously do not recommend you do that.

pliant gulch
#

I literally have made my own minimal library already

dapper cobalt
#

Oh wow, so you never touch grass.

#

Just kidding, haha.

covert igloo
#

on a userinfo command

#

only happens if i mention someone

slate phoenix
#

post code

covert igloo
slate phoenix
#

!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.pythondiscord.com/

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

dapper cobalt
# covert igloo

Because when you mention someone member doesn't become None. Which triggers the raise errors.

slate phoenix
#

you should do if member != None

dapper cobalt
#

You can instead do:

member = member or ctx.author

Which if member is None then member will be equal to ctx.author.

pliant gulch
#

Better practice to use is here

covert igloo
#

not sure why it works in the server that i have it live it

#

in*

#

but raises an error in my test server

slate phoenix
#

sure then you could do is not

#

doesnt comparing the value compare the object type though or am i being slow currently?

dapper cobalt
unkempt canyonBOT
#

Pasting large amounts of code

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

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

dapper cobalt
#

Paste your code there and send the URL here.

covert igloo
dapper cobalt
unkempt canyonBOT
#

@dapper cobalt :white_check_mark: Your eval job has completed with return code 0.

foo is nothing!
boreal ravine
#

hm

covert igloo
#

the indent looks screwed in there but its fine in vs

dapper cobalt
#

if not checks if the variable is None, same as if var == None and if var is None. I do prefer if not var, though.

paper bane
covert igloo
#

prints if theres an error

#

this, in this case

waxen monolith
#

How do you stop FFmpeg PCM audio streams? I'm trying to make a bot play something and I don't know how to stop it with a different command

slate phoenix
paper bane
#

errors is never defined

dapper cobalt
#
@commands.command(aliases=["whois"])
@commands.has_guild_permissions(send_messages = True)
async def userinfo(self, ctx, member: discord.Member = None):
  member = member or ctx.author
  # make the embed and other things here.
#

@covert igloo That's all, no need for if nor else.

glass sail
#

will this work if i dont it to respond to its own messages

dapper cobalt
#

Better ignore all bots in general. Not just your bot.

#
if msg.author.bot:
  return
glass sail
#

thank u

dapper cobalt
#

No problem. a_thumbsup

covert igloo
slate swan
#

Hello

#

How do I make a level up bot?

dapper cobalt
paper bane
#

that changes nothing

dapper cobalt
#

Not sure if that will work, but no harm of trying.

dapper cobalt
covert igloo
#

the previous code i sent u works fine in this server

#

but when i use the same cmd in my test server, it raises the error

dapper cobalt
#

That's confusing. I don't know if you have member intents or not as it works in a server but not in another.

#

But do you have member intents enabled?

covert igloo
dapper cobalt
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.

round yarrow
#
esnipe_message_before = {}
esnipe_message_after = {}
esnipe_message_author = {}

snipe_message_author = {}
snipe_message_content = {}

@client.event
async def on_message_edit(before, after):
  snipe_message_author[before.channel.id] = before.content
  snipe_message_author[before.channel.id] = before.author
    

@client.command()
async def editsnipe(ctx):
  channel = ctx.channel
  try:
    editsnipeembed = discord.Embed(description=snipe_message_content[channel.id], timestamp=ctx.message.created_at)
    editsnipeembed.set_author(name=snipe_message_author[channel.id])
    await ctx.send(embed=editsnipeembed) 
  except:
    await ctx.send(f"There is no edit to snipe")```
just shows there is no edit to snipe
paper bane
#

you never set it in snipe_message_content

#

they're both snipe_message_author

round yarrow
#

where do i set it then?

covert igloo
#

even tho its the same code lol

dapper cobalt
#

Great!

paper bane
#

I am guessing this line should be referencing snipe_message_content instead

snipe_message_author[before.channel.id] = before.content
#

Also, why not just combine them all into 1 dictionary

round yarrow
#

yeah ig i should do that

solemn grove
#
@bot.listen()
async def on_message(message):
    if bot.user.mentioned_in(message):
        embed= discord.Embed(title= '**Close Combat Esports®**', description= '**\nMy prefix is `+`\n\nType `+help` for more info.**', color=0x00FFFF)
        await message.channel.send(embed=embed)

How can I stop it to respond on @ everyone @ here or reply @on ?

dapper cobalt
#

!d discord.User.mention

unkempt canyonBOT
#

property mention: str```
Returns a string that allows you to mention the given user.
somber musk
#

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

waxen granite
#

Could name be nil in add_field?

maiden fable
waxen granite
#

A space like name = " " will work?

boreal ravine
#

you can use an invis character

waxen granite
#

What is that?

boreal ravine
boreal ravine
#

wait it doesnt

#

i forgot the name

dapper cobalt
#

You can use the description kwarg in discord.Embed.

#

!d discord.Embed.description

unkempt canyonBOT
hoary gust
#

guys is there anything like message.created_at

dapper cobalt
#

!d discord.Message.created_at

unkempt canyonBOT
hoary gust
#

thanks

waxen granite
dapper cobalt
#

Use an invisible character then. But why do you want to add a field if it doesn't have a name?

waxen granite
#

My embed passes thr word limit for which i had to make multiple fields

#

I dont want to name the additional fields

dapper cobalt
waxen granite
#

Ye

#

But it passes it too

#

Like this

#

The player list goes 7-10

tawdry pilot
#

I have a question,
Is there a way to make a bot create a role or atleast just move it down some placements in the rankings
If yes how (please ping me so i get a notification since its 1 am i have school tmrw not normal school as a 5/6 yo to 15/16 yo)
If no have a great day / night wherever you are

waxen granite
#

ctx.guild.create_role

limber mountain
#
Ignoring exception in command shop:
Traceback (most recent call last):
  File "C:\Users\Orange\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\Orange\Desktop\codes\eco\main.py", line 197, in shop
    price = item["price"]
KeyError: 'price'

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

Traceback (most recent call last):
  File "C:\Users\Orange\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\Orange\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\Orange\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: KeyError: 'price'```what is wrong
#
mainshop = [{"name":"Watch","price :HypesHaLfcurrency: ":100,"description":"Time"},
            {"name":"Laptop","price :HypesHaLfcurrency: ":1000,"description":"Work"},
            {"name":"PC","price :HypesHaLfcurrency: ":10000,"description":"Gaming"},
            {"name":"Ferrari :HypesHaLfcurrency: ","price":99999,"description":"Sports Car"},
            {"name":"House ","price :HypesHaLfcurrency: ": 100000, "description":"mansion"} ]
``` see
#
@client.command()
async def shop(ctx):
    em = discord.Embed(title = "Shop")

    for item in mainshop:
        name = item["name"]
        price = item["price"]
        desc = item["description"]
        em.add_field(name = name, value = f"${price} | {desc}")

    await ctx.send(embed = em)
visual island
#

your key is not "price"

slate swan
#

It basically classifies players and places them 15 per field.

#
Embed have max 25 fields. A field's name is limited to 256 characters and its value to 1024 characters.
#

Hi

#

Anyone knows how to do pagination with emoji

#

Like ➡️

#

U know? @slate swan

slate swan
#

Is more easy if you dont know how works

#

Idk all I'm new to py

#

Hm

slate swan
floral jacinth
#

is possible to join in vocal channel to let bot create another vocal channel, but in another category?

unkempt canyonBOT
#
Missing required argument

package

slate swan
#

Hm

#

!pypagination

#

!pypi reactionmenu

unkempt canyonBOT
slate swan
#

Ok

#

Where the link

floral jacinth
slate swan
#

Click on the title

slate swan
slate swan
#

reactionmenu v2.0.3

#

Only this

#

!py buttonmenu

slate swan
unkempt canyonBOT
#

await create_voice_channel(name, *, reason=None, category=None, position=..., bitrate=..., user_limit=..., rtc_region=..., video_quality_mode=..., overwrites=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

This is similar to [`create_text_channel()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.create_text_channel "discord.Guild.create_text_channel") except makes a [`VoiceChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.VoiceChannel "discord.VoiceChannel") instead.
slate swan
unkempt canyonBOT
#

discord.on_voice_state_update(member, before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") changes their [`VoiceState`](https://discordpy.readthedocs.io/en/master/api.html#discord.VoiceState "discord.VoiceState").

The following, but not limited to, examples illustrate when this event is called...
slate swan
#

Use this event

#

Hm

slate swan
slate swan
#

Ok

#

...

valid perch
#

If your under 75 guilds you can just use message intents and your fine haha

fair axle
#

I am using dislash

code:

                            options=[Option("user" "select the user", OptionType.USER, required=True),
                                     Option("channel" "select the channel", OptionType.CHANNEL, required=False)])

error:

[WARNING] Failed to overwrite commands in <Guild id=CENSORED_FOR_NOW> due to 400 Bad Request (error code: 50035): Invalid Form Body
In 7.options.0.name: String value did not match validation regex.
In 7.options.1.name: String value did not match validation regex.

why??

@ me in response

floral jacinth
valid perch
#

Thats if your over 75 guilds, at that point yes you need to use slash commands

slate swan
valid perch
fair axle
#

oh wait

#

u do

#

OMG LOL I AM SO DUMB

#

ty for pointing that out

valid perch
#

👍 you know best haha

orchid talon
#

why on member join is not working

sick talon
#

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

orchid talon
#

yea

#

ty

fair axle
#

using dislash

#

anyone???

#

is the slowmode that bad?

#

...lol

boreal ravine
#

why r u using the class name is that allowed?

fair axle
boreal ravine
#

o 2.0

fair axle
#

code:

@inter_client.slash_command(guild_ids=test_guilds, description="Adds a user to this channel",
                            options=[Option("user", "select the user you want to add to this channel", OptionType.USER,
                                            required=True)])
async def add(inter, user, channel: discord.TextChannel):
    await discord.TextChannel.set_permissions(channel, user, reason="Bot command", view_channel=True,
                                              send_messages=True)
    await inter.channel.send(f"Added {user.name} to this channel")

error:

  File "C:\Users\USER\Desktop\FOLDER\FOLDER\FOLDER\FOLDER\dislash\application_commands\core.py", line 72, in __call__
    return await self.func(*args, **kwargs)
TypeError: add() missing 1 required positional argument: 'channel'

WHYYYYYYYYYYYYY??????????

@ me in response

slate swan
fair axle
#

??

slate swan
#

!d discord.TextChannel.set_permissions

unkempt canyonBOT
#

await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sets the channel specific permission overwrites for a target in the channel.

The `target` parameter should either be a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that belongs to guild.

The `overwrite` parameter, if given, must either be `None` or [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/master/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite"). For convenience, you can pass in keyword arguments denoting [`Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions") attributes. If this is done, then you cannot mix the keyword arguments with the `overwrite` parameter.

If the `overwrite` parameter is `None`, then the permission overwrites are deleted.

You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this...
limber mountain
limber mountain
limber mountain
fair axle
#

Helloooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo

#

anyone there???

#

lol

slate swan
limber mountain
slate swan
#

What

#

What to show?

limber mountain
slate swan
#

O

#

Which category code

limber mountain
#

what commands do you have

slate swan
#

Yes error

fair axle
limber mountain
#

idk do you want a mute command take my

dim cedar
#

hey

#

is it possible to unmute some one in a server from my bot?

limber mountain
#
@client.command(description="Mute a person lol")
@commands.has_permissions(manage_messages=True, manage_roles=True)
async def mute(ctx,member: discord.Member, *, reason=None):
    guild = ctx.guild
    mutedRole = discord.utils.get(guild.roles, name="muted")

    if not mutedRole:
        mutedRole = await guild.create_role(name="muted")
        for channel in guild.channels:
            await channel.set_permissions(mutedRole, speak=False, send_messages=False, read_message_history=False, read_messages=False)

    await member.add_roles(mutedRole, reason=reason)
    await ctx.send(f"mute {member.mention} for reason {reason}")
    embed=discord.Embed(title=" you have been muted", color = discord.Colour.red())
    embed.add_field(name="Why were you muted", value=f"you were from {guild} because of {reason}")
    await member.send(embed=embed)
slate phoenix
dim cedar
#

no imean i am muted

dim cedar
slate swan
#

Type

async def mute(ctx,member : discord. member) 

Or use

async def mute(ctx,member : discord_member) 
slate phoenix
#

If it’s your bot yes

#

If it’s not no

slate swan
#

@slate swan

dim cedar
limber mountain
slate swan
#

Always welcome try working or not I'm using like that

slate swan
#

Yh

dim cedar
#

but i am muted

slate swan
#

Ik

slate swan
dim cedar
#

how will i exicute it?

slate swan
#

Not defence it's an auto-correct by my keyboard use def

dim cedar
#

i just wanna escape a mute with my bot

fair axle
slate phoenix
slate swan
#

It was my keyboard auto correct ssry really sry

fair axle
#

bruh someone tell me how to use this thing

slate phoenix
#

!d discord.on_message

unkempt canyonBOT
#

discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") is created and sent.

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

Warning

Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
fair axle
visual island
dim cedar
#

i mean i am new i dont understand it

slate swan
#

Someone know how to do pagination /reaction menu?

light night
#

trust me it's easy

slate phoenix
slate swan
light night
#

🤔 #help-bagel i made a function in a discord.py fork to allow you to generate a snowflake/user id by passing datetime or the utc time of the time the function was ran, I think it's accurate, but I am not sure if people enjoy it

slate swan
#

!pagination

light night
slate swan
#

Ok

#

!invite

light night
# slate swan Ok
GitHub

Contribute to Rapptz/discord-ext-menus development by creating an account on GitHub.

GitHub

A simple layer over discord.ext.menus using the new discord.ui components in discord.py v2.0. - GitHub - oliver-ni/discord-ext-menus-views: A simple layer over discord.ext.menus using the new disco...

#

there

granite prawn
#

im tryna do a currency heist command, when someone runs %heist it runs a heist and anyone who sends join heist within 30 seconds will be stored in a list full of their ids, i tried this


@client.command()
async def heist(ctx):
  await ctx.send('A heist has started, type join heist within 30 seconds')
  users = []
  def check():
    return msg.content.lower() == 'join heist'
  while True:
    try:
      msg = await client.wait_for_message(timeout= 30,check=check)
      users.append(str(msg.author.id))
    except:
      break

but then it just restarts the 30 second timer when someone says join heist, anyone know how to get by this?

dim cedar
#

well

#

will my code code work to prevent mute?

#
async def on_message(message):
    user.id == 760010546728402975
    if message.content == "!mute @Riad#1922":
        await user.remove_roles("Muted")```
hasty iron
dapper cobalt
#

That's full of problems.

hasty iron
#

!d asyncio.create_task

unkempt canyonBOT
#

asyncio.create_task(coro, *, name=None)```
Wrap the *coro* [coroutine](https://docs.python.org/3.10/library/asyncio-task.html#coroutine) into a [`Task`](https://docs.python.org/3.10/library/asyncio-task.html#asyncio.Task "asyncio.Task") and schedule its execution. Return the Task object.

If *name* is not `None`, it is set as the name of the task using [`Task.set_name()`](https://docs.python.org/3.10/library/asyncio-task.html#asyncio.Task.set_name "asyncio.Task.set_name").

The task is executed in the loop returned by [`get_running_loop()`](https://docs.python.org/3.10/library/asyncio-eventloop.html#asyncio.get_running_loop "asyncio.get_running_loop"), [`RuntimeError`](https://docs.python.org/3.10/library/exceptions.html#RuntimeError "RuntimeError") is raised if there is no running loop in current thread.

This function has been **added in Python 3.7**. Prior to Python 3.7, the low-level [`asyncio.ensure_future()`](https://docs.python.org/3.10/library/asyncio-future.html#asyncio.ensure_future "asyncio.ensure_future") function can be used instead...
dapper cobalt
dapper cobalt
#

Second of all, discord.Member.remove_roles() takes a role ID and not a role name.

#

!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/master/api.html#discord.Role "discord.Role")s from this member.

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

it takes a Role object

#

not id

dapper cobalt
#

8:32 AM brain is to blame. Haha.

dim cedar
slate swan
#

!reaction menu

dim cedar
#

pls teach me someone

fair axle
dapper cobalt
granite prawn
#

discord.ext.commands

slate swan
#

Use from discord.ext import commands

hasty iron
#

user is still not defined

slate swan
#

What

fair axle
slate swan
#

Wait

dapper cobalt
#

!resources if you don't have much knowledge about Python, please do not jump into discord.py too soon. Learn some basics first so you would know what you're doing.

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.

hasty iron
#

you asked where to put an import

slate swan
#
import discord 
from discord.ext import commands 
 
Do other import needed 
#

@slate swan

hasty iron
#

if you really did, you would’ve known

hasty iron
#

that’s not an excuse

dapper cobalt
#

I don't think staying up till 1 AM could make you forget how to import if you actually did know about Python?

granite prawn
#

why is my ide suddenly blue after this async thing

hasty iron
#

stop copying code

dapper cobalt
#

Are you using discord.Client?

hasty iron
#

why.. you ask

granite prawn
#

oh ya forgot the in

fair axle
#

code:

@inter_client.slash_command(guild_ids=test_guilds, description="Adds a user to this channel",
                            options=[Option("user", "select the user you want to add to this channel", OptionType.USER,
                                            required=True)])
async def add(inter, user, channel: discord.TextChannel):
    await discord.TextChannel.set_permissions(channel, user, reason="Bot command", view_channel=True,
                                              send_messages=True)
    await inter.channel.send(f"Added {user.name} to this channel")

error:

  File "C:\Users\USER\Desktop\FOLDER\FOLDER\FOLDER\FOLDER\dislash\application_commands\core.py", line 72, in __call__
    return await self.func(*args, **kwargs)
TypeError: add() missing 1 required positional argument: 'channel'

why?

@ me in response

hasty iron
#

yeah you clearly dont know python

dapper cobalt
#

!d discord.TextChannel.history

unkempt canyonBOT
#

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [`AsyncIterator`](https://discordpy.readthedocs.io/en/master/api.html#discord.AsyncIterator "discord.AsyncIterator") that enables receiving the destination’s message history.

You must have [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permissions to use this.

Examples

Usage...
hasty iron
#

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

slate swan
#

Use from discord.ext import commands (use command(s) commands

#

@slate swan

#

Show ur code

#

I can fix

#

If u like

hasty iron
#

#bot-commands

slate swan
#

I hate it

hasty iron
#

that autocorrect?

slate swan
#

Me using mobile

#

Yh

hasty iron
#

why

dapper cobalt
#

Are you coding on mobile?

slate swan
hasty iron
#

buy one

slate swan
dapper cobalt
slate swan
hasty iron
#

well python doesn’t require you to have 32gb of ram

dapper cobalt
# slate swan Yes

Not sure why, but I consider coding on mobile a crime. But yeah it's completely fine.

hasty iron
#

you could find a cheap pc

slate swan
dapper cobalt
#

A $200 laptop could do the job.

hasty iron
#

less even

dapper cobalt
#

You don't need more than 4GB of RAM to code.

slate swan
#

!ot

unkempt canyonBOT
slate swan
dapper cobalt
#

What's the issue again?

hasty iron
slate swan
#

Ye

dapper cobalt
#

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

hasty iron
#

lmao

hasty iron
#

copied code

#

went from an import to a whole muting command in about 5 seconds

umbral carbon
#

Add a prefic

dapper cobalt
#

Well, could you please take a look at the docs, and see if discord.Client has a command method?

slate swan
#

Capital m for Member in discord. Member

dapper cobalt
#

I don't think it does.

slate swan
#

!code reactionmenu

dapper cobalt
hasty iron
slate swan
boreal ravine
unkempt canyonBOT
#
I'm sorry Dave, I'm afraid I can't do that.

No documentation found for the requested symbol.

boreal ravine
#

you were saying?

dapper cobalt
#

!d discord.Member

unkempt canyonBOT
#

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

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

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

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

hash(x) Returns the member’s hash.

str(x) Returns the member’s name with the discriminator.
hasty iron
#

discord.member is a module

dapper cobalt
#

And read his error.

boreal ravine
#

isn't python case sensitive

dapper cobalt
hasty iron
dapper cobalt
#

He's using discord.Client instead of commands.Bot().

umbral carbon
#

Copying code is okay till you’re actually learning hoe it’s working

hasty iron
#

or right

umbral carbon
#

How*

hasty iron
#

i read that as case insensitive

boreal ravine
#

from discord.ext import commands

umbral carbon
#

Do you have a prefix

boreal ravine
#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.

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

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

my god

umbral carbon
#

Bru

hasty iron
#

if you don’t know, dont help

#

it’s annoying

#

prefix isnt the issue here

dapper cobalt
#

I'm having a stroke reading all those wrong answers, lmfao.

#

I just said it, twice.

#

You are using discord.Client and not commands.Bot.

#

Don't use discord.Client.

#

It's bad.

#

Unless you want to work with only events.

umbral carbon
boreal ravine
#

nope

dapper cobalt
#

Do you want an example?

hasty iron
#

bruh

hasty iron
slate swan
#

!d discord.on_message_delete

boreal ravine
#

discord.ext.commands is an extension so dw about rewriting your code

dapper cobalt
#
import discord
from discord.ext import commands

intents = discord.Intents.default()
# intents.members = True (remove the comment if you've enabled it on the dev portal)
bot = commands.Bot(command_prefix="your_prefix", intents=intents)

@bot.event
async def on_ready():
  print(f"{bot.user} is online.")

@bot.command()
async def ping(ctx):
  await ctx.send("Pong!")

bot.run("YOUR BOT TOKEN")
dapper cobalt
#

Never seen an example on the docs, lmao.

hasty iron
#

there is

dapper cobalt
hasty iron
#
from discord.ext import commands

bot = commands.Bot(command_prefix='$')

@bot.command()
async def test(ctx):
    pass

# or:

@commands.command()
async def test(ctx):
    pass

bot.add_command(test)
boreal ravine
ocean leaf
#

any mistake i have done? it is giving me command not found error. tis is the cog

dapper cobalt
ocean leaf
hasty iron
#

you aren’t decorating correctly

ocean leaf
hasty iron
#

the command

boreal ravine
#

the first two lines of the command

ocean leaf
#

oh

#

my @ key sometimes dosent work

boreal ravine
#

doesn't*

ocean leaf
#

yes sorry

dim cedar
#
async def on_message(message):
    if message.content == "!mute @Riad#1922":
        guild = ctx.guild
        mutedrole = discord.utils.get(guild.roles, name = "Muted")
        await user.remove_roles(mutedrole)
        await ctx.send("Did you just escaped a Mute @Riad#1922")```
#

what is wrong with my code now?

#

ctx not defined

boreal ravine
dim cedar
boreal ravine
slate swan
#

!d discord.on_message_edit

dapper cobalt
boreal ravine
dapper cobalt
#

He's using message events to make commands instead of a bot.command decorator.

boreal ravine
#

I know that but does djs do that too?

dapper cobalt
#

Nope.

#

Discord.js is only message events.

#
client.on("message", (message) => {
  if (message.content === "!ping") {
    message.channel.send("Pong!")
}
})
#

I'll be right back. Gotta feed my cat.

slate swan
#

This is not discord js

#

!d discord.on_member_update

granite prawn
#
@client.command()
async def event(ctx):
  embed = discord.Embed(title='Event Started',description=f'React to join the event within 30 seconds!',color=discord.Color.random())
  msg = await ctx.send(embed=embed)
  await msg.add_reaction('🎉')
  users = []
  await asyncio.sleep(30)
  msg = await ctx.channel.fetch_message(msg.id)
  reaction = [i for i in msg.reactions]
  for i in reaction.users:
    users.append(i.id)
  print(users)

I am trying to make a event command but doing this doesnt print the user ids so i cant do what i want with them

slate swan
#

is there like after.action on the member update event so i can tell what changed on there profile or like what changed

granite prawn
dapper cobalt
#

Not even []?

granite prawn
#

nope

#

after 2 mins still nothing

slate swan
#

thats a problem

leaden anvil
dapper cobalt
#

Try to print i.

leaden anvil
#

Ok I wanted a message with embeds, buttons and select menu but a error was occurring Positional argument cannot appear after keyword arguments for FS to solve this I did FS=FS but now it gives me send() got an unexpected keyword argument 'FS' how do I solve this ? here is the code: py @client.group(invoke_without_command=True) async def feedback(ctx, *, text = None,): try: text = text.split("|") report=discord.Embed(color=0xfff868) report.add_field(name='Pending Confirmation', value=f"{text[1]} #Tittle \r {text[2]} #Description") FB=[[Button(style=ButtonStyle.red, label="Discard", custom_id="n"), Button(style=ButtonStyle.green, label="Send", custom_id="y")]] FS=Select(placeholder = 'Where to post',options = [SelectOption(label="Bugs", value="value1"),SelectOption(label="Commands", value="value2"),SelectOption(label="Suggestions", value="value3"),SelectOption(label = "Other", value = "value4")]) await ctx.channel.send(embed=report,components=FB, FS=FS) except: await ctx.reply("Please enter `/feedback format` to check how to format.")

granite prawn
coral flame
leaden anvil
coral flame
#

ah

#

doesnt look like it has that as a param

slate swan
coral flame
#

!d discord.TextChannel.send

unkempt canyonBOT
#

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

Sends a message to the destination with the content given.

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

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

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

havent used them yet but i think u have to create a View and add the Select and Buttons to it

#

then use await message.channel.send(embed = report, view = view)

steep estuary
#

how i can get the reacter of reaction in dsicord.py on_reaction

#

:/

cobalt shoal
#

on_reaction is an event?

slate swan
slate swan
steep estuary
slate swan
#

Never used the one that's not raw but shouldn't be that different

#

First read the docs, they're very useful and give you the answer you need

steep estuary
#

ok

boreal ravine
#

how do I do this in cogs?

#

I tried self.bot but it still said self was undefined

visual island
#

show code?

slate swan
#

Self :monkas:

boreal ravine
#
import discord
from datetime import datetime
from discord.ext import commands

class Help(commands.Cog):
    def __init__(self, bot):
      self.bot = bot

    class MyNewHelp(commands.MinimalHelpCommand):
      async def send_pages(self):
        destination = self.get_destination()
        for page in self.paginator.pages:
          embed = discord.Embed(description=page)
          embed.timestamp=datetime.utcnow()
          embed.set_author(name=self.context.author, icon_url=self.context.author.display_avatar)
          embed.set_footer(text='Minimal Help Command', icon_url=self.context.author.display_avatar)
          await destination.send(embed=embed)
    
      async def send_command_help(self, command):
        embed = discord.Embed(title=self.get_command_signature(command))
        command_has_alias = command.aliases
        command_has_help = command.help
        if command_has_help:
          embed.add_field(name="Help", value=command.help)
        if command_has_alias:
          embed.add_field(name="Aliases", value=", ".join(command.aliases), inline=False)

        channel = self.get_destination()
        await channel.send(embed=embed)
    
      async def send_error_message(self, error):
        embed = discord.Embed(title="Error", description=error)
        channel = self.get_destination()
        await channel.send(embed=embed)

    self.bot.help_command = MyNewHelp()

def setup(bot):
  bot.add_cog(Help(bot))
visual island
boreal ravine
#

oh

visual island
#

wait

#

dont do that

boreal ravine
#

wot

visual island
#

nested class

boreal ravine
#

hmmm

visual island
#
import discord
from datetime import datetime
from discord.ext import commands

class MyNewHelp(commands.MinimalHelpCommand):
      async def send_pages(self):
        destination = self.get_destination()
        for page in self.paginator.pages:
          embed = discord.Embed(description=page)
          embed.timestamp=datetime.utcnow()
          embed.set_author(name=self.context.author, icon_url=self.context.author.display_avatar)
          embed.set_footer(text='Minimal Help Command', icon_url=self.context.author.display_avatar)
          await destination.send(embed=embed)
    
      async def send_command_help(self, command):
        embed = discord.Embed(title=self.get_command_signature(command))
        command_has_alias = command.aliases
        command_has_help = command.help
        if command_has_help:
          embed.add_field(name="Help", value=command.help)
        if command_has_alias:
          embed.add_field(name="Aliases", value=", ".join(command.aliases), inline=False)

        channel = self.get_destination()
        await channel.send(embed=embed)
    
      async def send_error_message(self, error):
        embed = discord.Embed(title="Error", description=error)
        channel = self.get_destination()
        await channel.send(embed=embed)

class Help(commands.Cog):
    def __init__(self, bot):
      self.bot = bot
      self.bot.help_command = MyNewHelp()

def setup(bot):
  bot.add_cog(Help(bot))

```do this
#

*indent still messy

boreal ravine
#

o ok

steep estuary
#

how to get the user who reacted in msg?

#

i want to check if the user who reacted is in the list?

#

list = [me , u , everyone]

#

in this list :/

#

async def on_reaction_add(reaction,user):
if user.id in list?

visual island
#
if any(user in list for user in await message.reactions[0].users.flatten())
spice atlas
#
Traceback (most recent call last):
  File "C:\Users\kusha\PycharmProjects\pythonProject\project 1 month.py", line 61, in <module>
    inpiration()
  File "C:\Users\kusha\PycharmProjects\pythonProject\project 1 month.py", line 53, in inpiration
    @client.event(youtubepy)
  File "C:\Users\kusha\PycharmProjects\pythonProject\venv\lib\site-packages\discord\client.py", line 1015, in event
    raise TypeError('event registered must be a coroutine function')
TypeError: event registered must be a coroutine function

so what should i do o correct my code

visual island
steep estuary
#

and how i can get guild id ?

visual island
#

async def...

visual island
spice atlas
steep estuary
spice atlas
steep estuary
#

ohh ok

odd pendant
#

if you're ever stuck finding attrs, look on the docs and just scroll through them, you'll usually find what you need

slate swan
#

yelp need an embed but its saying unident error pylance

#

! @commands.command()
@commands.has_permissions(manage_roles=True)
async def addrole(self, ctx, *, name):
guild = ctx.guild

    await guild.create_role(name=name)
        embed= discord.Embed(description=f"**Role {name} has been created without any Permissions !! **")
        await ctx.send(embed=embed)
#

!code @commands.command()
@commands.has_permissions(manage_roles=True)
async def addrole(self, ctx, *, name):
guild = ctx.guild

    await guild.create_role(name=name)
        embed= discord.Embed(description=f"**Role {name} has been created without any Permissions !! **")
        await ctx.send(embed=embed)
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
#

!dumb

unkempt canyonBOT
#

Dunder methods

Double-underscore methods, or "dunder" methods, are special methods defined in a class that are invoked implicitly. Like the name suggests, they are prefixed and suffixed with dunders. You've probably already seen some, such as the __init__ dunder method, also known as the "constructor" of a class, which is implicitly invoked when you instantiate an instance of a class.

When you create a new class, there will be default dunder methods inherited from the object class. However, we can override them by redefining these methods within the new class. For example, the default __init__ method from object doesn't take any arguments, so we almost always override that to fit our needs.

Other common dunder methods to override are __str__ and __repr__. __repr__ is the developer-friendly string representation of an object - usually the syntax to recreate it - and is implicitly called on arguments passed into the repr function. __str__ is the user-friendly string representation of an object, and is called by the str function. Note here that, if not overriden, the default __str__ invokes __repr__ as a fallback.

class Foo:
    def __init__(self, value):  # constructor
        self.value = value
    def __str__(self):
        return f"This is a Foo object, with a value of {self.value}!"  # string representation
    def __repr__(self):
        return f"Foo({self.value!r})"  # way to recreate this object


bar = Foo(5)

# print also implicitly calls __str__
print(bar)  # Output: This is a Foo object, with a value of 5!

# dev-friendly representation
print(repr(bar))  # Output: Foo(5)

Another example: did you know that when you use the <left operand> + <right operand> syntax, you're implicitly calling <left operand>.__add__(<right operand>)? The same applies to other operators, and you can look at the operator built-in module documentation for more information!

slate swan
#

!test @commands.command()
@commands.has_permissions(manage_roles=True)
async def addrole(self, ctx, *, name):
guild = ctx.guild

    await guild.create_role(name=name)
        embed= discord.Embed(description=f"**Role {name} has been created without any Permissions !! **")
        await ctx.send(embed=embed)
#

!work @commands.command()
@commands.has_permissions(manage_roles=True)
async def addrole(self, ctx, *, name):
guild = ctx.guild

    await guild.create_role(name=name)
        embed= discord.Embed(description=f"**Role {name} has been created without any Permissions !! **")
        await ctx.send(embed=embed)
#

heyo how to test

#

?

#

!eval @commands.command()
@commands.has_permissions(manage_roles=True)
async def addrole(self, ctx, *, name):
guild = ctx.guild

    await guild.create_role(name=name)
        embed= discord.Embed(description=f"**Role {name} has been created without any Permissions !! **")
        await ctx.send(embed=embed)
unkempt canyonBOT
#

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

001 |   File "<string>", line 2
002 |     @commands.has_permissions(manage_roles=True) 
003 | IndentationError: unexpected indent
slate swan
#

anyone

slate swan
#

IDK try

#

Or put administrator else for it

slate swan
slate swan
slate swan
#

What

slate swan
#

oh

#

Then put administration = True

boreal ravine
boreal ravine
#

a way to fix it is to not do that and just use tabs or spaces and not both

slate swan
#

@boreal ravine u know to make pagination

#

Or like that

boreal ravine
boreal ravine
slate swan
#

I need bunttons or emoji anything

boreal ravine
#

not really

#

theres this gist that has pagination for 1.7 i think

slate swan
#

Can u join my code in Replit and show?

boreal ravine
#

h

boreal ravine
dim cedar
slate swan
#

Ok

boreal ravine
slate swan
#

What will I do for pagination

#

😭

slate swan
boreal ravine
slate swan
#

Reaction menu

#

Eh

#

These smh

slate swan
dapper cobalt
dapper cobalt
slate swan
#

let it be

#

XD

hoary gust
#

guys what kind of error is this i mean why is it occuring discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ServerSelectionTimeoutError: cluster1-shard-00-00.teqte.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129),cluster1-shard-00-01.teqte.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129),cluster1-shard-00-02.teqte.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129)

dapper cobalt
#

You didn't pass a correct username/password.

solar pike
#

hello

#

anyone here

slate swan
#

👀

solar pike
slate swan
#

code?

solar pike
#

python

slate swan
#

bruh i asked for the code

solar pike
#

ooo

slate swan
#

show me import part

dapper cobalt
visual island
solar pike
#

MAIN.PY
import discord
import random
import os
from discord.ext import commands

client = commands.Bot(command_prefix = '.')

@client.command()
async def load(ctx, extension):
client.load_extension(f'cogs.{extension}')

@client.command()
async def unload(ctx, extension):
client.unload_extension(f'cogs.{extension}')

for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
client.load_extension(f'cogs.{filename[: -3]}')

client.run('token')

in cogs folder ( example .py )
class Example(commands.Cogs):

def init(self, client):
self.client = client

@commands.Cog.listener()
async def on_ready(self):
print('Bot is online.')

@command.command()
async def ping(self, ctx):
await ctx.send('Pong!')

def setup(client):
client.add_cog(Example(client))

waxen granite
slate swan
#

oh yes

#

lmao spelling

solar pike
#

hehe

#

scenic wren
#

send code @solar pike

solar pike
#

MAIN.PY
import discord
import os
from discord.ext import commands

client = commands.Bot(command_prefix = '.')

@client.command()
async def load(ctx, extension):
client.load_extension(f'cogs.{extension}')

@client.command()
async def unload(ctx, extension):
client.unload_extension(f'cogs.{extension}')

for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
client.load_extension(f'cogs.{filename[: -3]}')

client.run('Token here')

example.py

import discord
from discord.ext import commands

class Example(commands.Cog):

def init(self, client):
self.client = client

@commands.Cog.listener()
async def on_ready(self):
print('Bot is online.')

@command.command()
async def ping(self, ctx):
await ctx.send('Pong!')

def setup(client):
client.add_cog(Example(client))

dapper cobalt
solar pike
#

@scenic wren

scenic wren
#

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

solar pike
#

OOOOOOOOOOOOOOO ty

#

HA YES WORKED

dim cedar
boreal ravine
slate swan
#

Im making a bot with the new structural pattern matching, can someone answer my question here?
#help-cherries message

solar pike
#

import discord
from discord.ext import commands

class Example(commands.Cog):

def init(self, client):
self.client = client

@commands.Cog.listener()
async def on_ready(self):
print('Bot is online.')

@commands.command()
async def ping(self, ctx):
await ctx.send(f'Pong! {round(client.latency * 1000)}ms')

def setup(client):
client.add_cog(Example(client))

boreal ravine
solar pike
#

k

boreal ravine
#

k

dim cedar
#

I want to remove the muted role from myself

boreal ravine
#

message.author I guess?

dim cedar
#

That would be the author then

boreal ravine
#

yes

dim cedar
#

But i am not the author

#

The person trying to mute me is the auther

boreal ravine
#

or something

dim cedar
boreal ravine
#

!d discord.Guild.fetch_member

unkempt canyonBOT
#

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

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

Note

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

Ok i'll try

slate swan
#

how could i make a global wait time for welcome dms

#

so i dont have the event been triggered across multiple servers and dms sent to fast and bot risked being flagged

solar pike
#

import discord
from discord.ext import commands

class Example(commands.Cog):

def init(self, client):
self.client = client

@commands.command()
async def _8ball(self, ctx, *, question):
responses = ['it is certain.',
'it is decidedly so.',
'whithout a doubt.',
'yes - defenitely',
'you may rely on it.',
'as i see it, yes.',
'most likely.',
'outlook good.',
'yes.',
'Signs point to yes.',
'reply hazy, try again',
'ask again later',
'better not tell you now',
'cannot predict now.',
'concentrate and ask again.',
"don't count on it.",
'My reply is no.',
'my sources say no',
'outlook not so good',
'very doubtfull.', ]
await ctx.send(f'Question: {question}\nAnswer: {random.choice(responses)}')

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.

solar pike
#

?

leaden anvil
plucky sonnet
#

im searching for somebody to help me with webhooks and bots for my dc server

#

dm if u are able to help

#

(its a fortnite server) just to mention since people hate on fortnite

slate swan
#

!indent

unkempt canyonBOT
#

Indentation

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

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

Example

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

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

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

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

boreal ravine
slate swan
#
@bot.command()
async def pog(ctx):
  role = discord.utils.get(ctx.guild.roles,id = 882504055866396682)
  await ctx.send(f'{role.mention}')```
#

i use this it mention role but not ping why?

boreal ravine
#

isnt that the same thing

dim cedar
#
@bot.event
async def on_message(message):
    if message.content == "!mute @Riad#1922":
        user = message.guild.fetch_member(760010546728402975)
        guild = message.guild
        mutedrole = discord.utils.get(guild.roles, name = "Muted")
        await user.remove_roles(mutedrole)
        await message.send("Did you just escaped a Mute @Riad#1922")```
#

can anyone explain me?

#

why this code is not preventing me from getting muted

slate swan
#

Hm

dim cedar
static topaz
#

attempt to make a bot and am stuck on a few things, the main one is converting an sqlite query to a vertical list instead of its current output of [[1, 2, 3]].

I have put in py def results(): with conn: cur = conn.cursor() cur.execute("SELECT seriesName from sonarr") rows = cur.fetchall() result = rows(cur) return(result)
and converted it to a list, however i keep getting the error TypeError: 'list' object is not callable and I am very confused

solar pike
#

import discord
from discord.ext import commands

class Example(commands.Cog):

def init(self, client):
self.client = client

@commands.command(aliases=['8ball', 'test'])

async def _8ball(self, ctx, *, question):
responses = ['it is certain.',
'it is decidedly so.',
'whithout a doubt.',
'yes - defenitely',
'you may rely on it.',
'as i see it, yes.',
'most likely.',
'outlook good.',
'yes.',
'Signs point to yes.',
'reply hazy, try again',
'ask again later',
'better not tell you now',
'cannot predict now.',
'concentrate and ask again.',
"don't count on it.",
'My reply is no.',
'my sources say no',
'outlook not so good',
'very doubtfull.',
'Ask my creator SHOTO :))']
await ctx.send(f'Question: {question}\nAnswer: {random.choice(responses)}')

valid niche
#

why

#

use bot, self.bot etc

#

don't use client/self.client

dim cedar
valid niche
#

also your list isn't indented correctly

valid niche
solar pike
dim cedar
valid niche
upbeat otter
#

Guys, can I stop this link from embedding?

await ctx.send("https://www.google.com")
upbeat otter
upbeat otter
#

oh oh okay, thanx

valid niche
#

if you want to use commands: #bot-commands

boreal ravine
#

hm

slate swan
#

It's discord.abc.Messageable.send

dim cedar
#

how can i make it work?

boreal ravine
slate swan
#

Yeah but kind of useless to be fair xD

valid niche
#

so idk the solution

dim cedar
#

no errors

boreal ravine
#

e

slate swan
#

Just saying 'not working' doesn't give any information

valid niche
#

i don't know the issue

#

so i don't know the solution

boreal ravine
#

!d discord.abc.Messageable.send

dim cedar
#

from me

slate swan
#

And please don't make commands in events..

valid niche
slate swan
#

You can do the same a lot easier using commands

valid niche
#

also you could just add an if statement to your mute command that checks if you are getting muted instead of having an on_message

boreal ravine
#

maybe because of hierachy

slate swan
#

You would get an error

#

Which, apparently, they don't get

dim cedar
dim cedar
valid niche
#

not a check

#

literally just an if statement

#

it's first ctx then error in your arguments

#

with your if isinstance you're comparing error to the MissingPermissions, but error is context, and ctx is error

dim cedar
#

the if statement

valid niche
#

also use ctx.reply

#

not ctx.message.reply

#

!d discord.ext.commands.Context.reply

unkempt canyonBOT
#

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

A shortcut method to [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") to reply to the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message").

New in version 1.6.
dim cedar
valid niche
#

!d discord.ext.commands.Context read these attributes. Ctx has a LOT of attributes. It's a very powerful thing

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.
valid niche
dim cedar
valid niche
#

so it will first try removing the muted role, then after a delay the other bot starts working and you get the muted role

#

so in this case you want to have a on_member_update where it checks for role changes, and if it's you and the role is muted role, then remove it

slate swan
#

Anyone know how to add buttons when clicked shows another embed?

valid niche
#

!d discord.on_member_update

unkempt canyonBOT
#

discord.on_member_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") updates their profile.

This is called when one or more of the following things change:

• nickname

• roles

• pending...
dapper cobalt
unkempt canyonBOT
valid niche
slate swan
#

Which one should use?

slate swan
fading harness
#

why its say invalid syntax on async def 8ball(ctx, *, question)

dapper cobalt
fading harness
#

insert hyperlink

dapper cobalt
#
@bot.command(name="8ball")
async def _8ball(ctx, *, question):
  ...
valid niche
dapper cobalt
valid niche
#

so it is markdown

dapper cobalt
#

Well, Discord doesn't use markdown exactly.

#

So, if I do:

title1 title2
header1 header2
text1 text2

it won't become a table.

valid niche
#

there are a few limits yeah but they tried to follow the standards and even call it markdown in their guides

dapper cobalt
#

It's Discord's markdown, but it's not markdown itself.

#

Would be very cool if Discord used markdown itself, though! Imagine how easier it would be to make your text look more organized.

severe oar
#

discord.py + typing:
i have some command:

@commands.command()
async def ...(self, ctx, args: typing.Literal["test"]):
    ...

How do i make args work with Test?

hasty iron
hasty iron
#

oh didnt know

lofty heron
#

hi is logging all used commands allowed? just wanted to check before i did something

valid niche
lofty heron
#

hmm alright

hasty iron
#

but isnt logging message in a gray area-ish

lofty heron
slate swan
severe oar
hasty iron
#

no i just checked, its new in 2.0

severe oar
valid niche
#

your bot is missing permissions to do thsi action

hasty iron
#

!d discord.ext.commands.BadLiteralArgument

unkempt canyonBOT
#

exception discord.ext.commands.BadLiteralArgument(param, literals, errors)```
Exception raised when a [`typing.Literal`](https://docs.python.org/3/library/typing.html#typing.Literal "(in Python v3.9)") converter fails for all its associated values.

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

New in version 2.0.
valid niche
#

!d typing.Literal

unkempt canyonBOT
#

typing.Literal```
A type that can be used to indicate to type checkers that the corresponding variable or function parameter has a value equivalent to the provided literal (or one of several literals). For example:

```py
def validate_simple(data: Any) -> Literal[True]:  # always returns True
    ...

MODE = Literal['r', 'rb', 'w', 'wb']
def open_helper(file: str, mode: MODE) -> str:
    ...

open_helper('/some/path', 'r')  # Passes type check
open_helper('/other/path', 'typo')  # Error in type checker
```...
dapper cobalt
#

And I'm a guy, btw.

valid niche
#

then the bot doesn't have permission in that guild

severe oar
#

but how i can make option.lower() here?

slate swan
valid niche
#

role hierarchy?

#

server owner?

#

or someone with the same role

#

if 2 people both have the highest role they cannot affect each o ther

#

this is the line of error in your code

#

it's not allowed to add a reaction

solar pike
#

import discord
from discord.ext import commands

class Ban(commands.Cog):

def init(self, client):
self.client = client

@commands.command()
async def ban(self, ctx, member : discord.Member, *, reason=None):
await member.ban(reason=reason)
await ctx.send(f'Banned {member.mention}')

def setup(client):
client.add_cog(ban(self.client))

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.

odd pendant
solar pike
#

tried

hasty iron
#

Ban isnt a subclass of Cog

solar pike
#

hasty iron
#

?

#

Ban needs to be a subclass of Cog

#

the class

valid niche
# solar pike

when making a cog you need to subclass commands.Cog

dapper cobalt
#
class Ban(commands.Cog):
  ...
odd pendant
#

have any of you even looked at his code

hasty iron
boreal ravine
#

u did ban in setup but u did Ban in the class name

hasty iron
#

he did what you told him to do

valid niche
hasty iron
#

and the error occured

valid niche
#

capitalisation

boreal ravine
#

^

odd pendant
solar pike
#

got it

solar pike
#

ty

dapper cobalt
valid niche
#

their code has the cog Ban but in their setup they do ban

#

@solar pike

solar pike
#

ye ye got it

slate swan
#

twy6t

dapper cobalt
# valid niche ?

I did it with a small b but Discord changed it to a capital one somehow.

#

I don't see what that has to do with Python?

#

Access Denied?

#

Does the bot have manage messages permissions?

dim cedar
#

how to use discord.on_member_update(before, after)
to prevent mute

dapper cobalt
#

Try to remove the check.

odd pendant
dapper cobalt
#

check=is_me.

dim cedar
#

what is the code?

odd pendant
#

it might be because your top role is higher than the bots top role, or it just doesn't have the correct permission

dapper cobalt
#

Did you include the application.commands scope when adding your bot to the server?

#

What is user_roles?

dim cedar
#

what u are trying to make can u explain?

#

thn i might be able to help

dapper cobalt
reef shell
#

oh fuck

dim cedar
reef shell
#

wrong chat

dapper cobalt
#

Try to use a normal check. @commands.has_permissions(manage_messages=True) instead of an if statement.

odd pendant
dim cedar
#

let me help u

#
@bot.command()
@commands.has_permissions(administrator=True)  
async def clear(ctx, amount= 1): 
   await ctx.channel.purge(limit=amount) 
odd pendant
#

or just use commands.has_permissions

visual island
dim cedar
odd pendant
#

if the user changes the value from the default 1 then it would be a str, you need to specify the type or convert it. either use amount: int = 1 or purge(limit=int(amount))

maiden fable
#

!d discord.TextChannel.purge

steep estuary
#

i added intents for on_member_join but now if i am adding link to dm someone else bot is doing dm to itself help pls

dim cedar
#

eh

maiden fable
#

U don't have access to do that

dim cedar
#

it works for me tho

steep estuary
# maiden fable .....?

like i have command await member.send("hi")
it was working well but after i added intents = discord.Intents.all() it is doing dm to itself :(

odd pendant
#

has the bot got the add reactions permission?

maiden fable
steep estuary