#discord-bots
1 messages ยท Page 1094 of 1
Like where would you store the database
It's replit
u know whats happening
SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
u have 1gb
Ignore this warning
Replit feature
True. Replit is good for some little tests to not shutdown your complete bot
or you can use any external db
i ignore replit dosent
Just make github actions + docker work together that works perfect
So much work
its saying to pip install ur stuff
but I also use a vps and it's better. Replit bans you for a certain time when u restart your bot very often
what are you trying to install
Yeah takes a while to figure out
@shrewd apex
whats in it
How did u fix this issue?
yeah
oh lmao i found the correct encoding
and used that and have a few try except blocks
Then you just make a workflow https://github.com/Exenifix/AIAS/blob/master/.github/workflows/runner.yml
and a docker file https://github.com/Exenifix/AIAS/blob/master/Dockerfile
ez
Nice the resource usage
Ah I think my error is fixed
encoding="utf-8" adding this in the open()
how do i make a pass statement for buttons instead of ephemeral message
i just dont want this interaction failed stuff
Weird thing is it didn't work when I didn't specify
just make sure you catch the errors that might get raised
there are no errors inside the code, just this interaction failed in discord
because the button might be timed out
so it wont respond
nah i disable them on timeout
huh, do u have a callback for the button which fails?
ya :/
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_
I really have 0 error handlers in My code
GG
because u are not responding to the interaction
u need to respond to it, other wise it will say that
!paste
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.
i know, i want it to pass when someone else hits them DUH
i dont want them to see error message
Best of Luck trying to understand this
remember me telling something about aiohttp and dpy? its that
i dont think u can do that, u will have to edit the message with the same contents
U can't without doing anything on discord
there are python git repos which do that, so there should be some way
no errors when someone else hits
f i just remembered
lmao
what's that
Can u send link of 1 of them
sure
it seems aiohttp is not allowed in replit
it is allowed, it just dosent work w dpy there
Huh? That wasn't the case last time I used it to host a bot
Same goes for when trying with dpy
Just use dpy 2.0
dosent work either
need dpy LESS than 2.0
but dpy less than 2.0 is lame
@vale wing did u see this? ๐
Dpy 2.0 requires aiohttp <= 2.8.0 and python-template requires aiohttp >= 2.8.1 what's not understandable with that
I agree
Does anyone know this color's hex code https://media.discordapp.net/attachments/968145193847123968/984496762817503292/IMG_1293.png
if you need it for embeds then that color is default
Ah yes I remember something like exception_info(type(e), e, e.__traceback__)
Yea that used to suck, but in 3.11 that is gonna change!
no clue about hex codes then
Its all good
Lemme see rq
Tnx

