#discord-bots

1 messages ยท Page 1094 of 1

odd mango
#

its excellent for tokens and stuff

vale wing
#

Like where would you store the database

slate swan
#

It's replit

shrewd apex
#

u know whats happening

SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
shrewd apex
slate swan
#

Replit feature

narrow grail
#

True. Replit is good for some little tests to not shutdown your complete bot

odd mango
#

or you can use any external db

shrewd apex
#

i ignore replit dosent

vale wing
#

Just make github actions + docker work together that works perfect

slate swan
#

So much work

odd mango
narrow grail
odd mango
#

what are you trying to install

vale wing
shrewd apex
#

i did from requirements.txt

#

pip install -r requirements.txt

odd mango
#

pip install -r requirements.txt

#

yeah that

maiden fable
#

@shrewd apex

odd mango
#

whats in it

maiden fable
#

How did u fix this issue?

shrewd apex
#

yeah

#

oh lmao i found the correct encoding

#

and used that and have a few try except blocks

maiden fable
#

Nice the resource usage

#

Ah I think my error is fixed

#

encoding="utf-8" adding this in the open()

shrewd apex
#

yeah default is utf-8

#

remember to add everytime when writing

odd mango
#

how do i make a pass statement for buttons instead of ephemeral message

#

i just dont want this interaction failed stuff

maiden fable
paper sluice
maiden fable
#

nltk does takes time

odd mango
paper sluice
#

so it wont respond

odd mango
#

nah i disable them on timeout

paper sluice
#

huh, do u have a callback for the button which fails?

