#discord-bots
1 messages ยท Page 295 of 1
Does discord.utils.get only get objects that are already cached, or can it be used on any object?
Or am I thinking about fetch_message
when u send an embed msg with bot, how do u do so if 20 secs passed bot "forgets" that msg?
like, reaction does not work anymore
you should defer the interaction and followup
i should what? XD
!d discord.InteractionResponse.defer
await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
This is only supported with the following interaction types...
generally th ough reactions timeout after 3 seconds
like, if $p is a command, can i just do p?
i believe you have to have a prefix
short of putting all your commands in on_message events - which i do not recommend
i see
It's possible
I'd read this though
!d discord.ext.commands.Bot.command_prefix
The command prefix is what the message content must contain initially to have a command invoked. This prefix could either be a string to indicate what the prefix should be, or a callable that takes in the bot as its first parameter and discord.Message as its second parameter and returns the prefix. This is to facilitate โdynamicโ command prefixes. This callable can be either a regular function or a coroutine.
An empty string as the prefix always matches, enabling prefix-less command invocation. While this may be useful in DMs it should be avoided in servers, as itโs likely to cause performance issues and unintended command invocations.
honestly im not even sure why the api allows this
cause its not done via api its handled on client side
Useful for certain use-cases
i was referring to the discord.py api
okay fine - the api wrapper lol
i guess he means wrapper by api
What causes this? discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction? I am using interaction.defer
and It happens so rarely. Never for me tho.
Can you show the code and traceback
I cant show the traceback, already deleted it.
I can share that portion of the code tho.
best guess is that your code is taking longer than 3 seconds to defer
Hello, I was wondering if anyone knows if discord is still in a sandbox enviroment thats the info I am getting from chatgbt or if that has changed/updated struggling to get info on this past 2021.
you mean discord.py?
wdym sandbox environment
Like I understand what it is, but I don't see how it's applicable for discords API
I might have asked my question in the wrong chat maybe. But basically I am trying to make a discord bot where it replys with a link and opens up a metamask transaction without opening up a internet browser and I have been trouble shooting this for a couple days even asking chatgbt and it says that its not possible to do this due to the "Sandbox enviroment for discord"
wdym
Like it opens a website, inside Discord?
no no opens a google extenstion of meta mask (crypto wallet) without opening up a google browser with a website its pretty complex but for some reason chatgbt says this is not possible due to discord sandbox enviroment so I am just trying to figure out is this true or whats up with that situation
I'm not sure what a sandbox environment has to do with this
Either you're not making any sense, or I'm out of my depth
We will wait for somebody else to see which is true
Because honestly, I have no clue
whelp. here's an error I cant figure out how to fix ;-;
Traceback (most recent call last):
File "C:\Users\Declan\Desktop\discordbots2\battlemetrics_wrapper\example.py", line 25, in <module>
example = asyncio.run(api.player_identifiers(player_id=random_player_id))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python311\Lib\asyncio\runners.py", line 190, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "C:\Python311\Lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "C:\Users\Declan\Desktop\discordbots2\battlemetrics_wrapper\battlemetrics.py", line 677, in player_identifiers
return await _make_request(method="GET", url=url, data=data)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Declan\Desktop\discordbots2\battlemetrics_wrapper\battlemetrics.py", line 91, in _make_request
response = await r.json()
^^^^^^^^^^^^^^
File "C:\Python311\Lib\site-packages\aiohttp\client_reqrep.py", line 1120, in json
return loads(stripped.decode(encoding))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python311\Lib\json\__init__.py", line 346, in loads
return _default_decoder.decode(s)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python311\Lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python311\Lib\json\decoder.py", line 353, in raw_decode
obj, end = self.scan_once(s, idx)
^^^^^^^^^^^^^^^^^^^^^^
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 6949234 (char 6949233)
;-; no idea how to fix.
Show the json
It's being pulled from an API lol
this kind of error pops up occasionally because the size of the json response is massive
As u can see, in this 1 response, almost 7million characters.
!pastebin
Alr I don't need it lol
I'm not to experienced with this type of stuff
Could you share the code? Maybe I could spot something
I am trying to create a based on a link my discord bot gives you a crypto transaction to take place and Chatgbt is telling me that is not possible due to a sandbox enviroment
Why wouldn't it be possible
mainly because I dont want to have a webpage/website open up rather I just want the crypto wallet/transaction and thats what chatgbt say is not possible due to sandbox enviroment
How are you trying to process the transaction
Is there an API?
yes but the process is through a third party crypto wallet/transcation google extentsion app
So you need to use a Google extension without opening a web browser?
I don't really do web3/crypto stuff but this doesn't really seem possible without the user giving you their wallet address and password or whatever is used to secure wallets
This probably
looking at the dpy masterclass and just noticed that in the using intents section, the prefixed commands calls all intents
u just need message_content and that's it
in fact i actually don't recommend using .all() bc it's actually a footgun
i had this one bot owner who just shoved .all() intents and grew to 100 servers, and never got the intents verified
and thus the bot is offline
i'll write a database section in a bit
once i finish with work
When I make my bot public I'm only going to use the intents I require ngl
If I somehow get it to 100 servers I want it to be verified
yea
So when I do that, how should I format it?
Because I just don't want to have a shit ton of ... = True in my code
Subclass?
idk. discord.Intents.default() enables all of the intents except presence, member, and message_content
Yeah but I mean, I'm going to go through each one and disable/enable it
i.e I'll set typing to False
big typo
happens all of the time to me
You can set intents in the Intents constructor
!d discord.Intents.default
classmethod default()```
A factory method that creates a [`Intents`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents) with everything enabled except [`presences`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.presences), [`members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members), and [`message_content`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.message_content).
Oh true
that option also works
I might subclass for shits and giggles anyway
yea i was thinking the same
idk I feel like it just looks neater
agreed
what things does a mod-log has?
to name a few:
message delete
edit
join
leave
what else?
iirc i did put a note for that in first part
yes it is there but for the example section "Writing the Code", it is not explicitly told. Users will just copy and paste and then find it out later that it's a footgun
thats fair but if their bot actually grows to about 100 servers i think they would be aware
you need to set the precedent within the code saying that "hey you should use discord.Intents.default() instead" and then explain why
or atleast a decent amount of coding experience
trust me some dont
yeah thats true but then again if i do it for all code snippets then it would just be burdensome maybe i should do it for the first few ones
๐ฟ
u know that im already planning to cover some of the sections
aight cool
we have a server for this would u like to join?
no thanks
ah ok
and for the advanced bot example, you know there is something called async with
yeah
in fact, aiohttp.ClientSession() automatically supports closing with ctx managers
and that's the recommended way of doing it
thats true
but if u have a lot of dependencies which form connections and require cleanup its tidier defining it
u can always override the aexit method anyways
most of them support ctx managers iirc
asyncpg does
i plan on writing a primer on how to effectively use databases with dpy since most bots end up using databases in some form or way
only asyncpg and asqlite bc folks have reported connections constantly dropping and mysql has no atomic ddl. and also no mongo
only sqlite and pg
that would be a cool tutorial
sql db providers are generally paid so a bunch of ppl use mongo
This is the reason why I refuse to cover mongodb support:
MongoDB is a NoSQL database that stores data as documents in BSON format. Not recommended in general as most of Discord data you are storing is relational (e.g. economy things) while mongodb is for non-relational data, hence there is no reason to use NoSQL over SQL to store relational data.
just host it on the same machine as your vps
done and simple. and then just restrict all connections to only localhost
also motor is basically pymongo but wrapped in an run_in_executor
i would be interested if something wrote a full cython/c/rust version of motor but only using the direct i/o instead
ok ok just saying cause its still a pretty popular choice and beginners generally dont have vps or much knowledge about this so i would prefer a comparison and a tutorial for both cases
popular doesn't automatically make it good
yeah but it still makes it an option
i mean its still viable with an orm right
like prisma altho the python client is in dev state iirc
generally speaking of ORMs just add more complexity than needed. ORMs require the firsthand knowledge of SQL. If you don't know SQL, then there isn't any point of using an ORM because the concepts are fudmentally the same
directly using drivers is the most simple options
i mean if u want to use asyncpg and benefit from relational models u will still need sql and db knowledge
no way around it
that's the point. ORMs also completely limit your control when it comes to the scope of what you can do
yeah
but for beginners i doubt they would stumble upon a case where they need to make raw queries
but entirely upto what you prefer to use ig
i mostly prefer raw drivers such as asyncpg
same but i dont always have a vps or vm at my disposal ๐
so i end up using a bunch of diff db
mongo, sql, firebase (this one is decent for web dev)
i mean heznter is always a good option
dont have financial freedom to make that choice ๐ parents gonna kill me, I'll just host stuff on my rpi when i buy a heatsink this year later
rpi is still a somewhat decent to host
yeah
i personally just go with vps providers and then go from there.
thats cool
what i end up doing is creating vms that replicate the environment of the production server that i plan on running and then do all of my configuration on the vm server
by the time the production server goes live, I already have all of the configs i need ready to go
ig I'll get a vm in future setup docker then should be good to go I'll prolly get hetzner, or digital ocean
both are good options tbh