@slate swan #303135
Ty buddy
How can I remove the slash commands from my bot? I removed them from my code but the bot still has the options
I am using discord.py and discord_slash
I remember how I had the same issue and I ended up making raw requests to discord API ๐
oh
Why not use discord.py 2.0 or disnake or nextcord whatever that supports slash commands just not the discord_slash
idk
They are easier trust (dpy 2.0 is not)
lmao
I like dpy I started making a bot on it
imagine hating dpy
Its like 2k lines now
Not hating, just stating
Split it into cogs
mutual feelings
I hate cogs
imagine hating something
Cause you don't understand them?
Bad reason to hate something
No I like messy code
Sure
I can't figure out sry
oh its cool, even i bummed out
#esoteric-python best for you
ok
anyone know how to make a button which u can infinity click?
U can infinitely click buttons
Anyone here used text2emotion module?
without getting interaction error
and the same response
U mean without doing anything
without writing 50 lines of code what happens after every click if every click should do the same
yes
Can u send the ID here pls?
@slate swan
Thanks
So the user ID is correct
Do u have members intent?
How to make discord bots with python ?!
!d discord
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
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`.
!d contextlib.redirect_stdout
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...
Ah well I have access to Message Intents, soooo
!d nextcord.discord is a thing..?
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.
async def delete(ctx):
await ctx( delay=None)
``` i want it that it auto deletes messages
can you guys help me?
what?
what do you mean?
await ctx.message.delete() ez
thanks
Nice, Nakime should think of getting a job soon or start depositing money
does anyone know the six errors
async def delete(ctx):
await ctx.message.delete()``` @quaint epoch still doesnt work
what error does it raise
like i mean if i type !delete that it automatticly deletes messages
it has no error
oh i know
Seems like more of a db issue ig
@bot.command()
async def delete(ctx, messages:int=10):
await ctx.message.delete(messages+1)```
there you go
thank youuuu
then a JSON issue
it is such a nice day outside, i should go for a walk
Nice cya!
Wtf
so is disnake.discord and discordpy.discord
Wow
Bruh
use an if statement to check if money < 0
sry but i wanted to ask what do i have to write because if i write in my server where my bot is nothing happens
Before someone can withdraw, make sure the remainder won't be less than 0 ig?
It's not a coro
Yea
can someone help?
that should work... do u have an error handler?
!d discord.Guild.get_channel
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.
I am using nextcord
yes, but it just doesnt show an error yk
Heyy
I did
show the error handler
Then get an attribute error
i wanted to ask like what do i have to type in the chat?
how
Code and error
show the code
ok 1 sec
of the error handler
there is no error
do u have an on_command_error?
Nice
delay is a kwonly arg
no theres litterly no error
((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?
!d discord.Message.delete
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.
Ah u r looking for purge
maybe, i was very confused why they named delay message
Ryuga, any idea?
so idk
i dont understand
output := output + f'{t} '
change it to await ctx.purge(limit=messages+1)
okay
???
for t in text:
if t.parent.name not in self.element_blacklist:
output += f"{t} "
Wanna change this to a list comp
change += to := with that adjustment
(output is already defined)
@paper sluice :white_check_mark: Your eval job has completed with return code 0.
13
Oh cool thanks!
walrus operator...
btw is it fine if i host my discord bot on my rpi?
ya
Damn u got one?!
it's 3b+ model would there be decent performance?
2
Niceee
a discord bot is not very heavy as long as you have good internet it should work just fine ๐
cool thx
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
Commands exist
;-;
what do you mean sry im new to python
because you have if (message.content == "!test"):
do u know what if is?
yes i do
so what do i type instead of if?
then why do you look suprised?
U can do ```py
@bot.command()
async def test(ctx, arg):
pass
im sorry
what
i dont clearly understand, why would i put now instead of event command
no need to be sorry...
Is this outdated at all: https://discordpy.readthedocs.io/en/stable/api.html#messageable
Cause messages = await channel.history(limit=2).flatten() doesn't work
I just get AttributeError: 'async_generator' object has no attribute 'flatten'
ya flatten got removed iirc
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
so i need to delete my whole code and paste yours in right?
@paper sluice can you maybe help me?
I gotta go eat lunch and go to band class. Please ping me if you respond so i can find your message
alright, can confirm I know nothing
I need some help doing this
and I don't know what 'this' is
what do u want to do?
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.
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
can anybody tell me what I'm doing wrong?
use a command as spakry suggested and use ctx.channel.purge(limit=...)
yo okay I got it
async def ask(inter, ctx: commands.Context):
and
await ctx.send("Do you want to continue?", view=view)
where would i paste it?
whoops, had a seizure
dagnabit, those damn seizures
you will have to write it, we wont just write it for you
๐ ๐
okay.
brad u here?? ๐
you need message content intents
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 ?
Do you need me to be?
yes i knew you would respond, what is the max emojis u can send in one msg?
A good rule of thumb might be to keep it under double digits
ah ok, prefect then ๐
could somebody show an example of a button in a modal?
I can't seem to figure it out
dpy?
disnake
does discord even support that?
i know that select menus in modals are supported, but i'm not sure about buttons
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?
Not as of now I believe, theyโre quite limited
Nothing much really just text inputs think of it as a limited google form in discord
Text fields, selects as mentioned I believe
are those the only two?
Yes
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
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?
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
is not defined in the case where time < 0, so the "asyncio.sleep(timeS) can't work
Do pip install disnake and make slash commands with it
does it work the same?
Or just use discord-py which also supports slash commands ๐
!pypi disnake
i have discord.py 2.0
And have fun figuring out all that tree syncing stuff they have put in
Not discord bots related question
You probably need #web-development
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))
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)
I think so, I don't have issues accessing it later
whats the advantage of using default discord.py bot help command over rather disabling it and manually making one?
None
whAT
If I got you correctly there's no advantage
Except not having to do it yourself, there are no advantages
bro istg, i just removed my custom 200 lines one, and wrote 100 more lines to modify default one for no reason??
๐ญ
I wouldn't really call it "modifying the default one", it is custom
You don't need to do unnecessary stuff with subclassing unlike with using a function
is there inbuild slash commands in discord.py 2.0?
Yes
how?
just that? no default error handling and stuff?
how to import it?
import app_commands from discord
thx
do u also know how to use them?
somewhat, yeah, they're kinda similar to normal prefix commands
can u send a link?
if you want an example: https://github.com/Rapptz/discord.py/blob/master/examples/app_commands/basic.py
if you want the docs: https://discordpy.readthedocs.io/en/latest/interactions/api.html#appcommand
thx
isn't it from discord import app_commands
how do i access help <category> in subclassed help command
its just plain text, i wanna go embed it and stuff
send_cog_help iirc
isn't help <category> just help <cog> though?
i mean this thing
@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?
help <command> then?
yeah
don't do anything in on_ready, use setup_hook
command, my bad
sorry but i still don't understand how it works
maybe i am dumb
!d discord.ext.commands.HelpCommand.send_command_help
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").
could you be a bit more specific in what you don't understand?
You can't access to client.guilds in the setup_hook so how can I can sync the tree for each guild? :/
i only understand how to import it
sync manually (prefix command maybe), it's not recommended to sync when your bot starts up for multiple reasons
any examples?
https://gist.github.com/Rapptz/c4324f17a80c94776832430007ad40e6 maybe try reading this? it's a bit outdated, and some stuff has changed, but it explains most stuff fairly well
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
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
Any chance you know what the doc means by "guild (Optional[Snowflake]) โ The guild to sync the commands to. If None then it syncs all global commands instead."
What is a "global command" ?
i think i got it now thx
instead of syncing to a specific guild, it syncs globally
Would work until I need commands for specific guild..
You mentionned I should not sync in "on_ready" event, is the same for things like game status or so ? I was doing it in this before
yeah, you shouldn't generally do any API calls in on_ready, best if you just don't use it
where do i add that at
inside your HelpCommand subclass
Good to know, thanks a lot
commands.Bot has an activity and status kwarg if you wanna change its presence on startup
@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?
says no attribute embed in HelpCommand subclass
I'm probably saying something wrong but it might uses ms instead of seconds
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()
oh, you're using menus
what does that have to do with HelpCommand subclassing though?
yeah
!d discord.ext.commands.Cog you'll want these if you want to have command in different files
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.
What are you trying to do
i am trying to customize command_help looks
@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")```
!d discord.ext.commands.Cog
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.
If you just import it it won't work
well yeah, that's what this is doing await channel.send(file=discord.File("pimg.jpg"))
how can i fix this
add the content that you want to send to the send function..?
I know a tutorial for a fork
Depends what library you use, most likely gonna be suitable unless it is dpy 2.0
?
@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
what're you trying to even do?
@placid talon if this helps https://tutorial.vcokltfre.dev/tutorial/intermediate/disnake/11-cogs/
A tutorial to help you make better Discord bots.
send the image with the text , its a font i added
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
just sends the image
And what is expected output
send a text with the font i added
On the image right?
yes
So basically it doesn't add text to your base image
yes
@warped mirage ok let's go to #ot0-psvmโs-eternal-disapproval cause this is kinda not discord bots related
ok
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
!d discord.ext.commands.Cog
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.
Interesting
if you're not using cogs you basically put everything in the same file?
they haven't spent enough time with dpy then
everything that's a command, yeah
you can still have helper functions and whatnot in other files ofc
I think so. Cogs -> separate files
Oh not talking to me.....๐
i like having a few small files with a couple added lines vs one big long file
mAh bad for jumping in convo
no you answerd me, thx
Aight aight
!paste
ive got a semi relayted question
okay @fading marlin, this is the whole thing https://paste.pythondiscord.com/yimitojome
i have a bot that is set up to reload cogs when it changes
class MyHelp(commands.MinimalHelpCommand):
...
here's where you want to add the function I told you about
cool! tyy
but it seems to not work if theres too many reloads, like more than a couple . anyone else done that
when you change the code, it automatically reloads?
the cog loads but no on ready event is the failure mode
yeah
that's so cool
on_ready only dispatches when the bot is ready, not when the cog is loaded
if i make a small enough change it works beautifully haha
you're probably looking for something like cog_load (which you add inside your cog subclass)
oh maybe its the whole bot that gets reloaded
This is what I thought of as well.
you haven't defined anywhere in your subclass what embed_description should be, nor does MinimalHelpCommand have such a method
!d discord.ext.commands.Bot.reload_extension is what im using
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.
now i think i see what ive screwed up .. i was calling unload first
so what do i need to do uh
yah, on_ready only gets called once your bot boots up, it doesn't get called if you're reloading cogs
define embed_description...?
is there a case where the on_ready gets called again ?
like if you lose your connection or something
pretty sure if you loose connection and it reconnects it calls it again
not sure how, this is my first time subclassing stuff
ok thats what it seemed like, just wanted to check if im doing smth weird
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")
i used watchdog for file monitoring and its pretty kludgy the way i have it lol
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
Why does this error?
what's your thought process? what's self.embed_description supposed to do? Also, dpy has a lot of OOP, so you shouldn't be doing much with dpy if you don't know much about subclassing
what's the error?
company errors
?
so company = None
Why even make user arg optional
yeah
got it, thanks a lot
class MyHelp(commands.MinimalHelpCommand):
async def send_command_help(self, command):
embed = discord.Embed(title=self.get_command_signature(command))
embed.add_field(name="Help", value=command.help)
alias = command.aliases
if alias:
embed.add_field(name="Aliases", value=", ".join(alias), inline=False)
channel = self.get_destination()
await channel.send(embed=embed)```
if i had just read the doc for that function months ago it could have worked nicely this whole time haha ๐คฃ

oh thats good to know .. hmm
where should it be done ? in a cog_load ?
if you're on 2.0, I'd recommend setup_hook
im not, still using the older one
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
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
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))
i think i didnt have a setup_hook
oh ok yeah add_cog i think might have been part of it
setup_hook is just an event that allows you to do async stuff without worrying too much about ratelimits (unlike on_ready)
so if i do
class Bot(Bot)
...
async def setup_hook(self):
await self.load_extension("ext")``` thats a good way to do it ?
yep
what makes it so you dont need to worry much about rate limits in the setup_hook in particular
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
@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?
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
yes
exactly like Lee said
A list comp might be even better
thanks ๐

99% sure i am doing way too much in on_ready
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)
I believe that happens before it even connects to the websocket
you can always overwrite the function or just make a task
The amount of iterations would be (amount_of_role_names * amount_of_roles) idk what complexity the _contains_ of a list has but I think it will be better to do this
for role in guild.roles:
if role.name in roles_names:
data.append(role)```
a task would make sense prob
Comprehensed py data = [r for r in guild.roles if r.name in roles_names]
its just some house keeping stuff with roles
you can just access the internal loop attribute from the Bot class, thats literal to a AbstractEventLoop
Bot.loop
so self.bot.loop or self.loop depending where
if self is a subclass of the Bot class yes, if self.bot is literal to a Bot class instance yes
discord/client.py line 209
self.loop: asyncio.AbstractEventLoop = _loop```
which the private loop is literal to https://github.com/Rapptz/discord.py/blob/be6db2025580fd9e6298e5ad2bc0b93919f6c6a9/discord/client.py#L101
discord/client.py line 101
class _LoopSentinel:```
but now I wont have individual roles as a variable
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?
thats for the latest version in 1.7.3 of dpy Bot.loop is literal to
self.loop: asyncio.AbstractEventLoop = loop or asyncio.get_event_loop()
add_roles expects a discord.Role object, not a string, so no, it won't work
so how can I refer back to the roles that were appended?
await user.remove_roles(*roles)```
If `roles` is a list you need to convert it to args list
oh ok
Pretty sure your roles is actually role tho
ah
so how can I refer back to the roles that were appended?
Data is actually the list of discord.Role if you used something like this
does this put them into variables?
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)```
I used this
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')```
do you mean to add a role object there
Well that list of roles is kinda big do this instead (it is faster)
role_names = (...) # your big tuple goes here
roles = [r for r in ctx.guild.roles if r.name in role_names and r in user.roles]
honor_guard = discord.utils.get(roles, name="Honor Guard")
if company == "1st":
await user.remove_roles(*roles)
await user.add_roles(honor_guard)```
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
Another suggestion: don't make arguments that are supposed to be required optional and then handle unprovided arguments in the command itself.
Instead, use an error handler. For this case, local handler might be suitable but I highly recommend making global error handler and not writing error messages for literally every missing argument
I believe commands.MissingRequiredArgument provides an attribute that tells you which argument was missing
You can use that to provide more customized error messages
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
Can you paste the relevant code instead of sending a screenshot?
ah yeah, error.param.name
Given isinstance(error, commands.MissingRequiredArgument) is True
Anyone?
hard to figure out what the issue is because it's hard to read the screenshot
Paste your code and any errors
Don't send a screenshot
@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
Here is the code
Any errors?
Yeah
Undefined name โplaying_gameโ
First things I noticed, use guild.get_* methods instead of utils.get(...)
What is wrong with that
That has nothing to do with the problem
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
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
yes, the error is clear, "playing_game" was not defined
playing_service = playing_game_split[1]
playing_service = Playing_game.capitalize()
you reference it here, but it's not defined before
So like what do I put. I want it to be the name of the game
So what do I put instead of playing_game
member.activity.name can be used to find the name of the game, given it's an instance of discord.Game
if isinstance(member.activity, discord.Game):
activity_name = member.activity.name
The typeguard is important
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)
What lib
you can use the delete_after kwarg
Pretty sure most of them don't return anything tho
He wants to delete it after the view has been interacted with
disnake
inter.message.delete() should do
Then he can use the on_interaction callback and delete the message from it
I guess you need to work with interaction you have in your View callback, current interaction is not the one you need. For the view's interaction just do inter.delete_original_message()
Most inter.send don't return message object afaik
ah, okay
You can access the message in your View's callback interaction
How do you implement the view
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
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
await msg.delete() should work
!d disnake.InteractionResponse.send_message one check
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.
Command raised an exception: AttributeError: 'NoneType' object has no attribute 'delete'
I don't think send_message returns the Message object
Ah
it works for a regular command with ctx but not a slash command with inter
That's what I told you. Use this method
I assumed it would as sending a regular message does
Then yeah that's the right way to do it
the issue with deleting after the button is pressed is that then a timeout doesn't delete
Sorry what
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
i am asking which ones give the output within discord
and how do the default outputs look like
Default output right?
yeah
default of these
I don't think anything besides these gives output but you should check on_help_command_error source
cool!
looks like it gives no output, peace then
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()
what is the optimal way to handle CommandNotFound error
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
you do need to loop it if its an array
roles = []
for role in roles:
await user.remove_roles(roles)```
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)
await user.remove_roles(*roles)
thats just _ looping on the backend_
No itโs not
wat
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: discord.member.Member.remove_roles() argument after * must be an iterable, not Role
ohh right
remove_roles(*[roleOne, roleTwo])```
Yeah this
what goes in roleone, role two ??
get roles from guild
i wanted to remove the roles in data
roles = [role.name for role in user.roles]```
but you never used data
if company == '1st':
for roles in data:
await user.remove_roles(*[])
await user.add_roles(Honor_Guard)```
no need for for loop there
so what do I do
if company == '1st':
await user.remove_roles(*data)
await user.add_roles(Honor_Guard)```
@scarlet aurora ^^ ?
if you know about it
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
alr
i was thinking that
async sleep or time sleep
what's your goal here? remove all roles but one?
is it his intention?
yeah
well, just filter out that role before removing it all, lol
removing it first and adding it again is fucked up ofc
yeah right
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 )
no work
no they want to remove all roles, and then add honor guards
what if a user dosent already have honor guard
yeah it looks cool
you shouldnt use time sleep in this case
it is blocking
do anyone of yk about this?
do you mean within the code or a response to the user?
no bot gives response about that, so i think just within the code
is it possible to edit an ephemeral message?
edit? idts
will it be py @bot.event async def on_command_error(ctx, error): if isinstance(error, CommandNotFound): return raise error

