#discord-bots

1 messages · Page 1137 of 1

sullen pewter
#

can you show full code

#

there's also a tab button

#

at the bottom of the screen

paper sluice
#

its client.user not User

#

when your bot doesn't respond, look at your terminal, most of the time it would be interrupted by some error which will be displayed there

robust fulcrum
#

I want to make a custom prefix thing again. Can anyone here guide me pls?
|| Me not mean spoon feed ||

robust fulcrum
#

I want that users of my bot can change prefix

#

And i want to use sqlite but don't know how to use in dpy

paper sluice
#

there is nothing different

robust fulcrum
slate swan
#

How i can make that when my BOT joins to server it will send message on random channel like thank u for adding me

robust fulcrum
#

But i not understood how can I implement it in discird bot

paper sluice
spring flax
#

does anyone know why a bot would sent double messages each time?

paper sluice
paper sluice
robust fulcrum
spring flax
paper sluice
robust fulcrum
supple cobalt
slate swan
#

Why so much indent errors help today

robust fulcrum
#

And in mobile?

slate swan
#

no

robust fulcrum
#

Ok

slate swan
#

And self host

idle radish
#

Is it possible with discord embed to add an field which is an link:

I would like to make the key a link

embed=discord.Embed(color=0x8ff0a4)
embed.add_field(name="[key](https://google.nl)", value="value", inline=False)
await ctx.send(embed=embed)
paper sluice
#

you can make a hyperlink in the value of the field

slate swan
paper sluice
#

!d discord.Embed.add_field

idle radish
hushed galleon
#

itd be exactly the way you did it, except written after value=

shrewd apex
#

whats the permission kwarg for manage channel in commands.has_permissions

spring flax
#

!d discord.Permissions.manage_channels

unkempt canyonBOT
#

Returns True if a user can edit, delete, or create channels in the guild.

This also corresponds to the “Manage Channel” channel-specific override.

shrewd apex
#

cool thanks

spring flax
#

with this code https://paste.pythondiscord.com/metalimune.py
I got an error of ```
f"{member.mention} ({str(member)} is on timeout until <t:{int(member.current_timeout.timestamp())}>)"
AttributeError: 'NoneType' object has no attribute 'timestamp'

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

Traceback (most recent call last):
File "/pufferpanel/.local/lib/python3.10/site-packages/disnake/ext/commands/bot_base.py", line 570, in invoke
await ctx.command.invoke(ctx)
File "/pufferpanel/.local/lib/python3.10/site-packages/disnake/ext/commands/core.py", line 920, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/pufferpanel/.local/lib/python3.10/site-packages/disnake/ext/commands/core.py", line 178, in wrapped
raise CommandInvokeError(exc) from exc
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'timestamp'

#

so I checked and a member was recently removed from timeout

#

but i had some logic to remove them from the list, which doesn't seem to work

spring flax
#

yeah i know

#

but ```py
@commands.Cog.listener()
async def on_member_update(self, before: disnake.Member, after: disnake.Member):
if before.current_timeout is not None and after.current_timeout is None:
if before in self.timed_out:
self.timed_out.remove(before)

#

oh wait

#

hmm. I think i see the problem

#

current_timeout doesn't return a boolean, it returns a datetime

#

what would the solution be? add the ID's to the list instead of the object?

shrewd apex
#

what's the method to hyper link a link to text in embed title or name

spring flax
#

!d discord.Embed.url

unkempt canyonBOT
shrewd apex
#

is it possible in add_field also?

spring flax
#

in the name or value?

shrewd apex
#

name

#

!d discord.Embed.add_field

unkempt canyonBOT
#

add_field(*, name, value, inline=True)```
Adds a field to the embed object.

This function returns the class instance to allow for fluent-style chaining. Can only be up to 25 fields.
hushed galleon
placid skiff
#

except for the title of the embed

hushed galleon
#

in general you might get messier code by nesting try excepts, but in your case you dont need the try/excepts in the first place; the on_error event is automatically fired if your on_member_join event raises an error, which by default prints the error for you

pastel solar
hushed galleon
#

commands have their own error handlers, the global one being the on_command_error event

#

in cogs there's the cog_command_error method you can override, and on commands you can use the .error decorator: ```py
@bot.command()
async def hello(ctx):
raise RuntimeError('hello world!')

@hello.error
async def hello_error(ctx, error):
if isinstance(ctx, commands.CommandInvokeError):
original = error.original # = RuntimeError('hello world!')
await ctx.send(error) # sends "hello world!"```

pastel solar
hushed galleon
#

wdym all types

#

prefix + slash + message + user commands?

slate swan
pastel solar
#

Yes, instead of writing an individual error handler for every command (slash)

hushed galleon
#

the on_command_error event as i mentioned earlier

pastel solar
#

Ah okay

#

I missed that part, my bad,.

hushed galleon
#

just make sure to display the error if it doesnt match any of the exceptions you're handling, otherwise you'll eat up the error and never see it

#

a quick way to do that is with raise error: py @bot.event async def on_command_error(ctx, error): if isinstance(error, commands.MissingRequiredArgument): ... else: raise error

heady sluice
#

you made a new line

#

that's like 8 bytes wasted

#

how dare thou

vocal snow
#

What

hushed galleon
# heady sluice that's like 8 bytes wasted

how about this then py bot.event(lambda ctx, error: ctx.send(f'missing argument {error.param.name}') if isinstance(error, commands.MissingRequiredArgument) else exec('raise error'))

slate swan
#

O.o is it still MissingRequiredArgument.param i thought they changed it

#

!d discord.ext.commands.MissingRequiredArgument

hushed galleon
#

its the same in both 1.7 and 2.0

#

maybe you're thinking of MissingPermissions.missing_perms to MissingPermissions.missing_permissions

slate swan
#

oh yeah, thats it, i was confused Sweats

idle radish
paper sluice
hushed galleon
# spring flax wouldn't you have to await send?

its taking advantage of what a coroutine function is, which is a function that returns a coroutine; dpy expects a corofunc for the event handler but lambda only creates a regular function, so if i return the coroutine from ctx.send(), it works like a coro function and dpy awaits the send for me

paper sluice
#

it does?

spring flax
#

oh, interesting

hushed galleon
#

yeah i tested the lambda with jishaku earlier

#