how do i delete a message that has been sent by await interaction.response.send_message(embed=em)?
!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) in case you do not want to fetch the message and save an HTTP request.
do you know how i can delete 2 messages that have been sent by await interaction.response.send_message(embed=em)? because i am sending what they have reacted to and when both have reacted i want to delete the interaction message and both the responses
You can't send two messages with send_message
If you use something like followup, it returns the message as usual sends
so you do message = await interaction.followup.send(...) and await message.delete()
i just tried that but i get an Unkown Webhook error
Show your code
class Agree2(discord.ui.View):
def __init__(self, user1_id, user2_id):
super().__init__(timeout=None)
self.user1_id = user1_id
self.user2_id = user2_id
self.user1_has_agreed = False
self.user2_has_agreed = False
@discord.ui.button(row=0, label='Agree', style=discord.ButtonStyle.green, custom_id="agree", disabled=False)
async def button_callback2(self, button, interaction):
em = discord.Embed(description=f"{interaction.user.mention} has reacted to 'Agree'", color=discord.Color.green())
msg = await interaction.followup.send(embed=em)
if interaction.user.id == self.user1_id:
self.user1_has_agreed = True
elif interaction.user.id == self.user2_id:
self.user2_has_agreed = True
if self.user1_has_agreed and self.user2_has_agreed:
await interaction.message.delete()
await msg.delete()
amount_em = discord.Embed(title="Amount", description=f"Below please send the **amount** you would like to spend on this item", color=nocolor)
c = await interaction.channel.send(embed=amount_em)
while True:
def check_message(m):
return m.channel == interaction.channel
reply = await interaction.client.wait_for("message", check=check_message)
amount = reply.content
if amount.isdigit():
amount = float(amount)
await c.delete()
await reply.delete()
conf = discord.Embed(description=f"Is `{amount}` the **correct** amount you want to purchase this items for", color=discord.Color.orange())
user1 = i["ticket_author"]
user2 = i["user_added"]
agree_view2 = Agree_To_Amount(user1, user2)
await interaction.channel.send(embed=conf, view=agree_view2)
break
else:
await reply.delete()
await interaction.channel.send(f"{reply.author.mention} The amount **must** be a number!", delete_after=5)```
followup can be used only when you already responded to the interaction
if you used some other way to send the second message, it also should return the message i believe
oh
when ive used await interaction.response.send_message(embed=em), it sends the embed for each user but i jsut cant find out how to delete both
That can't be possible.
send_message will work only once, second would give an error
show the code you had before editing
async def foo(interaction: discord.Interaction):
await interaction.response.send_message("hi 1")
await interaction.response.send_message("hi 2")
sends hi 1 and gives error
discord.app_commands.errors.CommandInvokeError: Command 'foo' raised an exception: InteractionResponded: This interaction has already been responded to before
class Agree2(discord.ui.View):
def __init__(self, user1_id, user2_id):
super().__init__(timeout=None)
self.user1_id = user1_id
self.user2_id = user2_id
self.user1_has_agreed = False
self.user2_has_agreed = False
@discord.ui.button(row=0, label='Agree', style=discord.ButtonStyle.green, custom_id="agree", disabled=False)
async def button_callback2(self, button, interaction):
em = discord.Embed(description=f"{interaction.user.mention} has reacted to 'Agree'", color=discord.Color.green())
await interaction.response.send_message(embed=em)
if interaction.user.id == self.user1_id:
self.user1_has_agreed = True
elif interaction.user.id == self.user2_id:
self.user2_has_agreed = True
if self.user1_has_agreed and self.user2_has_agreed:
await interaction.message.delete()
await interaction.delete_original_response()
amount_em = discord.Embed(title="Amount", description=f"Below please send the **amount** you would like to spend on this item", color=nocolor)
c = await interaction.channel.send(embed=amount_em)
while True:
def check_message(m):
return m.channel == interaction.channel
reply = await interaction.client.wait_for("message", check=check_message)
amount = reply.content
if amount.isdigit():
amount = float(amount)
await c.delete()
await reply.delete()
conf = discord.Embed(description=f"Is `{amount}` the **correct** amount you want to purchase this items for", color=discord.Color.orange())
user1 = i["ticket_author"]
user2 = i["user_added"]
agree_view2 = Agree_To_Amount(user1, user2)
await interaction.channel.send(embed=conf, view=agree_view2)
break
else:
await reply.delete()
await interaction.channel.send(f"{reply.author.mention} The amount **must** be a number!", delete_after=5)```
i only use it once
but it sends 2 because its waiting for 2 reactions

You said you sent them with interaction.response.send_message ยฏ_(ใ)_/ยฏ
i have
You did that with channel.send , no?
`await interaction.channel.send(embed=conf, view=agree_view2)`

so it returns the message and you can do anything you want with it (delete in your case)
message = await interaction.channel.send(embed=conf, view=agree_view2)
await message.delete()
:hi:
Me when I send a message and delete it immediately ๐