yeah this
peace
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
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
I wouldn't filter on name if I were you
why not
also, the for loop is useless
i told them that
use ids instead
ok
names can change, ID's can't
๐
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
@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)```
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...
i want for role in data
no you don't
?
not needed
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
alright, will this bot only run in 1 guild?
yes
then use IDs instead
create some sort of config file which looks like
{
"Honor Guard": 515151,
"Catulan Reaver": 5151515,
...}```
because most likely, you'll need those IDs in multiple commands ,right?
prolly not
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
done
alright
no file needed in your case
r u serious
you can just initialize it in the command
do u know how long that just took me
you still need it....
we might as well use the json file
it's just rank_role_... = {<your file shit>}
so now, you don't need all the
Honor Guard = ...
shit anymore
you can just do
all_rank_roles = [ctx.guild.get_role(role_id) for role_id in rank_role_name_id_dict.values()]
but i kinda need da variables
for?
nope, let's say you need only Honor guard and Catulan Reaver, right?
you don't man
unless for every separate option, you have different roles to give
is it possible to make a slash command show only to the issuer without making it ephemeral?
i dont get pycharm, here ctx is needed but pycharm says its not being used
yep
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)```
remove the for loops lmao
alright, so first things first
remove all the time sleeps
use elifs
ignore that
then
use this
await user.add_roles(ctx.guild.get_role(rank_role_name_id_dict["Honor Guard"]))
its annoying to see that lmao
done
you could use _ as param name
but in the back of your head, you know that it's ctx
code?
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)```
restart IDE
no for loops needed
no work i tried
ye I haven't started on 2nd one yet
ditch it aint discord bot related anyways
first one is not completely good, fix it first, you're sharing unfinished shit
alr
also, please rename the arg to member, since member and user are different objects
can static data stored in json handle constant and heavy fetching?
use case?
static data would only be read once anyways... no need to open that json file every time...
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)```
yeah just on startup right
pretty close
aight, just rename hg to something obvious and you're good
yes, but that's not what the list represents
i understand, everything except hg
it's a list of all ranks EXCEPT honour guard
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)]
alright
ok, but there's still one problem here
what if honour guard was already a role he got? then he got it for nothing...?
wdym
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...
well, then that except_hg makes no sense
i was just looking at that and realised that it would remove all ranks except hg lool
it should be for roles in data
are you even sure you're removing roles the user has?
yes
what if you're removing roles of the member and he doesn't even have that role...?
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
have you checked out list comprehension by now?
yeah
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
the ~dict, yeah
would it be easier if I screen share?
ok
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
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)```
you should have 2 args in that command
the key, and the new value
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)
they arent 1 word
p a i n
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 ??
the new value isn't, I suppose?
both
that's rank_ids.values() in your case
well idk why you want to change the json regularly, but this feels like you need a db
okay, this is starting to really frustrate
not very "static" if you'd ask me
I want to respond to a slash command with some buttons for the user to press
this is only once
when and why?
and then I want the response to change once the user has responded
after i am done editing it for a nice 1 hour sitting, the json is static forever afterwards
@potent spear thanks a lot for ur help
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
so you'll manually need to do this after 1 hour every time the bot restarts? are you sure you can't automate this?
this is called "ephemeral"
because you can't edit an ephemeral response, and you can't delete an ephemeral response
not after every restart, just ONCE
as far as I can tell
that's correct
you can say i am just writing the json
so then I can't do what I want
because you can't do the whole hidden=True on a slash command
You can't delete it, but edit, maybe? idk
so then how do you edit an ephemeral message
that becomes the big question
and as far as I can tell, you can't
@potent spear discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'list' object has no attribute 'id'
probably a view.edit arg or whatever, I've never used slash
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'```
you forgot 1 thing
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 ^^
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
hmm, should be pretty simple
okay, so how would I do that within the view
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
never used slash, I can't say tbh
okay so does somebody here know how to edit an ephemeral message
yup, you'll need " for the key ofc, since otherwise, it'll never know when the new_value starts
unless you want to split by - or whatever
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
@potent spear it takes like 5 seconds to add the rank, is that normal?
depends on what your code looks like
the same code we made together
Hi guys, can someone help me ?
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
How can I fix this 
Like Cogs?
@potent spear
seems like a background task to me
@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")```
Idk what is it
read the error
What is the error?
I did it is installed
no error just doesn't work
your if statements make no sense
that's not what it says
Yeah like a function that takes input and does different things depending on whatโs the message
how
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")
Idk if I explained well ahah
Why is an enum error showing up 
the if statement would look like
if rank_ids["Neophytes"] in [role.id for role in user.roles]:
read the warning, that might be the issue
good enough, check out tasks in discord py
role = user.roles.id
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 rank_ids["Neophytes"] in [role.id for role in user.roles]:
await (ctx.guild.remove_roles(rank_ids["Neophytes"]))
await (ctx.guild.add_roles(rank_ids["Battle Brother"]))``` like this?
Well according to the documentation, what I have is right
yup, now do that in every if statement
Thanks buddy
well, a combination of nextcord and discord py can't be
I do not think that matters??
thanks
there's literally a warning...
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
Set disabled to true?
button.disabled = True
fast and easy
isn't disabled just a visual style?
try and see
I want to completely remove it
Hmmmm
I would rather do what Sniper up here said
Cause you still cannot use those
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
Then change like the others to gray and the one clicked is like green?
Just do what you did there in the original message
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

await inter.edit_original_message("Timed out", view=None)```
set the view to none when I edit and it does exactly what I want
def clear_views():
return None
await inter.edit_original_message("uwu", view=clear_views())
uwu
now, is there a way to set the view to only one of its elements?
hm, just disable every other view component?