well i only tested the lambda but i forgot dpy checks if its a corofunc before setting it, so i dont think it actually would work :(

#

maybe just manually assigning it would work py bot.on_command_error = lambda ctx, error: ctx.send(f'missing argument {error.param.name}') if isinstance(error, commands.MissingRequiredArgument) else exec('raise error')

slate swan
#

hi

#

:c help

pliant pagoda
#

Hi, I've got this far with trying to make a 'role' bot:

@bot.command()
async def verify(ctx):
    message = await ctx.send('React to verify!')
    await message.add_reaction('✅')

    def check(reaction, user):
        return reaction.emoji == '✅' and reaction.message == message

    reaction, user = await bot.wait_for('reaction_add', check=check)
    await ctx.send(f'Thank you {user.mention}!')

Any idea how to actually give the user the role now?

slate swan
#

@pliant pagoda why i can't open .py file with this code?

#

and token

hushed galleon
hushed galleon
hushed galleon
slate swan
#

WTF

#

i was instaled this

#

bro i have lag with my brain

hushed galleon
pliant pagoda
#

appreciate it

hushed galleon
#

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

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

thanks🙂

paper sluice
slate swan
hushed galleon
#

and it will await the coro because thats how coro functions work

paper sluice
#

ya, but u still need to await ctx.send

slate swan
#

will you help me? I am already tired of it for 2 hours

slate swan
hushed galleon
#

seems like vs code is referencing the correct python version and site packages

pliant pagoda
slate swan
pliant pagoda
slate swan
#

what's the issue though

hushed galleon
slate swan
hushed galleon
# slate swan

can you show the entire file structure of your project? and also maybe try py -m pip install --force-reinstall discord.py just to make sure the source wasnt somehow edited

paper sluice
# hushed galleon

well, ur await the ctx.send afterwards, the lambda returned the ctx.send coro. Im saying that dpy doesn't do that

hushed galleon
unkempt canyonBOT
#

discord/client.py line 456

await coro(*args, **kwargs)```
hushed galleon
#

try it again, and could you show a screenshot of the file explorer in vs code?

slate swan
#

that's all

hushed galleon
slate swan
#
    @commands.command(name = "BD2")
    async def comand_BD2(self, ctx):

        cursor.execute("""CREATE TABLE IF NOT EXISTS cooldown(
            id INT,
            name TEXT,

            work_1 timestamp,
            work_2 int
            )""")

        for guild in self.client.guilds:
            for member in guild.members:
                if cursor.execute(f"SELECT id FROM cooldown WHERE id = {member.id}").fetchone() is None:
                    cursor.execute("INSERT INTO  cooldown VALUES (?, ?, ?, ?)", (f'{member.id}', f'{member}', joining_date, 1))
                else:
                    pass
                conn.commit()
        await ctx.send("ДА") 

Dear, I found material on the Internet about SQL date and time. but for some reason it didn't work for me. how to write down the date and time in the value please tell me.

slate swan
hushed galleon
#

change vs code to use python 3.10

#

you installed it manually so maybe you'll have more luck with that

slate swan
#

so i need select this?

hushed galleon
#

also can you elaborate what you mean by "it didn't work"

slate swan
#

;-; and don't use that CREATE TABLE statement for each command invocation, you just need it once

#

@hushed galleon i change it and if i try open this file the window opens and closes

#

uh

#

this can also be moved out of the for loop, so you commit to the database only once

#

wait it work! Thank you @hushed galleon ❤️

hushed galleon
#

ig windows store python was the issue?

pliant gulch
# hushed galleon

I was so confused for a sec, then I realised the lambda is returning a coroutine lmao

hushed galleon
#

oh right, you hadnt defined it

#

you probably want to refer to member.joined_at

#

!d discord.Member.joined_at

unkempt canyonBOT
#

An aware datetime object that specifies the date and time in UTC that the member joined the guild. If the member left and rejoined the guild, this will be the latest date. In certain cases, this can be None.

slate swan
#

thats not how you use cogs.

from discord.ext import commands

class MyCog(commands.Cog):
    def __init__(self, bot: commands.Bot) -> None:
        self.bot = bot

    @commands.command()
    async def my_command(self, ctx: commands.Context)-> None:
        ...

def setup(bot: commands.Bot) -> None:
    bot.add_cog(MyCog(bot))```
here's a basic cog command example for reference. ( v1.7.3 )
#

for discord.py 2.0, setup would be a coroutine, and you would be awaiting bot.add_cog

#

@hushed galleonТвой баланс 2022-05-20 16:31:43.177000+00:00
Wow. hooray. He shows!!! If it's not difficult for you, can you please help me with one more. How can this time be changed? add hour year minute second? via UPDATE

pastel solar
slate swan
#
    @commands.command(name = "BD2")
    async def comand_BD2(self, ctx):

        cursor.execute("""CREATE TABLE IF NOT EXISTS cooldown(
            id INT,
            name TEXT,

            work_1 timestamp,
            work_2 int
            )""")

        for guild in self.client.guilds:
            for member in guild.members:
                if cursor.execute(f"SELECT id FROM cooldown WHERE id = {member.id}").fetchone() is None:
                    cursor.execute("INSERT INTO  cooldown VALUES (?, ?, ?, ?)", (f'{member.id}', f'{member}', member.joined_at, 1))
                else:
                    pass
                conn.commit()
        await ctx.send("ДА")

yes

#

OO

pliant pagoda
flint isle
#

lol i use github copilot and just got such a "useful" reccomendation for a command i was working on

#

lol such a mess it wouldve been

slate swan
#

Thank you. now the date looks human. however, is it possible to somehow add 1 hour to this value?

shrewd apex
#

copilot makes me feel everything i have learnt is useless ;-;

flint isle
shrewd apex
#

it's just recommendations the autocomplete is still cool

flint isle
pastel solar
slate swan
#

Not really. add hour minute second day to this value

shrewd apex
#

check Google there are tons of examples on datetime lib

hushed galleon
slate swan
winter gull
#

how to check when a channel is created in discord is in a specific category, discord.py?

paper sluice
#

!d discord.TextChannel.category

unkempt canyonBOT
rose ginkgo
#

!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
slate swan
paper sluice
slate swan
#

most probably just do ```py
if channel.category and channel.category.id == <the id of category you want to check>:

austere gust
#

Yo guys

wet ember
#

Yo?

austere gust
#

I made an embed message which can be sent by a command. and I want to make it if someone writes .addmdc the stuff they wrote will be added to the embed list

wet ember
#

I have no idea about that I’ve never seen that in a discord bot maybe someone else knows though

austere gust
#

so here is the list

#

and if I write .addmdc feri whynot 2022

#

and then resend the embed list it will appear

#

like Név Indok Dátum
feri whynot 2022

wet ember
#

Ik what you mean I just never seen something like that so you gotta ask someone else sorry

austere gust
#

okok, thanks anyways

wet ember
#

Np

slow fog
austere gust
torn sail
# austere gust so here is the list

you would have to clear the fields and add them back. you can get the names of the fields with list comprehension names = [field.name for field in embed.fields] after that you can iterate through that list and add the values with the names

torn sail
#

ok so you have to get the names of the existing fields

#

names = [field.name for field in embed.fields]

#

then you can iterate over it and add the fields back

#
names = [field.name for field in embed.fields]
for name in names:
    embed.add_field(name=name, value=<your value here>)
austere gust
torn sail
austere gust
#
@bot.command()
async def mdc(ctx):
    embed = discord.Embed(colour=0x0000FF)
    names = [field.name for field in embed.fields]
    for name in names:
    embed.add_field(name=name, value='asd')

    await ctx.send(embed=embed)```
#

should be like this?

slender mesa
#

what did i do wrong here

austere gust
#

I got lost

torn sail
#

so you can access the fields

austere gust
#
@bot.command()
async def mdc(ctx):
    embed = discord.Embed(colour=0x0000FF)
    embed.add_field(name='Név', value='name', inline=True)
    embed.add_field(name='Indok', value='reason', inline=True)
    embed.add_field(name='Dátum', value='date', inline=True)

    await ctx.send(embed=embed)```
#

this is the code I made

#

this will send the list

torn sail
#

oh the the field names are unchanging?

austere gust
#

they will be changing

#

I just put them in '' to make clear

#

well I wanna save them

torn sail
#

ok could you explain to me how you want the commands to work?

austere gust
#

Név Indok Dátum
feri whynot 2022
sanyi whynot2 2022

austere gust
#

and if I do .addmdc feri whynot 2022

torn sail
#

and if you do it again it puts the new words below the old ones?

austere gust
torn sail
#

alright

austere gust
#

so I want to save all the informations

#

which was added by .addmdc

torn sail
#

so you would need to save the embeds

#

you can use bot vars like this

wet ember
#

I need help this is my 2nd time ever making a discord bot and I don’t remember how to start it lmfao

torn sail
#
bot.embeds = {}

@bot.command()
async def command(ctx):
    embed = discord.Embed()
    bot.embeds[ctx.author.id] = embed  # i am storing by user id but you can do however you want
#

you understand this part?

austere gust
#
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='.')
@bot.command()
async def Hello(ctx):
    await ctx.reply('Hello') #u can make commands like this

bot.run('token')

@wet ember

austere gust
austere gust
torn sail
austere gust
#

the whole bot.embeds = {}

wet ember
#

stay

torn sail
unkempt canyonBOT
#

Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:

bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"

@bot.command()
async def get(ctx: commands.Context):
    """A command to get the current value of `test`."""
    # Send what the test attribute is currently set to
    await ctx.send(ctx.bot.test)

@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
    """A command to set a new value of `test`."""
    # Here we change the attribute to what was specified in new_text
    bot.test = new_text

This all applies to cogs as well! You can set attributes to self as you wish.

Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!

austere gust
slate swan
#

its a instance var that contains a dict as its value lol

austere gust
wet ember
austere gust
austere gust
wet ember
#

it wont stay running

torn sail
# austere gust ok I understand thanks

ok so now in the command where you create the embed you can do ctx.bot.embeds[ctx.author.id] = embed. so i am assigning the users id (can use whatever you want) to the embed you just created

wet ember
#

i got it

wet ember
#

is moderation commands easy to make?

torn sail
#

and then in the command where you update the embed, you can get the embed with embed = ctx.bot.embeds[ctx.author.id] .ctx.author.id can be replaced with whatever key you are using

austere gust
dapper thistle
#

What should I do if I get this error message when launching the bot?

wet ember
wet ember
#

anyone help me make warn command in pycharm seems hard

austere gust
wet ember
austere gust
torn sail
austere gust
#

my brain goes brr

torn sail
austere gust
#

oh

#

ctx.bot.embeds[ctx.author.id] = embed
and use this in which will add stuff to the embed?

torn sail
austere gust
torn sail
torn sail
#

it was just an example

austere gust
#

yep ik

#

I will add the embed fields

torn sail
#

so i think the name of your command was mdc

austere gust
#

yep

torn sail
#

just add ctx.bot.embeds[ctx.author.id] = embed to the end of the code for that command

austere gust
#
@bot.command()
async def mdc(ctx):
    embed = discord.Embed()
    bot.embeds[ctx.author.id] = embed  # i am storing by user id but you can do however you want
    embed.add_field(name='Név', value='name', inline=True)
    embed.add_field(name='Indok', value='reason', inline=True)
    embed.add_field(name='Dátum', value='date', inline=True)
    ctx.bot.embeds[ctx.author.id] = embed
    
    await ctx.send(embed=embed)```
#

like this?

torn sail
#

yes but you can remove bot.embeds[ctx.author.id] = embed # i am storing by user id but you can do however you want

austere gust
#

oh

#

okay

torn sail
#

ok so now lets move to addmdc

#

lets get the embed object with embed = ctx.bot.embeds[ctx.author.id]

austere gust
#

ok

torn sail
#

ok so how are you getting the new text in addmdc

#

so show code for addmdc

austere gust
#

I haven't done anything xd

torn sail
#

oh ok

wet ember
#

How to fix?

torn sail
#

have you ever used *args in discord bots

torn sail
wet ember
#

Oh I must have deleted it I had one and didn’t realize lol

austere gust
torn sail
austere gust
#

ofc I have used arguments

#

ban/kick command requires it

wet ember
#

What about now?

austere gust
#

and a lot others

austere gust
torn sail
#
@bot.command()
async def command(ctx, *args):
    print(args)

if we invoke it with .command a b c it will be a tuple of (a, b, c)

austere gust
#

I always tried with other ways

torn sail
austere gust
#

like
@bot.command()
async def command(ctx, asd):
print(asd)

wet ember
#

Yea

austere gust
#

use 3`

austere gust
wet ember
#

How to send in codeblock

torn sail
#

or `code`

#

alright so are the amount of embed fields always going to be 3?

austere gust
wet ember
#
    @command.has_permissions(ban_members=True)
    async def ban(ctx, member: discord.Member ,*, reason = "No reason provded"):
    await ctx.send(member.name + "Got banned from the server, Becasue" + reason)
    await memer.send("You got banned from the server, Because" + reason)
    await member.ban(reason=reason)```
#

thats my code i got error

torn sail
wet ember
#

wdym

austere gust
#
@bot.command()
@commands.has_permissions(ban_members=True)
async def ban(ctx, member: discord.Member, *, reason=None):
    if reason == None:
        await ctx.send('Please write a reason!')
        return
    await member.ban(reason=reason)
    await ctx.send(f"{member} was banned! Reason: {reason}")```
#

use this

wet ember
#

k ty

#

so what comand i type

#

.ban and then i ping the person?

austere gust
#

ban ping reason

torn sail
# austere gust correct

so we can go through the first second then third field and add the new values

fields = embed.fields
fields[0].value += name  # or whatever your variable is called
# now we can do the same thing for your other arguments
fields[1].value += ...
fields[2].value += ...
austere gust
#

if there is no reason, the bot will send 'Please write a reason'

wet ember
wet ember
#

in terminal

austere gust
wet ember
#

ban not fund

#

found omg i can type

austere gust
#

did you restart the bot

wet ember
#

i think so let me try again

austere gust
#

like this?

torn sail
wet ember
#

still saying it also the bot didnt go offline when i stopped it

torn sail
#

so now we have the fields but the old fields are still there.

torn sail
#

so now we will clear the old fields with embed.clear_fields() finally we will iterate through the fieldsvariable and add the fields back

for field in fields:
    embed.add_fields(name=field.name, value=field.value)
austere gust
#

I see

#
bot.embeds = {}

@bot.command()
async def mdc(ctx):
    embed = discord.Embed(colour=0x0000FF)
    embed.add_field(name='Név', value=namee, inline=True)
    embed.add_field(name='Indok', value=reason, inline=True)
    embed.add_field(name='Dátum', value=date, inline=True)
    ctx.bot.embeds[ctx.author.id] = embed
    
    await ctx.send(embed=embed)

@bot.command()
async def addmdc(ctx, namee, reason, date):
    embed = ctx.bot.embeds[ctx.author.id] 
    fields = embed.fields
    fields[0].value += namee  # or whatever your variable is called
    #now we can do the same thing for your other arguments
    fields[1].value += reason
    fields[2].value += date
    for field in fields:
        embed.add_fields(name=field.name, value=field.value)```
But at command **mdc** namee, reason, and date isn't defined
torn sail
wet ember
#

reason

austere gust
torn sail
slate swan
austere gust
austere gust
torn sail
#

try putting ‎‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎

#

i pasted some invisible characters

austere gust
#

sheesh

#

‎‎‏‏‎ ‎‏‏‎ ‎😂

torn sail
#

you only one of those probably

austere gust
#

I keep one only?

wet ember
#

can anyone help i have ban command i put the ban command and it said pls state reason i put it and it doesnt respond or ban them

austere gust
torn sail
austere gust
#

are we done?

torn sail
#

try it

cursive spindle
torn sail
cursive spindle
torn sail
torn sail
#

and how you invoked the command

austere gust
#

it is my discord id

torn sail
austere gust
#
bot.embeds = {}

@bot.command()
async def mdc(ctx):
    embed = discord.Embed(colour=0x0000FF)
    embed.add_field(name='Név', value='‏', inline=True)
    embed.add_field(name='Indok', value='‏', inline=True)
    embed.add_field(name='Dátum', value='‏', inline=True)
    ctx.bot.embeds[ctx.author.id] = embed
    
    await ctx.send(embed=embed)

@bot.command()
async def addmdc(ctx, namee, reason, date):
    embed = ctx.bot.embeds[ctx.author.id] 
    fields = embed.fields
    fields[0].value += namee  # or whatever your variable is called
    #now we can do the same thing for your other arguments
    fields[1].value += reason
    fields[2].value += date
    for field in fields:
        embed.add_fields(name=field.name, value=field.value)```
wet ember
#
    @commands.has_permissions(ban_members=True)
    async def ban(ctx, member: discord.Member, *, reason=None):
        if reason == None:
            await ctx.send('Please write a reason!')
            return
        await member.ban(reason=reason)
        await ctx.send(f"{member} was banned! Reason: {reason}")```
austere gust
cursive spindle
#

and what i must edit

austere gust
#

wdym

cursive spindle
#

for can make it works for dropdown menu

#

how i can make a dropdown menu works after the bot restart?

torn sail
#

it wont save after restarts

torn sail
wet ember
austere gust
torn sail
wet ember
austere gust
# wet ember didnt work

@bot.command()
@commands.has_permissions(ban_members=True)
async def ban(ctx, member: discord.Member, *, reason=None):
if reason == None:
await ctx.send('Please write a reason!')
return
await member.ban(reason=reason)
await ctx.send(f"{member} was banned! Reason: {reason}")

#

just paste this

wet ember
#

i did

#

@torn sail see mate gave me it so idk what that means

austere gust
#

@torn sail no errors now, but I ran mdc command again and still empty

torn sail
#

mdc isnt sending anything?

#

or addmdc

austere gust
#

brb

torn sail
wet ember
#

Naanmasyer got a working ban command you can just send me cause i have no idea how to fix mine

torn sail
#

well you gotta learn it. i wont just send the whole command

cursive spindle
#

i can add more fields in modal?

torn sail
unkempt canyonBOT
#

add_item(item)```
Adds an item to the view.

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

what are indents in commands?

torn sail
#

!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

wet ember
#

Don’t get it but ok

austere gust
#

addmdc just should add the arguments

paper sluice
austere gust
#

and when I write mdc, it should show up there

torn sail
#

!d discord.Message.edit

unkempt canyonBOT
#

await edit(*, content=..., embed=..., embeds=..., attachments=..., suppress=False, delete_after=None, allowed_mentions=..., view=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the message.

The content must be able to be transformed into a string via `str(content)`.

Changed in version 1.3: The `suppress` keyword-only parameter was added.

Changed in version 2.0: Edits are no longer in-place, the newly edited message is returned instead.

Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") instead of `InvalidArgument`.
slate swan
#

how do I run my bot so the bot will be online on Discord?

austere gust
#

I tried a way where I try to edit a message by its id

#

but if I restart the bot

#

then I have to run mdc again

#

and the message id will change so this method won't work

#

what do you think @torn sail

upper belfry
slate swan
upper belfry
#

Like if u wrote all ur code properly everything u have to do is run the program and u would see the bot online

slate swan
#

my bot is offline, how do i get it online?

upper belfry
slate swan
#

you code it, and run it on some device.

upper belfry
#

Question, Does Guild.get_role() Support Multiple Arguments?

wet ember
desert heart
#

!d discord.Guild.get_role

unkempt canyonBOT
#

get_role(role_id, /)```
Returns a role with the given ID.

Changed in version 2.0: `role_id` parameter is now positional-only.
upper belfry
cursive spindle
#

someone can help me?

upper belfry
#

I lack skill but I can try

cursive spindle
upper belfry
cursive spindle
upper belfry
cursive spindle
#
    ticket_category = await interaction.guild.get_channel(808888019159089152)
TypeError: object CategoryChannel can't be used in 'await' expression
wicked atlas
#

get_channel is not an async function, it does not need to be awaited

cursive spindle
#

in dropdown menu how i can if someone select something

#

bot create one channel. i mean something like if selectoption == 1 elif selectoption == 2 etc

prisma prism
#
@bot.command()
@commands.has_role("Admin")```
#

when I run this but I don't have the role

#

Ignoring exception in command info:

#

can I leave it like this? or do I need to add exception handling?

hushed galleon
#

you dont have to handle the check failure but your console will get cluttered with those tracebacks every time

prisma prism
#

Thanks

cursive spindle
#

then my cogs will not work

#

and yea

#

not working

#

Enable tracemalloc to get the object allocation traceback

paper sluice
#

huh?

slate swan
#

how do I combine this?

            await interaction.response.edit_message(content="", view=None)
            await interaction.response.edit_message(embed=discord.Embed(title="Authenticator", description="Authentication failed.", color=5793266))
paper sluice
#
            await interaction.response.edit_message(
embed=discord.Embed(title="Authenticator", description="Authentication failed.", color=5793266), 
view=None
)
cursive spindle
paper sluice
unkempt canyonBOT
#

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

cursive spindle
#
Exception has occurred: TypeError
object NoneType can't be used in 'await' expression
  File "C:\test\main.py", line 15, in load_extensions
    await bot.load_extension(f"cogs.{filename[:-3]}")
  File "C:\test\main.py", line 17, in <module>
    asyncio.run(load_extensions())
pliant pagoda
#
if member.reaction.add():
  await member.add_role (Role, reason=None, atomic=True)

Probably being really stupid right now but getting syntax error 'await is outside the function' and struggling to find the issue😅

paper sluice
paper sluice
#

probably indentation issue

pliant pagoda
# paper sluice can u send the code above it? you are using `await` outside an async function, i...
@bot.command()
async def verify(ctx):
    message = await ctx.send('React to verify!')
    await message.add_reaction('✅')

    def check(reaction, user):
        return reaction.emoji == '✅' and reaction.message == message

    reaction, user = await bot.wait_for('reaction_add', timeout=30.0, check=check)
    await ctx.send(f'Verified {user.mention} ✅')
  
if member.reaction.add():
  await member.add_role (Member,reason=None,atomic=True)
paper sluice
#
def foo():
  # inside function
# outside function
prisma prism
#

Hi Guys!
I am getting this error discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: can only concatenate str (not "Message") to str

#
@bot.command()
#@commands.has_role("Admin")
async def updateinfo(ctx):
    message1 = await ctx.send("woah, very nice!")
    try:
        msg = await bot.wait_for("message", timeout=300)
    except asyncio.TimeoutError:
        return await ctx.send("rip no hello :pensive:")
    await ctx.send("You enterd: " + msg)
#

This is the code giving me the error, could someone let me know what I am doing wrong?

slate swan
#

replace the last msg with msg.content

prisma prism
pliant pagoda
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

slate swan
paper sluice
gaunt mortar
#

Good evening, is it possible to gather the ID from a discord channel linked ? Like if in a message I type " #discord-bots ", is it possible to know the channel id from this ?

flat solstice
#

Can someone help me with making persistent dropdowns in Discord.py 2.0. I have looked at https://github.com/Rapptz/discord.py/blob/9fe19dcc6923e4b6133bdedafb33658bf37c9ab7/examples/views/persistent.py#L15-L29 and https://discordpy.readthedocs.io/en/latest/interactions/api.html?highlight=button#discord.ui.select and think I understand how to do it, sort of. The thing is I want to have both a non persistent and persistent dropdown which are identical, so my idea was make a non persistent dropdown then subclass and whack a custom_id onto the persistent one however it's not going so well as I'm getting a py ERROR:discord.app_commands.tree:Ignoring exception in command 'post' Traceback (most recent call last): File "C:\Users\Teagan\Documents\Coding\FAQ\env\lib\site-packages\discord\app_commands\commands.py", line 641, in _do_call return await self._callback(interaction, **params) # type: ignore File "C:\Users\Teagan\Documents\Coding\FAQ\main.py", line 92, in post await generate_dropdown( File "C:\Users\Teagan\Documents\Coding\FAQ\main.py", line 75, in generate_dropdown view.add_item(PersistentDropdown()) File "C:\Users\Teagan\Documents\Coding\FAQ\classes\dropdown.py", line 151, in __init__ super().__init__(custom_id="persistent_dropdown") TypeError: AlphaDropdown.__init__() got an unexpected keyword argument 'custom_id' This is the part of the code where the PersistentDropdown is declared`https://github.com/SnowyJaguar1034/ModMail-FAQ/blob/master/classes/dropdown.py#L149-L151 and this is where it's parent is declared https://github.com/SnowyJaguar1034/ModMail-FAQ/blob/master/classes/dropdown.py#L17

native wedge
flat solstice
prisma prism
#
    message6 = await ctx.send("Please specify the game version")
    try:
        GV = await bot.wait_for("message", timeout=20)
    except asyncio.TimeoutError:
        return await ctx.send("Aborting process due to no answer.")
#

I am sending a series of these messages asking a sure to input some data

#

how do I get which user entered the data?

#

like the username/discord ID

flat solstice
prisma prism
#

thank you

native wedge
#

how do i convert text commands to slash commands easily

slate swan
flat solstice
slate swan
#

whats the easiest way to delete the last message in a specific channel

patent lark
#

!d discord.TextChannel.purge

unkempt canyonBOT
#

await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=None, bulk=True, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.

You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own. The [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.

Changed in version 2.0: The `reason` keyword-only parameter was added.

Examples

Deleting bot’s messages...
patent lark
#

@slate swan ^

slate swan
#

oh nice thanks

shadow vigil
#

!e

print(dir(object))
# and
help(object)
unkempt canyonBOT
#

@shadow vigil :x: Your eval job has completed with return code 1.

001 | ['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
002 | Traceback (most recent call last):
003 |   File "<string>", line 3, in <module>
004 | NameError: name 'help' is not defined
shadow vigil
shadow vigil
slate swan
#

it does lol

shadow vigil
#

bruh

#

no it doesn't

#

!e help()

unkempt canyonBOT
#

@shadow vigil :x: Your eval job has completed with return code 1.

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

you mean the help command the python interpreter has?

shadow vigil
slate swan
#

no its a command

#

!e

__import__("os").system("help")
unkempt canyonBOT
#

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

[No output]
slate swan
#

doesnt really show but you get the gist

shadow vigil
#

bruh. i am not going to arg with that

shadow vigil
slate swan
#

what are you even referring to at this point

shadow vigil
#

i am saying python discord bot doesn't support the help function in the eval command

slate swan
#

How can I add command description?

shadow vigil
shadow vigil
slate swan
#

never heard of it nor do i care about it lmao

shadow vigil
#

okay. we're off topic

slate swan
#

use object.__doc__ or inspect.getdoc instead

pure peak
#

!e a =1 b = 2 print(a+b)

drifting arrow
#

ImportError: cannot import name 'PartialMessageable' from 'discord.channel' (C:\Users\Name\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\channel.py) what causes this? it was working yesterday and nothing has changed..

#

nvm. I reloaded my cmd prompt and suddenly it's working again..

#

grumbles

hardy yoke
haughty echo
#

raise CommandInvokeError(exc) from exc
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: unsupported operand type(s) for -: 'float' and 'datetime.datetime'

slate swan
#

How am I getting the error Command raised an exception: AttributeError: 'str' object has no attribute 'url' ? but when I ran the bot through vsc it wasn't an error

#

changing it to
icon_url=str(client.user.avatar_url)
would fix it no?

#

hov to change it to nick#0100

vocal snow
#

Prefix the string literal with f

slate swan
slate swan
vocal snow
#

Code?

slate swan
#

well the error is on this line

embed.set_author(name=f"{username}'s Grail", icon_url=ctx.author.avatar.url)
#

Command raised an exception: AttributeError: 'str' object has no attribute 'url'

vale wing
#

@slate swan what library do you use

slate swan
vale wing
#

Version?

slate swan
#

1.7.3

vocal snow
#

!d discord.User.avatar

unkempt canyonBOT
#

property avatar```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Asset "discord.Asset") for the avatar the user has.

If the user does not have a traditional avatar, `None` is returned. If you want the avatar that a user has displayed, consider [`display_avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.display_avatar "discord.User.display_avatar").
vale wing
#

It's ctx.author.avatar_url for that version

paper sluice
slate swan
#

what's the newest version?

#

I coulda swore there was like 2.0

vale wing
#

2.0 alpha

slate swan
#

How do I install that version

vale wing
#

You can install it from github

slate swan
#

How so?

vale wing
#

Search for instructions in pins

slate swan
#

I'm not very familiar with git.

vale wing
#

Common pip freeze > requirements.txt

slate swan
#

know you how to add bold to reason?

paper sluice
slate swan
paper sluice
#

no, ur terminal

slate swan
paper sluice
slate swan
slate swan
vale wing
#

@slate swan wait do you write your requirements.txt manually 😳

vale wing
#

Wtf

slate swan
#

I literally have a requirements.txt file 😭

paper sluice
vale wing
#

I would consider it normal if you manually wrote pyproject.toml

#

But requirements

#

Is not really meant to be written manually

slate swan
#

how else do I do it then

vale wing
#

There's pip freeze > requirements.txt that will write all your requirements to the file

slate swan
vale wing
#

However you should only use it with venv

slate swan
#

yea I dont wanna do that

#

isn't there like an easy way to install it

vale wing
#

Venv is an easy way cmon

slate swan
#

I got no clue how

vale wing
#

Another option is to use some system like poetry

slate swan
#

I've like never used git or heroku

vale wing
#

It's not related to git anyhow

vale wing
slate swan
#

vscode and thonny

vale wing
#

Kinda abandoned that tutorial sadly

slate swan
#

ive never used venv's

#

what are they

paper sluice
#

!venv

unkempt canyonBOT
#

Virtual Environments

Virtual environments are isolated Python environments, which make it easier to keep your system clean and manage dependencies. By default, when activated, only libraries and scripts installed in the virtual environment are accessible, preventing cross-project dependency conflicts, and allowing easy isolation of requirements.

To create a new virtual environment, you can use the standard library venv module: python3 -m venv .venv (replace python3 with python or py on Windows)

Then, to activate the new virtual environment:

Windows (PowerShell): .venv\Scripts\Activate.ps1
or (Command Prompt): .venv\Scripts\activate.bat
MacOS / Linux (Bash): source .venv/bin/activate

Packages can then be installed to the virtual environment using pip, as normal.

For more information, take a read of the documentation. If you run code through your editor, check its documentation on how to make it use your virtual environment. For example, see the VSCode or PyCharm docs.

Tools such as poetry and pipenv can manage the creation of virtual environments as well as project dependencies, making packaging and installing your project easier.

Note: When using Windows PowerShell, you may need to change the execution policy first. This is only required once:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

slate swan
#

git+https://github.com/Rapptz/discord.py@2.0.0a4396+g9fe19dcc
can I not do this?

#

the version I have installed is, 2.0.0a4396+g9fe19dcc

slate swan
#

the version is not found lmao

vale wing
#

This basically points to version of a repository per certain commit

#

Copy the latest version

slate swan
#

What is it though

vale wing
#

Same link but without @ and everything after it

slate swan
#

and that will install which evrsion

#

why does my discord python bot keeps responding to every single message?
python discord
error code:
Ignoring exception in on_ready
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "/Users/bai/Documents/Personal Things/Do not delete/Only viewable by me/Aww Pika Discord Bot/aww pika discord bot.py", line 58, in on_ready
send_message.start()
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/tasks/init.py", line 205, in start
raise RuntimeError('Task is already launched and is not completed.')
RuntimeError: Task is already launched and is not completed.
Ignoring exception in on_message
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "/Users/bai/Documents/Personal Things/Do not delete/Only viewable by me/Aww Pika Discord Bot/aww pika discord bot.py", line 216, in on_message
await message.channel.send(random.choice(greetings))
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/abc.py", line 1065, in send
data = await state.http.send_message(channel.id, content, tts=tts, embed=embed,
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/http.py", line 248, in request
raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions

placid skiff
#

probably because you have an on_message event

slate swan
#

i do, but i only want it to respond when user message contains "hello", and nothing else

vocal snow
#

could you send your code?

slate swan
#

why does it respond even when hello isnt even included in message?

#

sure

#

here's the code:

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

    if 'hello' in message.content.lower():
        await message.channel.send("Hello")```
vocal snow
#

that's not the code I'm seeing in the error

#

await message.channel.send(random.choice(greetings))

slate swan
#

yeah its just a variable wait

vocal snow
#

and what's in send_message?

#

don't start the task in on_ready... it can fire more than once

slate swan
#

here's the code:

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

    greetings = ['hello',
                 'hi',
                 'hii',
                 'hey',
                 'hewwo']

    if 'hello' in message.content.lower():
        await message.channel.send(random.choice(greetings))
        time.sleep(1)
        await message.channel.send(random.choice(cq))```
#

this is the code

vocal snow
#

use asyncio.sleep, not time.sleep

slate swan
#

and what else?

slate swan
#

then how do i start it?

vocal snow
#

not in on_ready

#

it doesn't need to be in an event or an async function

slate swan
#

ive got this error

#
Traceback (most recent call last):
  File "main.py", line 8, in <module>
    client = commands.Bot(command_prefix ='!')
TypeError: __init__() missing 1 required keyword-only argument: 'intents'

this is error

#

it cannot be in @client.event ? then how?

#

help

vocal snow
#

call it after defining the task if you want

placid skiff
slate swan
#

sorry im not so good at this

placid skiff
#

cuz d.py is an async package, time.sleep() will make the whole code to stop, asyncio.sleep() will stop only the block of code where it is executed

slate swan
#

why not working unban command?

#

and what should i import for asyncio.sleep?

vocal snow
#

asyncio? lol

placid skiff
vocal snow
slate swan
vocal snow
#

you sure you added a space there?

slate swan
#

+unban TheRezzaz#1876
yes

placid skiff
#

BanEntry is a class

#

not a method

#

!d discord.BanEntry

unkempt canyonBOT
#

class discord.BanEntry```
A namedtuple which represents a ban returned from [`bans()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.bans "discord.Guild.bans").
slate swan
#

what I need to scribble for it to work

placid skiff
#

so you should do ctx.guild.bans()

#

and most of all it is an async iterator, so it works differently

slate swan
#

Traceback (most recent call last):
File "main.py", line 8, in <module>
client = commands.Bot(command_prefix ='!')
TypeError: init() missing 1 required keyword-only argument: 'intents'

#

anyone know error?

#

from keep_alive import keep_alive
import discord
import os
from discord.ext import commands
client = discord.Client()

client = commands.Bot(command_prefix = '!')
client.remove_command('help')
my_secret = os.environ['token']

placid skiff
#

!d discord.Guild.bans read here

unkempt canyonBOT
#

async for ... in bans(*, limit=1000, before=..., after=...)```
Retrieves an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") of the users that are banned from the guild as a [`BanEntry`](https://discordpy.readthedocs.io/en/latest/api.html#discord.BanEntry "discord.BanEntry").

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

Changed in version 2.0: Due to a breaking change in Discord’s API, this now returns a paginated iterator instead of a list.

Examples

Usage...
placid skiff
slate swan
#

client = discord.Client(intents=discord.Intents.default())
this right?

placid skiff
#

Bot is a Client subclass

#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.

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

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

Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client"), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") and is automatically set upon instantiating the class.

async with x Asynchronously initialises the bot and automatically cleans up.

New in version 2.0.
slate swan
#

also

#
from keep_alive import keep_alive
import discord
import os
from discord.ext import commands


intents = discord.Intents.default()
client = commands.Bot(command_prefix = '!')
client.remove_command('help')
my_secret = os.environ['token']

placid skiff
#

you will have to add the intents in your Bot constructor

slate swan
#

dev portal?

placid skiff
#

no, you have only the default, you will have to add them into the constructor D_D

slate swan
#

!intents read this

unkempt canyonBOT
#

Using intents in discord.py

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

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

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

from discord import Intents
from discord.ext import commands

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

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

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

slate swan
#

Warning (from warnings module):
File "/Users/bai/Documents/Personal Things/Do not delete/Only viewable by me/Aww Pika Discord Bot/aww pika discord bot.py", line 606
asyncio.sleep(3)
RuntimeWarning: coroutine 'sleep' was never awaited

#

and stop naming your Bot as client.

slate swan
#

like this?
await asyncio.sleep(3)

placid skiff
# slate swan dev portal?
class MyClass():
   def __init__(smth): #constructor method, called when an instance of a class is created
    self.smth = smth

constructor = MyClass("abc")

That is a constructor

patent lark
placid skiff
patent lark
slate swan
slate swan
patent lark
slate swan
patent lark
#

yeah

placid skiff
patent lark
#

discord.Client() = "client" as it is a Client instance. discord.ext.commands.Bot = "bot" as it is your Bot instance

paper sluice
#

square = Rectangle() 😳

slate swan
slate swan
#

code?

slate swan
#

its supposed to only reply when i say hello

patent lark
#

in that code, you're using time.sleep()

slate swan
#

i changed that already

#

but still no work

patent lark
#

then dont redirect us to that code if its no longer up to date

slate swan
#

you need to use wait_for then, asyncio.sleep stops the function process for the seconds you mention in there, not wait for a message

#

here's the code:

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

    greetings = ['hello',
                 'hi',
                 'hii',
                 'hey',
                 'hewwo']

    if 'hello' in message.content.lower():
        await message.channel.send(random.choice(greetings))
        await asyncio.sleep(1)
        await message.channel.send(random.choice(cq))```
slate swan
#

!d discord.Client.wait_for read the example given below

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.10)"). 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.10)") 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.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
patent lark
#

