#discord-bots

1 messages ยท Page 747 of 1

vale wing
#

Oh no requests

small igloo
vale wing
#

Just saying their API might be very slow which may cause the blocking of the whole bot, better use aiohttp

vale wing
#

You could use nested list

if len(r) > 0:
    voted_usernames = [i['username'] for i in r]
#

And then enumerate it to add fields

small igloo
vale wing
#

This is good

small igloo
vale wing
#

Also have you tried printing the response?

small igloo
vale wing
#

@zealous dagger

pip install git+https://github.com/Rapptz/discord.py```
Iirc
#

Add -U flag as well

small igloo
#

@vale wing

@bot.command()
async def last1000voters(ctx):
    name = ctx.author.id
    if name == 828182019841327115:
        async with aiohttp.ClientSession() as cs:
            async with cs.get('https://top.gg/api/bots/879000165757890570/votes') as r:
                res = await r.json()
                le = len(list(res))
                em = discord.Embed(title="last 1000 voters", description="", colour=ctx.author.color)
                for i in range(le):
                    em.add_field(name=str(i + 1), value=f'{res["username"][i]}', inline=False)
                await ctx.send(embed=em)
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 'username'

waht

vale wing
#

@small igloo print the res

small igloo
vale wing
#

Also what is that thing

res['username'][i]```
#

That's the error

small igloo
#

is dat will giev a list of usernames or just a single one

vale wing
small igloo
vale wing
#

Lmao

small igloo
vale wing
#

You forgot Authorization header

small igloo
vale wing
#
async with aiohttp.ClientSession(headers={'Authorization': 'top.gg token'}) as session:
    ...```
slate swan
#

my bro tried

slate swan
#

still need help T^T

final iron
slate swan
#

What does that meam?

#

I can't use list[:-5]?

vale wing
#

Better name the variable differently, list is a builtin

#

You are trying to make a function to provide to command_prefix param right?

slate swan
#

i was trying to do jackpot but why it only gives "not jackpot"

#

it was for bot ofc

#

for example ๐ŸŒ, ๐ŸŒ, ๐ŸŒ but it prints not jackpot

vale wing
#

Because maybe your condition is wrong

slate swan
#

and how to fix it

#

ive been stuck with this like for 30 mins already

vale wing
#

When do you want not jackpot to occur

#

When none of these match?

slate swan
#

nono

#

when 2 matches it says not jackpot but when 3 matches it still says not jackpot

vale wing
#

Also your second condition is weird, I am sure you can't use it like this

#

!e

print('s1' == 's2' == 's3')```
unkempt canyonBOT
#

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

False
vale wing
#

Yeah

slate swan
#

so if s1 == s1 == s1

#

i had 3 bananas matching and it gives me not jackpot brohcat

#

oh

vale wing
#

This a weird lol I got confused

#

Ok forget it it's weird you should compare it using any or or

slate swan
#

ok

vale wing
#
if not any([
    final[0] == final[1],
    final[1] == final[2],
    final[0] == final[2]]):
    print('not jackpot')```
round yarrow
#

@client.command()
async def warn(ctx, member: discord.Member = None, *, reason=None):
    id = member.id
    if collection.count_documents({"memberid": id}) == 0:
        collection.insert_one({"memberid": id, "warns": 0})
    if reason == None:
        await ctx.send("Please mention a reason!")
    elif member == None:
        await ctx.send("Please mention a user!")
    warn_count = collection.find_one({"memberid": id})

    count = warn_count["warns"]
    new_count = count + 1
    collection.update_one({"memberid": id}, {"$set": {"warns": new_count}})
    await ctx.send(
        f"Warned {member} for {reason}. They now have {new_count} warnings.")```

Error : Ignoring exception in command warn:
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 179, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 31, in warn
    id = member.id
AttributeError: 'NoneType' object has no attribute 'id'
tender estuary
round yarrow
#

Its a basic warn with mongodb

tender estuary
#

you have to define it in the command parameters i guess

#
async def test(member : discord.Member)
#

did you do this?

vale wing
tender estuary
round yarrow
vale wing
#

I don't remember, lemme search

tender estuary
#

You can't warn no one

#

There got to be a person right

round yarrow
#

Does py elif member == None: await ctx.send("Please mention a user!")

#

this work if i remove the None

tender estuary
#

That is error handling

vale wing
#

It has to be the first then

tender estuary
#

use on_command_error

round yarrow
#

oh yeah i can do that

#

alright then, lemme try removing None

vale wing
#

But don't set default value to necessary argument for god's sake

round yarrow
#

thanks for the help both of you!

tender estuary
#

๐Ÿ˜„

vale wing
#

!d discord.on_voice_state_update @hidden hazel

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
vale wing
#

Could you show code?

left crater
#

im using replit cuz im not using my home computer

#

what happend

slate swan
#

You used replit, this happened.

#

One reason why you should not use replit:

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.

#
    @config.command()
    async def unwhitelist(self,ctx, channel: discord.TextChannel = None):
        if channel == None:
            channel = ctx.channel
        unwhitelist = {"channel" : channel.id}
        if not unwhitelist:
            return await ctx.send("This channel is not whitelisted")
        await self.coll.delete_one(unwhitelist)
        await ctx.send(f" Unwhitelisted <#{channel.id}> for typeracer")

Even though the channel isnt in my mongo collection it still says Unwhitelisted <#{channel.id}> for typeracer why?

hard trail
#

Just wait a few hours

#

You just ran the bot too much

#

In the mean time you can keep on coding

slim ibex
#

Send the code

#

Is that the whole listener?

tough lance
#

listener()

slim ibex
#

^

prime marten
#

Hi, so i have an economy bot with a deposit command (sqlite3)
Any idea on how to put a limit that your bank balance cannot be more than say 500k?

slim ibex
#

you could, in the command check if the users balance is 500k or more

#

But that wouldnโ€™t be the best because that could mean the balance COULD go over 500k in the database

#

and we want the table to be created with a maximum of 500k for the balance

tough lance
#

Just check when the money is being deposited

final iron
#

^

steel void
#

hello

@tasks.loop(minutes=1)
async def war_update_time(minutes=1):
    hours, remainder = divmod(int(war.end_time.seconds_until), 3600)
    minutes, seconds = divmod(remainder, 60)
    channel = bot.get_channel(931185915932577862)
    try:

        await channel.edit(name="test55")
    except Exception as e:
        print(traceback.format_exc())
war_update_time.start()
#

im trying to make it where the bot changes it name every 10m in the long run but every 1m now for I can test if the change work

#

but it seems to not be working any idea

#

i am aware of the discord rate lmimt being of 10m

vale wing
#

Have you checked if the loop works

final iron
#

Did you start the loop?

steel void
#

the loop work for this other code where i need a loop at

#

yh the loop starts with war_update_time.start()

vale wing
#

Discord sometimes has issues with renaming channels

#

Maybe that's a ratelimit indeed

sacred sigil
#

what event do I use to check if a member has changed their status?

vale wing
#

Not sure

steel void
#

its not cause the channel has never changed

#

the name

spring flax
#
@bot.event
async def on_member_update(before : disnake.Member, after:disnake.Member):
    if after.roles != before.roles:
        guild = before.guild
        channel = disnake.utils.get(guild.channels, id=930112620407697429)
        role_id_list = #a role list
        role = set(before.roles) - set(after.roles)
        if isinstance(role, guild.premium_subscriber_role):
            if booster_color := disnake.utils.find(lambda r: r.id in role_id_list, after.roles):
                await member.remove_roles(booster_color, reason="User stopped boosting the server")
                embed = disnake.Embed(description=f"{member.mention} {str(member)}  Stopped boosting the server!\nRemoved role: {booster_color.mention}")
                embed.set_thumbnail(url=after.avatar.url)
                embed.set_footer(text=f"{after.id}")
                await channel.send(embed=embed)

Does anyone see anything wrong here?

vale wing
#

Nvm

#

Wrong one

spring flax
#

!d discord.on_user_update

unkempt canyonBOT
#

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

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

โ€ข avatar

โ€ข username

โ€ข discriminator...
spring flax
#

this, perhaps

sacred sigil
#

on_member_update or on_user_update?

vale wing
#

For some reason it does have a status

honest vessel
#

member != user

#

member -> serverwise, user -> personalprofile

vale wing
#

I don't think it matters in terms of status

spring flax
#

oh wait status as in idle, do not disturb?

vale wing
#

So the status update seem to be unavailable in master

#

And in stable there is

#

๐Ÿคฏ

spring flax
vale wing
#

!d discord.utils.find

unkempt canyonBOT
#

discord.utils.find(predicate, seq)```
A helper to return the first element found in the sequence that meets the predicate. For example:

```py
member = discord.utils.find(lambda m: m.name == 'Mighty', channel.guild.members)
```  would find the first [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") whose name is โ€˜Mightyโ€™ and return it. If an entry is not found, then `None` is returned.

This is different from [`filter()`](https://docs.python.org/3/library/functions.html#filter "(in Python v3.9)") due to the fact it stops the moment it finds a valid entry.
vale wing
#

Ok no

sacred sigil
#

omds

#

i put .gg

languid jungle
#

please use a placeholder instead of the invite link

vale wing
#

Is it even a thing

spring flax
#

walrus operator, some call it

honest vessel
#

i think this is unnecesary if after.roles != before.roles:, it will never be same

sacred sigil
#

for a vanity check, does this work?

@bot.command
async def on_member_update(before:discord.Member, after:discord.Member):
  if after.status != before.status:
    if after.status == "my vanity":
        #do stuff
vale wing
#

I guess the status is not a string, it is discord.Status

slow fog
#

youre sus

honest vessel
#

i mean i dont think it triggers on_member_update, if nothing has changed

vale wing
#

!d discord.Member.status

unkempt canyonBOT
#

property status: discord.enums.Status```
The memberโ€™s overall status. If the value is unknown, then it will be a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") instead.
sacred sigil
#

how do i check for it?

vale wing
#

!d discord.Member.activity most likely

unkempt canyonBOT
#

property activity: Optional[Union[discord.activity.Activity, discord.activity.Game, discord.activity.CustomActivity, discord.activity.Streaming, discord.activity.Spotify]]```
Returns the primary activity the user is currently doing. Could be `None` if no activity is being done.

Note

Due to a Discord API limitation, this may be `None` if the user is listening to a song on Spotify with a title longer than 128 characters. See [GH-1738](https://github.com/Rapptz/discord.py/issues/1738) for more information.

Note

A user may have multiple activities, these can be accessed under [`activities`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member.activities "discord.Member.activities").
sacred sigil
#

hm?

#

how would I implement that into on_member_update?

vale wing
#

I need to check this by myself, never had a need to fetch user's status

honest vessel
sacred sigil
#

im a little confused on that

spring flax
slate swan
#

hi
i'm new to py and discord py bot develop
trying to create a nice bot for myself
i want to create a organize space for the work and i heard of something called Commands Handler and event handler,
how im bringing this into my project and acctually implementing this?

vale wing
slate swan
vale wing
#

What languages do you know else

slate swan
vale wing
#

Nice

slow fog
sacred sigil
#

anyone know how to check for a member status?

slate swan
slow fog
#

cool

vale wing
vale wing
#

Best languages for creating discord bots are python, js and kotlin I'd say

#

At least they have normal wrappers

slate swan
#

you have like 200 lines of code for just a ping command and a running bot

left crater
#
async def on_message(message):
  if message.content.lower() == "olorandom":
    rand = random.randint(0,15)
    await message.channel.send("Choose a number from 1-15")
    if message.content.lower() == rand:
      await message.channel.send("good job")
    if message.content.lower() != rand:
      await message.channel.send("wrong try again")```
#

can someone explain why no work

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
#

@left crater what are you trying to do here?

#

@vale wing can you help me with the handler?

vale wing
#

Also you don't have process_commands here, add it or use a listener

left crater
#

the generates a random number and the user has to guess it

#

if wrong then it will say wrong

steel void
#

how do i rename a discord voice channel

vale wing
#

And seems like you are implementing commands in on_message event which is bad practice

left crater
#

should i use ctx

vale wing
unkempt canyonBOT
#

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

Edits the channel.

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

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

Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead.
rotund creek
#

yo

#

why is client.fetch_user(id) not working in a regular function

vale wing
steel void
#

i wonder why mien doesnt work then

vale wing
rotund creek
#

client.fetch_user() only working in functions with @client.command() decorator

slate swan
vale wing
rotund creek
steel void
#

i get a nonetype

#

error

vale wing
sacred sigil
#
@bot.event
async def on_member_update(before, after):
    if before.status is discord.Status.WHAT and after.status is discord.Status.WHAT:
rotund creek
#

client = commands.Bot(command_prefix = "~", help_command = None, debug_guild = 12893413483)

steel void
#
@tasks.loop(minutes=1)
async def war_update_time(minutes=1):
    print("hi1")
    war = await client_coc.get_current_war('#2YY0LGG9G')
    hours, remainder = divmod(int(war.end_time.seconds_until), 3600)
    minutes, seconds = divmod(remainder, 60)
    channel = client_main.get_channel(931185915932577862)
    try:
        print("hi2")
        await channel.edit(name="test55")
    except Exception as e:
        print(traceback.format_exc())
war_update_time.start()
``` this is my code i get into both blocks or w.e
#

so it's something with the channel.edit that doesnt work

#

and im not sure why, it say n onetype object has no attribute edit

steel void
#

client_main

vale wing
#

Yeah that

#

How is it defined

steel void
#

im guessing you mean this

client_main = commands.Bot(command_prefix = cfg.config['bot_command_prefix'], activity=discord.Activity(type=discord.ActivityType.watching, name="for API updates"), intents = discord.Intents.all())
vale wing
#

Ok this is right

steel void
#

yh im pre lost and confused why it saying edit isnt valid or w.e

sacred sigil
#
@tasks.loop(seconds=3)
async def status_role():
    guild = bot.get_guild(ID) 
    role = get(guild.roles, id=id) 
    [await member.add_roles(role) for member in guild.members if member.activities[0] and 'vanity' in member.activities[0].name.lower()]
#

?

rotund creek
sacred sigil
#

but shudnt it be in the on_member_update() event?

maiden fable
#

@steel void what happened

maiden fable
unkempt canyonBOT
#

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

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

โ€ข status

โ€ข activity

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

Mind showing where u r defining it?

steel void
#

channel = client_main.get_channel(931185915932577862)

maiden fable
#

Recheck the ID

#

The ID is wrong

steel void
#

i just rechecked the id, it is correct, but it is a voice channel

#

if that makes a difference

maiden fable
#

No

cloud dawn
#

343944376055103488 This channel id
931185915932577862 your id

maiden fable
#

Huh?

#

Ah

maiden fable
#

U mean the different number series? @cloud dawn

cloud dawn
steel void
#

i coped it directly

maiden fable
#

Aaaah gotcha

steel void
#

from the copy id function twice

cloud dawn
steel void
cloud dawn
#

afaik all id's are 18 in lenght

maiden fable
#

Yea they are

#

Just confirmed it with my bot

quaint epoch
#

wait tha worked

steel void
#

so any ideas?

quaint epoch
steel void
#

on my issue

cloud dawn
steel void
#

yh

quaint epoch
steel void
#

right clicked on channel

maiden fable
#

Even voice channels have an ID of 18 digits

steel void
#
@tasks.loop(minutes=1)
async def war_update_time(minutes=1):
    print("hi1")
    war = await client_coc.get_current_war('#2YY0LGG9G')
    hours, remainder = divmod(int(war.end_time.seconds_until), 3600)
    minutes, seconds = divmod(remainder, 60)
    channel = client_main.get_channel(931185915932577862)
    try:
        print("hi2")
        await channel.edit(name="test55")
    except Exception as e:
        print(traceback.format_exc())
war_update_time.start()
``` this code i get this error https://images-ext-2.discordapp.net/external/d_h0eNu4LH4LFaX-0LITU2Y7_1VCc1XBFp6SKwV5vH0/https/xbb.speedygoat.net/dUJU7/COyePaYe19.png
cloud dawn
#

!e ```py
print(len(str(931185915932577862)))

unkempt canyonBOT
#

@cloud dawn :white_check_mark: Your eval job has completed with return code 0.

18
maiden fable
#

Lol

cloud dawn
#

!e ```py
print(len(str(343944376055103488)))

unkempt canyonBOT
#

@cloud dawn :white_check_mark: Your eval job has completed with return code 0.

18
maiden fable
#

@steel void can the bot "see" the channel?

steel void
#

yeah the bot has admin of the server

quaint epoch
cloud dawn
maiden fable
#

Yea try fetching

steel void
#

how would i do that

maiden fable
#

!d discord.Client.fetch_channel

unkempt canyonBOT
#

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

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

Note

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

New in version 1.2.
cloud dawn
maiden fable
#

Just like u r using get_channel, but with an await

cloud dawn
quaint epoch
#

i forgot how to define a bot var lol

maiden fable
#

Acc?

cloud dawn
maiden fable
unkempt canyonBOT
#

class discord.Client(*, loop=None, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.

A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client").
maiden fable
cloud dawn
quaint epoch
cloud dawn
#

sends client

quaint epoch
sacred sigil
#

works?

cloud dawn
#

!d disnake.ext.commands.Bot

unkempt canyonBOT
#

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

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

This class also subclasses [`GroupMixin`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.GroupMixin "disnake.ext.commands.GroupMixin") to provide the functionality to manage commands.
cloud dawn
#

I just subclassed the bot so i don't have bot "vars"

sacred sigil
maiden fable
maiden fable
unkempt canyonBOT
#

The activities that the user is currently doing.

Note

Due to a Discord API limitation, a userโ€™s Spotify activity may not appear if they are listening to a song with a title longer than 128 characters. See GH-1738 for more information.

cloud dawn
maiden fable
#

!d discord.CustomActivity is yr status

unkempt canyonBOT
#

class discord.CustomActivity(name, *, emoji=None, **extra)```
Represents a Custom activity from Discord.

x == y Checks if two activities are equal.

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

hash(x) Returns the activityโ€™s hash.

str(x) Returns the custom status text.

New in version 1.3.
maiden fable
left crater
#

why do my embed look like this

#

<discord.embeds.Embed object at 0x7f1a7a9761f0>

quaint epoch
maiden fable
#

send(embed=embed), not send(embed) @left crater

left crater
#

oh ok

#

thanks

cloud dawn
maiden fable
#

Why no error handler?

maiden fable
#

Cz there are no errors like MissingPerms and stuff?

cloud dawn
dreamy sluice
#

ayo

#

I think I figured out how to use cogs

maiden fable
maiden fable
quaint epoch
dreamy sluice
maiden fable
unkempt canyonBOT
#

class discord.ext.commands.Cog(*args, **kwargs)```
The base class that all cogs must inherit from.

A cog is a collection of commands, listeners, and optional state to help group commands together. More information on them can be found on the [Cogs](https://discordpy.readthedocs.io/en/master/ext/commands/cogs.html#ext-commands-cogs) page.

When inheriting from this class, the options shown in [`CogMeta`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CogMeta "discord.ext.commands.CogMeta") are equally valid here.
quaint epoch
#

.bm 931204919669698590

cloud dawn
# maiden fable FACTSSSSS

I denied my bot everything even send messages when i did slash it still sended me a message. Looks like slash isn't a message or smth.

honest vessel
#

what u mean with botvars?

cloud dawn
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!

dreamy sluice
#

Oh and

#

@maiden fable If I add a check for a cog, will it only affect that cog?

maiden fable
#

Yes

dreamy sluice
#

Ok thanks

maiden fable
#

!d discord.ext.commands.Bot.check is there BTW @dreamy sluice

unkempt canyonBOT
#

@check```
A decorator that adds a global check to the bot.

A global check is similar to a [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is applied on a per command basis except it is run before any command checks have been verified and applies to every command the bot has.

Note

This function can either be a regular function or a coroutine.

Similar to a command [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check"), this takes a single parameter of type [`Context`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context") and can only raise exceptions inherited from [`CommandError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError").

Example...
cloud dawn
dreamy sluice
maiden fable
#

That's more of a backend error haha

honest vessel
#

and u mean basicly make a class n put self.bot=commands.Bot()

cloud dawn
dreamy sluice
maiden fable
sacred sigil
#
@bot.event
async def on_presence_update(before, after):
    if before.activity != after.activity:
        if after.activity in ["vanity 1", "vanity 2"]:
            guild = bot.get_guild(914533133179813919)
            role = discord.utils.get(guild.roles, id=931191386076749896)
            #how do I add the role to that specific member?
maiden fable
dreamy sluice
maiden fable
unkempt canyonBOT
#

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

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

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

Remember before and after are Member objects

sacred sigil
#

ahhh

#

so after.add_roles

maiden fable
unkempt canyonBOT
#
Nuh-uh.

No documentation found for the requested symbol.

cloud dawn
maiden fable
#

!d discord.ext.commands.Bot.add_check

#

!d discord.ext.commands.Cog.cog_check

unkempt canyonBOT
#

cog_check(ctx)```
A special method that registers as a [`check()`](https://discordpy.readthedocs.io/en/master/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/master/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context").
maiden fable
#

Weird that it's named cog check, not check

dreamy sluice
cloud dawn
maiden fable
#

Yea ik

cloud dawn
#

What have you been working on hunt?

maiden fable
maiden fable
cloud dawn
#

:3

slate swan
#

nvm cog.check does not exist

maiden fable
#

Yea lol

cloud dawn
#

I actually wanted to replicate the eval of python discord

maiden fable
#

That's too complex for my IQ Level

cloud dawn
#

appears the eval command is combined around 2500 lines

#

I need to host my own API to that shit

maiden fable
#

holding back my urge to send a meme here

cloud dawn
#

If it is topical go for it lol

maiden fable
maiden fable
cloud dawn
cloud dawn
#

And when you got the API working you need to extract the code from the command itself that has a lot of hard coded checks.

maiden fable
#

Facts

spring flax
#

does set(before.roles) - set(after.roles) on an on_member_update return a role object or a set?

maiden fable
#

Set

#

U need to do list() on it

spring flax
#

ah yeah

cloud dawn
maiden fable
#

Ok, meme incoming (sorry)

sacred sigil
#

how do I check if a member has a specific role?

maiden fable
unkempt canyonBOT
#

property roles: List[Role]```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that the member belongs to. Note that the first element of this list is always the default [โ€˜@everyone](mailto:'%40everyone)โ€™ role.

These roles are sorted by their position in the role hierarchy.
maiden fable
#

Get a role object then use the in operator

cloud dawn
#

me too

maiden fable
#

Wait, that's my-

cloud dawn
#

our meme

maiden fable
#

yea yea

sacred sigil
#

of the role

maiden fable
#

!d discord.Guild.get_role

unkempt canyonBOT
maiden fable
#

This?

sacred sigil
#

let me try hollyp

maiden fable
#
role = guild.get_role(...) 
if role in member.roles:
    print("Yay, good boy") 
#

Ezz

sacred sigil
#

appreciate it

maiden fable
#

(:

tidal hawk
#

How often do on_ready async functions restart

cloud dawn
tidal hawk
#

on what

maiden fable
#

Whenever a bot gets ready

#

As in, whenever discord sends a Ready payload

tidal hawk
#

Yeah but sometimes it does it in middle of runnig

#

depends on network i guess

#

internet

maiden fable
#

And that happens
-> on startup
-> on reconnection
-> on restart

cloud dawn
#

It's very random.

maiden fable
cloud dawn
#

reconnections aren't really predictable.

maiden fable
#

Yea, but that's when on_ready is called

cloud dawn
#

Thus can be very random

maiden fable
#

Oops wrong ping

steel void
#

im completely lsot on waht you guys sugggested for me

#

i thought maybe it was cause it was running before the bot was up and i added wait_until_ready but still the edit error

maiden fable
#

Damn discord making our work difficult

maiden fable
steel void
#

yh still havent changed nothing sadly

maiden fable
#

Mind showing me the code?

steel void
#

updated code

@tasks.loop(minutes=1)
async def war_update_time(minutes=1):
    try:
        await client_main.wait_until_ready()

        print("hi1")
        war = await client_coc.get_current_war('#2YY0LGG9G')
        hours, remainder = divmod(int(war.end_time.seconds_until), 3600)
        minutes, seconds = divmod(remainder, 60)
        channel = client_main.get_channel(931185915932577862)
        try:
            print("hi2")
            await channel.edit(name="test55")
        except Exception as e:
            print(traceback.format_exc())
    except Exception as e:
        pass
war_update_time.start()
maiden fable
#

Hmm

steel void
#

ii thought maybe it was cause of the task starting before bot but it doesnt appear so

maiden fable
#

Yea that's a common issue ngl

steel void
#

so im completely lost

maiden fable
#

Still the NoneType issue?

steel void
#

i cant find any similiar issues on google

#

yup

drifting arrow
#

How do I send a message to channel on bot load?

maiden fable
#

Lmao

maiden fable
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**.
drifting arrow
#

I got that part.

#

I am talking about when the bot first turns on, I want it to send a message

cloud dawn
unkempt canyonBOT
#

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

Waits until the clientโ€™s internal cache is all ready.
steel void
#

wdym its just for the wait until ready event to get triggered

left crater
#

or in a channel?

maiden fable
steel void
#

no i read the documentation you guys sent but im confused wid it

maiden fable
#

Uhh, just try fetching the channel

left crater
#

@drifting arrow

sacred sigil
#

@maiden fable it didn;t work

left crater
#
async def on_ready():
    print("Bot is ready!")```
sacred sigil
#
@bot.event
async def on_presence_update(before, after):
    guild = bot.get_guild(914533133179813919)
    role = discord.utils.get(guild.roles, id=931191386076749896)
    if before.activity != after.activity:
        if after.activity in ["vanity 1", "vanity 2", "/uploaders"]:
            vanity_embed = Embed(description=f"{after.mention} thx 4 repping **vanity** ![packed](https://cdn.discordapp.com/emojis/930197134073036910.webp?size=128 "packed")", color=0x0f0f0f)
            channel = bot.get_channel(931191146099658822)
            await after.add_roles(role, reason="Repping Vanity")
            await channel.send(embed=vanity_embed)
            try:
                await after.send("appreciate it for repping **vanity**. you were given the vanity role")
            except:
                pass
        else:
            if role in after.roles:
                await after.remove_roles(role, reason="removed vanity")
#

shud it be after.status?

sacred sigil
cloud dawn
#

So you bare except it.?

sacred sigil
#

after it has sent its messages in the desired channel, if it cannot dm a member, it passes

#

what shud I do?

cloud dawn
#

!tags

sacred sigil
#

!except

unkempt canyonBOT
#

A key part of the Python philosophy is to ask for forgiveness, not permission. This means that it's okay to write code that may produce an error, as long as you specify how that error should be handled. Code written this way is readable and resilient.

try:
    number = int(user_input)
except ValueError:
    print("failed to convert user_input to a number. setting number to 0.")
    number = 0

You should always specify the exception type if it is possible to do so, and your try block should be as short as possible. Attempting to handle broad categories of unexpected exceptions can silently hide serious problems.

try:
    number = int(user_input)
    item = some_list[number]
except:
    print("An exception was raised, but we have no idea if it was a ValueError or an IndexError.")

For more information about exception handling, see the official Python docs, or watch Corey Schafer's video on exception handling.

sacred sigil
#

shud I print instead?

cloud dawn
#

Oh it's in here

cloud dawn
sacred sigil
#

except what

#

discord.Error.?

cloud dawn
#

The error that you get if you get an exception?

sacred sigil
#

if its the try statement, then it shudve worked until the try statement

#

but it didn't

sacred sigil
magic ore
#

discord.Forbidden

sacred sigil
#

except discord.Forbidden?

magic ore
#

try it out

sacred sigil
#

my code isn't working

#

its supposed to check my status

#

then send a message to a channel

#

then give a role

#

then dm the user if possible

#

it doesn't do anything

magic ore
#

on_presence_update isn't a thing

sacred sigil
#

?

final iron
#

!d discord.on_presence_update

unkempt canyonBOT
#

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

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

โ€ข status

โ€ข activity

This requires [`Intents.presences`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.presences "discord.Intents.presences") and [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be enabled...
final iron
magic ore
#

oh weird it wasn't showing up for me, nevermind

sacred sigil
#

!d discord.on_presence_update

unkempt canyonBOT
#

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

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

โ€ข status

โ€ข activity

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

do you have the necessary intents

sacred sigil
#
intents = discord.Intents.default()
intents.members = True
intents.presences = True 
final iron
#

Did you pass them in to the bot constructor?

sacred sigil
#

pass the intents?

final iron
#

Show me your bot constructor

sacred sigil
#

omds

#

i figured it out

#

lemme add it

#
bot = commands.Bot(command_prefix="$", intents=intents, owner_id=909799519477190656)
#

nvm i alr have it

brazen raft
#

What about dev portal

cloud dawn
brazen raft
#

These are privileged intents that need to be turned on at the developer portal too

maiden fable
cloud dawn
#

What is the best way to hide commands with a slash bot?

maiden fable
cloud dawn
#

That's why i'm thinking.

#

I could re-enable the prefix

#

Shut down help command etc

sacred sigil
#

presence and members

cloud dawn
#

Why not make a permission check?

#
@commands.has_permissions(administrator=True)
sacred sigil
#

if the role has admin perms it'll work

#

no need to check for the role itself thats a security risk

daring olive
#

@sacred sigil are your messages getting deleted?

#

if so it's bc you have a server invite in the code

#

remove that and try again please

sacred sigil
#
@bot.event
async def on_presence_update(before, after):
    guild = bot.get_guild(914533133179813919)
    role = discord.utils.get(guild.roles, id=931191386076749896)
    if before.activity != after.activity:
        if after.activity in ["vanity 1", "vanity 2", "vanity 3"]:
            vanity_embed = Embed(description=f"{after.mention} thx 4 repping **vanity** :packed:", color=0x0f0f0f)
            channel = bot.get_channel(931191146099658822)
            await after.add_roles(role, reason="Repping Vanity")
            await channel.send(embed=vanity_embed)
            try:
                await after.send("appreciate it for repping **vanity**. you were given the vanity role")
            except discord.Forbidden:
                pass
        else:
            if role in after.roles:
                await after.remove_roles(role, reason="removed vanity")
sacred sigil
#

i had to remove my vanity

drifting arrow
#

Is there a function that awaits users response?
I want my bot to send a question to a user in a DM (already got this part)
and now I want the bot to await a response before it continues

#

Like an input. Is there any functionality for this?

potent spear
quaint epoch
#

how do i delete the last, lets say 100 messages from a certain user?

#

in a text channel?

#

And only those

potent spear
slate swan
#

with a check

quaint epoch
#

!d disnake.TextChannel.purge

slate swan
#
await channel.purge(amount , check = lambda m : m.author = user)```
unkempt canyonBOT
#

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

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

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

Examples

Deleting botโ€™s messages...
potent spear
#

the check is a bit hacky, since it'll check 100 messages, instead of 100 messages from a certain user, so I hope you're happy with that

quaint epoch
potent spear
#

I guess the around kwarg in disnake fixes that lol

potent spear
quick gust
#

@sacred sigil Your message got deleted I guess, ask the question again

quaint epoch
#

like, if i want to delete my last 10 messages, i loop through the last 10 messages that were not by me. But the last one IS MINE, so it deletes that messages instead of my last 10

sacred sigil
#

What I want to do:

  • check member's status
    • if it changed, check if its my vanity
      - if its my vanity, send an embed to a channel, give the member a role, and send them a dm if possible
      if it changed, and they have the vanity role, remove the role since they are not repping my vanity
potent spear
unkempt canyonBOT
#

property activity: Optional[Union[discord.activity.Activity, discord.activity.Game, discord.activity.CustomActivity, discord.activity.Streaming, discord.activity.Spotify]]```
Returns the primary activity the user is currently doing. Could be `None` if no activity is being done.

Note

Due to a Discord API limitation, this may be `None` if the user is listening to a song on Spotify with a title longer than 128 characters. See [GH-1738](https://github.com/Rapptz/discord.py/issues/1738) for more information.

Note

A user may have multiple activities, these can be accessed under [`activities`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member.activities "discord.Member.activities").
quick gust
potent spear
quick gust
#

The custom status

slate swan
#

and .status if you mean the idle , online thing

quaint epoch
#

how do i get the last 10 messages from a user, like ctrl+f in the ui of discord

quick gust
sacred sigil
# slate swan !d discord.Member.activity

What I want to do:

  • check member's status
    • if it changed, check if its my vanity
      - if its my vanity, send an embed to a channel, give the member a role, and send them a dm if possible
      if it changed, and they have the vanity role, remove the role since they are not repping my vanity
slate swan
quick gust
#

yeah mb

sacred sigil
# sacred sigil What I want to do: - check member's status - if it changed, check if its my...
@bot.event
async def on_presence_update(before, after):
    guild = bot.get_guild(914533133179813919)
    role = discord.utils.get(guild.roles, id=931191386076749896)
    if before.activity != after.activity:
        if after.activity in ["vanity 1", "vanity 2", "vanity 3"]:
            vanity_embed = Embed(description=f"{after.mention} thx 4 repping **vanity** :packed:", color=0x0f0f0f)
            channel = bot.get_channel(931191146099658822)
            await after.add_roles(role, reason="Repping Vanity")
            await channel.send(embed=vanity_embed)
            try:
                await after.send("appreciate it for repping **vanity**. you were given the vanity role")
            except discord.Forbidden:
                pass
        else:
            if role in after.roles:
                await after.remove_roles(role, reason="removed vanity")
maiden fable
#

yea this.... what happened

potent spear
maiden fable
#

It is correct tho

potent spear
#

a different library probably

maiden fable
#

!d discord.on_presence_update

unkempt canyonBOT
#

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

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

โ€ข status

โ€ข activity

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

I copy and pasted it to make sure

sacred sigil
potent spear
maiden fable
#

yea

potent spear
#

I'd check first if his event even triggers

slate swan
maiden fable
#

if u r using dpy 1.7, then use on_member_update @sacred sigil

slate swan
#

you can then use if vanity in the_activity_name

potent spear
#

he also needs some intents enabled, you guys are skipping some steps

maiden fable
potent spear
#

I only started reading from where he shared his code

maiden fable
#

he has been asking about the code since like 30 min or smth, soooooooo

potent spear
#

feelsbadman

sacred sigil
#

if so how do I change it?

potent spear
#

thinking is not enough

#

print(discord.__version__)

sacred sigil
#

do I change the event name thats it?

maiden fable
#

yea

#

also a few more small changes

sacred sigil
#

such as?

maiden fable
#

Uhhh nvm

#

ignore it

#

u don't need to do any changes

sacred sigil
#

just change the event to on_member_update?

maiden fable
#

yea...

sacred sigil
maiden fable
#

try printing discord.__version__

quaint epoch
#

!d disnake.TextChannel.delete_messages

unkempt canyonBOT
#

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

Deletes a list of messages. This is similar to [`Message.delete()`](https://docs.disnake.dev/en/latest/api.html#disnake.Message.delete "disnake.Message.delete") except it bulk deletes multiple messages.

As a special case, if the number of messages is 0, then nothing is done. If the number of messages is 1 then single message delete is done. If itโ€™s more than two, then bulk delete is used.

You cannot bulk delete more than 100 messages or messages that are older than 14 days old.

You must have the [`manage_messages`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.manage_messages "disnake.Permissions.manage_messages") permission to use this.
quaint epoch
#

nice

maiden fable
#

!d discord.TextChannel.purge is better @quaint epoch

unkempt canyonBOT
#

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

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

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

Examples

Deleting botโ€™s messages...
sacred sigil
#

hosting

maiden fable
#

Ouch

quaint epoch
#

in the last 14 days?

maiden fable
#

yea

quaint epoch
#

both work just as well for me

maiden fable
#

okay

quaint epoch
#

but thanks

sacred sigil
maiden fable
#

by adding it to a file?

#

like add print(discord.__version__) to the file

maiden fable
#

Ah

#

then u need

#

!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...
maiden fable
#

u need this then

#

change yr event name to this and it will work

sacred sigil
#

i did lol

#

one sec

#
@bot.event
async def on_member_update(before, after):
    guild = bot.get_guild(914533133179813919)
    role = discord.utils.get(guild.roles, id=931191386076749896)
    if before.activity != after.activity:
        if after.activity in ["v1", "v2", "v3"]:
            vanity_embed = Embed(description=f"{after.mention} thx 4 repping **v1** :packed:", color=0x0f0f0f)
            channel = bot.get_channel(931191146099658822)
            await after.add_roles(role, reason="Repping Vanity")
            await channel.send(embed=vanity_embed)
            try:
                await after.send("appreciate it for repping **v**. you were given the vanity role")
            except discord.Forbidden:
                pass
        else:
            if role in after.roles:
                await after.remove_roles(role, reason="removed vanity")
quaint epoch
#

does py ctx.message.delete() have a reason param?

slate swan
#

!d discord.Message.delete

unkempt canyonBOT
#

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

Deletes the message.

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

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

or py ctx.message.channel.delete_messages() have a reason param

slate swan
#

As you can see, no.

quaint epoch
honest shoal
#

how can we create buttons in disanke without classes

quaint epoch
#

!d disnake.TextChannel.delete_messages

unkempt canyonBOT
#

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

Deletes a list of messages. This is similar to [`Message.delete()`](https://docs.disnake.dev/en/latest/api.html#disnake.Message.delete "disnake.Message.delete") except it bulk deletes multiple messages.

As a special case, if the number of messages is 0, then nothing is done. If the number of messages is 1 then single message delete is done. If itโ€™s more than two, then bulk delete is used.

You cannot bulk delete more than 100 messages or messages that are older than 14 days old.

You must have the [`manage_messages`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.manage_messages "disnake.Permissions.manage_messages") permission to use this.
quaint epoch
#

oh

#

it doesn't

#

alr

slate swan
#

It will take all the kwargs you would use with the class

honest shoal
slate swan
#

Send the code and issue u face

honest shoal
#

oke, lemme try recreating

#

and how we'll add the button there?

knotty gazelle
#

?

honest shoal
#

@slate swan

slate swan
#
view = disnake.ui.View()
button = disnake.ui.Button()
view.add_item(button)
await send(view=view)```
honest shoal
#

ohk lemme try

#

getting an error 2022-01-13T16:52:44.189475+00:00 app[worker.1]: /app/.heroku/python/lib/python3.9/asyncio/events.py:80: RuntimeWarning: coroutine 'Command.__call__' was never awaited 2022-01-13T16:52:44.189498+00:00 app[worker.1]: self._context.run(self._callback, *self._args) 2022-01-13T16:52:44.189499+00:00 app[worker.1]: RuntimeWarning: Enable tracemalloc to get the object allocation traceback This is the code py @bot.command() async def Google(ctx: commands.Context, *, query: str): button = disnake.ui.Button view = disnake.ui.View() query = quote_plus(query) url = f"https://www.google.com/search?q={query}" view.add_item(button(label="Click here", url=url)) await ctx.send(f"Google Result for: `{query}`", view=Google(query))

#

@slate swan

slate swan
honest shoal
#

await send(view=view)?

slate swan
#

nah whats the Google thing?

honest shoal
#

for the query?

final iron
#

Yes

#

If its async you would need to await it

#

If its not async I wouldn't suggest you use it

honest shoal
#

but await what

#

removing view=Google(query) makes the command work but not adding the button

left crater
#
async def on_member_ban(self, member: discord.Member):
        channel = self.bot.get_channel(814956709290049596)

        if not channel:
            return
        await channel.send(f"{member} was banned!")```
#

when i ban someone nothing happens

slate swan
#

whats the quote_plus function>

#

hello

honest shoal
slate swan
#

makes sense , but your view class is named view , so it would be view=view

honest shoal
#

oh yes

#

ty!

slate swan
#

you view your class name

#

view=classname()

leaden hollow
#

what is the variable for name + #tag
{ctx.author.name} only gives names not the # tag

maiden fable
#

str(ctx.author) iirc

#

smh dpy

silk nest
#

Is anyone familiar with nextcord? I'm running into some issues with the slash_command function not registering any commands to my guild

maiden fable
#

it takes upto 2 hours

#

discord issue shrug

steel void
#

isnt their slash command not stable apparently, i think ir ead where they said not to use it in production builds

maiden fable
#

idk

#

I use disnake

leaden hollow
silk nest
#

Hm, that's unfortunate. I got it to pop up really quick using the command from nextcord.ext.commands.Bot, but doing it withnextcord.Client yields nothing.

#

I'll try waiting to see if it pops up after a while

steel void
#

a lot of ppl i know went to pycord, someone said it only took them 1h to get everything working again since its very close to discord.py

silk nest
#

I'll take a look at pycord then. Nextcord seemed nice cause I could just run my old stuff really fast, but I'd like to use slash commands lmao

steel void
#

pycord supports slash, i just heard a lot of good stuff about it, ima switch to pycord eventually

vocal plover
maiden fable
#

we

vocal plover
#

I'm a nextcord maintainer lol

maiden fable
#

How many forks do u even contribute to ๐Ÿ˜

vocal plover
#

2 kek

maiden fable
#

yea yea won't be surprised if more come out

vocal plover
#

And also has a better slash command implementation in general, but thats my opinion

maiden fable
#

Hmm

silk nest
vocal plover
#

Yup

silk nest
#

Sick, I'll go look at that. Trying to find a good replacement

harsh stump
#

where do is tart with discord bots?

boreal magnet
slate swan
#

so lets say

harsh stump
slate swan
#

I had a users ID how can I assign them with a certain role using the ID that is saved to a variable

boreal magnet
vale wing
#

More depends on the tutorial lol

boreal magnet
#

it brings you closer how to setup the bot

quick gust
honest shoal
#

I'm having an issue with anime quote command of my bot. This is the code py @bot.command(aliases=['aq']) async def animequote(ctx, *,anime: str): if not anime: async with aiohttp.ClientSession() as session: request = await session.get('https://animechan.vercel.app/api/random') quotejson = await request.json() embed = disnake.Embed(title=quotejson['anime'],description=quotejson['quote'] , color=ctx.author.color) embed.set_author(name="Anime Quote") saidby = quotejson['character'] embed.set_footer(text=f"- {saidby}") await ctx.send(embed=embed) else: async with aiohttp.ClientSession() as session: request = await session.get(f'https://animechan.vercel.app/api/random/anime?title={anime}') quotejson = await request.json() embed = disnake.Embed(title=quotejson['anime'],description=quotejson['quote'] , color=ctx.author.color) embed.set_author(name="Anime Quote") saidby = quotejson['character'] embed.set_footer(text=f"- {saidby}") await ctx.send(embed=embed) This is how the sample json looks like json {"anime":"Naruto","character":"Naruto Uzumaki","quote":"If you don't like the hand that fate's dealt you with, fight for a new one!"} When I run it I don't get any error and command doesn't work

vale wing
#

Do you have on_command_error event?

honest shoal
#

no

harsh stump
#

oh ooops

vale wing
#

Also you should set default value of anime arg as without it it will raise MissingRequiredArgument and if it is provided if not anime will always be False

honest shoal
vale wing
#

I mean

async def animequote(ctx, *, anime = None)```
boreal magnet
#

well I started new aswell and I guess the best way to start in making a bot is by watching videos on how to set one up first, and then going to solve a problem one by one

honest shoal
#

oh

harsh stump
#

k

quick gust
vale wing
#

I never watched a single youtube tutorial (they're too slow for me)

vale wing
#

@honest shoal also make sure request goes properly

boreal magnet
boreal magnet
#

anyways, does anybody know how to generate images with code as input?

vale wing
#

When I started learning discord bots I had like intermediate python knowledge, I could for example make a game with pygame or a pyqt app

#

So wasn't a big issue

boreal magnet
#

thats great, I have some programming experience in general but no specific language

#

so I wanna sneak peak here slowly and I cant find a solution to my first problem ๐Ÿ˜‚

vale wing
#

I don't remember how's it named on pypi tho

boreal magnet
# vale wing There's PIL module

I dont actually need to edit an image specifically, its more like putting different png elements together to generate one jpg

#

it sounds basic but I didnt find any solution online

vale wing
boreal magnet
#

for example:
Make a simple variable called "Balance" and adjust the image to the count of your balance

vale wing
#

I hate image generation personally

#

Too much of calculations and coordinates ๐Ÿคฏ

boreal magnet
#

yeah it might be pretty hard to achieve but it looks great when its done

honest shoal
#

ok, so I was tired up and made the command simpler for now this is the code py @bot.command(aliases=['aq']) async def animequote(ctx): async with aiohttp.ClientSession() as session: request = await session.get('https://animechan.vercel.app/api/random') quotejson = await request.json() embed = disnake.Embed(title=quotejson['anime'],description=quotejson['quote'] , color=ctx.author.color) embed.set_author(name="Anime Quote") saidby = quotejson['character'] embed.set_footer(text=f"- {saidby}") await ctx.send(embed=embed) I'm now stuck with same issue again command doesn't work and no error

vale wing
#

Yesterday there was a guy with similar issue and it turned out he had error handler that was eating the error, I am not saying you have exactly the same issue but are you totally sure you don't have any error handlers?

honest vessel
#

print ur quotejson also n see fi u even get json

#

quotejson = await request.json()
print(quotejson)

#

if no json ur embed wont work

#

but should get error

honest shoal
honest vessel
#

then u need to investigate why ur json not working ๐Ÿ˜„

vale wing
#

@honest shoal add this to your code so we can 100% catch the error

@bot.listen('on_command_error')
async def error_handler(ctx, error):
    raise error```
honest vessel
#

cause json is there

honest shoal
#

yeah got the error

honest vessel
#

that happend to one of my webradio urls ssl issue

#

i nvr bothered try fix it

honest shoal
#

๐Ÿ’€

honest vessel
#

ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired

#

ssl verification is old n not valid for client

#

(serverside)

honest shoal
#

sadge

#

anyways thanks

honest vessel
#

but throu my browser it is a valid ssl cert

#

i googled someone sais this i dunno

#

    Go to discord.com with Internet Explorer (Ran as Administrator)

    Click the lock on the top right

    Click view certificates

    Install one
#

and this

#
import ssl

try:
    _create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
    # Legacy Python that doesn't verify HTTPS certificates by default
    pass
else:
    # Handle target environment that doesn't support HTTPS verification
    ssl._create_default_https_context = _create_unverified_https_contex
honest shoal
#

sheesh

quick gust
honest vessel
#

i tried but got directed to https

quick gust
#

wait who had the SSL certificate error?

honest shoal
#

me

quick gust
honest vessel
#

he means try http:// instead of https://

#

request = await session.get(f'http://animechan.vercel.app/api/random/anime?title={anime}')

honest shoal
#

yeah tried

#

same error

honest vessel
#

try that ssl python code

#

let me know if it worked

honest shoal
#

oke

honest shoal
slate swan
#

How do I add a specific role using someones ID thats saved to a variable?

#

paying someone $10 any crypto

#

if they can dm a solution

honest shoal
#

!rule 9

unkempt canyonBOT
#

9. Do not offer or ask for paid work of any kind.

slate swan
#

bro its $10

#

for a simple solution as I am very busy right now

honest shoal
#

doesn't matter, you aren't allowed to offer paid works here

#

also I don't get your ques.

quick gust
unkempt canyonBOT
#

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

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

You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
drifting arrow
#
 @commands.Cog.listener()
    async def on_reaction_add(self, reaction, user):
        if user == self.client.user:
            return
        if reaction.message == self.message:

            def check(m):
                if m.author == user:
                    return m.content

            await user.send("Please enter a description of the discord")
            cheat_discord_description = await self.client.wait_for(
                "message", check=check
            )

            await user.send("Please enter the link to the discord.")
            cheat_link = await self.client.wait_for("message", check=check)
            
            if 'https://discord.gg/' not in cheat_link:
                await user.send('No cheat discord entered. Closing report.')
                return
            
            await user.send("Please enter the software type")
            software_type = await self.client.wait_for("message", check=check)

            await user.send("When was the last major update? YYYY-MM-DD preferably.")
            major_update = await self.client.wait_for("message", check=check)

            await user.send(
                "Please enter a link to the website. If it has none, just say none."
            )
            cheat_website = await self.client.wait_for("message", check=check)

            await user.send("Are there any hidden features?")
            hidden_features = await self.client.wait_for("message", check=check)
            await user.send("Thank you for the report. It has been submitted successfully.")

            embed = discord.Embed(title="Cheater discord report")
            mychannel = self.client.get_channel(self.reports_channel)
            await mychannel.send(embed=embed)

How do I make this work for multiple users?

#

At the moment if 2 people react to a message at the same time, it just stops everything

slate swan
#

Does it return any errors at all?

drifting arrow
#

It did. reading it now it might be my code actually

slate swan
#

Paste it here

drifting arrow
#

Yep. It was my code

#
if 'https://discord.gg/' not in cheat_link:
        await user.send('No cheat discord entered. Closing report.')
        return
#

\o/ figured it out

brisk helm
#

You know you could use regex , this will work like ....

slate swan
#

sorry wrong server

#

js really?

#

wrong server

cloud dawn
#

ew js

slate swan
#

how does that look like js

#

just shut up

cloud dawn
#

๐Ÿ˜‚

slate swan
#

its the wrong server

#

thats like saying oh yeah that looks like python when its clearly js

honest vessel
frank tartan
#

I have a question.
How can i require a role? (Like you must one of the roles on a list to run the command)

tawdry flume
#

Sus

honest vessel
#

@frank tartanu can use decoration and has_role()

#

@commands.has_role() check this up in documentation

drifting arrow
#

The only check is for discord link

frank tartan
honest vessel
#

tbh i dont know if it accepts a list, why i referenced to check docs

frank tartan
honest vessel
#

seems like u can only have 1 role to be checked

#

either by id or name

#

so no list

#

but u can also check permissions

deep torrent
#

How do I get my bot to choose a line from a text file because so far all I'm getting is just a letter

honest vessel
deep torrent
#

ok

honest vessel
#

or google, "how to read specific line from a textfile"

#

maybe it has soemthing with .seek()

deep torrent
#

Maybe

honest vessel
#

@deep torrenthttps://www.kite.com/python/answers/how-to-read-specific-lines-of-a-text-file-in-python

Kite is a free autocomplete for Python developers. Code faster with the Kite plugin for your code editor, featuring Line-of-Code Completions and cloudless processing.

deep torrent
#

Maybe you can answer this when I use the with open function I get this error

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape (test.py, line 46)
honest vessel
#

this examples reads 2 lines from 3 lines, 0 and 2 (aka 1st and 3rd)

deep torrent
#

Thank you

deep torrent
#

Alright

honest vessel
#

error basicly sais u cant uncicode escape a byte

#

need string

#

or something that way

dire folio
#

My bot is sending all msgs twice

#

Does anyone know a possible reason

magic ore
#

Is your bot sending more of the same messages than you were expecting? You are probably running multiple instances of the bot / program / process.

Typical cases for this are:-
โ€ข Double clicking the file many times.
โ€ข Running it through any IDE (most commonly Atom).
If you do any of these: don't. Please see ?tag dbc for how to properly run your Python code.

To correct this issue, please open your process manager (Task Manager on Windows) and kill the relevant Python processes. Then start the bot correctly, within your CLI.

Other common causes:
โ€ข Using process_commands(Message) many times, or in a listener.

This can be corrected by not doing this in a listener, and only using this method once within the overriding on_message event.

honest vessel
#

make sure no bot is running n start 1

#

yeah like he said -> @magic ore

dire folio
#

ye i had it running in both the shell and console (on replit)

slate swan
#

keep getting this error dont quite know what it means
Command raised an exception: TypeError: tuple indices must be integers or slices, not str

#

You cannot use var["something"] on a tuple.

tacit token
#

hi guys, my problem is this. i click the button, but the dadjoke link to facts, and dadjoke not work but use facts buttons
`@commands.command()
async def dadjoke(self, ctx):
await ctx.send(embed=discord.Embed(color = 0x34568B, title="Dad Jokes From CTRL", description=f"{random.choice(dadjokes)}"), components=[[
Button(style=ButtonStyle.green, label="Next โ–ถ๏ธ", custom_id="button1"),
Button(style=ButtonStyle.red, label="Stop ๐Ÿ›‘", custom_id="button2")

        ]])
    
@commands.Cog.listener()
async def on_button_click(self, interaction):
        if interaction.component.custom_id == "button1":
            await interaction.respond(type=7, embed=discord.Embed(color = 0x34568B, title="Dad Jokes From CTRL", description=f"{random.choice(dadjokes)}"))
        
        elif interaction.component.custom_id == "button2":
            await interaction.edit_origin(embed=discord.Embed(color = 0x34568B, title="Dad Jokes Stopped! ๐Ÿ‘ฎ", description=f"If you would like to use it longer, then push the next button or >dadjoke"))

@commands.command(aliases=["Facts","facts","Fact"])
async def fact(self, ctx):
        await ctx.send(embed=discord.Embed(color = 0x990033, title="Did you know? ๐Ÿ˜ฒ", description=f"{random.choice(facts)}"), components=[[
            Button(style=ButtonStyle.green, label="Next", custom_id="button3"),
            Button(style=ButtonStyle.red, label="Stop", custom_id="button4"),

        ]])
    
@commands.Cog.listener()
async def on_button_click(self, interaction):
        if interaction.component.custom_id == "button3":
            await interaction.respond(type=7, embed=discord.Embed(color = 0x990033, title="Did you know? ๐Ÿ˜ฒ", description=f"{random.choice(facts)}"))
        
        elif interaction.component.custom_id == "button4":
            await interaction.edit_origin(embed=discord.Embed(color = 0x990033, title="random Facts Stopped!", description=f"If you would like to use it longer, then push the next button or >fact"))

`

slate swan
#

Needs to be something like var[3]

slate swan
#

Bascially, what's inside the [] can't be a string.

#

so like indexing a list?

#

Exactly

#

ah alright thank you

slate swan
#

now i have to do a atm with buttonspithink

#

That's nice ^^

#

yeah im loving dbspithink

tacit token
#

guys dont spam this channel please

slate swan
#

were notpithink

#

We don't

tacit token
#

discord_components

slate swan
#

Also, please use the correct code formatting ^^

#

!code

unkempt canyonBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

slate swan
#

discord components has horrible coding just saying

#

For just buttons, I recommend to use discord.py 2.0

#

yeah

#

Or directly switch to disnake or similar for future updates.

#

!d discord.ui.View and just subclass view

unkempt canyonBOT
#

class discord.ui.View(*, timeout=180.0)```
Represents a UI view.

This object must be inherited to create a UI within Discord.

New in version 2.0.
slate swan
#

but i would recommend disnake

#

since it has View and slash commands

tacit token
#

All right, but that's what I use. So the problem is, the nanny refers to facts when I press the button. I've rewrote custom id but then the buttons just didn't work

slate swan
#

cant help with that sorry

#

I don't think having 2 same listeners but separated will work.

#

Pretty sure it will only take one of the two.

#

And discord_components is deprecated and archived, so it might lead to more errors.

tacit token
#

So which one should I use? since I did this too much time I had to look for a well-functioning button system and my time is running out. I spend more with debug than I do with regular development because of the buttons.

dire folio
#

Is disnake.ext a thing?

slate swan
#

You just need to replace all discord to disnake.

tawdry flume
#

how can I create a json that separates the command modules from the bot menu?

#

Uff

frank tartan
#

I have a couple questions.

1) How can I make it so the person who runs the command has to have one of three roles to run the command?

2) How can I make it so they can do `-add :angry_man:`, and they will get a role called `angry man`?
#

i can give you more info if you need it

slate swan
#

!d discord.ext.commands.has_any_role

unkempt canyonBOT
#

@discord.ext.commands.has_any_role(*items)```
A [`check()`](https://discordpy.readthedocs.io/en/master/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/master/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/master/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/master/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/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").

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

use that decorator, passing it a list with the ID's of the 3 roles the command checks for

frank tartan
slate swan
#

yes

frank tartan
frank tartan
frank tartan
tawdry flume
#

?

slate swan
frank tartan
slate swan
tawdry flume
#

how can I create a json that separates the command modules from the bot menu?

slate swan
#

make sensepithink

frank tartan
quaint epoch
#

i need a bit of (lang) context of this convo

#

i just joined

slate swan
quaint epoch
frank tartan
# quaint epoch what emoji?

lets say if someone says
-add ๐Ÿ‘ฎโ€โ™‚๏ธ
then they will get a role called @acoustic loom_man (SRRY FOR THAT PING, I DIDNT MEAN IT)

slate swan
quaint epoch
#

one sec then

tawdry flume
#

how can I create a json that separates the command modules from the bot menu?

slate swan
#

wait for the emoji and remove the colons from it

frank tartan
tawdry flume
#

how can I create a json that separates the command modules from the bot menu?

quaint epoch
#

format it

#

:happy:

frank tartan
#

?????????

slate swan
quaint epoch
#
:police_officer:```
#

๐Ÿ‘ฎ

#

creates that

#

but it actually has to be an emoji lol

slate swan
#

!e

a = ":hello:"
print(a.strip(":"))
unkempt canyonBOT
#

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

hello
tawdry flume
#

Aaaaaa

#

Aaaaaaaaaaaaaaaaaa

quaint epoch
#

so, create a role called "Role_name ๐Ÿ‘ฎ"

frank tartan
frank tartan
#

so i cant do that

quaint epoch
#

still works

#

py_strong is a custom emoji

#

you just get it in your server, then :emoji_name:

frank tartan
#

!e

a = "![HappyDog](https://cdn.discordapp.com/emojis/912890650326876201.webp?size=128 "HappyDog")"
print(a.strip(":"))
unkempt canyonBOT
#

@frank tartan :white_check_mark: Your eval job has completed with return code 0.

:HappyDog:
slate swan
frank tartan
quaint epoch
#

so, lets say i have an emoji, ":test:"

#

and i want to make a role, "role_name, :test:"

tawdry flume
#

@frank tartan can you help me pls?

frank tartan
tawdry flume
tawdry flume
#

how can I create a json that separates the command modules from the bot menu?

slate swan
frank tartan
slate swan
#

and split it on a colon

tawdry flume
# frank tartan ??

how can I create a json that separates the command modules from the bot menu?

frank tartan
slate swan
#

you mean separete your bot file in cogs?

quaint epoch
#

so, py @bot.command() async def create_role(ctx, role_name: str, emoji_id: int): emoji = await ctx.guild.fetch_emoji(emoji_id) await ctx.guild.create_role(name=f"{role_name} {emoji}") i think

tawdry flume
frank tartan
slate swan
quaint epoch
tawdry flume
tawdry flume
frank tartan
#

i dont use cogs so im not the right person to ask

slate swan
#

cough cough

tawdry flume
#

Uh

frank tartan
umbral nacelle
#

how do i make it so that when a certain person sends a message the discord bot replies immediately

quaint epoch
slate swan
quaint epoch
#

Do you want to create a role, add a role, or get an emoji?

frank tartan
slate swan
slate swan
frank tartan
#

wait

#

im dumb, roles would also be predefined...

vale wing
#

You need to create a dict like

{'๐Ÿ‘ฎโ€โ™‚๏ธ': police_officer_role_id}```
tacit token
#

Help me. What button directory should I use?

vale wing
#

And other emoji-role_id pairs

slate swan
vale wing
tacit token
slate swan
vale wing
vale wing
# tacit token yeah

Well personally I recommend disnake, but there are other options like pycord or nextcord, choice is up to you

slate swan
#

nvm that

#

just use the emoji name and set the role with it