its only for self bots to see
๐คซ
how do i go about deleting the two messages i want to?
ah i understood what's going on
Then fetch the message to delete it later
!d discord.Interaction.original_response
await original_response()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Fetches the original interaction response message associated with the interaction.
If the interaction response was a newly created message (i.e. through [`InteractionResponse.send_message()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.send_message) or [`InteractionResponse.defer()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.defer), where `thinking` is `True`) then this returns the message that was sent using that response. Otherwise, this returns the message that triggered the interaction (i.e. through a component).
Repeated calls to this will return a cached value.
On first click you save message, on second click you save the message. And then delete them both
save the message id?
saving just the message object would be easier
because for message only id is not enough
so like store them in a reference?
Variable
class Agree2(discord.ui.View):
def __init__(self, user1_id, user2_id):
super().__init__(timeout=None)
self.user1_id = user1_id
self.user2_id = user2_id
self.user1_has_agreed = False
self.user2_has_agreed = False
self.message_references = []
@discord.ui.button(row=0, label='Agree', style=discord.ButtonStyle.green, custom_id="agree", disabled=False)
async def button_callback2(self, button, interaction):
em = discord.Embed(description=f"{interaction.user.mention} has reacted to 'Agree'", color=discord.Color.green())
message = await interaction.response.send_message(embed=em)
self.message_references.append(message)
if interaction.user.id == self.user1_id:
self.user1_has_agreed = True
elif interaction.user.id == self.user2_id:
self.user2_has_agreed = True
if self.user1_has_agreed and self.user2_has_agreed:```
that?
.
this fetches the responded message
send_message doesn't return it
response.send_message doesn't return the sent message
it's a method
but yes
i dont understand what you're saying
It's a method of interaction objects
its not a function its interaction method

if send_message doesnr return it then what do i use?
Use for what
this?
how does that send the message
It doesn't, it fetches the sent message
em = discord.Embed(description=f"{interaction.user.mention} has reacted to 'Agree'", color=discord.Color.green())
await interaction.response.send_message(embed=em)
msg = await original_response() ```
like that?
No, it's a method
I
use it as method 
i dont know what that means
in that code you'd get error because original_response is not defined
msg = await interaction.original_response()
Yes
yes
store them in a variable?
yes
If its the same message then one varriable ja enough
The thing you did first with the list was easier
But if you want you can do like that ofc
yes.
you already did it multiple times even before asking, just in your original code
why don't you know it now 
i get an attribute error
AttributeError: 'Interaction' object has no attribute 'orginal_response'
oh
nvm
@slate swan hey sir can we have a vc chat
i want to discuss soemthing related to my bot to ya
ye i still get this error
it's original_response not orginal_response
jee how didnt i see that
its still only deleteing one
Show current code
@discord.ui.button(row=0, label='Agree', style=discord.ButtonStyle.green, custom_id="agree", disabled=False)
async def button_callback2(self, button, interaction):
em = discord.Embed(description=f"{interaction.user.mention} has reacted to 'Agree'", color=discord.Color.green())
await interaction.response.send_message(embed=em)
msg = await interaction.original_response()
user1 = msg
user2 = msg
if interaction.user.id == self.user1_id:
self.user1_has_agreed = True
elif interaction.user.id == self.user2_id:
self.user2_has_agreed = True
if self.user1_has_agreed and self.user2_has_agreed:
await interaction.message.delete()
await user1.delete()
await user2.delete()```
Because your user1 and user2 is the same one message
so i have to do 2 msg = await interaction.original_response()?
No. You have to set first variable first time and second variable second time. That's why using a list was much easier
.
class Agree2(discord.ui.View):
def __init__(self, user1_id, user2_id):
super().__init__(timeout=None)
self.user1_id = user1_id
self.user2_id = user2_id
self.user1_has_agreed = False
self.user2_has_agreed = False
self.message_references = []
@discord.ui.button(row=0, label='Agree', style=discord.ButtonStyle.green, custom_id="agree", disabled=False)
async def button_callback2(self, button, interaction):
em = discord.Embed(description=f"{interaction.user.mention} has reacted to 'Agree'", color=discord.Color.green())
await interaction.response.send_message(embed=em)
msg = await interaction.original_response()
self.message_references.append(msg)
that?
yes
then
for message_reference in self.message_references:
await message_reference.delete()```
yes
so this is my code:
https://srcb.in/b4Y2OMPwkP
and the bot keeps on sending embed after 1 minute...
because that's what you told it to do?
async def update_timeout_countdown():
while get_remaining_time().total_seconds() > 0:
formatted_remaining = f"<t:{int(timeout_until.timestamp())}:R>"
embed = discord.Embed(
title="User Timed Out",
color=discord.Color.green()
)
embed.add_field(name="User", value=member.mention)
embed.add_field(name="Moderator", value=ctx.author.display_name)
embed.add_field(name="Reason", value=reason)
embed.add_field(name="Time Remaining", value=formatted_remaining)
await ctx.send(embed=embed)
await asyncio.sleep(60) # Update every 1 minute
await member.edit(timed_out_until=None)
asyncio.ensure_future(update_timeout_countdown())
You also shouldn't need to update that timestamp, since it's a fixed point in time discord just changes what it displays
oh yeah.... ๐
and timeouts expire by themselves, yeah?
yup
What's a free way to host a discord bot? Python anywhere won't let you use websocket on free plan. Replit works but crashes even with the uptimebot manager and keep_alive.py. I need something free and simple for hosting the python scripts
!hosting
Using free hosting options like repl.it or Heroku for continuous 24/7 bot hosting is strongly discouraged.
Instead, opt for a virtual private server (VPS) or use your own spare hardware if you'd rather not pay for hosting.
See our Discord Bot Hosting Guide on our website that compares many hosting providers, both free and paid.
You may also use #965291480992321536 to discuss different discord bot hosting options.
some vps providers have free tiers
The only ones i know of are aws (has 1 year free trial) and daki
But free hosting has a downside that it uses shared ip
gcp
Gcp the one by google?
yes
Doesn't it have credit system and i think you receive 300 credits free?

is it possible to make ui.Button redirect to another link?
Wdym by "another link"? You can redirect to anywhere
like theres these ui buttons with an arrow
and it brings you outside of discord
Yes
And what do you want instead?
I want that but idk how
thank you
!paste
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
How can I fix this 2 errors?
https://paste.debian.net/1290490/
!e 1 + None
@slate swan :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | 1 + None
004 | ~~^~~~~~
005 | TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
you are trying to add those two
total_members = sum([guild.member_count for guild in client.guilds]) here
meaning for some guild .member_count is None
!d discord.Guild.member_count
property member_count```
Returns the member count if available.
Warning
Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members) to be specified.
Changed in version 2.0: Now returns an `Optional[int]`.
total_members = sum([guild.member_count for guild in client.guilds if guild.member_count is not None])```
@slate swan Is this it?
yeah i guess if guild.member_count is even less and will work
cause when this will be 0 it will make 0 difference to sum func
You can also sum guild.member_count or 0
!e ```py
print([x or 0 for x in [None, 1, None]])
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
[0, 1, 0]
.topic
Suggest more topics here!
Good practices
real
So many git repos that are just some python files thrown around
and not naming Bot instance client
No proper project structure, no workflows, no linting
nsfw features
why did this show up and how do i fix it
https://paste.pythondiscord.com/EKNA
i even changed the token and it still showed up
What python version are you using?
is there a way for me to check
How do you not know
Sounds like you have Internet issues
Please make sure you read this fully
When you look for hosting your bot, you might be tempted to use free services or providers that claim to support hosting discord bots (eg PebbleHost and others). Do not uses them. Why? Let me explain.
Free hosts and tiers always have drawbacks - The point of a free tier or a host is to get the user to use their product, and upgrade for all of the good features. Hosts such as replit (see ?tag replit for more info) use shared cpus, oftentimes will run into ratelimits, and have "gotchas" that make you tempted to upgrade to their paid tiers. They also literally remove all control out of how you run your bot. Think about it: Hosts need to make money somehow in order to either break even or gain profit. So naturally they will tempt you into upgrading in order to do that. This is basic economics and quite literally how businesses run.
If you are still looking for a host after reading this, then you have some options. And here are them:
-
Pay up - Pay up and use a VPS provider. My pick is Heznter, but see
?tag vpsfor the full list (if you are on the Python discord server, then see!hostingfor your options). More than likely if you are not an eligible HS or uni student, this is your option. -
Self Host - If you are able to self host your own server, then go for it. This is really the only "free" way if you already pay for your electricity bill and have the equipment to do so
-
GitHub Student Developer Pack - IF you are an eligible student in an verified HS or college (you will need to either provide an valid student ID or proof of education of your HS or college. school transcripts work in this case), then you may apply for this deal. The deal offers $200 free credits on DigitalOcean for 6 months, so if you are a student and need to host your bot, go for it.
daki is jackshit so...
Gotta use a credit/debit card + questionable privacy policies
i mean even for most offers with aws, gcp, azure all u need credit card
That's standard
mhm
It's to prevent spam and stuff
weird never happened before
changed wifi still didnt work
are u using some vpn?
no
do u have any firewall or some antivirus which might be blocking your python programme?
Asher
tcp 443 port is the default port for https requests if its blocked it would likely lead to failing https requests
yeah?
hi
hello ๐
nothing like that it has always worked up until this point
u might wanna check your ssl certs then
im writing a command for the economy side of my bot but i keep getting the same error message.
code:
@bot.tree.command(name='steal', description='Steal from a User')
@app_commands.checks.cooldown(1, 1800, key=lambda i: (i.user.id))
@app_commands.describe(member = 'member')
async def steal(ctx:discord.Interaction, member: discord.Member):
probability = [1,6]
chance = random.randint(probability)
if chance > 2:
with open('userBalances.json', 'r') as f:
balances = json.load(f)
user_id = str(ctx.user.id)
user_balance = balances.get(user_id, 0)
member_id = str(member.id)
member_balance = balances.get(member_id, 0)
if member_id in balances:
if member_balance > 0:
stolen_amount = [1,int(member_balance)]
amount_stolen = random.randint(stolen_amount)
user_balance += amount_stolen
balances[user_id] = user_balance
with open('userBalances.json', 'w') as f:
json.dump(balances, f, indent=4)
member_balance -= amount_stolen
balances[member_id] = member_balance
with open('userBalances.json', 'w') as f:
json.dump(balances, f, indent=4)
embed = discord.Embed(title='Steal Coins', description=f"{ctx.user.mention} has stolen {format(amount_stolen, ',')} Coins from {member.mention}!", color=discord.Color.brand_green())
await ctx.response.send_message(embed=embed)
else:
embed = discord.Embed(title='Steal Coins', description=f"{ctx.user.mention} the user {member.mention} does not have any Coins for you to steal!", color=discord.Color.brand_red())
await ctx.response.send_message(embed=embed)
else:
embed = discord.Embed(title='Steal Coins', description=f"{ctx.user.mention} the user {member.mention} does not have any Coins for you to steal!", color=discord.Color.brand_red())
await ctx.response.send_message(embed=embed)
else:
with open('userBalances.json', 'r') as f:
balances = json.load(f)
user_id = str(ctx.user.id)
user_balance = balances.get(user_id, 0)
member_id = str(member.id)
member_balance = balances.get(member_id, 0)
if member_id in balances:
if member_balance > 0:
stolen_amount = [1,(user_balance)]
amount_stolen = random.randint(stolen_amount)
user_balance -= amount_stolen
balances[user_id] = user_balance
with open('userBalances.json', 'w') as f:
json.dump(balances, f, indent=4)
embed = discord.Embed(title='Steal Coins', description=f"{ctx.user.mention} was caught stealing from {member.mention} and was fined {format(amount_stolen, ',')} Coins!", color=discord.Color.brand_red())
await ctx.response.send_message(embed=embed)
else:
embed = discord.Embed(title='Steal Coins', description=f"{ctx.user.mention} the user {member.mention} does not have any Coins for you to steal!", color=discord.Color.brand_red())
await ctx.response.send_message(embed=embed)
else:
embed = discord.Embed(title='Steal Coins', description=f"{ctx.user.mention} the user {member.mention} does not have any Coins for you to steal!", color=discord.Color.brand_red())
await ctx.response.send_message(embed=embed)
Error:
Traceback (most recent call last):
File "C:\Users\jackf\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\jackf\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "C:\Users\jackf\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\commands.py", line 842, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'steal' raised an exception: TypeError: randint() missing 1 required positional argument: 'b'
!d random.randint
random.randint(a, b)```
Return a random integer *N* such that `a <= N <= b`. Alias for `randrange(a, b+1)`.
i know how to use it. it just wont detect the value
randit takes 2 integers a and b, whereas you've passed a list
stolen_amount = [1,(user_balance)]
amount_stolen = random.randint(stolen_amount)
it works with a list on my work command
Why are you using a JSON file as your db ?
That can't be possible.
because its simpler and its not a big bot
I can assure you it is
Sure, show it
!e
import random
_list = [1, 4]
print(random.randint(1, _list))
@final iron :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 3, in <module>
003 | print(random.randint(1, _list))
004 | ^^^^^^^^^^^^^^^^^^^^^^^^
005 | File "/lang/python/default/lib/python3.11/random.py", line 362, in randint
006 | return self.randrange(a, b+1)
007 | ~^~
008 | TypeError: can only concatenate list (not "int") to list
It doesn't matter. You will run into file corruption, locks and instability issues with it
it's easier until you have to handle file corruption and other shit
Json is a data serialization format, that turns primitive data structures into a string.
A database is a formalized system designed to store and retrieve data, with a substantial
number of features and functionalities designed to support doing so at various scales,
and with a large number of guarantees.
A Json file as-a-db* is fundamentally flawed due to its lack of atomic writes
which results in data corruption and loss when:
โข The disk runs out of storage
โข The program crashes during the write
โข The computer crashes during write
โข Two programs try to write to the file at the same time
Additionally:
โฃ All reads require the entire file to be read
โฃ All reads require the entire structure to be loaded into memory *this does make it fast!
โฃ All writes require the entire file to be re-written
The Json module makes no effort to ameliorate any of these concerns, because json-as-a-db falls
completely and entirely out of the scope of the standard.
If you need the file to be portable and want minimum setup, use sqlite, a standard designed to
solve all these issues.
*Using the json stdlib module
SQLite is the recommended option here
If you want to use a thin wrapper around sqlite3 and make it work with asyncio, consider using this:
https://github.com/Rapptz/asqlite
Not possible
Aiosqlite is still in the dumps bc Amethyst still refuses connection pooling support
https://github.com/omnilib/aiosqlite/issues/254#issuecomment-1663210530
!e
from random import randint
print(randint(*[1, 6]))
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
2
What's * again? Does it unpack the list?
yeah
cool
(any iterable object)
The nested if statements are killing me
I still don't understand why op needs to use JSON as a db. Like the size of your bot doesn't matter
I dunno, I guess they think it's okay because their bot isn't going to be used much
because you don't need to know anything for it
you can use mongodb then though
SQLite with WAL enabled is already pretty fast
This honestly
No need to learn SQL or anything
from experience, don't use mongoDB for a discord bot in my opinion
Mongo is trash anyways
It's an well maintained db but not suited for the task of dbots
Most data you will find you need to store is relational, meaning that they form relationships
And if you are looking for MongoDB bc of it's clustering and sharding abilities, PostgreSQL can do the exact same thing
pymongo/motor-asyncio annoys me with dodgy type hinting, at least that's my experience
Also motor is pretty much trash as well bc of the lack of type hinting
They still use mypy
.topic
Suggest more topics here!
i still dont know why discord.py dont want to add getch methods
class MyCoolBot(Bot):
async def getch_channel(self, id):
return self.get_channel(id) or await self.fetch_channel(id)
done 
yeah i know its easy to add i just dont know why discord.py dev team doesnt want to add that builtin
to not have too much function mb
get and fetch and getch
though it could go to utils
Interesting
i really dont get what decisions are supposed to make with it
mhm
(Danny is owner of discord.py if you are not aware)
decisions 
problem with that is that there are many models
not only channels but Member, User, Message
iterate over methods and if it starts with get and there is the same thing with fetch, create a getch