cq isnt defined

paper sluice
slate swan
slate swan
patent lark
#

it doesnt wait one second?

paper sluice
slate swan
#

here's the code:

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

    greetings = ['hello',
                 'hi',
                 'hii',
                 'hey',
                 'hewwo']

    cq = ['What is your favourite colour?',
          'What is your name?',
          'Where are you from?',
          'What is your favorite food?',
          'Hows life going?',
          'Hows your day?',
          'How are you doing?',
          'Do you like going outside?',
          'Do you like sports?',
          'Are you a boy or a girl?',
          'Do you like watching YouTube?',
          'Do you like watching TV?']

    if 'hello' in message.content.lower():
        await message.channel.send(random.choice(greetings))
        await asyncio.sleep(1)
        await message.channel.send(random.choice(cq))```
#

this is full code*

patent lark
#

im confused

#

whats your goal here? or whats your issue?

#

what is not happening that you want to happen?

slate swan
#

i want the bot to ONLY respond when the message contains the word "hello"
for example, "hello ansdlkdn"

and i dont want it responding when it doesnt contain that word...
(check my image)

#

this is what i want the bot to do, and its not working... :/

#

look at this image i sent here, it doesnt contain "hello"

#

so that bot shouldnt respond...

#

is there any fix for this?

patent lark
#

im gonna be honest, unless there is code i am not seeing, or there is something i dont understand. your code should be working the way you want it to.

paper sluice
#

did you restart the bot after making the changes?

patent lark
#

yeah that would be the only reason it isnt working

slate swan
patent lark
#

do you have more than one on_message event?

slate swan
#

no i dont

patent lark
#

honestly.

#

i have no idea lmao.

#

this is like the first time ive not been able to help someone, that code should run as intended, unless its being manipulated in some other part of your program somehow.

#

make sure that is actually your updated code, restart your bot once updated, make sure you only have one instance of the bot running.

slate swan
#

yes its only one instance and its restarted every time i update it

patent lark
#

@desert heart

patent lark
slate swan
slate swan
slate swan
#

dude

#

Finally back home :)

slate swan
#

idk im clueless

slate swan
slate swan
slate swan
#

I just told you to try but nvm 😔

#

!e

if 'hello' in [1,2,3,"hello"]:
   print(True)
elif "hello" in [1,2,3,"hello"]:
   print(False)
unkempt canyonBOT
#

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

True
slate swan
slate swan
slate swan
#

if 'hello' in message.content.lower(): -> if "hello" in message.content.lower():

slate swan
slate swan
#

!e

unkempt canyonBOT
#
Missing required argument

code

slate swan
#

!e
if "hello" in [1,2,3,'hello']:
print(True)

unkempt canyonBOT
#

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

True
slate swan
#

!e

if 'e' in "hello":
  print("test")```