paper sluice
odd mango
#
    async def interaction_check(self, interaction):
        """Only allow the author that invoke the command to be able to use the interaction"""
        return interaction.user == self.ctx.author``` i use this for obvious reasons, so when author hits buttons its clean and cool.

but when someone who is not command author hits them, they see _this interaction failed_
slate swan
#

I really have 0 error handlers in My code

maiden fable
#

GG

paper sluice
#

u need to respond to it, other wise it will say that

shrewd apex
#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

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

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

odd mango
shrewd apex
#

someone plz

odd mango
#

i dont want them to see error message

maiden fable
odd mango
paper sluice
slate swan
odd mango
#

no errors when someone else hits

shrewd apex
shrewd apex
odd mango
#

yeah switch to requests

#

lol, this is why i got on pycharm

maiden fable
slate swan
odd mango
#

sure

slate swan
#

Alr

#

Let me check

shrewd apex
odd mango
#

it is allowed, it just dosent work w dpy there

maiden fable
#

Huh? That wasn't the case last time I used it to host a bot

#

Same goes for when trying with dpy

vale wing
#

Just use dpy 2.0

odd mango
#

dosent work either

odd mango
#

but dpy less than 2.0 is lame

maiden fable
#

@vale wing did u see this? ๐Ÿ˜›

vale wing
#

Dpy 2.0 requires aiohttp <= 2.8.0 and python-template requires aiohttp >= 2.8.1 what's not understandable with that

maiden fable
slate swan
odd mango
#

if you need it for embeds then that color is default

slate swan
#

๐Ÿ™„

vale wing
maiden fable
#

Yea that used to suck, but in 3.11 that is gonna change!

odd mango
slate swan
slate swan
vale wing
#

@slate swan #303135

slate swan
#

Ty buddy

stable spire
#

How can I remove the slash commands from my bot? I removed them from my code but the bot still has the options

vale wing
#

I remember how I had the same issue and I ended up making raw requests to discord API ๐Ÿ˜”

stable spire
#

oh

vale wing
stable spire
#

idk

vale wing
#

They are easier trust (dpy 2.0 is not)

slate swan
#

lmao

stable spire
#

I like dpy I started making a bot on it

slate swan
#

imagine hating dpy

stable spire
#

Its like 2k lines now

vale wing
#

Not hating, just stating

vale wing
slate swan
#

mutual feelings

stable spire
#

I hate cogs

slate swan
#

imagine hating something

vale wing
#

Bad reason to hate something

stable spire
#

No I like messy code

vale wing
#

Sure

slate swan
odd mango
#

oh its cool, even i bummed out

slate swan
stable spire
#

ok

narrow grail
#

anyone know how to make a button which u can infinity click?

slate swan
maiden fable
#

Anyone here used text2emotion module?

narrow grail
#

and the same response

slate swan
#

U mean without doing anything

maiden fable
#

can u print id_?

#

yea

narrow grail
maiden fable
#

yes

#

Can u send the ID here pls?

#

@slate swan

#

Thanks

#

So the user ID is correct

#

Do u have members intent?

slate swan
#

How to make discord bots with python ?!

maiden fable
#

!d discord

unkempt canyonBOT
#
maiden fable
#

message intent != members intent

#

is yr bot verified?

#

Hm then u gotta write a ticket to discord and ask for permission

#

or use fetch_user and get ratelimited lol

#

hm?

#

Haha thanks

#

!d exec is what I used

unkempt canyonBOT
#

exec(object[, globals[, locals]])```
This function supports dynamic execution of Python code. *object* must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs). [1](https://docs.python.org/3/library/functions.html#id2) If it is a code object, it is simply executed. In all cases, the code thatโ€™s executed is expected to be valid as file input (see the section [File input](https://docs.python.org/3/reference/toplevel_components.html#file-input) in the Reference Manual). Be aware that the [`nonlocal`](https://docs.python.org/3/reference/simple_stmts.html#nonlocal), [`yield`](https://docs.python.org/3/reference/simple_stmts.html#yield), and [`return`](https://docs.python.org/3/reference/simple_stmts.html#return) statements may not be used outside of function definitions even within the context of code passed to the [`exec()`](https://docs.python.org/3/library/functions.html#exec "exec") function. The return value is `None`.
maiden fable
#

!d contextlib.redirect_stdout

unkempt canyonBOT
#

contextlib.redirect_stdout(new_target)```
Context manager for temporarily redirecting [`sys.stdout`](https://docs.python.org/3/library/sys.html#sys.stdout "sys.stdout") to another file or file-like object.

This tool adds flexibility to existing functions or classes whose output is hardwired to stdout.

For example, the output of [`help()`](https://docs.python.org/3/library/functions.html#help "help") normally is sent to *sys.stdout*. You can capture that output in a string by redirecting the output to an [`io.StringIO`](https://docs.python.org/3/library/io.html#io.StringIO "io.StringIO") object. The replacement stream is returned from the `__enter__` method and so is available as the target of the [`with`](https://docs.python.org/3/reference/compound_stmts.html#with) statement:

```py
with redirect_stdout(io.StringIO()) as f:
    help(pow)
s = f.getvalue()
```  To send the output of [`help()`](https://docs.python.org/3/library/functions.html#help "help") to a file on disk, redirect the output to a regular file...
maiden fable
#

Ah well I have access to Message Intents, soooo

slate swan
#

!d nextcord.discord is a thing..?

unkempt canyonBOT
#

To work with the library and the Discord API in general, we must first create a Discord Bot account.

Creating a Bot account is a pretty straightforward process.

swift pumice
#
async def delete(ctx):
    await ctx( delay=None)
``` i want it that it auto deletes messages
#

can you guys help me?

quaint epoch
quaint epoch
#

await ctx.message.delete() ez

swift pumice
#

thanks

maiden fable
#

Nice, Nakime should think of getting a job soon or start depositing money

analog parrot
#

does anyone know the six errors

swift pumice
#
async def delete(ctx):
     await ctx.message.delete()``` @quaint epoch still doesnt work
swift pumice
swift pumice
quaint epoch
#

oh i know

maiden fable
#

Seems like more of a db issue ig

quaint epoch
#
@bot.command()
async def delete(ctx, messages:int=10):
  await ctx.message.delete(messages+1)```
#

there you go

maiden fable
#

then a JSON issue

quaint epoch
#

it is such a nice day outside, i should go for a walk

maiden fable
#

Nice cya!

slate swan
maiden fable
#

so is disnake.discord and discordpy.discord

maiden fable
#

Weird

#

Nice

slate swan
#

Bruh

maiden fable
#

use an if statement to check if money < 0

frozen patio
#

Ptero good

#

Anyways

#

How can I fix this it should have worked heh

swift pumice
maiden fable
#

Before someone can withdraw, make sure the remainder won't be less than 0 ig?

maiden fable
#

Yea

maiden fable
slate swan
#

!d discord.Guild.get_channel

unkempt canyonBOT
#

get_channel(channel_id, /)```
Returns a channel with the given ID.

Note

This does *not* search for threads.

Changed in version 2.0: `channel_id` parameter is now positional-only.
maiden fable
#

๐Ÿ˜

#

I uh

frozen patio
maiden fable
#

Hi there Snoggy!

swift pumice
stone beacon
#

Heyy

frozen patio
maiden fable
frozen patio
#

Then get an attribute error

swift pumice
swift pumice
slate swan
maiden fable
swift pumice
swift pumice
maiden fable
swift pumice
frozen patio
#

@slate swan I fixed

#

Change get_channel -> fetch_channel

maiden fable
slate swan
paper sluice
swift pumice
maiden fable
#

((output += f"{t} ") for t in text if t.parent.name not in self.element_blacklist) anyone has any idea how can I get smth like this to work?

paper sluice
#

!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/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission.

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

Ah u r looking for purge

paper sluice
#

maybe, i was very confused why they named delay message

swift pumice
paper sluice
maiden fable
swift pumice
#

okay

maiden fable
#
        for t in text:
            if t.parent.name not in self.element_blacklist:
                output += f"{t} "

Wanna change this to a list comp

paper sluice
#

change += to := with that adjustment

maiden fable
#

(output is already defined)

paper sluice
#

doesn't matter

#

!e

a = 10
[(a := a + 1) for _ in range(3)]
print(a)
unkempt canyonBOT
#

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

13
maiden fable
#

Oh cool thanks!

shrewd apex
#

btw is it fine if i host my discord bot on my rpi?

paper sluice
#

ya

maiden fable
shrewd apex
#

it's 3b+ model would there be decent performance?

shrewd apex
maiden fable
#

Niceee

paper sluice
shrewd apex
#

cool thx

swift pumice
#
async def on_message(message):
    if (message.content == "!test"):
        await message.delete()
``` hey guys how do i make that my bot deletes more than only 1 message
#

like it only deletes the !test message

swift pumice
#

what do you mean sry im new to python

paper sluice
#

do u know what if is?

swift pumice
swift pumice
paper sluice
#

then why do you look suprised?

slate swan
swift pumice
swift pumice
#

i dont clearly understand, why would i put now instead of event command

paper sluice
glad lagoon
#

I just get AttributeError: 'async_generator' object has no attribute 'flatten'

paper sluice
#

ya flatten got removed iirc

glad lagoon
#

hmm

#

Okay so what would be the best way of getting the last 2 messages sent?

Eg i want to get

message 1
message 2

When message 2 is sent

#

I tried this but message.content is just always blank for some reason

swift pumice
#

@paper sluice can you maybe help me?

glad lagoon
karmic marsh
#

alright, can confirm I know nothing

#

I need some help doing this

#

and I don't know what 'this' is

paper sluice
karmic marsh
#

this code does not work:

class Ask(commands.Cog):

    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def ask(inter):
        """Asks the user a question to confirm something."""
        # We create the view and assign it to a variable so we can wait for it later.
        view = Confirm()
        await inter.response.send("Do you want to continue?", view=view)
        # Wait for the View to stop listening for input...
        await view.wait()
        if view.value is None:
            print("Timed out...")
        elif view.value:
            print("Confirmed...")
        else:
            print("Cancelled...")


def setup(bot):
    bot.add_cog(Ask(bot))
#

it doesn't stop the bot from loading but it cashes when run

#

this is basically just the example of buttons adapted to be a cog

#

but clearly it doesn't quite work

#

the error I get is

disnake.errors.ClientException: Callback for ask command is missing "ctx" parameter.

swift pumice
# paper sluice what do u want to do?

i want that my code @bot.event async def on_message(message): if (message.content == "!delete"): await message.delete() deletetes more than 1 msg. so like if i type !delete 10 that it deletes 10 msgs. my problem is rn that it will only delete the msg !delete

karmic marsh
#

can anybody tell me what I'm doing wrong?

paper sluice
karmic marsh
#

yo okay I got it

#
async def ask(inter, ctx: commands.Context):

and

await ctx.send("Do you want to continue?", view=view)
swift pumice
quaint epoch
#

dagnabit, those damn seizures

paper sluice
paper sluice
paper sluice
#

brad u here?? ๐Ÿ‘€

slate swan
gaunt mortar
#

Hi guys, I got a strange issue with my Discord bot..
I was testing it on my PC in local and everything was fine

I'm now trying to make it run on my VPS (which is using Ubuntu, not Windows dunno if that makes a difference)
For a reason that I can't figure out, it seems like cogs are not loaded when I'm running the bot, I'm wondering if someone heres has an idea of what causes the problem and eventually, how to fix it ?

velvet compass
paper sluice
#

yes i knew you would respond, what is the max emojis u can send in one msg?

velvet compass
#

Hmmmm

#

I'm not sure if that is something that should be publicly disclosed tbh

maiden fable
#

nice, brad lurking

#

Time to join with my alt and test

velvet compass
#

A good rule of thumb might be to keep it under double digits

paper sluice
karmic marsh
#

could somebody show an example of a button in a modal?

#

I can't seem to figure it out

spring flax
#

dpy?

karmic marsh
#

disnake

spring flax
#

does discord even support that?

karmic marsh
#

uhh

#

I have no clue

spring flax
#

i know that select menus in modals are supported, but i'm not sure about buttons

karmic marsh
#

I thought so, but I might just be crazy

#

I've gotten selection menus working

#

so allow me to rephrase my question:

#

does anybody know whether it's possible to put a button in a modal?

sick birch
#

Not as of now I believe, theyโ€™re quite limited

karmic marsh
#

ah, alright

#

what elements do modals support then?

winged orchid
sick birch
#

Text fields, selects as mentioned I believe

karmic marsh
#

are those the only two?

winged orchid
#

Yes

karmic marsh
#

it appears to implement disnake.ui.WrappedComponent

#

which includes buttons

#

of course, the facts are against me on this one:

The specified component type is invalid in this context

slate swan
#
        try:
            mute = discord.utils.get(ctx.message.guild.roles, name ="ะœัƒั‚")
            await ctx.channel.purge(limit = 1)
            await member.add_roles(mute)
            
            if time > 0:
                if time1 == ["m", "M", "ะผ", "ะœ"]:
                    timeS = time * 60
                    time2 = 60
                if time1 == ["h", "H", "ั‡", "ะง"]:
                    timeS = time * 3600
                    time2 = 3600
                if time1 == ["d", "D", "ะด", "ะ”"]:
                    timeS = time * 86400
                    time2 = 86400
            else:
                time = 'ะ”ะพ ั€ะฐะทะฑะธั€ะฐั‚ะตะปัŒัั‚ะฒ'

            if time > 0:
                await asyncio.sleep(timeS)
                await member.remove_roles(mute)

        except discord.Forbidden:   return

Dear please tell me how to fix the error?

stable leaf
#

i want to make a slash commands but when i do pip install discord-py-slash-command and try from discord_slals import ___ it doesn't find any discord_slash

gaunt mortar
vale wing
stable leaf
gaunt mortar
#

Or just use discord-py which also supports slash commands ๐Ÿ‘€

vale wing
#

!pypi disnake

unkempt canyonBOT
stable leaf
vale wing
#

And have fun figuring out all that tree syncing stuff they have put in

#

Not discord bots related question

gaunt mortar
#

I'm trying to add my slash commands to each guild my bot joined, but self.guilds (in a subclass of commands.Bot) is returning an empty list instead of a list that contains 2 servers, does someone know why am I getting this result? The full command :

    async def setup_hook(self) -> None:
        for guild in self.guilds:
            for ext in self.initial_extensions:
                await self.load_extension(ext)
            await self.tree.sync(guild=discord.Object(id=guild.id))
vale wing
#

Afaik at the moment when setup_hook is called bot is not connected to discord yet so it can't access the guilds data (not completely sure about it tho)

gaunt mortar
odd mango
#

whats the advantage of using default discord.py bot help command over rather disabling it and manually making one?

vale wing
#

None

odd mango
#

whAT

vale wing
#

If I got you correctly there's no advantage

gaunt mortar
#

Except not having to do it yourself, there are no advantages

odd mango
#

bro istg, i just removed my custom 200 lines one, and wrote 100 more lines to modify default one for no reason??

#

๐Ÿ˜ญ

vale wing
#

What

#

If you subclassed the HelpCommand you did the right thing

odd mango
#

yeah

#

i am asking whats the advantage of subclassing over removing help command

vale wing
#

I wouldn't really call it "modifying the default one", it is custom

vale wing
stable leaf
vale wing
#

Yes

stable leaf
#

how?

odd mango
stable leaf
fading marlin
#

import app_commands from discord

stable leaf
#

thx

stable leaf
fading marlin
#

somewhat, yeah, they're kinda similar to normal prefix commands

stable leaf
#

can u send a link?

stable leaf
#

thx

spring flax
fading marlin
#

yes

#

but I wasn't showing code, I was just telling him from where to import it

odd mango
#

how do i access help <category> in subclassed help command

#

its just plain text, i wanna go embed it and stuff

fading marlin
#

send_cog_help iirc

odd mango
#

not using cogs

#

just classes

fading marlin
#

isn't help <category> just help <cog> though?

odd mango
#

i mean this thing

gaunt mortar
#
@client.event
async def on_ready():
    game = discord.Game('/help')
    await client.change_presence(status=discord.Status.online, activity=game)
    for ext in client.initial_extensions:
        await client.load_extension(ext)
    for guild in client.guilds:
        await client.tree.sync(guild=discord.Object(id=guild.id))
    print(client.cogs)

Cogs are loaded but commands are not working when used, am I synchronizing it in a wrong way?

fading marlin
odd mango
#

yeah

fading marlin
odd mango
#

command, my bad

stable leaf
#

maybe i am dumb

fading marlin
unkempt canyonBOT
#

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

Handles the implementation of the single command page in the help command.

It should be noted that this method does not return anything โ€“ rather the actual message sending should be done inside this method. Well behaved subclasses should use [`get_destination()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.HelpCommand.get_destination "discord.ext.commands.HelpCommand.get_destination") to know where to send, as this is a customisation point for other users.

You can override this method to customise the behaviour.

Note

You can access the invocation context with [`HelpCommand.context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.HelpCommand.context "discord.ext.commands.HelpCommand.context").
fading marlin
gaunt mortar
stable leaf
fading marlin
fading marlin
fading marlin
# odd mango any examples?

if my memory is correct, it should be something like this

async def send_command_help(self, command: commands.Command):
  #  do something
  await super().get_destination().send(...)

I'm guessing there should be an example in some gist somewhere

odd mango
#
def send_command_help(self, command):
        embed = self.embed_description(command.help, command)
        embed.set_author(name=self.get_command_signature(command))
        if command.aliases:
            embed.add_field(name="Aliases", value=", ".join(command.aliases))
        await self.send_embed(embed) ```
#

oh

gaunt mortar
fading marlin
gaunt mortar
fading marlin
#

yeah, you shouldn't generally do any API calls in on_ready, best if you just don't use it

fading marlin
fading marlin
#

commands.Bot has an activity and status kwarg if you wanna change its presence on startup

slate swan
#
    @commands.has_role(982744620792426537)
    @commands.command(name = "123")
    async def command_mutes(self, ctx, member: discord.Member, reason, time: int, *, time1):

        try:
            mute = discord.utils.get(ctx.message.guild.roles, name ="ะœัƒั‚")
            await ctx.channel.purge(limit = 1)
            await member.add_roles(mute)
            

            if time1 == "m":
                timeS = time * 60
                time2 = 60
            if time1 == "h":
                timeS = time * 3600
                time2 = 3600
            if time1 == "d":
                timeS = time * 86400
                time2 = 86400
            if time1 == "i":
                timeS = time * 1
                time2 = 1
            else:
                timeS = 0
                
            if time >=1:
                timeF = timeS
            else:
                timeF = 10

            await asyncio.sleep(timeF)
            await member.remove_roles(mute)
            await ctx.send("ะœัƒั‚ ัะฝัั‚")
        except discord.Forbidden:   return

Dear, please tell me why, when you enter (.123 @slate swan reason 10 m), the bot removes the mute not after 10 minutes, but after a second?

odd mango
gaunt mortar
fading marlin
odd mango
# fading marlin show code?
import discord
from itertools import starmap
from discord.ext import menus


class HelpPageSource(menus.ListPageSource):
    def __init__(self, data, helpcommand):
        super().__init__(data, per_page=6)
        self.helpcommand = helpcommand

    def format_command_help(self, no, command):
        signature = self.helpcommand.get_command_signature(command)
        docs = self.helpcommand.get_command_brief(command)
        return f"{no}. {signature}\n{docs}"
    
    async def format_page(self, menu, entries):
        page = menu.current_page
        max_page = self.get_max_pages()
        starting_number = page * self.per_page + 1
        iterator = starmap(self.format_command_help, enumerate(entries, start=starting_number))
        page_content = "\n".join(iterator)
        embed = discord.Embed(
            title=f"Help Command[{page + 1}/{max_page}]", 
            description=page_content,
            color=0xffcccb
        )
        author = menu.ctx.author
        embed.set_footer(text=f"Requested by {author}", icon_url=author.avatar.url) 
        return embed```
#

import aa

#

then use stuff from aa like
aa.stuff()

odd mango
#

yeah

#

that block is the help command thingy

fading marlin
#

what does that have to do with HelpCommand subclassing though?

odd mango
#

yeah

fading marlin
#

!d discord.ext.commands.Cog you'll want these if you want to have command in different files

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/latest/ext/commands/cogs.html#ext-commands-cogs) page.

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

What are you trying to do

odd mango
warped mirage
#
@client.command()
async def w(ctx, member: discord.Member = None):
    if member == None:
        member = ctx.author

    channel = await client.fetch_channel(970353123375874051)

    img = Image.open("pobrany plik.jpg")

    font = ImageFont.truetype("OMEGLE.otf", 225)
    font2 = ImageFont.truetype("OMEGLE.otf", 200)

    draw = ImageDraw.Draw(img)
    welcome = "WELCOME!"
    name = member.display_name

    draw.text((950, 750), welcome, (255, 225, 255), anchor="ms", font=font)
    draw.text((950, 950), name, fill="white", anchor="ms", font=font2)

    img.save("pimg.jpg")

    await channel.send(file=discord.File("pimg.jpg"))
    await asyncio.sleep(1)
    os.remove("pimg.jpg")```
odd mango
#

!d discord.ext.commands.Cog

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/latest/ext/commands/cogs.html#ext-commands-cogs) page.

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

If you just import it it won't work

fading marlin
warped mirage
#

how can i fix this

fading marlin
#

add the content that you want to send to the send function..?

vale wing
#

I know a tutorial for a fork

#

Depends what library you use, most likely gonna be suitable unless it is dpy 2.0

glad lagoon
warped mirage
# fading marlin well yeah, that's what this is doing `await channel.send(file=discord.File("pimg...
@client.command()
async def w(ctx, member: discord.Member = None):
    if member == None:
        member = ctx.author

    channel = await client.fetch_channel(970353123375874051)

    img = Image.open("pobrany plik.jpg")

    font = ImageFont.truetype("OMEGLE.otf", 225)
    font2 = ImageFont.truetype("OMEGLE.otf", 200)

    draw = ImageDraw.Draw(img)
    welcome = "WELCOME!"
    name = member.display_name

    draw.text((950, 750), welcome, (255, 225, 255), anchor="ms", font=font)
    draw.text((950, 950), name, fill="white", anchor="ms", font=font2)

    img.save("pimg.jpg")

    await channel.send(file=discord.File("pimg.jpg", "OMEGLE.otf"))
    await asyncio.sleep(1)
    os.remove("pimg.jpg")``` would this work
fading marlin
#

what're you trying to even do?

vale wing
warped mirage
vale wing
#

Damn I really need to continue working on my tutorial

#

@warped mirage and what the problem with your command is?

#

The image gets generated but doesn't get sent

warped mirage
#

just sends the image

vale wing
#

And what is expected output

warped mirage
#

send a text with the font i added

vale wing
#

On the image right?

warped mirage
#

yes

vale wing
#

So basically it doesn't add text to your base image

warped mirage
#

yes

vale wing
warped mirage
#

ok

livid hinge
#

you guys think cogs are worth it right

#

got someone complaining it made it more complicated .. but i think it makes it way easier to work on

remote stratus
#

!d discord.ext.commands.Cog

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/latest/ext/commands/cogs.html#ext-commands-cogs) page.

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

Interesting

livid hinge
#

if you're not using cogs you basically put everything in the same file?

fading marlin
fading marlin
#

you can still have helper functions and whatnot in other files ofc

remote stratus
#

Oh not talking to me.....๐Ÿ˜…

livid hinge
#

i like having a few small files with a couple added lines vs one big long file

remote stratus
#

mAh bad for jumping in convo

livid hinge
#

no you answerd me, thx

remote stratus
#

Aight aight

odd mango
#

!paste

livid hinge
#

ive got a semi relayted question

odd mango
livid hinge
#

i have a bot that is set up to reload cogs when it changes

fading marlin
livid hinge
#

but it seems to not work if theres too many reloads, like more than a couple . anyone else done that

fading marlin
livid hinge
#

the cog loads but no on ready event is the failure mode

fading marlin
fading marlin
livid hinge
#

if i make a small enough change it works beautifully haha

fading marlin
#

you're probably looking for something like cog_load (which you add inside your cog subclass)

livid hinge
#

oh maybe its the whole bot that gets reloaded

remote stratus
fading marlin
# odd mango

you haven't defined anywhere in your subclass what embed_description should be, nor does MinimalHelpCommand have such a method

livid hinge
#

!d discord.ext.commands.Bot.reload_extension is what im using

unkempt canyonBOT
#

await reload_extension(name, *, package=None)```
Atomically reloads an extension.

This replaces the extension with the same extension, only refreshed. This is equivalent to a [`unload_extension()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.unload_extension "discord.ext.commands.Bot.unload_extension") followed by a [`load_extension()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.load_extension "discord.ext.commands.Bot.load_extension") except done in an atomic way. That is, if an operation fails mid-reload then the bot will roll-back to the prior working state.
livid hinge
#

now i think i see what ive screwed up .. i was calling unload first

fading marlin
fading marlin
livid hinge
#

is there a case where the on_ready gets called again ?

#

like if you lose your connection or something

fading marlin
#

pretty sure if you loose connection and it reconnects it calls it again

odd mango
livid hinge
#

ok thats what it seemed like, just wanted to check if im doing smth weird

fading marlin
#

though if you wanna call the event once your cog gets reloaded you would have to do something like this

class Cog(commands.Cog):
    ...
    def cog_load(self):
        self.bot.dispatch("event")
livid hinge
#

i used watchdog for file monitoring and its pretty kludgy the way i have it lol

fading marlin
#

as a side note, you should generally not do much with on_ready (specially when it comes to API requests), since it gets called a lot and at random times

scarlet aurora
#

Why does this error?

fading marlin
fading marlin
scarlet aurora
#

company errors

fading marlin
#

?

scarlet aurora
fading marlin
#

oh

#

all args after a default should have defaults too

scarlet aurora
#

so company = None

vale wing
#

Why even make user arg optional

fading marlin
#

yeah

odd mango
livid hinge
#

if i had just read the doc for that function months ago it could have worked nicely this whole time haha ๐Ÿคฃ

livid hinge
#

where should it be done ? in a cog_load ?

fading marlin
#

if you're on 2.0, I'd recommend setup_hook

livid hinge
#

im not, still using the older one

fading marlin
#

then probably like a helper function of some sorts, and if you need your bot to be logged in before calling it, use bot.wait_until_ready() inside the function

livid hinge
#

the reason im still using the old one was i was getting some message seems like about load_extension that i couldnt figure out

#

maybe i'll try it again

fading marlin
#

on 2.0 everything cog-loading-related is async, so you'd go from

bot.load_extension(...)
def setup(bot: commands.Bot): 
    bot.add_cog(...(bot))

to

await bot.load_extension(...)
async def setup(bot):
    await bot.add_cog(...(bot))
livid hinge
#

i think i didnt have a setup_hook

#

oh ok yeah add_cog i think might have been part of it

fading marlin
livid hinge
#

so if i do

class Bot(Bot)
  ...
  async def setup_hook(self):
    await self.load_extension("ext")``` thats a good way to do it ?
fading marlin
#

yep

livid hinge
#

what makes it so you dont need to worry much about rate limits in the setup_hook in particular

fading marlin
#

it doesn't get called a bunch of times and randomly when your bot starts

#

not really sure how it internally works, but that's what it's supposed to do ig

scarlet aurora
#
    @commands.command()
    @commands.has_permissions(administrator=True)
    async def move(self, ctx, user: discord.Member = None, company = None):
        
        if user is None:
            await ctx.send("Choose someone to promote")
        
        if company is None:
            await ctx.send("Choose a company")

        data = []
        roles = [role.name for role in user.roles]

        Honor_Guard = discord.utils.get(user.guild.roles, name='Honor Guard')
        Catulan_Reaver = discord.utils.get(user.guild.roles, name='Catulan Reaver')
        Despoiler_Marine = discord.utils.get(user.guild.roles, name='Despoiler Marine')
        Seeker_Marine = discord.utils.get(user.guild.roles, name='Seeker Marine')
        Assault_Marine = discord.utils.get(user.guild.roles, name='Assault Marine')
        Destroyer_Marine = discord.utils.get(user.guild.roles, name='Destroyer Marine')
        Apothocarion = discord.utils.get(user.guild.roles, name='Apothocarion')
        Devastator_Marine = discord.utils.get(user.guild.roles, name='Devastator Marine')
        Techmarine = discord.utils.get(user.guild.roles, name='Techmarine')
        Librarians = discord.utils.get(user.guild.roles, name='Librarians')
        Breacher_Siege_Marine = discord.utils.get(user.guild.roles, name='Breacher Siege Marine')
        Chaplain = discord.utils.get(user.guild.roles, name='Chaplain')

        data.append(Honor_Guard)
        data.append(Catulan_Reaver)
        data.append(Despoiler_Marine)
        data.append(Seeker_Marine)
        data.append(Assault_Marine)
        data.append(Destroyer_Marine)
        data.append(Apothocarion)
        data.append(Devastator_Marine)
        data.append(Techmarine)
        data.append(Librarians)
        data.append(Breacher_Siege_Marine)
        data.append(Chaplain)

        if company == '1st':
            for roles in data:
                await user.remove_roles(roles)
                await user.add_roles(Chaplain)```Is there faster way
#

To do this?

fading marlin
#

yikes

#

you could do data.append(discord.utils.get(...)) instead, and maybe iterate through the roles ```py
for role_name in ("Honor Guard", "Catulan Reaver", ...):
data.append(discord.utils.get(..., name=role_name))

#

not really sure how fast it would get, but it'd be much more clean than before lol

sick birch
#

exactly like Lee said

#

A list comp might be even better

fading marlin
livid hinge
#

99% sure i am doing way too much in on_ready

sick birch
#
role_names = (
  ...
)

data = [discord.utils.get(..., name=role_name) for role_name in role_names]
# OR
data = map(lambda role_name: discord.utils.get(..., name=role_name), role_names)
sick birch
livid hinge
#

oh gotcha

#

then i will not try to make api calls there lol

slate swan
vale wing
livid hinge
#

a task would make sense prob

vale wing
#

Comprehensed py data = [r for r in guild.roles if r.name in roles_names]

livid hinge
#

its just some house keeping stuff with roles

slate swan
livid hinge
#

oop that list doc still missing ig

#

ok cool

#

.loop?

slate swan
#

Bot.loop

livid hinge
#

so self.bot.loop or self.loop depending where

slate swan
#

if self is a subclass of the Bot class yes, if self.bot is literal to a Bot class instance yes

livid hinge
#

didnt realize it was that easy to get the event loop

#

i get to delete some code ๐Ÿ˜Ž

unkempt canyonBOT
#

discord/client.py line 209

self.loop: asyncio.AbstractEventLoop = _loop```
slate swan
unkempt canyonBOT
#

discord/client.py line 101

class _LoopSentinel:```
scarlet aurora
#

how can I refer back to the roles?

#
        if company == '1st':
            for roles in data:
                await user.remove_roles(roles)
                await user.add_roles('Honor Guard')``` Would this work?
slate swan
fading marlin
scarlet aurora
#

so how can I refer back to the roles that were appended?

vale wing
scarlet aurora
#

oh ok

vale wing
#

Pretty sure your roles is actually role tho

scarlet aurora
vale wing
scarlet aurora
vale wing
# scarlet aurora how can I refer back to the roles?

This construction makes no sense btw โ€” you literally add the same role every time you remove some other. If you intend to remove all roles in data from the user and add a single role, use this

await user.remove_roles(*data)
await user.add_roles(honor_guard_role)```
scarlet aurora
#

does that mean there are no variables?

#

@vale wing so smthing like this ```py
@commands.command()
@commands.has_permissions(administrator=True)
async def move(self, ctx, user: discord.Member = None, company = None):

    if user is None:
        await ctx.send("Choose someone to promote")
    
    if company is None:
        await ctx.send("Choose a company")

    data = []
    roles = [role.name for role in user.roles]


    for role_name in ('Honor Guard', 'Catulan Reaver', 'Despoiler Marine', 'Seeker Marine', 'Assault Marine', 'Destroyer Marine', 'Apothocarion',
        'Devastator Marine', 'Techmarine', 'Librarians', 'Breacher Siege Marine', 'Chaplain'):
        data.append(discord.utils.get(user.guild.roles, name=role_name))




    if company == '1st':
        for roles in data:
            await user.remove_roles(*data)
            await user.add_roles('Honor Guard')```
livid hinge
#

do you mean to add a role object there

vale wing
livid hinge
#

idk if this is a problem but it seems to imply it will let them choose but always does Honor Guard

#

oh nvm it is doing something else

#

you get demoted to honor guard when you are noved

vale wing
scarlet aurora
#

oh ok

#

ty

sick birch
#

I believe commands.MissingRequiredArgument provides an attribute that tells you which argument was missing

#

You can use that to provide more customized error messages

formal basin
#

Hello Iโ€™m trying to make a notification were when someone plays a game and it shows on their discord profile then the bot will send a message but I have a problem what do I put here

sick birch
#

Can you paste the relevant code instead of sending a screenshot?

formal basin
sick birch
#

Given isinstance(error, commands.MissingRequiredArgument) is True

formal basin
sick birch
#

Paste your code and any errors

#

Don't send a screenshot

formal basin
#

@client.event
async def on_member_update(self, before, after):
        if after.guild.id == 964841408257200179:
            if before.activity == after.activity:
                return

            role = get(after.guild.roles, id=984560896460357633)
            channel = get(after.guild.channels, id=984561160953139231)

            async for message in channel.history(limit=200):
                if before.mention in message.content and "is now playing" in message.content:
                    if isinstance(after.activity, Playing):
                        return

            if isinstance(after.activity, Playing):
                await after.add_roles(role)
                playing_service = playing_game_split[1]
                playing_service = Playing_game.capitalize()
                await channel.send(f"{before.mention} is now playing {playing_service}")
            elif isinstance(before.activity, Playing):
                await after.remove_roles(role)
                async for message in channel.history(limit=200):
                    if before.mention in message.content and "is now playing" in message.content:
                        await message.delete()
            else:
                return

sick birch
#

Any errors?

formal basin
#

Yeah

Undefined name โ€œplaying_gameโ€

sick birch
#

First things I noticed, use guild.get_* methods instead of utils.get(...)

formal basin
sick birch
#

guild.get_* is cleaner, it's also O(1) due to hash map lookup. utils.get(...) I believe is exponential

#

I know, but issues like that are distracting when it comes to finding the main issue

formal basin
#

Ok

#

But do you know the problem Iโ€™m having?

sick birch
#

And another thing, this entire chunk doesn't do anything:

            async for message in channel.history(limit=200):
                if before.mention in message.content and "is now playing" in message.content:
                    if isinstance(after.activity, Playing):
                        return
sick birch
#
                playing_service = playing_game_split[1]
                playing_service = Playing_game.capitalize()

you reference it here, but it's not defined before

formal basin
#

So what do I put instead of playing_game

sick birch
#

member.activity.name can be used to find the name of the game, given it's an instance of discord.Game

formal basin
#

Ok

#

Thanks

sick birch
#
if isinstance(member.activity, discord.Game):
  activity_name = member.activity.name
#

The typeguard is important

karmic marsh
#

quick question

#

how do I delete this message after it's been sent?

#
msg = await inter.response.send_message("Do you want to continue?", view=view)
vale wing
#

What lib

crisp drift
#

you can use the delete_after kwarg

vale wing
#

Pretty sure most of them don't return anything tho

vale wing
karmic marsh
#

disnake

paper sluice
crisp drift
#

Then he can use the on_interaction callback and delete the message from it

vale wing
karmic marsh
#

yup, that's why I assign to msg

#

I just don't know what I need to do to delete msg

vale wing
#

Most inter.send don't return message object afaik

karmic marsh
#

ah, okay

vale wing
#

You can access the message in your View's callback interaction

#

How do you implement the view

karmic marsh
#
class Confirm(disnake.ui.View):
    def __init__(self):
        super().__init__()
        self.value = None

    @disnake.ui.button(label="Confirm", style=disnake.ButtonStyle.green)
    async def confirm(self, button, interaction):
        await interaction.response.send_message("Confirming", ephemeral=True)
        self.value = True
        self.stop()

    @disnake.ui.button(label="Cancel", style=disnake.ButtonStyle.grey)
    async def cancel(self, button: disnake.ui.Button, interaction: disnake.MessageInteraction):
        await interaction.response.send_message("Cancelling", ephemeral=True)
        self.value = False
        self.stop()
#

it's just the default example

vale wing
#

Try adding await inter.delete_original_message() or await inter.message.delete() (I don't remember what exactly the first one does but might work too) to each callback

karmic marsh
#

seems excessive

#

shouldn't there be a way to delete the bot's message?

vale wing
#

!d disnake.InteractionResponse.send_message one check

unkempt canyonBOT
#

await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., allowed_mentions=..., view=..., components=..., tts=False, ephemeral=False, suppress_embeds=False, delete_after=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Responds to this interaction by sending a message.
karmic marsh
vale wing
sick birch
#

Ah

karmic marsh
#

it works for a regular command with ctx but not a slash command with inter

vale wing
sick birch
#

I assumed it would as sending a regular message does

#

Then yeah that's the right way to do it

karmic marsh
#

the issue with deleting after the button is pressed is that then a timeout doesn't delete

vale wing
#

Sorry what

odd mango
#

hey

#

can any of these be observed from within the discord?

command_callback
filter_commands
on_help_command_error
prepare_help_command```
#

cause i am only doing these to make it look cool in an embed and stuff

vale wing
odd mango
#

and how do the default outputs look like

vale wing
#

Default output right?

odd mango
#

yeah

vale wing
odd mango
#

cool!

#

looks like it gives no output, peace then

karmic marsh
#

Alright, I figured out deleting original message

#
await inter.send("Do you want to continue?", view=view)
await view.wait()
await inter.delete_original_message()
odd mango
#

what is the optimal way to handle CommandNotFound error

scarlet aurora
#
await user.remove_roles(roles)``` roles is an array, how can I get this to remove the roles in 1 go
#

and not keep looping through

odd mango
#

you do need to loop it if its an array

#
roles = []
for role in roles:
    await user.remove_roles(roles)```
scarlet aurora
#

it loops only once

#

but for some reaosn

#

it keeps removing the role

karmic marsh
#

there's no difference between looping through it manually and whatever 'in one go' solution you could find (which would actually just be looping on the backend)

odd mango
#

thats just _ looping on the backend_

torn sail
#

No itโ€™s not

odd mango
#

wat

scarlet aurora
odd mango
#

ohh right

remove_roles(*[roleOne, roleTwo])```
torn sail
#

Yeah this

scarlet aurora
#

what goes in roleone, role two ??

odd mango
#

get roles from guild

scarlet aurora
#

i wanted to remove the roles in data

#
        roles = [role.name for role in user.roles]```
odd mango
#

but you never used data

scarlet aurora
#
        if company == '1st':
            for roles in data:
                await user.remove_roles(*[])
                await user.add_roles(Honor_Guard)```
odd mango
#

no need for for loop there

scarlet aurora
#

so what do I do

odd mango
#
        if company == '1st':
                await user.remove_roles(*data)
                await user.add_roles(Honor_Guard)```
odd mango
#

if you know about it

scarlet aurora
#

it removes all the rnaks

#

it removes Honor_Guard that was added

#

i mean

odd mango
#

...

#

lmao just remove honor guard role from data

scarlet aurora
#

BROOO

#

I CAN'T DO THAT

#

because if they choose '2nd' for example, it will ask to remove a different role that's in data

odd mango
#

oh

#

then uh try sleeping 1 sec before adding Honor_Guard

scarlet aurora
#

alr

scarlet aurora
#

async sleep or time sleep

odd mango
#

time sleep

#

is what i prefer, your choice really

potent spear
odd mango
#

not mine, the other guy

#

yeah seems like it

potent spear
#

is it his intention?

odd mango
#

yeah

potent spear
#

well, just filter out that role before removing it all, lol

#

removing it first and adding it again is fucked up ofc

odd mango
#

yeah right

potent spear
#

can be done with a simple list comprehension

#

await member.remove_roles([role for role in member.roles if role.id != <honor guard role id>])

#

or to split things up
member_roles_except_honour_guard = [role for role in member.roles if role.id != <honor guard role id>]
await member.remove_roles(member_roles_except_honour_guard )

scarlet aurora
odd mango
#

no they want to remove all roles, and then add honor guards
what if a user dosent already have honor guard

potent spear
#

then filter it out anyways...

#

its not like it would error

odd mango
#

yeah it looks cool

torn sail
#

it is blocking

odd mango
torn sail
#

do you mean within the code or a response to the user?

odd mango
#

no bot gives response about that, so i think just within the code

karmic marsh
#

is it possible to edit an ephemeral message?

odd mango
#

edit? idts

#

will it be py @bot.event async def on_command_error(ctx, error): if isinstance(error, CommandNotFound): return raise error

heady sluice
odd mango
#

peace

karmic marsh
#

I would like to send a response to a slash command with an ephemeral message containing buttons

#

and then edit the response after a button is pressed

scarlet aurora
#
        if company == '1st':
            for roles in data:
                await user.remove_roles([role for role in user.roles if role.name != 'Honor Guard'])``` @odd mango @potent spear what about this? why doesn't this work
potent spear
scarlet aurora
#

why not

potent spear
#

also, the for loop is useless

odd mango
#

i told them that

odd mango
scarlet aurora
#

ok

potent spear
scarlet aurora
#

1 last thing

#

it aint working

odd mango
#

๐Ÿ˜‚

potent spear
#

what is data?

#

I could tell you
shit("a")
"this function isn't working"

that's the equivalent of info I'm getting from you currently

scarlet aurora
#
    @commands.command()
    @commands.has_permissions(administrator=True)
    async def move(self, ctx, user: discord.Member = None, company = None):
        
        if user is None:
            await ctx.send("Choose someone to promote")
        
        if company is None:
            await ctx.send("Choose a company")

        data = []
        roles = [role.name for role in user.roles]

        Honor_Guard = discord.utils.get(user.guild.roles, name='Honor Guard')
        Catulan_Reaver = discord.utils.get(user.guild.roles, name='Catulan Reaver')
        Despoiler_Marine = discord.utils.get(user.guild.roles, name='Despoiler Marine')
        Seeker_Marine = discord.utils.get(user.guild.roles, name='Seeker Marine')
        Assault_Marine = discord.utils.get(user.guild.roles, name='Assault Marine')
        Destroyer_Marine = discord.utils.get(user.guild.roles, name='Destroyer Marine')
        Apothocarion = discord.utils.get(user.guild.roles, name='Apothocarion')
        Devastator_Marine = discord.utils.get(user.guild.roles, name='Devastator Marine')
        Techmarine = discord.utils.get(user.guild.roles, name='Techmarine')
        Librarians = discord.utils.get(user.guild.roles, name='Librarians')
        Breacher_Siege_Marine = discord.utils.get(user.guild.roles, name='Breacher Siege Marine')
        Chaplain = discord.utils.get(user.guild.roles, name='Chaplain')

        data.append(Honor_Guard)
        data.append(Catulan_Reaver)
        data.append(Despoiler_Marine)
        data.append(Seeker_Marine)
        data.append(Assault_Marine)
        ...

        if company == '1st':
            for roles in data:
                await user.remove_roles([role for role in user.roles if role.name != 'Honor Guard'])
                time.sleep(1)
                await user.add_roles(Honor_Guard)```
potent spear
#

alright

#

simple fix

#

remove this shit

if company == '1st':
            for roles in data:
                await user.remove_roles([role for role in user.roles if role.name != 'Honor Guard'])
                time.sleep(1)
                await user.add_roles(Honor_Guard)```
replace with
```py
if company == '1st':
  member_roles_except_honor_guard = [role for role in user.roles if role.id != <honor guard role id>]
  await user.remove_roles(member_roles_except_honor_guard )```
#

also, replace all those names with ID's please
unless you want your bot to work in multiple guilds...

scarlet aurora
#

i want for role in data

potent spear
#

no you don't

scarlet aurora
#

?

potent spear
#

not needed

scarlet aurora
#

but i only want to to remove roles that the user.roles have that sync with data

#

cause I don't want to remove external ranks

potent spear
scarlet aurora
#

yes

potent spear
#

then use IDs instead

scarlet aurora
#

sooo, how I do this?

#

make it remove only the ranks from data and user.roles

potent spear
#

create some sort of config file which looks like

#
{
"Honor Guard": 515151,
"Catulan Reaver": 5151515,
...}```
scarlet aurora
#

alr

#

json

potent spear
#

because most likely, you'll need those IDs in multiple commands ,right?

scarlet aurora
#

prolly not

potent spear
#

well, in that case, you can optionally just initialize it in that command only

#

just call it rank_role_name_id_dict

#

no json needed then

#

once that's done, you can do some sexy stuff

scarlet aurora
#

done

potent spear
#

alright

scarlet aurora
#

I finished the json

#

file

potent spear
#

no file needed in your case

scarlet aurora
#

r u serious

potent spear
#

you can just initialize it in the command

scarlet aurora
#

do u know how long that just took me

potent spear
scarlet aurora
#

we might as well use the json file

potent spear
#

it's just rank_role_... = {<your file shit>}

scarlet aurora
#

oh ok

#

d one

potent spear
scarlet aurora
#

but i kinda need da variables

potent spear
#

for?

scarlet aurora
#

to add those roles

#

to the people

potent spear
#

nope, let's say you need only Honor guard and Catulan Reaver, right?

scarlet aurora
#

12 ranks

#

but i still need the variables

#

or not?

potent spear
scarlet aurora
potent spear
#

unless for every separate option, you have different roles to give

karmic marsh
#

is it possible to make a slash command show only to the issuer without making it ephemeral?

odd mango
#

i dont get pycharm, here ctx is needed but pycharm says its not being used

scarlet aurora
#

exactly that

#
        if company == '1st':
            hg = [role for role in user.roles if role.id != <honor guard role id >]
            await user.remove_roles(hg)
            time.sleep(1)
            await user.add_roles(Honor_Guard)

        if company == '2nd':
            for roles in data:
                await user.remove_roles(*data)
                time.sleep(1)
                await user.add_roles(Catulan_Reaver)

        if company == '3rd':
            for roles in data:
                await user.remove_roles(*data)
                time.sleep(1)
                await user.add_roles(Despoiler_Marine)

        if company == '4th':
            for roles in data:
                await user.remove_roles(*data)
                time.sleep(1)
                await user.add_roles(Seeker_Marine)```
odd mango
#

remove the for loops lmao

potent spear
#

remove all the time sleeps
use elifs

scarlet aurora
#

alr

#

say less

odd mango
#

dont like the slight warning bugging me

#

can i go disable it somewhere

potent spear
#

then
use this
await user.add_roles(ctx.guild.get_role(rank_role_name_id_dict["Honor Guard"]))

odd mango
#

its annoying to see that lmao

torn sail
#

yeah

scarlet aurora
#

done

potent spear
#

but in the back of your head, you know that it's ctx

potent spear
scarlet aurora
#
        if company == '1st':
            hg = [role for role in user.roles if role.id != <honor guard role id >]
            await user.remove_roles(hg)
            await user.add_roles(ctx.guild.get_role(rank_ids["Honor Guard"]))

        elif company == '2nd':
            for roles in data:
                await user.remove_roles(*data)
                await user.add_roles(Catulan_Reaver)```
karmic marsh
potent spear
odd mango
scarlet aurora
#

ye I haven't started on 2nd one yet

odd mango
#

ditch it aint discord bot related anyways

potent spear
scarlet aurora
#

alr

potent spear
#

also, please rename the arg to member, since member and user are different objects

odd mango
#

can static data stored in json handle constant and heavy fetching?

potent spear
#

use case?

#

static data would only be read once anyways... no need to open that json file every time...

scarlet aurora
#
        if company == '1st':
            hg = [role for role in user.roles if role.id != (rank_ids["Honor Guard"])]
            await user.remove_roles(hg)
            await user.add_roles(ctx.guild.get_role(rank_ids["Honor Guard"]))

        elif company == '2nd':
            await user.remove_roles(*data)
            await user.add_roles(Catulan_Reaver)```
scarlet aurora
#

there is a chance

#

but it's not intended for that

potent spear
scarlet aurora
#

hg = honour guard

#

i'm fine with that

potent spear
#

yes, but that's not what the list represents

scarlet aurora
#

i understand, everything except hg

potent spear
#

it's a list of all ranks EXCEPT honour guard

scarlet aurora
#

alright hold on

potent spear
#

that's list comprehension, you should read more on that
example

shit = []
for number in range(5):
  shit.append(number)

# is the exact same as
shit = [number for number in range(5)]
scarlet aurora
#

alright

potent spear
#

what if honour guard was already a role he got? then he got it for nothing...?

scarlet aurora
#

wdym

potent spear
#

your "except_hg"
is currently a list of all roles the member has EXCEPT the honour guard role (if he even got it)

#

you previously mentioned that you don't want to remove certain roles...

scarlet aurora
#

yes

#

i only want to remove the ones in data = []

potent spear
#

well, then that except_hg makes no sense

scarlet aurora
#

i was just looking at that and realised that it would remove all ranks except hg lool

#

it should be for roles in data

potent spear
#

are you even sure you're removing roles the user has?

scarlet aurora
#

yes

potent spear
#

what if you're removing roles of the member and he doesn't even have that role...?

scarlet aurora
#

removing only marine ranks

#

all those ranks, are marine ranks, when the command is executed, his marine command gets wiped and gets the new one

potent spear
#

have you checked out list comprehension by now?

scarlet aurora
#

yeah

potent spear
#

because this is what it should look like without list comprehension:

marine_rank_role_ids_except_hg = []
for rank_role_id in marine_ranks_dict.values():
  if rank_role_id != <hg role id>:
  marine_rank_role_ids_except_hg.append(rank_role_id)```
#

I hope you know what .values() does

scarlet aurora
#

ofc i know what values does

#

selects all values in the array

potent spear
#

the ~dict, yeah

scarlet aurora
#

would it be easier if I screen share?

potent spear
#

ofc not

#

you can perfectly move on now

scarlet aurora
#

ok

odd mango
#

casual question, can i make a command to EDIT dict keys? cause the dict values are too long and i dont wanna scroll just to edit keys

potent spear
# scarlet aurora ok

you can make it even better

marine_rank_role_except_hg = []
for rank_role_id in marine_ranks_dict.values():
  if rank_role_id != <hg role id>:
  rank_role = ctx.guild.get_role(rank_role_id)
  marine_rank_role_ids_except_hg.append(rank_role)

await member.remove_roles(marine_rank_role_except_hg)```
potent spear
#

async def change_shit(ctx, key:str, new_value: str)
(this is if the key and value are 1 word, else you'll need another approach)

scarlet aurora
#
        if company == '1st':

            marine_rank_role_except_hg = []
            for rank_role_id in marine_ranks_dict.values():
                if rank_role_id != (rank_ids["Honor Guard"]):
                    rank_role = ctx.guild.get_role(rank_role_id)
                    marine_rank_role_ids_except_hg.append(rank_role)

            await user.remove_roles(marine_rank_role_except_hg)
            await user.add_roles(ctx.guild.get_role(rank_ids["Honor Guard"]))``` @potent spear  What is marine_ranks_dict.values ??
potent spear
odd mango
#

both

potent spear
potent spear
# odd mango both

well idk why you want to change the json regularly, but this feels like you need a db

karmic marsh
#

okay, this is starting to really frustrate

potent spear
#

not very "static" if you'd ask me

karmic marsh
#

I want to respond to a slash command with some buttons for the user to press

odd mango
#

this is only once

potent spear
#

when and why?

karmic marsh
#

and then I want the response to change once the user has responded

odd mango
#

after i am done editing it for a nice 1 hour sitting, the json is static forever afterwards

scarlet aurora
#

@potent spear thanks a lot for ur help

karmic marsh
#

I don't care if that means deleting the first response, editing it, or what

#

and I want this to only be visible to the user sending it, which is what causes problems

potent spear
karmic marsh
#

because you can't edit an ephemeral response, and you can't delete an ephemeral response

odd mango
karmic marsh
#

as far as I can tell

potent spear
odd mango
#

you can say i am just writing the json

karmic marsh
#

so then I can't do what I want

#

because you can't do the whole hidden=True on a slash command

potent spear
karmic marsh
#

so then how do you edit an ephemeral message

#

that becomes the big question

#

and as far as I can tell, you can't

scarlet aurora
#

@potent spear discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'list' object has no attribute 'id'

potent spear
scarlet aurora
#

full trace back ```Ignoring exception in command move:
Traceback (most recent call last):
File "C:\Users\llVll\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\llVll\Desktop\Luna Bot\cogs\utils.py", line 145, in move
await user.remove_roles(except_hg)
File "C:\Users\llVll\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\member.py", line 822, in remove_roles
await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'list' object has no attribute 'id'

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

Traceback (most recent call last):
File "C:\Users\llVll\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\llVll\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\llVll\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'list' object has no attribute 'id'```

scarlet aurora
#
        if company == '1st':

            except_hg = []
            for rank_role_id in rank_ids.values():
                if rank_role_id != (rank_ids["Honor Guard"]):
                    rank_role = ctx.guild.get_role(rank_role_id)
                    except_hg.append(rank_role)

            await user.remove_roles(except_hg)
            await user.add_roles(ctx.guild.get_role(rank_ids["Honor Guard"]))``` code ^^
potent spear
#

you have to do
await user.remove_roles(*****except_hg)

#

the *

scarlet aurora
#

ah ofc

#

astrisk

odd mango
# potent spear when and why?

the json is directly scraped from a website and i dont like its key names so i just want to edit it to whatever i want and then use the json. after i am done editing the json IT WILL REMAIN UNTOUCHED hence static forever after that

potent spear
karmic marsh
potent spear
#

you can do
async def change_shit(ctx, key:str, * ,new_value: str)
command can be called like
!change_shit "my key value" this is my new value

potent spear
odd mango
#

so like this

#

!change_shit "small shit" very big shit

karmic marsh
#

okay so does somebody here know how to edit an ephemeral message

potent spear
#

unless you want to split by - or whatever

karmic marsh
#

here's my code:

class Confirm(disnake.ui.View):
    def __init__(self):
        super().__init__()
        self.value = None

    @disnake.ui.button(label="Confirm", style=disnake.ButtonStyle.green)
    async def confirm(self, button, interaction):
        await self.edit("Confirming", ephemeral=True) # This doesn't work
        self.value = True
        self.stop()

class Ask(commands.Cog):

    def __init__(self, bot):
        self.bot = bot

    @commands.slash_command()
    async def ask(inter):
        """Asks the user a question to confirm something."""
        view = Confirm()
        await inter.send("Do you want to continue?", view=view, ephemeral=True)
#

I just need something instead of ```py
await self.edit("Confirming", ephemeral=True)

#

there has to be some solution

scarlet aurora
#

@potent spear it takes like 5 seconds to add the rank, is that normal?

potent spear
scarlet aurora
#

the same code we made together

karmic marsh
#

this is driving me crazy

stark fable
#

Hi guys, can someone help me ?

sick birch
stark fable
# sick birch ask away

I m developing a simple discord bot that starts when I type a command (for example !start) and then enters in an infinite loop. I wanna implement a command !stop to pause the bot and then I can type again !start to restart the bot
Note that I donโ€™t want to turn offline the bot, it should be online always, even if itโ€™s on pause. I hope you understand my problem, sorry for bad English

frozen patio
#

How can I fix this heh

scarlet aurora
#

@potent spear

potent spear
scarlet aurora
#

@potent spear Can you help me with this? ```py
@commands.command()
@commands.has_permissions(administrator=True)
async def promote(self, ctx, user: discord.Member = None):

    if user is None:
        await ctx.send("Choose someone to promote")

    rank_ids = {
        "Luna Wolves": 939938651209617498,
        "Neophytes": 857617871290630184,
        "Battle Brother": 890735518982230046,
        "Sergeant": 857616094469947392,
        "Lieutenant": 889420538160742410,
        "Cheiftan": 889421271954251786
    }

    role = user.roles

    if role in rank_ids.values():
        if user.roles(rank_ids["Luna Wolves"]):
            await (ctx.guild.remove_role(rank_ids["Luna Wolves"]))
            await (ctx.guild.add_role(rank_ids["Neophytes"]))

        elif user.roles(rank_ids["Neophytes"]):
            await (ctx.guild.remove_roles(rank_ids["Neophytes"]))
            await (ctx.guild.add_roles(rank_ids["Battle Brother"]))

        elif user.role(rank_ids["Battle Brother"]):
            await (ctx.guild.remove_roles(rank_ids["Battle Brother"]))
            await (ctx.guild.add_roles(rank_ids["Sergeant"]))

        elif user.role(rank_ids["Sergeant"]):
            await (ctx.guild.remove_roles(rank_ids["Sergeant"]))
            await (ctx.guild.add_roles(rank_ids["Lieutenant"]))

        elif user.role(rank_ids["Lieutenant"]):
            await (ctx.guild.remove_roles(rank_ids["Lieutenant"]))
            await (ctx.guild.add_roles(rank_ids["Cheiftan"]))

        elif user.role(rank_ids["Cheiftan"]):
            await ctx.send(f"``{user} is at the highest rank possible")```
stark fable
potent spear
frozen patio
scarlet aurora
#

no error just doesn't work

potent spear
potent spear
stark fable
scarlet aurora
karmic marsh
#

okay... this should be an easy problem to solve: I'm trying to edit this message (which has a View element in it) after one of the buttons in the View is clicked. So far I can edit the text, but I would also like to remove the buttons and not have the 'interaction failed' message
here is the code:

class Confirm(disnake.ui.View):
    def __init__(self,):
        super().__init__()
        self.value = None

    @disnake.ui.button(label="Confirm", style=disnake.ButtonStyle.green)
    async def confirm(self, button, interaction):
        self.value = True
        self.stop()

    @disnake.ui.button(label="Cancel", style=disnake.ButtonStyle.grey)
    async def cancel(self, button, inter):
        await inter.send()
        self.value = False
        self.stop()

class Ask(commands.Cog):

    def __init__(self, bot):
        self.bot = bot

    @commands.slash_command()
    async def ask(inter):
        """Asks the user a question to confirm something."""
        view = Confirm()
        await inter.send("Do you want to continue?", view=view, ephemeral = True)
        await view.wait()
                # There needs to be a line here to remove the View's elements
        if view.value is None:
            await inter.edit_original_message("Timed out")
        elif view.value:
            await inter.edit_original_message("Confirmed")
        else:
            await inter.edit_original_message("Cancelled")
frozen patio
potent spear
# scarlet aurora how

the if statement would look like
if rank_ids["Neophytes"] in [role.id for role in user.roles]:

potent spear
potent spear
scarlet aurora
frozen patio
potent spear
stark fable
potent spear
frozen patio
#

I do not think that matters??

scarlet aurora
#

thanks

potent spear
frozen patio
#

The warning didn't change anything

karmic marsh
#

okay come on

#

does nobody here know about views?

#

like having a button attached to a message?

#

I just want to remove the button once it has been interacted with

potent spear
karmic marsh
#

isn't disabled just a visual style?

potent spear
#

try and see

karmic marsh
#

I want to completely remove it

frozen patio
#

Hmmmm

#

I would rather do what Sniper up here said

#

Cause you still cannot use those

karmic marsh
#

I want it to disappear completely

#

I am changing the text of the message when the button is pressed

#

I want it to look like a response

frozen patio
#

Then change like the others to gray and the one clicked is like green?

karmic marsh
#

I want this:

#

to become this:

#

by editing the original response

frozen patio
#

Just do what you did there in the original message

karmic marsh
#

this is what my code is doing currently:

#

the text changes

#

but the buttons stay

#

and it says interaction failed

#

here's the code that I have:

#
class Confirm(disnake.ui.View):
    def __init__(self,):
        super().__init__()
        self.value = None

    @disnake.ui.button(label="Confirm", style=disnake.ButtonStyle.green)
    async def confirm(self, button, interaction):
        self.value = True
        self.stop()

    @disnake.ui.button(label="Cancel", style=disnake.ButtonStyle.grey)
    async def cancel(self, button, inter):
        button.disabled = True
        self.value = False
        self.stop()

class Ask(commands.Cog):

    def __init__(self, bot):
        self.bot = bot

    @commands.slash_command()
    async def ask(inter):
        """Asks the user a question to confirm something."""
        view = Confirm()
        await inter.send("Do you want to continue?", view=view, ephemeral = True)
        await view.wait()
        view.clear_items() # does nothing
        if view.value is None:
            await inter.edit_original_message("Timed out")
        elif view.value:
            await inter.edit_original_message("Confirmed")
        else:
            await inter.edit_original_message("Cancelled")
#

I can edit the text just fine

#

AH

#

I got it

#

rubber duck programming lmao

frozen patio
karmic marsh
#
await inter.edit_original_message("Timed out", view=None)```
#

set the view to none when I edit and it does exactly what I want

slate swan
#
def clear_views():
     return None
await inter.edit_original_message("uwu", view=clear_views())

uwu

karmic marsh
#

now, is there a way to set the view to only one of its elements?

slate swan