and what is worse there is for example Message which is not accessable via Bot instance so you cant really make custom method for it unless it would accept the abc.Messageable
i guess there are not a lot of thing like this one
for that just setattr
nah, modify source
not interesting
disnake/guild.py lines 3464 to 3466
async def get_or_fetch_member(
self, member_id: int, *, strict: bool = False
) -> Optional[Member]:```
now i see what "decistions" must be made
i don't :p
monkeypatches are better
apply_monkeypatches()
yeah!
i forgot the provided id might be invalid
so it still returns Optional xd
That looks fine for me
Though since usually mine ids are correct (h), then it means it some id given by the user, so i'd use strict and get an error
well that's a brain issue and at least you get an error
if strict is enabled
raise BrainIssue() from e
I think partially due to the differing behaviour between get and fetch
get simply returns None if the channel isn't found whereas fetch raises an exception, so how exactly would a getch method behave?
It's easy enough for someone to implement and control this themselves if one outcome is preferable over the other so it's not really worth being added as a built-in in my opinion
oftentimes it's down to design. get will always be a cached call (take commands.Bot.get_channel() for example), thus it will not contact the API for the information. fetch will always make an API call (consider commands.Bot.fetch_channel() for example) no matter what
with this design, I implement my coros to have the same exact design principle
yeah reasonable
well it wont fetch the api when its found in the cache
now with get_or_fetch_* methods, it first does an cached lookup and then if not found, contact the API
that's pretty much the point
in my case, when I have a feature that can be enabled/disabled (this is implemented as a check), what I do instead is my coro first looks up the cached config or value on Redis, and returns that. If not found, it will get the data from Postgres instead, and then update or create a new value based on the key on Redis
async def get_or_fetch_enabled_status(
guild_id: int, pool: asyncpg.Pool, redis_pool: ConnectionPool
) -> Union[bool, None]:
query = """
SELECT pins
FROM guild
WHERE id = $1;
"""
key = f"cache:kumiko:{guild_id}:guild_config"
cache = KumikoCache(redis_pool)
if await cache.cache_exists(key=key):
return await cache.get_json_cache(key=key, path=".pins", value_only=False) # type: ignore
else:
status = await pool.fetchval(query, guild_id)
if status is None:
return None
await cache.merge_json_cache(key=key, value=status, path=".pins")
return status
this is the best example of what I mean
the caching library depends on redis-py, but the KumikoCache class is custom
ise e
one thing that is bothering me there
why Union[bool, None] instead of Optional[bool]
both are pretty much the exact same thing
Optional[bool] boils down to Union[bool, None]
unless you are inclined to make a PR fixing all of the instances where that happens (which is a lot spanning 9.3K lines of code), i probably won't change it
bet
probably got lazy
i think that's the simplest answer on why
what the repo link though
feel free to make a PR
there is a good chunk of code i still have to clean up but it's not really my priorities rn to do that
ok sure
btw you can use a script for that
feel free to write that script if you want to do that
Hi everyone, I've coded an embed with a button when you press it, a message comes up. unfortunately interaction fails. somehow i can't give my bot an administrator in the application. or is it something else. thank you very much for your help ps i'm from germany.
code?
@bot.command()
async def regeln(ctx):
# Erstelle ein Embed mit den Regeln
embed = discord.Embed(
title="Server Regeln",
description="Bitte lies die Regeln sorgfรคltig durch und bestรคtige, dass du sie akzeptierst, indem du auf den Button klickst.",
color=discord.Color.blue()
)
rules = [
"Regel 1: Keine Beleidigungen oder Diskriminierung.",
"Regel 2: Kein Spam oder Flooding im Chat.",
"Regel 3: Respektiere die anderen Mitglieder.",
"Regel 4: Halte dich an die Channel-Themen.",
]
embed.add_field(name="Regeln:", value="\n".join(rules), inline=False)
# Erstelle einen Button fรผr die Bestรคtigung
confirm_button = discord.ui.Button(
style=discord.ButtonStyle.primary,
label="Akzeptieren",
custom_id="accept_rules"
)
# Erstelle eine Ansicht mit dem Button
view = discord.ui.View()
view.add_item(confirm_button)
# Sende das Embed und die Ansicht in den aktuellen Kanal
await ctx.send(embed=embed, view=view)
@bot.event
async def on_button_click(interaction: discord.Interaction):
if interaction.custom_id == "accept_rules":
# Bestรคtigungsbutton wurde geklickt
await interaction.response.send_message("Du hast die Regeln akzeptiert!", ephemeral=True)
there is no such event as on_button_click
https://github.com/Rapptz/discord.py/blob/master/examples/views/confirm.py
here is how to use buttons in discord.py
thank you so much
you always have the option of making a PR and i'll code review it
Is it possible use a variable like this? This gives a error
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: UnboundLocalError: cannot access local variable 'role' where it is not associated with a value
role = int(1146549387628122286)
@bot.command()
async def bm(ctx):
# ADMIN ROLE
role = discord.utils.get(ctx.guild.roles, id=role)
do you need to check if the user running the command is an admin or not?
then there is a better way of doing that. https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.has_role
or better yet, just check the permissions needed
Ok, but I want to have the role ID in a variable. If I want to change the role ID I just have to change the variable and not in all the commands
Is that possible?
Same here
restart_feed_channel = bot.get_channel(1146109246115680386)
I want to have the channel ID in a variable as well
dont think you can change the id of a role
what i would recommend doing is making constants and storing the variables in there if you dont need to change them
hello does anyone know how to host the bot on a v server
Clone it then run
^
@bot.tree.command()
async def sendticketpanel(interaction: discord.Interaction):
embed = discord.Embed(
title="Create a Ticket",
description="Click the button below to create a ticket:",
color=0x0000ff
)
button = Button(label="Create a ticket", style=discord.ButtonStyle.green)
view = View()
view.add_item(button)
await interaction.response.send_message(embed=embed, view=view)
user = interaction.user
guild = interaction.guild
ticket_channel_name = f"ticket-{user.name}"
existing_channel = discord.utils.get(guild.text_channels, name=ticket_channel_name)
if not existing_channel:
ticket_channel = await guild.create_text_channel(ticket_channel_name)
support_team_role_name = "Support Team"
support_team_role = discord.utils.get(guild.roles, name=support_team_role_name)
if support_team_role is None:
support_team_role = await guild.create_role(name=support_team_role_name)
await user.add_roles(support_team_role)
overwrites = {
guild.default_role: discord.PermissionOverwrite(read_messages=False),
user: discord.PermissionOverwrite(read_messages=True, send_messages=True),
support_team_role: discord.PermissionOverwrite(read_messages=True, send_messages=True)
}
await ticket_channel.edit(overwrites=overwrites)
what i do wrong bruh the embed sends and the button
when i click da button nothing happens
what is it supposed to do..?
you don't assign a callback in your code
im tryna make tickets
and where's the code to make the channel?
Can we host discord bot on our mobile phone ๐ค?
U could but not recommended
Yes I know but I'll let you figure it out
@commands.hybrid_command(name="test", description="test")
async def test(interaction: discord.Interaction):
await interaction.defer(ephemeral=False)
user = interaction.author
for activity in user.activities:
if isinstance(activity, Spotify):
await interaction.send(f"You are listening to {activity.title} by {activity.artist}")
else:
await interaction.send("You are not listening to Spotify")
is this the correct usage for the discord.Spotify class? doesnt seem to output anything
Might be a stupid question, but how would I pass the function as choices for an app command?
async def shipping_line_choices(
self,
) -> list[app_commands.Choice[str]]:
all_lines = [line for lines in self.shipping_lines.values() for line in lines]
all_lines.sort()
return [
app_commands.Choice(name=line, value=line)
for line in all_lines
]
I've never worked with choices before
Pretty sure choices have to be strings
They need to be displayed on discord
Is this for autocomplete?
It was originally for autocomplete, then I'm miragiting it to choices
I removed a few unneccesary bits
They do, but I don't want to have to do
@app_commands.choices(country=[
discord.app_commands.Choice(name=..., value=...)]
)
For each of them
I mean you probably can use the func that gives the choices. So u can use shipping_line_choices and since that returns a list of app_commands.Choice, it should work
Ofc I haven't tested this so idk if it would actually work or not
I was trying to do that, but if I call the function I get a await error, but I can't await it because it's outside of a function
@app_commands.choices(country=DeclarationCalculator().shipping_line_choices)
Unless I'm doing it wrong
Ah I see. I don't think you need your func to be async unless there is a part of your choice that needs to be awaited
True
Nothing is coming up now for the option
nvm
This is why they say don't code at night
You make stupid mistakes
Wouldn't this be blocking though?
anyone?
idk what fork that is, but you possibly need presence intents
true true
did you enable the intent for guild members
or presence, i forgot
presence
Hellow I'm doing scrapping but problem is that cookie is session cookie it expired in few minutes how to retrieve new cookie1 and auto update in my code anyone know or help me
I've got a verified discord bot but when I try use it the commands takes around 10 minutes to execute
And sometimes don't at all
No error can someone help?
Hello how can I fix the bug that when I press the button again, the interaction failed
can someone give me a slash command template
like a slash /say prompt:
thanksp
ur a life saver (not really, just extremely helpful)
!d discord.ext.commands.before_invoke
@discord.ext.commands.before_invoke(coro)```
A decorator that registers a coroutine as a pre-invoke hook.
This allows you to refer to one before invoke hook for several commands that do not have to be within the same cog.
New in version 1.4.
Changed in version 2.0: `coro` parameter is now positional-only.
Example
any event?
!d discord.on_interaction
discord.on_interaction(interaction)```
Called when an interaction happened.
This currently happens due to slash command invocations or components being used.
Warning
This is a low level function that is not generally meant to be used. If you are working with components, consider using the callbacks associated with the [`View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View) instead as it provides a nicer user experience.
New in version 2.0.
hmm
tree has interaction_check
so do what you want and return just True
but the command still executes
no i want to check for something before the command executes
check is called before the command
and if it true then dont execute
though looks like using on_interaction would be the same thing
how can i stop it executing
true = execute
false = don't
?
like look
@bot.event
async def on_interaction(interaction: discord.Interaction):
if interaction.channel.is_nsfw():
await interaction.followup.send("zagzag does not support nsfw channels.", ephemeral=True)
this is my code
how do i loop through users with a specific role?
if this turns true
it still executes the command
and sends the "zagzag does not support nsfw channels."
how can I make it stop executing it
here you are doing nothing except sending
and it's not a check too
it's like on_message, but it seems slash commands are called not from here
!d discord.app_commands.CommandTree.interaction_check
await interaction_check(interaction, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A global check to determine if an [`Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction) should be processed by the tree.
The default implementation returns True (all interactions are processed), but can be overridden if custom behaviour is desired.
thanks ๐
wait do I do await interaction_check(interaction, nsfw)
you "override" it and add custom logic
easiest way would be subclass it
or setattr, why not
so what do I use?
tree.interaction_check = my_custom_check i guess
where my_custom_check is coro that accepts interaction
would my_custom_check = await interaction_check(interaction, nsfw)
loop through role.members
ty
!d discord.Role.members
property members```
Returns all the members with this role.
yes
my_custom_check is function with which you will replace the interaction_check
iterate if you wanna sound real smart
no.
async def my_custom_check(interaction):
...
my_custom_check = interaction_check works tho
just doesn't make sense
oh right down said that
for a use that makes sense
what would be in thst function
you can check everything you want
yeah
for example if only one person can use commands you would do return interaction.user.id == 12345
you return False
return False
what do i return false?
imagine before the interaction is invoked it checks if interaction_check returns True
if it returns False it aborts
discord/app_commands/tree.py lines 1209 to 1212
async def _call(self, interaction: Interaction[ClientT]) -> None:
if not await self.interaction_check(interaction):
interaction.command_failed = True
return```
yeah but if i check for if the channel is nsfw it and it returns true
it will still execute
why is that?
cause its true
what is True
if the channel is nsfw
??
here
you say if it is true
but you know you dont have to do return interaction.channel.nsfw you can do more than that
it still execute
for example you can invert it
here what are we checking
if the interaction is an interaction
Guys how can I host a discord bot on a mobile phone?
No that's the source code
It checks if it should invoke the command
It checks if the interaction_check returned true
pretty easy if you have termux
I did once , it got offline after 10 mins
Hmm imma try
how can I just stop the command from executing
async def my_custom_check(interaction):
return not interaction.channel.is_nsfw()
Not so hard 
You can do that if it's a phone that's not for your personal use
Otherwise I don't recommend doing it on personal use phone
It's my personal but doesn't have anything important, I use it or only study
Phones have which architecture? Arm?
Yeah
return False ๐ญ ?
Then again I don't recommend using a phone that u have to use for some other purpose
What's so hard in understanding
- if interaction_check returns True -> command does run
- if interaction_check returns False -> command does not run
Cuz u will need the app open 24/7 to keep the bot running continuously
In the foreground not background
why cant i use something else
like ```if not interaction.channel.is_nsfw:
Whats problem in that?
Yeah sure paste it into every command
heck no
For some reason it automatically stops if kept in background
That happened with me when I did last time
why not in the on_interaction event
Should I get raspberry? It's way too expensive
If u can afford yes
You can only have 2
- Supports slash commands - self explainatory
- Uses AutoMod - self explainatory
Otherwise you can use aws it has 1 year free trial
I can but my dad won't buy that for me
Or gcp
my bot doesnt have slash commands one
Cause it does not decide whether the command runs or not its just invoked on each interaction
how to use interaction_check
idk how to use it
Didnt i explain that already?
Then create slash commands for your bot and sync them
i couldnt understand
discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
im so confused
I have GitHub education but the digital ocean asks me for card which i don't have
Welp then you will need a card for aws and gcp too
Why will a student have a card , they TF should understand
,
Tho i have 3 cards?
U student?
Yeah
Which grade?
In my country there are lot of children like ~12 years old that already have a card.
I don't have it tho
University
Oh lol , i in 9 grade
There are lots of mobile wallets that have v-cards
Why they need card though they can get our verification from GitHub student
Welp it's their ToS
Hmm
Can't do anything about that
Lots of benefits if u know how to utilize them
Which benefits, they all need cards probably
Nope not all
Like namecheap , heroku , etc
Welp as far as I'm concerned for me it provided with 3 domains for websites
@bot.event
async def on_interaction(interaction: discord.Interaction):
channel = interaction.channel
if channel.is_nsfw():
interaction.command_failed = True
await interaction.followup.send('zagzag does not support NSFW channels.', ephemeral=True)
return
``` this code works but the command executes after
That event is simply called when any interaction occurs between a user and the bot, the event does not control command invocations or anything else
I believe there's a built-in decorator for NSFW commands
how can i make the commands stop executing?
i would have to put it in every command
Hmmm
i just need to know how to make it stop executing
!d discord.app_commands.CommandTree.interaction_check Overwriting this method might be an option for you
await interaction_check(interaction, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A global check to determine if an [`Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction) should be processed by the tree.
The default implementation returns True (all interactions are processed), but can be overridden if custom behaviour is desired.
i dont understand how it works
await self.interaction_check(nsfw) wouldnt work
You don't call it yourself
The library calls it to check whether a command should be invoked, you can overwrite the method to implement your own logic
The default implementation just returns True
async def on_interaction(interaction: discord.Interaction):
channel = interaction.channel
if not channel.is_nsfw():
await self.interaction_check(interaction)
return
else:
await interaction.followup.send('zagzag does not support NSFW channels.', ephemeral=True)```
as per delliott's explanation, you should override the CommandTree class that's used by your bot which will let you change what interaction_check() does
for example: ```py
class MyCommandTree(app_commands.CommandTree):
async def interaction_check(self, interaction):
if interaction.user.id == 1146836125290344540:
await interaction.response.send_message("I don't like you in particular")
return False
return True
bot = commands.Bot(tree_cls=MyCommandTree, ...)```
Is it better to do:
if account_age.days > 30 and member.avatar:
return
unverified_role = discord.utils.get(guild.roles, id=769451860884062228)
if unverified_role:
await member.add_roles(unverified_role)
or
if account_age.days <= 30 or not member.avatar:
unverified_role = discord.utils.get(guild.roles, id=769451860884062228)
if unverified_role:
await member.add_roles(unverified_role)
You were told Like 3 times to use interaction_check 
1
thats more of a #software-architecture question, but generally "guard clauses" (the former) reduce indentation and makes it easier to read
Can you motivate why?
Easier to read
Especially when it grows
Makes sense, thanks
that doesnt work
Explain what you mean by that
Sorry, I mean what do you think about the code?
Why do you have to introduce a delay?
like this ```@bot.event
async def on_interaction(interaction: discord.Interaction):
channel = interaction.channel
if not channel.is_nsfw():
await self.interaction_check(interaction)
return
else:
await interaction.followup.send('zagzag does not support NSFW channels.', ephemeral=True)```
no.
And why do u have to ping them and then delete the message?
This is on_interaction and Like i said it does not decide whether command is invoked or not
I don't really know
It does :/
What exception would you use? What do you think about this:
except discord.NotFound:
pass
except discord.Forbidden:
pass
except Exception as e:
print(f"An error occurred: {type(e).__name__} - {e}")```
There should be some sort of feedback instead of ignoring exceptions
Or if you really wanna do nothing about some exceptions use contextlib.suppress
i have this error trying running my program on vscode
even if i pip install discord.py
i tried to uninstall and reinstall but not working
!dashm
When trying to install a package via pip, it's recommended to invoke pip as a module: python -m pip install your_package.
Why would we use python -m pip instead of pip?
Invoking pip as a module ensures you know which pip you're using. This is helpful if you have multiple Python versions. You always know which Python version you're installing packages to.
Note
The exact python command you invoke can vary. It may be python3 or py, ensure it's correct for your system.
Install it using this
PS C:\Users\canai\Desktop\Partins_bot> python -V
Python 3.11.5
Now, in vscode press Ctrl shift p
Type in Interpreter
Find setting Like Python: Set Interpreter or something about that
And select it to the 3.11.5
okay and now
and now run the script?
same error
okay i changed it to another because i had 2 options and now for some reason its working
Thanks !
๐
Then u don't need it
Do someone know a good repo who has a ticket system for my bot ?
hello I can't find the function to give the number of channels on the server could someone help me
!d discord.Guild.channels
property channels```
A list of channels that belongs to this guild.
ty
can someone give me a method to get every banned member's id in a server in a list
c'est pas toi qui t'est fait tej d'mx aujd ?
!d discord.Guild.bans
async for ... in bans(*, limit=1000, before=..., after=...)```
Retrieves an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator) of the users that are banned from the guild as a [`BanEntry`](https://discordpy.readthedocs.io/en/latest/api.html#discord.BanEntry).
You must have [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members) to get this information.
Changed in version 2.0: Due to a breaking change in Discordโs API, this now returns a paginated iterator instead of a list.
Examples
Usage...
HMMMM
does anyone know how to get rid of these types of errors? i have to click the button a few times for it to work
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
You can make your own
If you're currently using channels to implement "tickets" (short lived conversations between a subset of people), please consider using discord's thread feature instead. Threads were made for exactly this purpose: to have a short, separate discussion with a subset of people. Trying to use channels for this is antiquated and has several limitations:
- There is a strict limit on the number of channels in a server/category as well as the rate they can be created
- Channel names can have strict limitations on partnered servers. There are certain numbers which can cause your channel to fail in creation
- Threads have a much cleaner permissioning and archiving process
While you may be used to channels or prefer the UI, please consider if this is the correct tool for what you're trying to accomplish.
all interactions must be responsed in 3 seconds or less. There are two things that could be happening here that would cause the error:
- You have blocking code
- Your code is not blocking, but is taking a very long time for some reason. In this case, you will need to defer the interaction. Deferring the interaction allows you to have up to 15 mins to respond, which will you will need to use
await interaction.followup.send()in order to respond to the interaction
idk how
you can think of tickets as either fourm posts or short-lived threads
but i asked for a repo -_-
so when i use interaction.response.defer(), after that i have to use await interaction.followup.send()?
no one is going to spoonfeed you code here. Figure it out yourself
yes
althogh not for discord.py, FastAPI actually has a really good section on their docs on what async really means: https://fastapi.tiangolo.com/async/
can i use await interaction.channel.followup.send()?
nope
oh
the dpy docs also has a good explaination on what blocking is: https://discordpy.readthedocs.io/en/stable/faq.html#what-does-blocking-mean
ok ty
np
Hey, is it possible to code Modals Pagination? Already spent 1 hour on trying to find out how to do it
wdym by that
have an pagination menu within modals? nope you cant
thanks
guys recently an customer ask me a nomination system, the fields exceed the discord limits in the forms plus there are requirements as well, and I don't have any very good idea how to handle it: How to show the fields and requirements? (PS: don't want to use google form)
@client.tree.command()
@app_commands.describe(
channel='The voice channel to lock.',
allowed_roles='Roles allowed to join the locked channel.'
)
async def lockvc(interaction: discord.Interaction, channel: discord.VoiceChannel, allowed_roles: discord.Role = None):
"""Lock a voice channel to prevent everyone from joining."""
everyone_role = interaction.guild.default_role
if not allowed_roles:
# If no roles are specified, set the channel permissions to deny @everyone to connect
await channel.set_permissions(everyone_role, connect=False)
await interaction.response.send_message(f"{channel.mention} is now locked. `@everyone` can see but not join.")
else:
# If allowed roles are specified, set the channel permissions to allow those roles to connect
await channel.set_permissions(everyone_role, connect=False)
for role in allowed_roles:
await channel.set_permissions(role, connect=True)
allowed_role_mentions = ' '.join(role.mention for role in allowed_roles)
await interaction.response.send_message(f"{channel.mention} is now locked. Only ''{allowed_role_mentions}` can join.")```
the command works fine without the role selected
but when u add a role it breaks and says that
Just show it in the placeholder of the text input
It would be uncomfortable for the user
the error is in:
async def lockvc(interaction: discord.Interaction, channel: discord.VoiceChannel, allowed_roles: discord.Role = None):```
Unless you throw them instructions before sending the modal, that's the only other option
hey could you try identify the error in my code?
Any ideas without modals? i would have them but am not convinced to use them
Idk it depends on how u have things set up
Hello. I'm a python newbie, but I just want to edit an existing open-source bot for my discord. The thing I want to do is that every user from this list gets a list with the others and their roles. How should I start?
Lemme check the code
is jungle a role?
a role in the server?
idk
or you're talking about the game
here it says jungle
Yeah: mid, jungle, adc, top, support are their choices
so you want it to display roles they choose?
Let me do it simpler, I want to do so every user in the embed gets this list (embed)(Like @hollow owl - Mid, @onyx elk - Adc etc.)
how are they getting these roles? through a button or reaction as is it a discord role
multiple buttons, they aren't discord roles, just their choices for a League of Legends match
oh idk what lol does
sorry
no need to worry, I don't know either, just trying to help a friend but I think I need to explore more the code first as I'm not sure how to explain xd
thanks for trying to help me and understand :))
sorry i coudlnt be more help
could someone help?
You want to create an embed for each participate?
allowed_roles: discord.Role -> only 1 role, it's not a Iterable
yes, in their dms
Why?
i only select 1 role
@hollow owl Did you upload the code?
iterable = list, sets, tuples and dict
iterable is something you can iterate over
so how would i edit it
so one Role object is not
!paste
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
how could i edit it im new to application commands
that's what my friend wanted :)) the code is open-source but I'm not sure that you can help me, https://github.com/InHouseQueue/InHouseQueue
@hollow owl You just need something that randomize users in a specific voice channel?
@client.tree.command()
@app_commands.describe(
channel='The voice channel to lock.',
allowed_roles='Roles allowed to join the locked channel.'
)
async def lockvc(interaction: discord.Interaction, channel: discord.VoiceChannel, allowed_roles: discord.Role = None):
"""Lock a voice channel to prevent everyone from joining."""
everyone_role = interaction.guild.default_role
if not allowed_roles:
# If no roles are specified, set the channel permissions to deny @everyone to connect
await channel.set_permissions(everyone_role, connect=False)
await interaction.response.send_message(f"{channel.mention} is now locked. `@everyone` can see but not join.")
else:
# If allowed roles are specified, set the channel permissions to allow those roles to connect
await channel.set_permissions(everyone_role, connect=False)
await channel.set_permissions(allowed_roles, connect=True)
allowed_role_mentions = allowed_roles.mention
await interaction.response.send_message(f"{channel.mention} is now locked. Only ''{allowed_role_mentions}` can join.")
i get an error
allowed_role_mentions allowed_roles.mention
Sure, good luck
thanks
are you sure you know the basics of python?