unkempt canyonBOT
#

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

test
slate swan
#

how do quotes matter dude ¯_(ツ)_/¯

#

nvm

paper sluice
#

wtf are you guys doing?

slate swan
#

Ye they dont

#

That's not the issue..

slate swan
slate swan
#

i was wrong lmao

#

who needs help

#

@slate swan

#

PIKA what's ur issue

paper sluice
#

@slate swan delete your bot, make a new and paste the code :p

slate swan
#

nice

#

bot is responding to every message he send, but he want his bot to respond when there is hello in it

#

Ok wait

slate swan
paper sluice
#

!paste @slate swan can u send ur whole code ( hide token )

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.

slate swan
#
async def on_message(m):
   if m.content.lower() == "hello":
         await m.channel.send("hi")
#

!e

def check(content: str) -> bool:
   return "no" in content
print(check("uwuhellouwuwuwuwu"))

that works perfectly fine

unkempt canyonBOT
#

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

True
slate swan
#

and lower is a callable

slate swan
paper sluice
#

wish i could do that

slate swan
#

dont

#

you guys getting sleep?

#

smh

#

absolutely not

maiden fable
slate swan
maiden fable
paper sluice
slate swan
slate swan
slate swan
#

I sleep at 11 and wake at 5:30

paper sluice
#

