#discord-bots
1 messages ยท Page 132 of 1
inside your select class...?
there is no interaction to get the original response for
what?
he means that can u develop a bot on 2 dif computers?
IN VSC*
vsc has a live share feature
Appelsy is online!
Ignoring exception in command <nextcord.application_command.SlashApplicationCommand object at 0x0000019B24EE9C40>:
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\application_command.py", line 863, in invoke_callback_with_hooks
await self(interaction, *args, **kwargs)
File "c:\Users\PC\Desktop\Appelsy Bot\main.py", line 78, in embed_create
embed.colour = dict(black="0x000000", white="0xffffff")
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\embeds.py", line 313, in colour
raise TypeError(
TypeError: Expected nextcord.Colour, int, or None but received dict instead.
The above exception was the direct cause of the following exception:
nextcord.errors.ApplicationInvokeError: Command raised an exception: TypeError: Expected nextcord.Colour, int, or None but received dict instead.```
nvm i dont know how to read is all. trying it now
convert it to an int when you grab it from the dict
or are you trying to grab more than one?
its saying you gave it a dict
wdym
i wrote white
can somebody help me
future: <Task finished name='discord-ui-view-timeout-f2bc84966b2c58a04ef27a4873cfa588' coro=<Roles.on_timeout() done, defined at /home/luke/Desktop/levels.py:517> exception=AttributeError("'Roles' object has no attribute 'message'")>
Traceback (most recent call last):
File "/home/luke/Desktop/levels.py", line 521, in on_timeout
await self.message.edit(view=self)
AttributeError: 'Roles' object has no attribute 'message'
print("menu has timed out")
for item in self.children:
item.disabled=True
await self.message.edit(view=self)```
'Roles' is my view
!paste
Views doesn't have message property
You have to set it yourself
Appelsy is online!
Ignoring exception in command <nextcord.application_command.SlashApplicationCommand object at 0x0000019B24EE9C40>:
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\application_command.py", line 863, in invoke_callback_with_hooks
await self(interaction, *args, **kwargs)
File "c:\Users\PC\Desktop\Appelsy Bot\main.py", line 78, in embed_create
embed.colour = dict(black="0x000000", white="0xffffff")
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\embeds.py", line 313, in colour
raise TypeError(
TypeError: Expected nextcord.Colour, int, or None but received dict instead.
The above exception was the direct cause of the following exception:
nextcord.errors.ApplicationInvokeError: Command raised an exception: TypeError: Expected nextcord.Colour, int, or None but received dict instead.```
i understand that but how to i get the original message sent? thats my struggle
the message im trying to edit is sent inside an on_message
it was something like that
you can set it as an attribute to the view no?
the original interaction comes back as the message sent that triggers the on_message. which comes from a user so i get an error saying it cant be edited
help
@fading marlin can i dm u
@bot.slash_command(description="Buy things!")
async def buy(interaction: nextcord.Interaction, Literal: Literal["Potato", "Watermelon"] = nextcord.SlashOption(description="Item Name", required=True)):
it's saying that literal is not defined, someone told me to use literals instead of strings
Move it in the class, but not in the __init__
i need more elaboration
โ ```py
def init():
...
def callback():
...
โ
```py
def __init__():
...
def callback():
...
@slate swan ?
correct
got this now
select argument should not be there
if self.values[0] == 'Shop':
view = View()
view.add_item(mt.select)
view.add_item(mt.shop)
await interaction.response.send_message(view=view, ephemeral=True)
Traceback (most recent call last):
File "/home/runner/miner-bot/venv/lib/python3.8/site-packages/discord/ui/view.py", line 425, in _scheduled_task
await item.callback(interaction)
File "main.py", line 183, in callback
await interaction.response.send_message(view=view, ephemeral=True)
File "/home/runner/miner-bot/venv/lib/python3.8/site-packages/discord/interactions.py", line 769, in send_message
await adapter.create_interaction_response(
File "/home/runner/miner-bot/venv/lib/python3.8/site-packages/discord/webhook/async_.py", line 220, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.1.components.0.options.1.label: This field is required
In data.components.1.components.0.options.1.value: This field is required
what should
Is there a way to find out who a user replied to and get the message that they replied to? (so like if I replied to John and he said xyz, I want to get the name John and the text xyz)
so i tried the edit_original_response method and it just tells me 'message' object doesnt have that attribute. because thats just for interactions. and if i try to edit the interaction specified for the view itself, it says it cant edit a message authored by another user. so that returns the original message that triggered my on_message
mt.shop = myselect2(min_values=1, max_values=1,
placeholder = 'Zio Miner Shop',
options=[
discord.SelectOption(label='Upgrade Pick', emoji=funny, description='Upgrade your pickaxe!'),
discord.SelectOption(label=f'{mt.drilldisplay}', emoji=arrow, description=f'{mt.drilldesc}')
])
with open("users.json", "r") as f:
users = json.load(f)
user = interaction.user
drill = users[f'{user.id}']['drill']
if drill == 0:
drilldisplay=str("Drill")
drilldesc=str("This is locked!")
if drill != 0:
drilldesc=str("Upgrade your drill power!")
drilldisplay=str(f"Upgrade drill")
why isnt this changing
when I have a score of 1 or greater its not suppose to say its locked
Someone know free host for discord bots?
umh ur computer?
ืื ืืืฉ ืืื
ืื ืืืฉืืช ืฉืืื ืืฉืืืจ ืืช ืืืืฉื ืืชืื ืื ืืจืื
ืืืืจืื ืคื ืืขืืจืืช? 
ืฉืืงื ื ืืืกืื ื2$
ืืื ืืื ื
ืืืืืง
ืจืืฆื ืืื ื ืชืจืืฅ ืืืืฉื
How come there is no hidden attribute for Slash commands?
cause slash commands can't be hidden
its a discord thing, not related to the library
prefix commands on the other hand are discord.py thing
yeah that's one possibility
I see. I had a help command from somewhere online, and it was a super nice format where it would add all the commands a user could use to the help embed
And it would hide the commands that were hidden
So I guess I'd have to change that command to add ones that everyone has permission to use
someone please
@mt.tree.command(name='shop', description='Use your moneu here!')
async def shop(interaction: discord.Interaction):
with open("users.json", "r") as f:
users = json.load(f)
user = interaction.user
drill = users[f'{user.id}']['drill']
if drill == 0:
mt.drilldisplay=str("Drill")
mt.drilldesc=str("This is locked!")
if drill != 0:
mt.drilldesc=str("Upgrade your drill power!")
mt.drilldisplay=str("Upgrade drill")
view = View()
view.add_item(mt.select)
view.add_item(mt.shop)
await interaction.response.send_message(view=view, ephemeral=True)
can someone tell me why the bottom one isnt changing??
hello guys please help File "C:\ss\main.py", line 4, in <module> import client ModuleNotFoundError: No module named 'client' its wont download client i did pip install client
@slate swan you dont import client
i do
its wont download client i did pip install client
why are you importing it?
for discord bot
client = commands.Bot(command_prefix='-', intents=discord.Intents.all())
replace that with this
dm me
anyone know why the bots message wont delete
roblox bots ?
hi misk
!d discord.InteractionResponse.send_message - it doesn't return the sent message
who are u
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
ah alr
send_message doesn't return anything. You have to call Interaction.delete_original_response
this?
also, you're responding to an interaction twice, you can't do that
!d discord.Interaction.delete_original_response
await delete_original_response()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the original interaction response message.
This is a lower level interface to [`InteractionMessage.delete()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.delete "discord.InteractionMessage.delete") in case you do not want to fetch the message and save an HTTP request.
..
help
read the error...?
.
could you elaborate?
so basically when you do /shop its suppose to get your drill objective
if its more than one it will say you can upgrade it and if you dont have it then it will say to buy it
but it doesnt update, so it doesnt tell me I have it
what doesn't update?
see where is says buy this
thats suppose to update
with open("users.json", "r") as f:
users = json.load(f)
user = interaction.user
drill = users[f'{user.id}']['drill']
if drill == 0:
mt.drilldisplay=str("Drill")
mt.drilldesc=str("This is locked!")
if drill != 0:
mt.drilldesc=str("Upgrade your drill power!")
mt.drilldisplay=str("Upgrade drill")
Does drill == 0 in your json?
Hi, so I have designed a system that when a user presses a button, it creates a new channel and posts a selectionList in it. How can I make it so that only the person who pressed the button can use the selectionList.
Then it's going to say it's locked because if drill ==0
self.author
self.author?
yea but when I change it doesnt update
give me a second
ok boss
I think you want an interaction check async def interaction_check(self, interaction): if interaction.user != self.author: await interaction.channel.send( f"Whoa there Team Rocket Grunt <@{interaction.user.id}>, you can't steal other people's role menu!") else: return True
the thing is the button and selection are two seperate classes
so how would this work
wouldn't the author of the selectionlist be who every uses it
Interaction.user is who is using it and self.author is the person who made the thing happen. You need to specify self.author in init
how does init work
I tried using it yesterday and i got confused
does the init go in the selection class or the button class
whats wrong when i want to do npm install
@mighty pilot
Print what drill is and see what it says after drill is set to 1
alr alr
someone help?
it prints one
how can i check if the owner used the command ? for example i do .test it prints hi {user} but if the owner does it it will print hi {user} is the owner of the bot
This is a python server
;-; ik
where do i even get help on that one then
on a javascript server
cereal?
.gg/djs
ty
elp
@mighty pilot prints one
whats the -> None for in your init line
Idk might be something to do with it being a json file. I don't mess with those
??
๐ฆ
I don't exactly remember tbh
its wtv tho ill just make it fancy
You add your select to a view right? I believe it would go in the init inside the view
the init inside the view?
You could try making it an if/else instead of if/if and making the !=0 above the other and see if that helps? Idk why it's Following the ==0 if your value ==1
What is the problem
how does that relaate to the init being inside the view
Can slash commands have more than 1 name
i've been getting the error:
AttributeError: 'Intents' object has no attribute 'GUILD_PRESENCES'```
when trying to use any intents for interactions discord bot. i've looked online and there isn't even a flag for that
probably aliases=[]
no
disccusion said they will not add aliases to slash commands
but im sure there are work arounds
not sure why you want aliases tho considering commands can have full names and desciptions now its ease of use to know
with open("badges.json", "r") as f:
users = json.load(f)
badge1d = users[f'{user.id}']['badge1']
badge2d = users[f'{user.id}']['badge2']
badge3d = users[f'{user.id}']['badge3']
funny = ":adsmd:"
if badge1d == 1:
badge1 = funny
if badge2d == 1:
badge2 = funny
if badge3d == 1:
badge3 = funny
File "/home/runner/miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 294, in profile
profile2.add_field(name='Badges', value=f'{badge1}\n{badge2}\n{badge3}')
UnboundLocalError: local variable 'badge1' referenced before assignment
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'profile' raised an exception: UnboundLocalError: local variable 'badge1' referenced before assignment
did you pip install discord.py
Hello,Iโm planning to make a discord music bot
With a web-app, that allows for media control over the music-bot
Is it possible to receive status updates from the bot
And send commands like, play/pause from the web-app to the bot ?
I fixed it but thx
lets say i want to change the name of a command. people might think it got deleted if they can't find the old one
thats what descriptions are for
not enough info
i fixed it dw
also i wouldn't structure your code that way kinda DRY
I suppose. But if someone is used to typing /balance and i change it to /profile, they're probably not going to look through and read the descriptions to find the command
They might just assume that it got deleted or removed because not every user is smart
well skill issue lmao but i believe you can just make a function x and pass the ctx to the old function a
however that seems counter intuitive why change the name in the first place
think like a developer
I don't care if its counter intuitive, its a possibility, and user experience matters in every possibility
how do I get custom emojis in embeds
like i said
create a new bot command, call it the name u want, invoke the old command and pass the ctx to it
and whatever other *args, **kwargs
@bot.command()
async def new_command(ctx, *args, **kwargs):
await asyncio.gather(asyncio.create_task(old_command(ctx, *args, **kwargs))
might be the wrong asyncio command but u get the idea
I'm using slash commands btw
may i suggest a better way to rewrite that
btw you don't need to use f-strings when you're only accessing a variable
@north pecan sure
sorry got distracted
anyway after you load users you can do users[user.id] = {key : (funny if value == 1 else value) for key, value in users[user.id].items()}
if u want u can also do it for all users easily
i know i know not the most intuitive
how do i get my bot to send 2 sepereate messages after interacting to a dropdown?
u can use send_message and then either use .followup.send or .channel.send
can i see the docs
oh i see
i think
you can also use Interaction.send
it only works for
You dont have a requirements.txt
ie:
discord.py==1.7.3
dnspython==2.1.0
motor==2.5.1
humanize==3.12.0
attrs==21.2.0
buttons==0.1.9```
1 interaction
oof
no
yes
-d discord.Interaction.send
interaction.channel returns the channel use that to send
hell
i said Interaction.send
yeah so either followup.send or channel.send not sure abt interaction.send
lemme check source
ah it doesn't exist in discord.py
@glad cradle it wont work
how do u use followup.send
!d disnake.Interaction.send
await send(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).
Sends a message using either [`response.send_message`](https://docs.disnake.dev/en/latest/api.html#disnake.InteractionResponse.send_message "disnake.InteractionResponse.send_message") or [`followup.send`](https://docs.disnake.dev/en/latest/api.html#disnake.Webhook.send "disnake.Webhook.send").
If the interaction hasnโt been responded to yet, this method will call [`response.send_message`](https://docs.disnake.dev/en/latest/api.html#disnake.InteractionResponse.send_message "disnake.InteractionResponse.send_message"). Otherwise, it will call [`followup.send`](https://docs.disnake.dev/en/latest/api.html#disnake.Webhook.send "disnake.Webhook.send").
Note
This method does not return a [`Message`](https://docs.disnake.dev/en/latest/api.html#disnake.Message "disnake.Message") object. If you need a message object, use [`original_response()`](https://docs.disnake.dev/en/latest/api.html#disnake.Interaction.original_response "disnake.Interaction.original_response") to fetch it, or use [`followup.send`](https://docs.disnake.dev/en/latest/api.html#disnake.Webhook.send "disnake.Webhook.send") directly instead of this method if youโre sending a followup message.
a good library
didn't find any interaction.send in dpy source oh ic
bruh same thing i said
snipy how familiar u r with interactions.py
how do i use .folloup??
await interaction.followup.send(embed=embed) # same as normal sending
depends on the library, in general I know them
have you had this issue with intents:
AttributeError: 'Intents' object has no attribute 'GUILD_PRESENCES'```
when i try to pass my intents
without intents it works but i need my intents
what lib are you using
interactions, discord
intents = discord.Intents.all()
intents.members = True
intents.presences = True
intents.message_content = True
client = interactions.Client(token=os.environ.get('SYMBASY_BOT_TOKEN'), intents=intents)```
bro
?
is that like 2 diff libs? are u passing intents class instance from dpy to interactions lib?
is there interactions.intents?
am i not supposed to use dpy at all
i just got back into dpy and slash commands are new to me im unaware of the libraries needed
I think the problem is that you're using the discord.py intents class with another library so that's why
plus the docs showed using discord intents
... bro just use discord.py dont use same random third party lib even if u are using atleast use disnake hikari nextcord
btw guys does anyone i can make my dropdown so only you click it once??
discord api lib packages generally cause conflicts with each other
its not third party its offical
"at least" Currently the implementation of discord.py of new components is not the best
pretty sure there is an attr for that but i can't remember u can check the docs or u can create a boolean var and put it in a if statement
which?
yeah it works now ty
are you using a view class?
!d discord.ui.View.interaction_check
await interaction_check(interaction, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A callback that is called when an interaction happens within the view that checks whether the view should process item callbacks for the interaction.
This is useful to override if, for example, you want to ensure that the interaction author is a given user.
The default implementation of this returns `True`.
Note
If an exception occurs within the body then the check is considered a failure and [`on_error()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View.on_error "discord.ui.View.on_error") is called.
self.stop
u can that stops the view
nope this runs before the callback so it would be more efficient to have a bool in only the select callback if u would create a check in this its gonna run for every component
that was an example u are supposed to make one for ur project specifically
there is some conflict within the packages u installed
since idk contents of bot.py i have no idea what dependencies u need
how do i make my bot copy and paste into general ids i send to it and only ids nothing else?
in replit work perfect but on another host
its because replit automatically download packages for u
elaborate or give an example
i want my bot to literally just copy a id i send and send it into chat thats it
but just ids and nothing else and when i mean ids i mean discord ids
@any_type_of_command()
async def(ctx_or_inter, my_id: int):
#send here as content
oh yeah it cant be a command sorry
discord
i js need it to copy a id i send of someone and paste it but i only want it to paste ids nothing else
role, user, channel, message ๐ฟ
i have ticket tool for that
yeah and my question is how are u sending it
via chat message?
so why cant it be a command?
it js cant
so the ids that are being sent by this ticket tool is part of the bot itself right?
or is it another bot or something
do u know what ticket tool is
bascially i js need my bot to copy ids i send and paste them into chat but it cant be a command i just want it to be ids
given the limited amount ik from your question my suggestion would be to use the on_message event then
i can do that but i just need it to do ids
just create a seperate channel for dumping ids
what do u mean?
i mean alot a channel for dumping ids make it a pvt channel and let bot listen to it
go ahead
ok
shoot me a dm
@shrewd apex dmed u
ok
hey
can anyone help me to get started?
i want to get into making bots
but i would need some help
Has anyone got a simple mute command?
!d discord.Member.timeout
await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.11)").
You must have [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") to do this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
does anyone know how i can make my bot dropdown options only clickable once?
simple logic gates
button_presses = []
*pressed
if button in buttons_pressed
return
Is there a way to see users use commands for other bots?
There's a bump reminder bot that starts a timer when you bump Disboard and that intrigues me
What ๐คจ
you can probably just use on_message and check if the message is the bump command
It's a slash command though
oh? ๐ค
Yea it's got me lol
Then check if the content is from the bot and bump related or not probably
Ohh it can see the message content sent from the disboard bot
after i click 1 on these i want the whole dropdown to be unavaialble
Use self.stop()
I would just disable it
but where do i put the self.stop
Or remove the view from the message entirely
Inside the interaction
set Select.disabled to True or set view to None when you edit the message
like this @mighty pilot ?
Inside your if statements for self.values you could put self.stop() and the menu will still be there but unable to interact with it. Or you can make the menu go away like Lee and Catgal said
that only makes it useless programmatically, you can still interact with the dropdown on Discord
Yea that's what i interpreted unavailable as
Many ways to skin a cat
pick your poison
like this?
My god
!d discord.Message.type this is probably simpler
The type of message. In most cases this should not be checked, but it is helpful in cases where it might be a system message for system_content.
what is this suppose to do?
Try this
your entire code
i dont understand it
Is there a way to find out who a user replied to and get the message that they replied to? (so like if I replied to John and he said xyz, I want to get the name John and the text xyz)
you might be after discord.Message.reference
do "ls" and check if the file is actually there
Do "ls" in the terminal?
yeah
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 11/13/2022 5:52 PM 828 badge.py
PS C:\Users\dynam\Documents\badge>```
is what i got
Also do you know why my slash commands dont show up?
from discord import app_commands
class aclient(discord.Client):
def __init__(self):
super().__init__(intents = discord.Intents.default())
self.synced = False
async def on_ready(self):
await self.wait_until_ready()
if not self.synced:
await tree.sync()
self.synced = True
print(f"Logged in as {self.user}.")
client = aclient()
tree = app_commands.CommandTree(client)
@tree.command(name = 'discord_badge', description='Active Developer Badge')
async def self(interaction: discord.Interaction, name: str):
await interaction.respond.send_message(title="Hello {name}", description=f"Thank you for running the Slash Command")
client.run("token.")```
slash commands take a few minutes to register in discord since you don't have any test servers set
Oh it registered just doesn't work
File "C:\Users\dynam\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 876, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "C:\Users\dynam\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 869, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'discord_badge' raised an exception: AttributeError: 'Interaction' object has no attribute 'respond'```
Did you do interaction.respond(...)?
@tree.command(name = 'discord_badge', description='Active Developer Badge')
async def self(interaction: discord.Interaction, name: str):
await interaction.respond.send_message(title="Hello {name}", description=f"Thank you for running the Slash Command")```
It's interaction.response
Okay I'll test
File "C:\Users\dynam\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 851, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "C:\Users\dynam\Documents\badge\badge.py", line 21, in self
await interaction.response(title="Hello {name}", description=f"Thank you for running the Slash Command")
TypeError: 'InteractionResponse' object is not callable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\dynam\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\tree.py", line 1240, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\dynam\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 876, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "C:\Users\dynam\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 865, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'discord_badge' raised an exception: TypeError: 'InteractionResponse' object is not callable```
It's just interaction.response.send_message(...)
from discord import app_commands
class aclient(discord.Client):
def __init__(self):
super().__init__(intents = discord.Intents.default())
self.synced = False
async def on_ready(self):
await self.wait_until_ready()
if not self.synced:
await tree.sync()
self.synced = True
print(f"Logged in as {self.user}.")
client = aclient()
tree = app_commands.CommandTree(client)
@tree.command(name = 'discord_badge', description='Active Developer Badge')
async def self(interaction: discord.Interaction, name: str):
await interaction.response.send_messagee(title="Hello {name}", description=f"Thank you for running the Slash Command")
client.run("")
Good?
Run it and see โข๏ธ
Traceback (most recent call last):
File "C:\Users\dynam\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 851, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "C:\Users\dynam\Documents\badge\badge.py", line 21, in self
await interaction.response.send_messagee(title="Hello {name}", description=f"Thank you for running the Slash Command")
AttributeError: 'InteractionResponse' object has no attribute 'send_messagee'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\dynam\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\tree.py", line 1240, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\dynam\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 876, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "C:\Users\dynam\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 869, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'discord_badge' raised an exception: AttributeError: 'InteractionResponse' object has no attribute 'send_messagee'```
Traceback (most recent call last):
File "C:\Users\dynam\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 851, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "C:\Users\dynam\Documents\badge\badge.py", line 21, in self
await interaction.response.send_message(title="Hello {name}", description=f"Thank you for running the Slash Command")
TypeError: InteractionResponse.send_message() got an unexpected keyword argument 'title'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\dynam\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\tree.py", line 1240, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\dynam\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 876, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "C:\Users\dynam\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 865, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'discord_badge' raised an exception: TypeError: InteractionResponse.send_message() got an unexpected keyword argument 'title'```
Are you trying to send an embed?
I want to just do a slashcommand where it respondes with what I put
no embeds I just want to run an slash command
So you'd just do something like
await interaction.response.send_message("message here")
thats what i have bro
no, you're trying to set 'title' and 'description'
yeah, which are not arguments that send_message() takes
!d discord.InteractionResponse.send_message
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
The documentation is pretty clear
Do you know how I could send a discord embed using json?
What do you mean by "using JSON"?
Maybe
{
"content": null,
"embeds": [
{
"color": null,
"author": {
"name": "Krush#9999"
}
}
],
"attachments": []
}
!d discord.Embed.from_dict
classmethod from_dict(data)```
Converts a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.11)") to a [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") provided it is in the format that Discord expects it to be in.
You can find out about this format in the [official Discord documentation](https://discord.com/developers/docs/resources/channel#embed-object).
I wanna send out embed, it has a lot of information and needs to be edited often
Thinking I can just have it as a json and send it from that
Load the json into a dict
Looks like this is more than just an embed JSON
^
It looks like it's all the data for sending a message
I would suggest you send a raw API POST request to the endpoint then
im using discohook to create it
with a webhook?
Though I don't really get how using a raw JSON is going to make it easier to send it
easier to write
how so? Instead of having a list of descriptions/titles
It'll be easier in the fact that JSON removes all library abstractions but, it'll backfire if you don't know what you're really doing
just seems like a lot of extra effort using an external tool to make something that you then have to parse
External tool is sort of miss-leading, you can also fit discord.py or any other wrapper under that definition, I should probably clarify in my eyes I see easier as simpler as well
Of course this should follow case-by-case, sometimes it's fine to curl and other times it's best to use a wrapper
But for webhooks and what not I usually make my own requests manually
Since I won't need a server or what not
eh only because you have to type data into that website, open the json, save that, just a lot of unnecessary stuff that would be easier in python itself
dpy also has stuff for handling webhooks too btw
never seen this before who can help not even importing discord.sinks
get token -> create bot instance -> add function or something to get a member via id -> get Member instance -> print member instance id
vs
get token -> curl -H "Authorization: Bot {token}" https://discord.com/api/v10/users/:id
Do you see what I mean
And again this is case-by-case
You shouldn't be using curl and simple stuff for things that requires gateway connection
Mhm yep
No idea what this guy's actually trying to do though so can't exactly tell what to suggest
can u help me
just ask your question
never seen this before who can help not even importing discord.sinks
Are you using a fork?
Or some 3rd party lib
iion think so
check, use pip list
Give me a yes/no answer
k
discord 2.0.0
discord.py 2.0.1
discord-webhook 0.17.0
show the full output
Leaves the server??
I use replit.
I invite the bot to my server.
My bot is alive and writes a message to the server.
Then it leaves the server.
yeah
the bot shouldn't be leaving the server on its own
unless you have another instance of your bot running / someone has your token and is running their own script on your bot
both of which can be solved by resetting your token
Hmm..
doenst work
initial_extensions = ['cogs.simple']
# Here we load our extensions(cogs) listed above in [initial_extensions].
async def load():
for extension in initial_extensions:
try:
await bot.load_extension(extension)
except Exception as e:
print(f'Failed to load extension {extension}.', file=sys.stderr)
traceback.print_exc()
I can't get my cog to load. Ive double checked that the cog works by running the file by itself.
I have used a couple different methods for loading but nothing seems to work
What's the traceback?
nothing at all
Try putting a print statement in the cog's __init__
And the print inside the cog init gets called?
class SimpleCog(commands.Cog):
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
print('This bitch loaded')
thats what you mean correct?
In the __init__
Not the listener
try printing above the await bot.load_extension(extension) line
oooh found the problem
Its not reading that portion
Ill post more of the file in few
does anyone know how I can make a event or something like when someone sends a message in a channel from another serv a bot copy and pastes it into a channel of my choice
@bot.event
async def on_message():
thats it?
not really
You'll need to implement the logic
^^
@bot.listen()
async def on_message(message: discord.Message) -> None:
channel = bot.get_channel(...) # this is the channel which the message should be sent to
await channel.send(f"User {message.author} said: '{message.content}' in server {message.guild}")
@slate swan
something similar to that will do
would it be @client.listen
since im using client
Yes
thanks man ill test it rn
class RocBot(commands.Bot):
def __init__(self) -> None:
super().__init__(command_prefix="!", intents=discord.Intents.all(),
#NinjaPanda ID, change to yours while running.
description='Pheonix 2 iOS information bot', owner_ids= [352986404621647873])
async def setup_hook(self) -> None:
self.tree.copy_global_to(guild=discord.Object(id=722310060671500410)) #replace your guild id.
await self.tree.sync()
bot = RocBot()
initial_extensions = ['cogs.simple']
# Here we load our extensions(cogs) listed above in [initial_extensions].
async def load():
for extension in initial_extensions:
print('blah')
try:
print('work bitch')
await bot.load_extension(extension)
except Exception as e:
print(f'Failed to load extension {extension}.', file=sys.stderr)
traceback.print_exc()
bot.run(token)
?
Which print statements are executed?
none
Are you actually calling the load() function?
i think its getting skipped entirely
what is this
im not using cogs
Their code
oh ok
They're asking for help, not providing help
oh sorry
no worries
it might help if i do this
smh
the unfortunate side of rewriting other peoples code
Why not just smack that all inside of setup_hook
You could yeah
async def on_message(message: discord.Message) -> None:
channel = client.get_channel("1041476774531432480") # this is the channel which the message should be sent to
await channel.send(f"User {message.author} said: '{message.content}' in server {message.guild}")```
I have this now how could I add where the bot gets message from channels from other servers?
But since you've already got it in another function, you can just await load()
It already does that
on_message gets triggered whenever there is a message anywhere
Where? unless you somehow allow top-level await (without exec flags)
i wanna do custom servers though custom channels
put it under the class?
It's must easier to get rid of manually setting an entry point and just let the wrapper do it for you
In the setup_hook
oh yeea
I'm not quite understanding
Okay so I want my bot to get messages from other server channels and send that to my server channel
And only a select list of other channels?
i want to do a few channels
Alright. You'd probably create a list of channel IDs, and in your on_message function, you would check if message.channel.id in channel_ids where channel_ids is the aforementioned list of channel IDs
could you send a example of like code or something I don't really understand what you mean ๐
sure
channel_ids = [...]
async def on_message(m):
if m.channel.id in channel_ids:
# send message to your own server
add that to the code I have now?
that's not a copy paste example
you'll have to modify your existing code
it should only be a 2 line addition
i wish I knew how man
first add a list of channel IDs
alright one sec
which parts do you not understand?
I don't know how to get my bot to send the message to my channel
I have
async def on_message(m):
if m.channel.id in channel_ids:
# send message to your own server```
right now
!d discord.TextChannel.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
!d discord.Client.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
what's "my channel"
my channel id where the bot sends the message from the selected channel ids
I see this but I don't know how to add that to my code
you add it where you want to send a messge?
initial_extensions = ['cogs.simple']
# Here we load our extensions(cogs) listed above in [initial_extensions].
async def load():
for extension in initial_extensions:
print('blah')
try:
print('work bitch')
await bot.load_extension(extension)
except Exception as e:
print(f'Failed to load extension {extension}.', file=sys.stderr)
traceback.print_exc()
class RocBot(commands.Bot):
def __init__(self) -> None:
super().__init__(command_prefix="!", intents=discord.Intents.all(),
#NinjaPanda ID, change to yours while running.
description='Pheonix 2 iOS information bot', owner_ids= [352986404621647873])
async def setup_hook(self) -> None:
await self.load()
self.tree.copy_global_to(guild=discord.Object(id=722310060671500410)) #replace your guild id.
await self.tree.sync()
bot = RocBot()
await self.load()
TabError: inconsistent use of tabs and spaces in indentation```
I dont understand
could you show an example please
of what
theres examples here
error says exactly what the issue is
like how I can do it the docs confuse me
what part is confusing
how is it that though
I dont see self.load in here?
I don't know how to do what I want and put it into my code
yes but what dont you understand
appolgies, it's there. made an edit before pasting
I just said bruh
I have this and it runs but doesnt work
async def on_message(m):
if m.channel.id in channel_ids:
channel = client.get_channel(1041527847396835338)
await channel.send('{message}')```
youre missing the @client.listen() decorator
from discord import app_commands
class aclient(discord.Client):
def __init__(self):
super().__init__(intents = discord.Intents.default())
self.synced = False
async def on_ready(self):
await self.wait_until_ready()
if not self.synced:
await tree.sync()
self.synced = True
print(f"Logged in as {self.user}.")
client = aclient()
tree = app_commands.CommandTree(client)
@client.listen()
async def on_message(m):
channel_ids = [1041476774531432480]
if m.channel.id in channel_ids:
channel = client.get_channel(1041527847396835338)
await channel.send('{message}')
# send message to your own server
client.run("")```
looks good
I don't think client objects have a listen method do they
is my code I got the error of @client.listen()
AttributeError: 'aclient' object has no attribute 'listen'
ugh
might just be a thing of Bot
wait_until_ready waits for asyncio.Event() to be set (ready) and on_ready is also called when ready is set
was there as reason for it
mb, youd use @client.event
yeah its only bots sorry
TypeError: Client.event() missing 1 required positional argument: 'coro```
dont call it
AttributeError: module 'discord' has no attribute 'Bot'
you shouldnt be syncing in on_ready, do it in setup_hook
bot = discord.Bot(command_prefix=">")
discord.Bot doesnt exist in discord.py
I'm not in a cog
Are you using pycord?
no
okay? and?
its discord.ext.commands.Bot
It's commands.Bot then given you imported from discord.ext import commands
but even it still dont work
oh I thought that was for cogs sry
ok
How do I do that?
oops
sorry i read it wrong
setup_hook is a method of client that you can override
it only runs once so you dont have to worry about self.synced
if youre watching a tutorial, its pretty bad
does that affect my code
I'm not
well no its just cleaner
a better way that does affect it is syncing using a command
... can you help me with the error
what error
this
i answered already
.
wdym acting like you can read my mind
calling is a basic python term/concept
I expect you to know this
I don't understand why you cant be specific
am I not?
do you know what calling a function means?
Whatever imma go to a help channel im not tryna fight wit u
I'm with Chris on this one, sorry. They're pretty specific. discord.py is not a library suitable for beginners, so unfortunately we do expect a certain level of Python knowledge before coming in. You may find !resources to be helpful before continuing
is there a certain level of beginner here where I can say go learn python

It's hard to quantify, so not really
We just need to use our best judgement
When they ask how to install python kek
really cant help witht his one over discord sorry
maybe turn on indentation guides/extensions etc in your ide
@sick birch do you have any idea before i go down a rabbit hole?
Yeah this is a simple indentation error. Like Chris said hard to tell over Discord
Your IDE/editor will usually tell you
Exception has occurred: AttributeError
'Bot' object has no attribute 'slash_command'
helppppppp pls
Please don't crosspost
whats that
Sending your question in multiple channels
You've already sent your question in #ot2-never-nesterโs-nightmare
the first time i didnt mean to
People are going to try to help you even if someone already helped you
No worries. It just wastes energy on whoever is helping you
ye
found it, weird indentation that looked proper
@upbeat gust when I remove the on_ready the whole thing under it is an error
^

nice
nice drawing
wow what a bunch of a holes innit whats the point of being here to not help ๐คก
for the people who actually have some idea what theyre doing
We're willing to help, but not give you the answer so that you can copy and paste. We don't write code for people. If you're looking for help: !resources is here
What's the event for select menu when using wait_for()?
why do you need an event?
Actually, are you using discord.py?
Yes discordpy 2.0. I need the event for a select menu to make sure that the bot waits for the user to choose before they can proceed executing the rest of the code.
Why not use the callback?
Components in dpy use callbacks
You don't use events like forks
1 sec
I am doing it already. I was just trying to figure out if there is a way to call another select menu without doing it inside the callback.
You can use view.wait() in the command
then access the select values
oh my bad
view = View()
view.add_item(select)
await view.wait()
await ctx.send("SELECT MENU", view = view)```
subclassing view and select makes this easier
now it doesn't even call the menu
You would generally want to subclass discord.ui.View, then wait for it
view.wait waits till stop is called that happens when timeout or u explicitly call it
u put wait after sending the message containing view
@shrewd apex@sick birch i'll try that after this
async def my_callback(interaction):
await interaction.response.send_message(f"nice choice: {select.values}")
select.callback = my_callback
view = View()
view.add_item(select)
await ctx.send("SELECT MENU", view = view)
await view.wait()```
well how do I format the spaces on Discord? this message looks ugly.
Also, now it sends the SELECT MENU but apparently it keeps waiting. When is stop() called? can I just put it inside my_callback()?
either i am seeing wrong or is the indentation messed up
It worked guys! tysm!
nah it's just that idk how to make it work on discord formatting. It works fine on my editor because i've ifs and elses.
view = View()
select = Select()
async def foo(inter):
# respond
view.stop()
select.callback = foo
view.add_item(select)
await ctx.send(view=view)
await view.wait()
@potent light
Yeah my bad, stop isn't a coroutine.
@bot.command(name='sync')
@commands.guild_only()
@commands.is_owner()
async def sync(ctx: commands.Context, guilds: Greedy[discord.Object], spec: Optional[Literal["~", "*", "^"]] = None) -> None:
me again
getting a greedy is not defined. using code written by someone else, don't know how to define it within the bot file.
unsure if it's an import that i need. I have from typing import Optional, Literal already
got an error when i tried to import Greedy
would guilds: Get[discord.Object] be better for this case?
@shrewd apex what if I want to close interaction in select menu after the user picks one without using send_message() what should be used in this case?
It means that Greedy isn't an object.
I think you probably want Greedy[discord.Guild]
not sure if that's a valid converter though let me check
not subscriptable
Where is Greedy defined in your code?
it is commands.Greedy[]
that makes sense
yeah
lemme try
!d discord.ext.commands.Greedy
class discord.ext.commands.Greedy```
A special converter that greedily consumes arguments until it canโt. As a consequence of this behaviour, most input errors are silently discarded, since it is used as an indicator of when to stop parsing.
When a parser error is met the greedy converter stops converting, undoes the internal string parsing routine, and continues parsing regularly.
For example, in the following code:
```py
@commands.command()
async def test(ctx, numbers: Greedy[int], reason: str):
await ctx.send("numbers: {}, reason: {}".format(numbers, reason))
``` An invocation of `[p]test 1 2 3 4 5 6 hello` would pass `numbers` with `[1, 2, 3, 4, 5, 6]` and `reason` with `hello`...
nice
someone github got 99% of the way there lol
How do I close https://discordpy.readthedocs.io/en/stable/interactions/api.html?highlight=select menu#interactionresponse without using send_message()?
anyone got a recommended library for interacting with twitter?
Probably this: https://pypi.org/project/twitter/
u can disable the select and edit the message then stop the view
What if I want to let their choice appear but not close or edit the interaction response message?
was wondering if anyone had smth different like twython or tweepy lmao
oh idk tbh
i said edit the view not the message
in an interaction u need to respond somehow no matter what
what if I respond with something else than a message?
apparently there are not enough methods provided for InteractionResponse so...
like?
showing their response in the select menu without the "timeout error" thing
once u select it already marks ur response with a tick
then it says This interaction failed
when there is no response.
u need to respond thats what my point is if u want no change at all u can just edit the message again with just the view that way nothing changes
I just expected that there would be another way. I will just respond in this case haha
def give_rank(rank=["Trades: 0", "Trades: 5", "Trades: 20", "Trades: 35", "Trades: 50", "Trades: 75"]):
@client.event
async def on_message(message):
if message.content == "CALC":
if v_MN[0] > 0:
pos = [0,5,20,35,50,75].index(v_MN[0])
role = get(message.author.guild.roles, name=rank[pos])
await message.author.add_roles(role)```
I am trying to give a role automaticly.
v_MN[0] is a function that basicly just returns the correct number (0, 5, 20, 35, 50 or 75).
I use .index to receive the position of the rank list.
So that I can precisely name the correct rank "Trades: 5".
role = get(message.author.guild.roles, name="Trades: 5")
await message.author.add_roles(role)```
Should then give me that rank.
So why does it not work?
- you shouldn't be nesting client.event inside a function
- add_roles accepts role objects or i think snowflake objects if you didnt want to get the whole role
Is there a way to hide commands from showing in the slash command list? Iโm using hybrid commands with hidden=True to hide it in the help menus. I havenโt seen anything for hiding commands in the slash list
slash commands dont have a help command or menu
what i mean is when you type / it shows a list of available commands
im wondering if there is a way to hide commands in that list
such as a command that has is_owner()
tweepy
yes you can use default_member_permissions and it will only show the command to users with those permissions
i use it to hide dev cmds. i set a guild_id for the command and set default perms to admin so only ppl in my server with admin will see the command which is just me.
nextcord.errors.ApplicationInvokeError: Command raised an exception: TypeError: Expected nextcord.Colour, int, or None but received dict instead.
what are u trying to do? mix the colors if so thats not possible has to be one solid color
its an embed builder that the users need to build their embed, trying to do that if they write white so the embed would be white and same w black
then do
if colour == "white":
embed.colour = white
elif statement for black
if colour == "white":
embed.colour = 0xffffff
mhm
thanks!
ill try
WORKS
tysmm
yup np
Guys, how to make a program to show 2 modal forms in a row. discord.py
not possible since a modal cannot send another modal
uhm you can ask the user directly to add an rgb value then use discord.Colour.from_rgb(r, g, b) method, so the user will have more input option
and you will not need to convert every string into a Colour object
if you want to add something fancy, you can check if the user types "random" and then use discord.Colour.random()
!d discord.Colour.random
classmethod random(*, seed=None)```
A factory method that returns a [`Colour`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Colour "discord.Colour") with a random hue.
Note
The random algorithm works by choosing a colour with a random hue but with maxed out saturation and value.
New in version 1.6.
is there a server where i can pay crypto for an experienced developer to build a bot for me
i don't think that this is the right place to ask that
where do i ask
fiverr
Just search locally, and yes it's expensive, but you are paying for time and experience.
It's pretty normal for people to pay over 10k for temporary single release bots in Python.
10k for a bot? lmao
is it made with gold? 
@client.event
async def on_ready():
user = await client.fetch_user(596956753657069599)
print(f'{user}')
a = user._asdict()
print(a)```
"It says User object has no attribute _asdict"
So how to print the user obj as json?
If you go to companies that's pretty standard payout, considering they are in teams of 2-4 you'd only have them for a month 30-40hrs/week
So an hourly rate of 10_000/4 people / 40hrs * 4 = 15.625 euro/dollar, pretty reasonable and on the cheap side lol
There isn't any method to convert a user object completely into json
You can:
do it manually
use the method discord.BaseUser._to_minimal_user_json, it returns a json with user username, id, avatar, discriminator and bot status
Import json and loads it.
i shall look into it
!d json.loads
json.loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)```
Deserialize *s* (a [`str`](https://docs.python.org/3/library/stdtypes.html#str "str"), [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") or [`bytearray`](https://docs.python.org/3/library/stdtypes.html#bytearray "bytearray") instance containing a JSON document) to a Python object using this [conversion table](https://docs.python.org/3/library/json.html#json-to-py-table).
The other arguments have the same meaning as in [`load()`](https://docs.python.org/3/library/json.html#json.load "json.load").
If the data being deserialized is not a valid JSON document, a [`JSONDecodeError`](https://docs.python.org/3/library/json.html#json.JSONDecodeError "json.JSONDecodeError") will be raised.
Changed in version 3.6: *s* can now be of type [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") or [`bytearray`](https://docs.python.org/3/library/stdtypes.html#bytearray "bytearray"). The input encoding should be UTF-8, UTF-16 or UTF-32.
Changed in version 3.9: The keyword argument *encoding* has been removed.
tried it but says no attribute __dict__
Convert the dict to string.
hm I shall try that too
!e ```py
import json
test = {"hello": "world", "1": "2"}
print(type(test))
dmp = json.dumps(test)
print(type(dmp))
jos = json.loads(dmp)
print(type(jos))
print(jos)
@cloud dawn :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | <class 'dict'>
002 | <class 'str'>
003 | <class 'dict'>
004 | {'hello': 'world', '1': '2'}
Now it's serialized so considered a "json object"
ok lemme test it
Basically ```py
import json
def dict_to_json(dict_obj: dict) -> dict:
return json.loads(json.dumps(dict_obj))
It's weird that there isn't a function for this smh
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type User is not JSON serializable```
Then there is an issue somewhere in your dict that needs attention.
Do you have anything as key that isn't a string?
Because you do need to still follow json rules, there isn't a "converter" that does that for you.
@client.event
async def on_ready(): user = await client.fetch_user(596956753657069599)
print(f'We have logged in as {client.user}')
print(f'\n {user}')
a = json.loads(json.dumps(user))
print(a)```
This is the code
monkey patching ๐
Well it's cursed but you can iterate over the object lmfao
Just use this
so do I need to write a subroutine to just print the variable I need?
wtf is it possible to iterate over a User obj?
it saves all necessary attributes
What do you want to do? Why would it need to be a json? Are you trying to send it somewhere?
tell me its for saving the user in a json file and im calling the FBI
read the user info

XD
dir(user) + getattr I didn't say it's going to be pretty
user object has its attributes, just use them
Pls don't tell us that you want to use it as a database 
What's wrong with interaction.client.user.*?
I am learning. haven't reached the level of app command yet
Or just get or fetch it again.
Or just use self with subclassing.
Or botvar
Ill stop
why doesn't discord.py let the users get the raw payloads lol
I think you can.
btw if dir(obj) works you can lmao
oh lol didn't read that
Also I think it's better to use inspect.
Well i still think that there is no use in doing that lol
https://github.com/Rapptz/discord.py/blob/24bdb44d54686448a336ea6d72b1bf8600ef7220/discord/user.py#L89
it just takes the data and sends it to a function
discord/user.py line 89
def __init__(self, *, state: ConnectionState, data: Union[UserPayload, PartialUserPayload]) -> None:```
could have just added it as an attr of the class
even if you want to save some data the only user attribute that you really need is the id
I agree
you can use typing.Literal and supply an option like so
example?
async def random_number(number: typing.Literal["1", "2"])
will give the option of choosing 1 or 2
number: int
this will only accept integers
for integer use app_command.range iirc something similar
but takes the user's input right
yes
ok
will do this if u dont supply an integer
does it need to be a slash command
nah
ok
how to store that value as a variable
and use that variable in the command
.
what about to get the pop up thingys
are there any webhook example?
how do i fix py Privileged message content intent is missing, commands may not work as expected.
go to the discord dev portal
Integrate your service with Discord โ whether it's a bot or a game or whatever your wildest imagination can come up with.
open the application
with the bot
go to the bot section
switch the privileged message content intent on
did it work
you need to enable message_content intents in the code as well
by doing: intents = discord.Intents().all()
i already did
like way before
yeah i alrd did but doesnt work
good for you
like 3 hrs ago
show code lol
just your intents and bot constructor
k
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix="k!",
intents=intents,case_insensitive=True)
tracker = DiscordUtils.InviteTracker(client)```
my commands doesnt work but my event works
intents.message_content=True bro
ill just put that?
put it next to the intents= discord.Intents.default()
thx
bad practice doing that especially if youre not using all
that enables all intents thats unnecessary
but either works fine
then you when u go to verify you have to explain why you want all intents
then realize u dont need them then yea
if something works that doesn't mean you should be doing that
^
wut
oh ye
i stupid
whereโs documentation for this stuff
i have too many questions to ask in this server
oo its documented in the bot
it's python typing 
wut
!d typing
New in version 3.5.
Source code: Lib/typing.py
Note
The Python runtime does not enforce function and variable type annotations. They can be used by third party tools such as type checkers, IDEs, linters, etc.
This module provides runtime support for type hints. The most fundamental support consists of the types Any, Union, Callable, TypeVar, and Generic. For a full specification, please see PEP 484. For a simplified introduction to type hints, see PEP 483.
The function below takes and returns a string and is annotated as follows...
ok
cus me want to make it for all integers less than smth
i couldnโt find anything anywhere
do you mean with a command?
with commands things work differently
but it is suggested that you learn to work with typing first
Hey. I tried to add a slash command but I get this error:
also typing is very helpful
bot = commands.Bot(command_prefix='.', intents=intents)
tree = app_commands.CommandTree(bot)
bot.remove_command("help")
@tree.command(name = "hello", description = "Badge", guild=discord.Object(id=959079594886070372))
async def first_command(interaction):
await interaction.response.send_message("Hello!")```
this is the code
you don't declare a command tree for commands.Bot
it already has one by default
oo
agreed, i wanna throw all the untyped code away
remove dat line, use bot.tree whenever you want the tree
๐ณ save trees
the command isnt working
@bot.tree.command(name = "hello", description = "Badge", guild=discord.Object(id=959079594886070372))
async def first_command(interaction):
await interaction.response.send_message("Hello!")```
Did I do something wrong?
!d discord.app_commands.CommandTree.command
@command(*, name=..., description=..., nsfw=False, guild=..., guilds=..., auto_locale_strings=True, extras=...)```
A decorator that creates an application command from a regular function directly under this tree.
did you sync the command tree?
in your on_ready, make sure to do await bot.tree.sync()
that would work yeah, but its suggested to sync manually using some command or on_message event instead
on_ready can get triggered multiple times
oop ok
@bot.tree.command(name = "hello", description = "Badge", guild=discord.Object(id=959079594886070372))
async def first_command(interaction):
await interaction.response.send_message("Hello!")
@app_commands.context_menu()
async def react(interaction: discord.Interaction, message: discord.Message):
await interaction.response.send_message('Very cool message!', ephemeral=True)
@bot.event
async def on_ready():
await bot.tree.sync()```
Still no
oh this is for the badge lmao
xD
it needs to be a global command
bru
examples/app_commands/basic.py lines 22 to 28
# In this basic example, we just synchronize the app commands to one guild.
# Instead of specifying a guild to every command, we copy over our global commands instead.
# By doing so, we don't have to wait up to an hour until they are shown to the end-user.
async def setup_hook(self):
# This copies the global commands over to your guild.
self.tree.copy_global_to(guild=MY_GUILD)
await self.tree.sync(guild=MY_GUILD)```
guild=discord.Object(None))
Why would it
I thought it was but ok
for the badge thats a requirement
wdym by typing
type hinting
what is that
in your sync(), set guild=None like the example
yep
for any arguement, you can sort of tell python what type of input you are trying to get
ye
basically letting your ide/code know whats the datatype of a variable ```py
def foo(a: int):
bot.listen()
async def on_ready():
async def setup_hook(self):
# This copies the global commands over to your guild.
self.tree.copy_global_to(guild=None)
await self.tree.sync(guild=None)```
Should it be like this?
if you wanna set max values for options just use a slash command lol
how to use those
brej
wat
do you really wanna work with slash commands or is it just for the badge? Askin cuz i have easier ways
for the badge lol
I have never used slash commands, thats why I am dumb
how do ya use setup slash commands
discord.py 2.0a slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
then just run the example in the discord.py github's example folder with your token in it
wdym
is it possible to not use them
https://gist.github.com/Ash-02014/b6f57065f394b54f43666037ade38d32
or the link that chrispy sent
wdym
Oo that's a good one
..?
basically
i want to setup a function to do something n times, but n is set by the user but has to be below a certain value
and sarth said that itโs easier with slash commands
It is
how much easier
in normal command the user will be able to provide any value they want, and you'll have to check the value
in slash command discord won't let them enter the value greater than want you want
so its easier and faster
@slate swan you seen the automod feature?
yes but too lazy to use it
The regex matching is fire
Now we still need regex matching for interaction command values
might actually consider migrating to slash then