it was on a second line for some reason the way i copied lol
Or general programming?
thank you for helping!
guys does anyone know if discord bots show activity field and display something like listening to spotify
!d discord.ActivityType.listening
A โListeningโ activity type.
oh, hmmm i was trying to set my bot to auto show whenever i go live on twitch or like start listening to spotify
i'll check it out
let me know if something like this even exists for twitch
yes it does
hmm maybe im missing out something
this is what i have done so far:
@client.event
async def on_ready():
print(f'Logged in as {client.user.name} ({client.user.id})')
while not client.is_closed():
stream_title = await fetch_stream_title()
if stream_title:
await client.change_presence(
activity=discord.Streaming(
name=stream_title, url="https://www.twitch.tv/codemiko"
)
)
print(f'Bot status set to "streaming" with title: {stream_title}')
else:
await client.change_presence(status=discord.Status.online)
print('Bot status set to online (user not streaming)')
await asyncio.sleep(60) # Check every 60 seconds
# Run the bot
client.run(TOKEN)```
it will show the status, now i'm trying to put it in the activity tab and have the watch now button too
!d discord.Streaming
class discord.Streaming(*, name, url, **extra)```
A slimmed down version of [`Activity`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Activity) that represents a Discord streaming status.
This is typically displayed via **Streaming** on the official Discord client.
x == y Checks if two streams are equal.
x != y Checks if two streams are not equal.
hash(x) Returns the streamโs hash.
str(x) Returns the streamโs name.
see what arguments it takes
alrighty
!d discord.ActivityType.playing
A โPlayingโ activity type.
!d await client.change_presence(status=discord.Status.dnd, activity=discord.Game(name="Roblox"))
!d status
Rich can display a status message with a โspinnerโ animation that wonโt interfere with regular console output. Run the following command for a demo of this feature:
python -m rich.status
``` To display a status message, call [`status()`](https://rich.readthedocs.io/en/stable/reference/console.html#rich.console.Console.status) with the status message (which may be a string, Text, or other renderable). The result is a context manager which starts and stops the status display around a block of code. Hereโs an example:
```py
with console.status("Working..."):
do_work()
``` You can change the spinner animation via the `spinner` parameter...
!d discord.Status.dnd
The member is โDo Not Disturbโ.
Does anyone knows why imgur direct links isn't working in embed.set_image, ( some work and other no, is it only me? )
oh you have to put in in the fisld
i did
i did, but it's not showing image
could you send code?
oh ale
print(data["Poster"]) > output: imgur link
embed.set_image(url=data["Poster"])
no exceptions raised
if image_url:
embed = discord.Embed(title=f"{prompt} has been generated!", color=discord.Color.blue())
embed.set_image(url=image_url)
embed.set_footer(text=f"ยปBOT BY ALF!ยซ")
await interaction.response.send_message(embed=embed)
heres a code for my bot that generates images from my webserver
it's somehow like this, but the image isn't been displayed ( i can access it from browser normally )
is ot just a link?
idk if it's imgur's fault, or something else
yep, str link
hmm
checked with printing
when u on ur pc send code
Discord is buggy sometimes
If the link works in your url, most likely it's an issue with Discord
It gotta be the same url that you use in markdowns ( one with a file extension in the end )
ensure that the url points to an asset
Url that points to the image address on Imgur won't work
How can I know which servers the bot is located on? And how do I get their links?
!d discord.Client.guilds
property guilds```
The guilds that the connected client is a member of.
this will return a list of Guild objects your server is in
For the invite you'll have to create an invite thru a channel in the guild
!d discord.abc.GuildChannel.create_invite
await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates an instant invite from a text or voice channel.
You must have [`create_instant_invite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_instant_invite) to do this.
Can give an example?
What now
Hello, I try to make it send a message every 10 second, but it say "improper token"
This is false, i have check the token 100 times, yes it is correct. Help !
import os
import discord
import random
import asyncio
from discord.ext import commands
from colorama import Fore, Style
token = input("[TOKEN:")
client = commands.Bot(command_prefix=commands.when_mentioned_or("$"))
os.system('cls')
os.system(f'-7TACEY PRESS')
os.system(f'mode 100,25')
SENTENCES = [
"Hey",
"Hi",
"Lol",
"Haha",
"How are you doing today?",
"What's up?",
"How's your day going so far?",
"Good morning!",
"Good afternoon!",
"Good evening!",
"Hello there!",
"Nice to meet you!",
"I'm glad we could chat!",
"Have a great day!",
"See you later!"
]
async def send_messages(channel):
for sentence in SENTENCES:
await channel.send(sentence)
await asyncio.sleep(10)
@client.event
async def on_ready():
print(f""" \u001b[31m
{Fore.BLUE} โโโโโโโ โโโโโโโโโโโโโโโโโ โโโโโโ โโโโโโโโโโโโโโโโโโ โโโ
{Fore.BLUE} โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโ
{Fore.BLUE} โโโโโโโโโ โโโโ โโโ โโโโโโโโโโโ โโโโโโ โโโโโโโ
{Fore.BLUE} โโโโโโโโโ โโโโ โโโ โโโโโโโโโโโ โโโโโโ โโโโโ
{Fore.BLUE} โโโโโโโโโ โโโ โโโ โโโ โโโโโโโโโโโโโโโโโโโ โโโ
{Fore.BLUE} โโโโโโโ โโโ โโโ โโโ โโโ โโโโโโโโโโโโโโโ โโโ
{Fore.BLUE}
{Fore.BLUE}
{Fore.BLUE} MADE BY:{Fore.RED} ESCAPE/07TACEY
---------------------------------
""")
channel = client.get_channel(985266327088410664)
while True:
await send_messages(channel)
client.run(token, bot=False)```
What version of discord.py are you using? bot is no longer an argument for discord.ext.commands.Bot.run (at least it's no longer documented)
self-botting 
It work like 5 months back
read what Roie said then
post the full traceback
(looks like you're also forgetting to pass intents into the Bot constructor)
no i dont need intents, its not bot
Instead of pasting the token for the line with input, save the token in a text file and read the text file for the token. Maybe input is messing with you or you're pasting unexpected characters
It seems as though you are using an outdated version of discord.py then
intents is a required keyword argument for the constructor of discord.ext.commands.Bot
and use tasks loop 
won't surprise me if that on_ready is causing all sorts of problems
Maybe outdated, It worked some months back
For better clarity and assurance you could move the sleeping into the infinite while loop
A lot has changed some months back. Who knows, maybe the outdated version of the library you're using doesn't support even the oldest still running version of Discord's API?
It is ok, i do fix later
but that is main error
Traceback (most recent call last):
File "main.py", line 10, in <module>
client = commands.Bot(command_prefix=commands.when_mentioned_or("$"))
TypeError: init() missing 1 required keyword-only argument: 'intents'
See, intents is required. You need to add intents=your_intents_here in commands.Bot(...)
You think that is for bot
do anyone know whats this error? my bot showed this for a very long time and it doesnt reply to commands now
WARNING discord.ext.commands.bot Privileged message content intent is missing, commands may not work as expected.
enable it
how do i do that
hi
i enabled it just now but it still doesnt work
Read about intents here
You need to enable it on the developer portal and in code
you think that would work if i do this
i copy that message request from network and i keep sending it in console
it will work i think
ah the code works fine after i added that
tysm
OK
I need help someone help
import os
import discord
import random
import asyncio
from discord.ext import commands
from colorama import Fore, Style
from keep_alive import keep_alive
intents = discord.Intents.default()
intents.typing = True
token = input("TOKEN:")
client = discord.Client(intents=intents)
os.system('cls')
os.system(f'-7TACEY PRESS')
os.system(f'mode 100,25')
SENTENCES = [
"Hey",
"Hi",
"Lol",
"Haha",
"How are you doing today?",
"What's up?",
"How's your day going so far?",
"Good morning!",
"Good afternoon!",
"Good evening!",
"Hello there!",
"Nice to meet you!",
"I'm glad we could chat!",
"Have a great day!",
"See you later!"
]
async def send_messages(channel):
for sentence in SENTENCES:
await channel.send(sentence)
await asyncio.sleep(10)
@client.event
async def on_ready():
print(f""" \u001b[31m
{Fore.BLUE} โโโโโโโ โโโโโโโโโโโโโโโโโ โโโโโโ โโโโโโโโโโโโโโโโโโ โโโ
{Fore.BLUE} โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโ
{Fore.BLUE} โโโโโโโโโ โโโโ โโโ โโโโโโโโโโโ โโโโโโ โโโโโโโ
{Fore.BLUE} โโโโโโโโโ โโโโ โโโ โโโโโโโโโโโ โโโโโโ โโโโโ
{Fore.BLUE} โโโโโโโโโ โโโ โโโ โโโ โโโโโโโโโโโโโโโโโโโ โโโ
{Fore.BLUE} โโโโโโโ โโโ โโโ โโโ โโโ โโโโโโโโโโโโโโโ โโโ
{Fore.BLUE}
{Fore.BLUE}
{Fore.BLUE} MADE BY:{Fore.RED} ESCAPE/07TACEY
---------------------------------
""")
channel = client.get_channel(985266327088410664)
while True:
await send_messages(channel)
keep_alive()
client.run(token)
``` I have made a bit changes since the last one
ERROR
File "main.py", line 61, in <module>
client.run(token)
File "/home/runner/auto-typer-2/venv/lib/python3.8/site-packages/discord/client.py", line 860, in run
asyncio.run(runner())
File "/nix/store/5g6y3nzq80fkq54ahan2slc57j6327nj-python3-3.8.15/lib/python3.8/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/nix/store/5g6y3nzq80fkq54ahan2slc57j6327nj-python3-3.8.15/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
return future.result()
File "/home/runner/auto-typer-2/venv/lib/python3.8/site-packages/discord/client.py", line 849, in runner
await self.start(token, reconnect=reconnect)
File "/home/runner/auto-typer-2/venv/lib/python3.8/site-packages/discord/client.py", line 777, in start
await self.login(token)
File "/home/runner/auto-typer-2/venv/lib/python3.8/site-packages/discord/client.py", line 612, in login
data = await self.http.static_login(token)
File "/home/runner/auto-typer-2/venv/lib/python3.8/site-packages/discord/http.py", line 807, in static_login
raise LoginFailure('Improper token has been passed.') from exc
discord.errors.LoginFailure: Improper token has been passed.```
Uhhh why do you need an token input
Do I need to make 2 classes?
Yes. You would want to make two select classes and then just add them to the view
Are they two seperated messages?
No. Just part of the same view
And with knowing that the environment being run on is NixOS, I already know that you are running it on replit
ty
Np
Also the error is called not using the correct token
And why are you sending messages every 10 seconds to a channel? You know this is called spam right. And funnily enough you are running it in an on_ready event
I would recommend just completely removing your message spam feature bc we all know how it will end up
My dude you have created a spam bot. Why do you need to go through like 14 different messages every 10 seconds? On top of this, have fun with getting rate limited
As a result, I'm not helping you out
It is not spam, it is every 10 seconds.
And this error is very recent, I used this in April with 0 problems.
it sure is correct
I know how to copy and paste my token
I am running it on replit because these school computers are so limited that I cant download or run files, so replit is the only option
Removing the so called "spam feature" ruins the whole point of it
discord.errors.LoginFailure: Improper token has been passed.
And discord knows how to identify correct tokens, which it doesn't
is this a selfbot, by any chance?
Yes it is
yeah discord.py doesn't support self bots, and we are not supposed to help with that here. Sorry
Yes it does
there are working selfbots
figure it out then lol, it's against rule 5 to discuss self bots here
it is not self bot

lol
i seen that bot its a nuke bot from github
can someone tell me why this doesnt show in appspy @client.tree.context_menu(name='Shows user Join Date') async def show_join_date(interaction: discord.Interaction, member: discord.Member): member = member await interaction.response.send_message(f'{member} joined {discord.utils.format_dt(member.joined_at)}')
Why do you even need the line member = member
to say that members mean members