i haven't slept before like 1 for about 5 months now

slate swan
#

good boi.

slate swan
desert heart
paper sluice
patent lark
slate swan
slate swan
paper sluice
#

sleep = waste of time

slate swan
paper sluice
#

ok not that extreme, but like couple hrs less sleep than i need rn

slate swan
#

I swear if I could sleep properly, I'd never get out of my bed unless I was sure that I got 12 hours of sleep

paper sluice
#

do u have insomnia?

slate swan
paper sluice
#

ah sad

robust fulcrum
#

Hi

placid skiff
#

Hi ash

slate swan
robust fulcrum
#

😴

slate swan
#

Hi

paper sluice
#

hi 👋

slate swan
#

Ded chat

spring flax
#

can someone please tell me why this error is coming ```py

class Timeouts(commands.Cog):
def init(self, bot):
self.bot = bot
self.timed_out = []

async def get_timeouts(self):
    await self.bot.wait_until_ready()
    guild = self.bot.get_guild(619762818266431547)
    timed_out_members = [*filter(lambda x: x.current_timeout, guild.members)]
    self.timed_out.extend([member.id for member in timed_out_members])
    print("Completed getting timeouted members. Bot is ready")

        
        
@commands.Cog.listener()
async def on_member_update(self, before: disnake.Member, after: disnake.Member):
    if before.current_timeout is None and after.current_timeout is not None:
        self.timed_out.append(after.id)

    if before.current_timeout is not None and after.current_timeout is None:
        if before in self.timed_out:
            self.timed_out.remove(before.id)

    else:
        return

@commands.command()
@needed_check()
async def timeouts(self, ctx):
    members = []
    members.extend([ctx.guild.get_member(id) for id in self.timed_out])

    if not self.timed_out:
        description = "No members are currently on timeout"
    else:
        description = "\n".join(
            [
                f"{member.mention} ({str(member)} is on timeout until <t:{int(member.current_timeout.timestamp())}>)"
                for member in members
            ]
        )
#

it raises ```
f"{member.mention} ({str(member)} is on timeout until <t:{int(member.current_timeout.timestamp())}>)"
File "/pufferpanel/cog/timeouts.py", line 43, in <listcomp>
for member in members
AttributeError: 'NoneType' object has no attribute 'timestamp'

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

Traceback (most recent call last):
File "/pufferpanel/.local/lib/python3.10/site-packages/disnake/ext/commands/bot_base.py", line 570, in invoke
await ctx.command.invoke(ctx)
File "/pufferpanel/.local/lib/python3.10/site-packages/disnake/ext/commands/core.py", line 920, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/pufferpanel/.local/lib/python3.10/site-packages/disnake/ext/commands/core.py", line 178, in wrapped
raise CommandInvokeError(exc) from exc
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'timestamp'

slate swan
#

????

paper sluice
# slate swan

type exit() then type py -m pip install git+https://github.com/Rapptz/discord.py

slate swan
#

got this problems

#

how do I resolve it?

#

Someone said that i should type py -m pip install git+https:// github. com/Rapptz/discord.py

#

and then it resolved but if i open up the code by folder in VSC I got this errors

heady sluice
#

python interpreter?

#

oh old case

arctic nacelle
slate swan
#

My bot doesw task for like 34 hours and then it stops idk why, it stays online, doesnt give error, just stops

heady sluice
#

when you use pip install discord in terminal you will see requirement already satisfied and the python version

#

I'm too dumb to check it otherways

#

then you do ctrl shift p, type select python interpreter and choose the right one

arctic nacelle
heady sluice
arctic nacelle
heady sluice
#

I don't know what to say

#

why do you need those

heady sluice
#

is there really a difference

slate swan
#

should i choose the first one?

#

the recommended?

arctic nacelle
vale wing
arctic nacelle
#

maybe your discord was installed in the global python.

slate swan
#

i still have these issues

arctic nacelle
arctic nacelle
slate swan
#

thanks :D

#

resolved

arctic nacelle
#

yes...

slate swan
#

now how do I start up the bot? So the bot go online in my discord server?
I dont remember the command tho

#

lol

arctic nacelle
#

btw, u r using virtual env, but maybe u dont know how it works yet! 😐

arctic nacelle
slate swan
#

alright, thanks

#

yeye

heady sluice
#

remember that functions are called functions

#

or methods bru

vale wing
#

Procedures 😳

vale wing
arctic nacelle
heady sluice
#

that contain weird stuff

arctic nacelle
#

Why is reactions not available in these channels! -_-

heady sluice
vale wing
#

The function itself isn't really a variable, variable contains pointer to the function or smth, anyway forget me I am not into that stuff

slate swan
#

@arctic nacelle i got this errors again...
so i tried that you said to me and got this

heady sluice
vale wing
#

Is python extension installed

heady sluice
#

!e print(print)

unkempt canyonBOT
#

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

<built-in function print>
heady sluice
#

function Object

#

objects are stored in vars

vale wing
#

Had to dir

#

Does it inherit from object

#

!e print(issubclass(print.class, object))

unkempt canyonBOT
#

@vale wing :white_check_mark: Your eval job has completed with return code 0.

True
vale wing
#

Ok it inherits

heady sluice
#

python (or programming in general) is dope

vale wing
#

What is dope idk english

heady sluice
#

cool

vale wing
#

Drug?

arctic nacelle
#

opposite of flop

upper belfry
#

Im trying to make a command that is only useable by people that have the roles like the Mod, Admin, etc

arctic nacelle
vale wing
#

Google translate said it's drug lmfao

#

Anyway thanks

vale wing
#

!d discord.ext.commands.has_any_role

unkempt canyonBOT
#

@discord.ext.commands.has_any_role(*items)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has **any** of the roles specified. This means that if they have one out of the three roles specified, then this check will return True.

Similar to [`has_role()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.has_role "discord.ext.commands.has_role"), the names or IDs passed in must be exact.

This check raises one of two special exceptions, [`MissingAnyRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") if the user is missing all roles, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").

Changed in version 1.1: Raise [`MissingAnyRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
vale wing
#

!d discord.ext.commands.Cog.cog_check iirc for cogs

unkempt canyonBOT
#

cog_check(ctx)```
A special method that registers as a [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") for every command and subcommand in this cog.

This function **can** be a coroutine and must take a sole parameter, `ctx`, to represent the [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context").
upper belfry
vale wing
#

Yes

#

It's *items

upper belfry
#

oh ok great

vale wing
#

Arglist

upper belfry
#

thanks

upper belfry
#

How to make a ban list for the ban command so for example whenever I ban someone he will be added into a list of the banned people so if I wanted to unban them I would just have to write ?unban <id of banned member>

#

i did a ban command already

upper belfry
#

and a unban command

vale wing
unkempt canyonBOT
#

async for ... in bans(*, limit=1000, before=..., after=...)```
Retrieves an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") of the users that are banned from the guild as a [`BanEntry`](https://discordpy.readthedocs.io/en/latest/api.html#discord.BanEntry "discord.BanEntry").

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

Changed in version 2.0: Due to a breaking change in Discord’s API, this now returns a paginated iterator instead of a list.

Examples

Usage...
vale wing
#

For unban command you can just typehint with discord.User I think although I am not sure about that

slate swan
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: type object 'datetime.datetime' has no attribute 'timedelta'

@bot.command()
async def timeout(ctx, member: discord.Member, minutes: int=None):

        duration = datetime.timedelta(minutes=minutes)
        await member.timeout_for(duration)

        embed=discord.Embed(description=f"", color=discord.Colour.blurple())
        embed.set_author(name=f"Successfully timedout {member.name} for {minutes} minutes", icon_url="https://cdn.discordapp.com/emojis/951165672031940668.gif?size=96&quality=lossless")

        await ctx.reply(embed=embed)    ```
loud junco
#

what library do i need

#

to record time

#

i want to make a farm command
so when they plant something
after 5 mins it will grow

arctic nacelle
#

!e ```py
import datetime
print(datetime.timedelta)

unkempt canyonBOT
#

@arctic nacelle :white_check_mark: Your eval job has completed with return code 0.

<class 'datetime.timedelta'>
#
Missing required argument

code

#
Command Help

!eval <code, ...>
Can also use: e

*Run Python code and get the results.

This command supports multiple lines of code, including code wrapped inside a formatted code block. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.

If multiple codeblocks are in a message, all of them will be joined and evaluated, ignoring the text outside of them.

We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!*

loud junco
#

what library do i need
to record time
i want to make a farm command
so when they plant something
after 5 mins it will grow

robust fulcrum
#

Hi

tacit aspen
#

guys can u suggest a good source to learn about discord api
specifically speaking:
cogs,intents and discord2.0 with good examples

kindred oracle
#

Hey I have a few slash commands that I want to be able to pass arguments to, and possibly to list possible arguments, is this possible somehow? (I use discord.py v2)
current example: ```py
@client.tree.command()
async def hello(interaction: discord.Interaction):
await interaction.response.send_message(f"Hello, {interaction.user.mention}")

#

but I don't really find any example for arguments yet

#

maybe the extras thing?

loud junco
loud junco
robust fulcrum
maiden fable
unkempt canyonBOT
#
I'm sorry Dave, I'm afraid I can't do that.

No documentation found for the requested symbol.

tacit aspen
tacit aspen
#

yes

loud junco
#

like a mini game

tacit aspen
#

u mean with cogs and stuff?

#

or in general

vocal snow
maiden fable
unkempt canyonBOT
#

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

Sleep until a specified time.

If the time supplied is in the past this function will yield instantly.

New in version 1.3.
tacit aspen
loud junco
#

but im not trying to sleep

#

im trying to make a time recorder

vocal snow
# tacit aspen yes i used them in school while learning java

A cog is a subclass of discord.ext.commands.Cog. You can group multiple commands in one for categorisation. You add cogs with Bot.add_cog.
Extensions are python modules which have a function called setup which is called when the extension is loaded. Extensions can be loaded with Bot.load_extension