#discord-bots
1 messages · Page 271 of 1
await interaction.response.send_message("Opened a ticket", ephemeral=True)```
you assign the select callback after already sending the view
what
you assign callback in this line selectmenu.callback = selectmenu_callback
and you send view in this line await interaction.response.send_message("Select a platform", view=view)
sending is before assigning
but the "Opened a ticket" message is getting sent
as a callback
no
and you have no errors in the terminal?
no
can you do print(guild) before creating text channel?
code?
async def ticket_callback(interaction):
guild = interaction.guild
Moderator_role = guild.get_role(config.MODERATOR_ROLE)
overwrites = {
guild.default_role: discord.PermissionOverwrite(view_channel=False),
interaction.user: discord.PermissionOverwrite(view_channel=True),
Moderator_role: discord.PermissionOverwrite(view_channel=True)
}
minecraftemojiID = "1127972711193391267"
discordemojiid = "1127973464179998780"
discordemoji = await interaction.guild.fetch_emoji(discordemojiid)
minecraftemoji = await interaction.guild.fetch_emoji(minecraftemojiID)
selectmenu = ui.Select(placeholder="Select a platform", options=[
discord.SelectOption(
label= "Minecraft",
value="01",
emoji = minecraftemoji
),
discord.SelectOption(
label= "Discord",
value="02",
emoji = discordemoji
)
])
view = ui.View(timeout=None)
view.add_item(selectmenu)
await interaction.response.send_message("Select a platform", view=view)
async def selectmenu_callback(interaction):
if selectmenu.values[0] == "01":
print(guild)
category = discord.utils.get(guild.categories, id=1130129162489827389)
channel = await guild.create_text_channel(f"ticket-{interaction.user.display_name}", category=category, overwrites=overwrites)
await interaction.response.send_message("Opened a ticket", ephemeral=True)
selectmenu.callback = selectmenu_callback```
error says this line caused the error await interaction.response.send_message(view=view) i dont see it here
its line 430 in main.py
@bot.tree.command(name="ticketmenu", description="Sends ticket menu")
async def ticketmenu(interaction):
ticketbutton = ui.Button(label="Open Ticket", style=discord.ButtonStyle.primary, custom_id="ticketbutton")
view = ui.View(timeout=None)
view.add_item(ticketbutton)
ticketbutton.callback = ticket_callback
await interaction.response.send_message(view=view)```
how can this cause error
what
how do i fix it
did you even read the github issue comments?
Vexus says:
Maybe an antivirus is flagging the connection?```
but other commands are working
ok nvm
i restarted the bot and the error gone now
the command works
It prints the guild name
ok wait
It prints the channel name
ticket-trix
So it got created
When i remove the category parameter from the channel, it creates the channel
channel = await guild.create_text_channel(f"ticket-{interaction.user.display_name}", overwrites=overwrites)```
this works
but this doesn't
channel = await guild.create_text_channel(f"ticket-{interaction.user.display_name}",category=category, overwrites=overwrites)
maybe the category is None and it creates it outside of any category
no, it doesnt create the channel anywhere
you can just do category.create_text_channel(...)
category = discord.utils.get(guild.categories, id=1130129162489827389``` is this the problem?
nope
not working, same issue
see what category is
print it out
yes it prints the category name
try this then
same issue meaning the channel is not created?
yes
I checked everywhere
it should create the channel in the category
but its not creating it
no idea then try asking in discord.gg/dpy
Im banned from there
i dont even know why
we do
Errors?
no error

D:
is there any other way
you are trying to create a channel in a specific category?
.
he is trying to create a channel in category. He gets no errors. If he doesnt pass category kwarg it is created category.create_text_channel(...) doesnt work as well simple as that
is his category being returned?
yes
class discord.CategoryChannel```
Represents a Discord channel category.
These are useful to group channels to logical compartments.
x == y Checks if two channels are equal.
x != y Checks if two channels are not equal.
hash(x) Returns the category’s hash.
str(x) Returns the category’s name.
^
uh what
can u show the snippet?
try using this
.
weird
I checked everywhere but didnt find the solution
and it even returns the category name
but still the channel isn't getting created
Im banned from there
idk why but i am
Works fine by me
from there too
¯_(ツ)_/¯
Documentation 
check your dpy version then
Version: 2.3.1
check the action log
see what actually happens
or audit log
however is that called
print(channel, channel.category)
gives the channel and category?
whats action log
audit log
your guild audit log
tf

by expand i mean click the arrow on the right
..
wrong server discord.gg/djs
My slash command seems to be registered twice. How can I solve it?
you are using discord.js its python server not java script
one of the slash command is guild specific while the other is global, just sync the guild specific without including that command to remove them
My codes are now so long that I need to divide them into cogs or not it will be super inconvenient. Maybe I should give up to try this :(
do you need that many commands in a single group?
i guess an alternative if you dont mind reloading a lot of code at once is to have the extension define the group and add commands to it in separate modules without cogs (imo this is even more unconventional than using other refactoring techniques)
!d discord.ext.commands.Group.add_command
add_command(command, /)```
Adds a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") into the internal list of commands.
This is usually not called, instead the [`command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin.command "discord.ext.commands.GroupMixin.command") or [`group()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin.group "discord.ext.commands.GroupMixin.group") shortcut decorators are used instead.
Changed in version 1.4: Raise [`CommandRegistrationError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandRegistrationError "discord.ext.commands.CommandRegistrationError") instead of generic [`ClientException`](https://discordpy.readthedocs.io/en/latest/api.html#discord.ClientException "discord.ClientException")
Changed in version 2.0: `command` parameter is now positional-only.
You can add commands in the group manually
But yeah what you are trying to do is weird
Commands from the same group logically would be in the same cog
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.
When using JSON, you might run into the following error:
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
This error could have appeared because you just created the JSON file and there is nothing in it at the moment.
Whilst having empty data is no problem, the file itself may never be completely empty.
You most likely wanted to structure your JSON as a dictionary. To do this, edit your empty JSON file so that it instead contains {}.
Different data types are also supported. If you wish to read more on these, please refer to this article.
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.
What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:
import discord
# Bunch of bot code
async def ping(ctx):
await ctx.send("Pong!")
What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.
async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!
but the urls are supposed to return one
in simple terms:
- you are trying to get data in json format from a website
- website did not return json, returned error page instead (request failed)
- you tried to convert it to json which failed
use aiohttp and check if the response status is okay
example here
is there anyway that i can avoid this?
ValueError: 'corrupt' is not in list```
```py
if "corrupt" in details.lower():
position = values.index("corrupt") - 1
multiplier = float(values[position])
price = multiplier * 8.65
total_price.append(price)
elif "corrupts" in details.lower():
position = values.index("corrupts") - 1
multiplier = float(values[position])
price = multiplier * 8.65```
if i input corrupts, then it thinks ive inputted corrupt and throws an error
You are checking in details.lower() and then indexing in values
These are two different variables
details is what is in my db column, values is that data but split
so they have the same data in them
Same data? Like literally?
print out details and values
details = 100,iceps,100,corrupts
values = ['100', 'iceps', '100', 'corrupts']
!e
details = "Uwu corrupts owo"
if "corrupt" in details.lower():
print("Corrupt")
elif "corrupts" in details.lower():
print("Corrupts")
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
Corrupt
just check for corrupts in the list
!e
details = "Uwu corrupts owo"
if "corrupts" in details.lower():
print("Corrupt")
elif "corrupt" in details.lower():
print("Corrupts")```
@left dew :white_check_mark: Your 3.11 eval job has completed with return code 0.
Corrupt
ok got it
what about this, the abbreviations, which would i check first?
if "icepiercers" in order_details.lower():
position = values.index("icepiercers") - 1
multiplier = float(values[position])
price = multiplier * 8.45
total_price.append(price)
elif "icepiercer" in order_details.lower():
position = values.index("icepiercer") - 1
multiplier = float(values[position])
price = multiplier * 8.45
total_price.append(price)
elif "iceps" in order_details.lower():
position = values.index("iceps") - 1
multiplier = float(values[position])
price = multiplier * 8.45
total_price.append(price)
elif "icep" in order_details.lower():
position = values.index("icep") - 1
multiplier = float(values[position])
price = multiplier * 8.45
total_price.append(price)```
ok
But actually your code is doing some inefficient duplication of code
yea idk how to make it more efficient
At least you could iterate over the words
for word in "ice", "icep", "icepir", ...:
if word in values:
position = values.index(word) - 1
multiplier = float(values[position])
price = multiplier * 8.45
total_price.append(price)
Also you can maybe iterate just over the values instead of using in each time but can't say from that part of code
would that eliminate the errors ive been having?
What errors
this is what happens if i input for example icepiercer and it thinks icep is in it and it cannot index the position
ValueError: 'corrupt' is not in list```
@naive briar
print values for us
why subtract 1 for position? index is already 0 based
!e ```py
x = [1, 3, 5]
y = x.index(5)
print(y)
@upbeat ice :white_check_mark: Your 3.11 eval job has completed with return code 0.
2
details = 100,iceps,100,corrupts
values = ['100', 'iceps', '100', 'corrupts']
makes sense that corrupts isn't in the values list right? so what is your actual goal here?
to skip the error if it's not found in the list?
you do realize that this is very repetitive code, hence a loop would be very appropriate, right?
you also can make your life easier by storing your data in details as a list in your db instead of some concatenated string
yes i just realised
if i input corrupts, then it would say that corrupt is in order details and therefore give me a value error because it cannot index the list
corrupt isnt in the list
it’s just an example that’s what happens
yes that’s my error
corrupts is in your list corrupt is not
yes so it gives me a value errror cuz it thinks corrupt is in corrupts, and it cannot index the list
why aren't you using this code
#discord-bots message
i will do
this fixed EXACTLY what you want (that's what the if statement does)
and was suggested 45 mins ago...
that will fix my error?
what??
it gives you a value error because its not in the list
never mind
don't blindly copy paste the code, try to understand it
!e ```py
x = ["word", "ice", "corrupt"]
y = x.index("corrupts")
print(y)```
@upbeat ice :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 | y = x.index("corrupts")
004 | ^^^^^^^^^^^^^^^^^^^
005 | ValueError: 'corrupts' is not in list
seems like you didn't even read what the error you were having meant
well, then you'd also understand that
if "corrupts" in <your_list>:
would mean that you'd only index if the word is in the list
it suggests some logic error in your code/database if you are trying to index something not in your list of values to index.
do you mean SelectOption?
are you using slash commands?
ctx begs to differ
select options are a part of app_commands or "choices" not sure what discord actually calls it
still, options are only available for interactions not context commands
well actually nvm
Im reading the docs for pycord
you sure you have pycord installed? @slate swan
and you are not in a venv?
i tried this code and it still doesnt work
what error did you get
position = values.index(word) - 1
ValueError: 'icep' is not in list```
my code:
for word in "icepiercer", "icepiercers", "icep", "iceps":
if word in order_details.lower():
position = values.index(word) - 1
multiplier = float(values[position])
price = multiplier * 8.45
total_price.append(price)```
i inputted iceps
what is in order_details
100,harvs,100,iceps
should i be using values?
Make it a list
values = ['100', 'harvs', '100', 'iceps']
you need to convert your order_Details to a list
Try and see
ok
this really depends on your use case. I dont really know the goal of all of this code
are you sure this is correct: position = values.index(word) - 1
youre starting your index at -1?
what was happening was it wasn’t giving me the correct value every time, so i just did -1 and it worked
yea works fine
im not sure how lol
same but ill take it
list[-1] will give you the last item in the list
!e ```py
x = [1, 2, 3]
y = x[-1]
print(y)```
@upbeat ice :white_check_mark: Your 3.11 eval job has completed with return code 0.
3
oh
anyone know how to put a timer on an on_message event?
I want to do an event that when I say something the bot responds like normal... but you cant run the command again for a certain amount of time
You are doing commands in on_message? 
like you would do on windows
in terminal
also dont use requests within a discord bot
it is blocking
pip not found
also its for roblox api
try pip3
you are installing discord.py thats why i warn you
so what would i install then
instead of requests?
ok i am trying to make a verify command that goes to roblox api
how does that answer my question
so install requests correct?
you can but i dont recommend
why?
it will be synchronous
oh
meaning slower
because i want to download it for it can fetch the persons roblox username
response = requests.get(f"https://api.roblox.com/users/get-by-username?username={roblox_username}")```
alr thanks
roblox api does not require api key?
i am creating one on their dashboard
i think you dont understand questions im asking
most likely not
You can run requests in an executor
hehehe sorry
just how do I put a timer on an on message
what do you mean timer?
when I say the key word the bot responds like normal. but I want it so if i try and do it again it will only work again in a certian amount of time
!d asyncio.sleep
coroutine asyncio.sleep(delay, result=None)```
Block for *delay* seconds.
If *result* is provided, it is returned to the caller when the coroutine completes.
`sleep()` always suspends the current task, allowing other tasks to run.
Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.
Example of coroutine displaying the current date every second for 5 seconds:
xd
ah again in amount of time
then use cooldowns or sum
but if its in on message may be hard
just use commands with built-in cooldowns lol
don't implement everything by yourself with on_message
and then you can apply cooldown on it
Hi guys, I was wondering if it was possible on discord.py to mention commands in a embed please ? because I only find programs on discord.js... thanks have a nice day
You can do </NAME:COMMAND_ID> to get that
For instance: </tag:1079848585027399791> becomes </tag:1079848585027399791>
You can just copy it from the client
If you right click on the dark gray area above the text box
alright, thank you soo much robin for your help
no worries
you can also subclass CommandTree to cache the AppCommand objects if you prefer dynamically fetching IDs over hardcoding it
https://gist.github.com/Soheab/fed903c25b1aae1f11a8ca8c33243131
this is my personal modification of their example:
~~https://paste.pythondiscord.com/XVVA~~
https://gist.github.com/thegamecracks/2305df6753e2a622d2cf8bbcf2935e02
You can't
Huh?
group commands
but I wanna do it so each person has a cool down
2 different people can do it but not the same
That's how cooldowns work
idk how to do a cooldown
A hands-on guide to Discord.py
hehehe
You wouldn't do this in on message
ya reallized that
@client.command()
@commands.cooldown(1, 10, commands.BucketType.user)
async def foo(ctx: commands.Context):
await ctx.send("Success!")```
I copied what the link you sent said to see if it worked... and it didnt
What's your error
Show your file
Do any of your cmds work
Comment outyour on message event for now and try
You need to add await client.process_commands(message) to the end of that function
like this?
No that goes in on_message
uhhhh
The 1 is the rate and 10 is per
also it doesnt respond when its on cooldown to the command... when I do it the bot just doesnt respond
It raises an error that you'll have to catch now
and you are doing absolutely nothing in on_message so you can just remove it
I have it on my real bot codes
so if I add the code im working on now those wont work
I did this and it doesnt work
check the link
get it out from if
with that it will work only when message starts with !hi
The last line shouldn't be under the if statement
so like this?
ye
it worked! but now back to the command...
I have the cooldown working but I want it to say how much time remaining you have left when you try and do it again
you can send the error back in your error handler
Make an error handler
For example you can copy the one that was used in that guide https://fallendeity.github.io/discord.py-masterclass/checks/#built-in-checks
idk how to do this stuff
A hands-on guide to Discord.py
like this?
but the part that says foo.error I replace foo with the name of my command right?
Try it and see 
yeah, you use the same name as the function was
it worked!!!!!!!!!!! thank you guys so much
you can also do error.retry_after instead of hardcoding it
imma stick with the one that worked lmao
and send it in an f string
f"You are on cooldown. You need to wait {error.retry_after} to use that command."
heheh thx for that
is their a way for it to not show all those extra numbers?
you can add {error.retry_after:.2f}
{error.retry_after:.1000f}

I actually did lmao
is their a way to do hours instead of seconds?
i think you just have to represent the hours in seconds
?
hour = 60 * 60 seconds
so your parameters are (1, 3600, w/e)
but where do I put this
hour=60*60 seconds
@client.command()
@commands.cooldown(1, 60, commands.BucketType.user)
async def foo(ctx: commands.Context):
embed=discord.Embed(title="test", description="it worked!", color=discord.Color.red())
await ctx.send(embed=embed)```
like this?
i'll just spoonfeed...
@client.command()
@commands.cooldown(1, 3600, commands.BucketType.user)
async def foo(ctx: commands.Context):
embed=discord.Embed(title="test", description="it worked!", color=discord.Color.red())
await ctx.send(embed=embed)
it's one hour
ik but for the error I want it to say how mnay hours left you have until you can use it again
not how many seconds left
you would need to convert it back to hours
you can't convert seconds into hours?
classic programming 101 problem
yes... but how
Go without programming
You have 31245 seconds
How will you find out how many hours is it?
Like just in words
maths 
you know what
imma just make the error say... "your on six hour cooldown before you can use the command again" instead of the exact
make life easy

Don't do that
last thing.... can I make the bot respond to it... but delete the message it says after 5 seconds
They could run the command with one hour left and it will always says 6
tru
!d discord.ext.commands.Context.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.
This works similarly to [`send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for non-interaction contexts.
For interaction based contexts this does one of the following...
the answer is there in the documentation of send method.
you should find out what to use by yourself
im a genius... but how do I make it 5 seconds
you already did
im not done...
how do I make the command only work in a specific channel
Ik how to do it on an on_message but idk how to do a command
You can just add if in the beggining of the function
Or you can make a custom check and apply it
?
thats very vague
@bot.command()
async def foo(ctx):
if ctx.channel.id == ...:
await ctx.send("ok")
def in_channel(ctx):
return ctx.channel.id == ...
@bot.command()
@commands.check(in_channel)
async def foo(ctx):
await ctx.send('ok')
channel would be undefined right? I would have to do
channel=(my id)
as the second value to compare
if I do this but in the spots you dod ... put my channel id
would it work only in that channel?
yes
this didnt work. No errors just didnt respond
wait nvm
I spelt it wrong
heheheh sorry
- It's not similar to the any of two codes i gave
- You need to cast channel id to string or your ids to integers
- To check for a value in a list you can't use ==. It is comparing
it worked... but it worked in all channels
What do you have now
oh waittttt why do I have return instead of if
You can check negative and do return
@bot.command()
async def foo(ctx):
if ctx.channel.id != ...:
return
await ctx.send("ok")
2 and 3
anyone know if there is a way to determine if an interaction has been deferred
is this number 2?
nope
what about this?
It won't even run
cmonnnn
I dont knowwwwwwwwwwwww
!d discord.InteractionResponse.type
property type```
The type of response that was sent, `None` if response is not done.
maybe this? it would be some of these. but i am not sure
this?
ohh maybe this
Now the third
YES
this?
no
then what do I use? I only know ==
ye
still works in all channels T-T
what's the current code?
in the specified channels too?
hm it doesnt work in those
BROOOOO In my real code I have an on message one with a list of channels that it only works in... but I watned it to work in every channel accept one. But I didnt know how so I just made it only work in ALL the channels
when I COULDA JUST DONE WHAT I JUST DID
uh?
make an opposite condition
can I take away the return?
or like this and put the code inside if
I do that with { that right?
do what
to put the code inside if I surrouned it with this symbe {?
you learned some other language?
did I?
no, for that you use indentation in python
ohhhh
idk from where else you could get such idea
hehehe
how
@buoyant quail this time it worked in all of them. (even the specified channels)
current code
works in all channels?
ya
rerun the code
I dont use commands I only use on message. I made a help message that the bot responds to and gives info... But now that I added a command I get the one I made. And the built in help
how do I fix that
how to remove built in help?
ya
client = commands.Bot(..., help_command=None)
ah ok thx
didnt work
this worked
yayayay
tried this one and got an error
whats on line 22
Pretty sure it's just @commands.check
^that seems right
See this example for how discord.py does it
how about this
instead of worrying about that. How do I make the bot send a message in a different channel when you say something
- get the channel object you want to send a message to
- use the .send() method of that object
https://discordpy.readthedocs.io/en/stable/faq.html#how-do-i-send-a-message-to-a-specific-channel
Is there any way to get the amount of subcommands under a command group?
len(group.commands)?
Wait what? Discord supports link markdown for users now?
yes
Does it only work for select websites?
no
Only in servers?
only in large server so far it seems
Ah that's cool
Hey so I wanted to update todays date in my python bot code every 5 mins, is there any way I can achieve it?
I have already made a function to get todays date
Update it where?
And why do you need to update it every 5 minutes? The date changes every 24 hours
Like I want the bot to work on specific dates only
That is just for example
Do you have a list of dates? Or is there some pattern?
is it possible to make custom options for a slash command argument
@discord.app_commands.choices(**parameters)```
Instructs the given parameters by their name to use the given choices for their choices.
Example...
yep
theres a list of dates on which I want my bot to run
So for that I have to check daily right
Just check before you process commands
I want it to work without intervention
like a reminder
Override the bots on_message event and call bot.process_commands only if the current date is a valid date
import os
import discord
from get_date import get_date
TOKEN = os.environ['BOT_TOKEN']
client = discord.Client(intents=discord.Intents.all())
@client.event
async def on_ready():
print(f"Logged in as {client.user}")
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith("?h"):
await message.channel.send("Hello")
if message.content.startswith("?p"):
await message.channel.send("Ping")
client.run(TOKEN)
from datetime import date
def get_date():
today = date.today()
today_date = today.strftime("%d %m %Y")
return today_date
get_date.py
What I was thnking of doing was to check date after a certain time interval and if it matches a date then it will do certain commands
i think datetime.now() works fine
it appeared like some months ago and then was deleted
now it's again appearing somewhere
it's slowly rolling out i think
does it also warn you when its redirecting to discord site
apparently not
or i have it whitelisted
why would it tho

could be for every link
oh this feature is out now uwu
oh the embed looks ugly
Can’t u remove?
Oh ok
That suppresses the embed
Isn’t there like a cross on the top right if embed to remove tho
I swear there was one before
Oh ok
I don't see any cross
Without suppressing embed
What do you mean not working? If you mean Discord isn't making the [Text](URL) a hyperlink, it's because it's still rolling out
Im so confused rn, which is the actual original way of doing discord.py buttons
Is cuz it’s only in 5% servers
Using a view I think so why?
anyone knows the docs for the discord.py buttons
Hold up
If you wish to use Buttons (and Selects/Dropdowns), please view the documentation for discord.ui here:
https://discordpy.readthedocs.io/en/latest/interactions/api.html#bot-ui-kit
You can also view examples in the repo: https://github.com/Rapptz/discord.py/tree/master/examples/views
Lol used R. Danny in d.py server
yeah
Would have done same
i once tried refering ppl to that server but for some reason my url were getting blocked
Was about to do then saw u do it and knew it was for this
Prob they thought u we’re adversely
so i stopped sending server invite link
Which u kinda were
Ye they should add the offical d.py server link just in case cuz u get a lot of help there
Or they should add R. Danny
that would actually help alot
Not as much as d.py
but will need to recreate tags that danny uses
There is one for like everything
Not many ppl do cuz it’s not that popular here as this is a python general server
and i usually get confused using them since they are for whole python
Ye
especially the !d command
Mhm
you got rate limited
Well, why is most bot economy built in JavaScript????
Because if people google "how to maek deez crod bot" they get js tutorial ig
That is, it cannot be created with python economy
You can create whatever discord bot with python
Economy?
How i create datebase?
#databases pins
learn SQL first
Can you send me a course in google
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
There are tutorials in those pins as well
or u can check w3schools
This?
you can check it
Bro why tf 90% of recommended bots on top.gg are anime, I'm trying to do market research
XD
bot developers are weebs, I guess
Lol
check in the economy tag
but i guess they will also fetch anime bots
Yes
I tryna figure out if bobux bot is unique
Good luck figuring
Has anyone made a discord for listing hypixel skyblock accounts where it displays all of the stats and you set price/payment method
Try searching git hub for that
there is for sure
its SkyHelper
Couldn’t find any
support server: fd4Be4W
Sky helper will tell you your stats
I want to list accs for sale in my server
accounts for sale?
Like this bot
then no and we wont help with it its against hypixel tos
!rule 5
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
That’s crazy
is it really against hypixel's tos
there's probably an API to get this data but other than that I don't have much clue on this
never mind
it's against Minecraft's ToS to sell accounts
buying/selling accounts is against minecraft tos anyways
yeah apparently he meant selling accounts is against the tos
yes
Well it is for educational purposes
But I figured it out
It’s easy with hypixel api
I robbed a bank for educational purposes
oh okay then its fine
when using this code
for word in "corrupt", "corrupts":
if word in values:
position = values.index(word) - 1
multiplier = float(values[position])
price = multiplier * 8.65
total_price.append(price)
it appends the price to total_price, however when i input a new order with different items, it seems to print the total of all the orders ive inputted. how do i make it print the total price for just the ones ive inputted? do i need to do total_price.clear()?
If you want to remove all of the items from the list then yes, you can do that
You just have to spend 3652.5 days in prison then everything will be fine
thats like 10 years 

can anyone help me with this https://discord.com/channels/267624335836053506/1130894205766615271
Ppl are literally telling u what to do there
wdym?
Enable Intents from Dev Portal Too
who code
me
show code
import discord
intents = discord.Intents.all()
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print('Bot is Online & ready to work!!')
@client.event
async def on_message(message):
if message.author == client.user :
return
print("Message content:", repr(message.content))
if message.content == 'hey' :
await message.channel.send('hellooo')
client.run('TOKEN')
message.content string is empty
!intents
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
I created a new bot and now it is working fine
thanks
Do you know python basics and oop?
ik python
oriented object programming or oop idk it
idk how to code with it
and i dont even know what its name
meaning*
ik python basics
but im not advanced
like print or loop or elif or else
these things yk
ty
heres some reading for you
probably should start with the basics first before worrying about hosting
ok
Don't use repl plz it's not made for hosting
discloud, daki
what is this
Nodes
ok
i just got into the introduction :
import discord
class MyClient(discord.Client):
async def on_ready(self):
print(f'Logged on as {self.user}!')
async def on_message(self, message):
print(f'Message from {message.author}: {message.content}')
intents = discord.Intents.default()
intents.message_content = True
client = MyClient(intents=intents)
client.run('my token goes here')
and i dont understand
Wise words
i gotta go anyways
anyone got docs for slash commands
you got the money?
oh no larpc
💀
enjoy
thy
ty
Here is the basics there is no official docs -> https://github.com/Rapptz/discord.py/blob/v2.3.1/examples/app_commands/basic.py
Cruel to send this but technically, you're not wrong.
I think there are docs, but they're in development... 👀
so not in the "main" branch of dpy's gh
if i input harvs, then it prints 2x the price, anyone know how to stop it from happening?
for word in "harvester", "harvesters", "harv", "harvs":
if word in values:
position = values.index(word) - 1
multiplier = float(values[position])
price = multiplier * 8.50
total_price.append(price)```
Is there anywhere I can host my python discord bot for free
your computer 
!e ?
values = [1, "harvs"]
total_price = []
for word in "harvester", "harvesters", "harv", "harvs":
if word in values:
position = values.index(word) - 1
multiplier = float(values[position])
price = multiplier * 8.50
total_price.append(price)
print(total_price)
@buoyant quail :white_check_mark: Your 3.11 eval job has completed with return code 0.
[8.5]
!e ?
values = [1, "harv"]
total_price = []
for word in "harvester", "harvesters", "harv", "harvs":
if word in values:
position = values.index(word) - 1
multiplier = float(values[position])
price = multiplier * 8.50
total_price.append(price)
print(total_price)
@left dew :white_check_mark: Your 3.11 eval job has completed with return code 0.
[8.5]
is it possible to change a users focus? like what text channle they're on? Or is that client side
client side
unless the channel is removed
yeah, I'm deleting a channel, but I want them to be redirected to another channel
But I don't think I can do that
I wish I could handle a user clicking on a channel mention, but I can't do that either
no all you can do is give them a jump url they can click on to get redirected
yeah. its for a party invite system. I create a temp channel with a party invite for them, and if they clicked join I wanted it to redirect them to the party channel and delete the invite channel.
then give them a jump url to follow
So my issue is that after slash command /help bot responding with 'APP DIDNT RESPOND', how do i get rid of that? (Command works and output is correct, sent to a text channel where command was mentioned)
import discord
import pyuac
from discord import app_commands
from datetime import datetime, timedelta
from config import token, GUILD_ID
SnoopRat_icon = 'https://i.ibb.co/sPZ0TDD/images.png'
bot_token = token
intents = discord.Intents.all()
client = discord.Client(intents=intents)
tree = app_commands.CommandTree(client)
def console_msg(msg):
print(f'[{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}] [Console]: {msg}')
@tree.command(name="help", description="Shows a list of commands.", guild=discord.Object(id=GUILD_ID))
async def help(ctx):
embed = discord.Embed(title="SnoopRat Bot",
description="__SnoopRat client information tab__\n\n> Supported commands\n"
"\n**Developers**\n@void mauve",
colour=0x00b0f4,
timestamp=datetime.now())
embed.set_thumbnail(url=SnoopRat_icon)
embed.set_footer(text="SnoopRat",
icon_url=SnoopRat_icon)
await ctx.channel.send(embed=embed)
def main():
client.run(bot_token)
if __name__ == "__main__":
main()
it uses discord.Interaction not commands.Context as parameter
@tree.command(name = "help")
async def help(interaction: discord.Interaction):
await interaction.response.send_message("Hello, World!")
also when using actual Context in prefixed commands the ctx.send is short for ctx.channel.send
ty so much!
ok, ill consider using it
np
I have another issue now 😄 So basically Im using function to find channel by its name, but how do i make sure interaction was made in a channel where command was called (e.g. i have seperate channel for commands and seperate channel for screenshots)? It appears to be the same error mesage 'APP DIDNT RESPOND'.
def find_channel(name):
return discord.utils.get(client.get_all_channels(), name=name)
@tree.command(name="ss", description="Takes a screenshot and sends it", guild=discord.Object(id=GUILD_ID))
async def screenshot(interaction: discord.Interaction):
output_file = os.path.join(outputdir, f"screenshot_{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.png")
with mss.mss() as sct:
monitor = sct.monitors[0]
sct_img = sct.grab(monitor)
mss.tools.to_png(sct_img.rgb, sct_img.size, output=output_file)
await find_channel("📷-screenshots").interaction.response.send_message(file=discord.File(output_file))
os.remove(output_file)
oh ic, so how should i rewrite it
if you want to send a message to a channel you just do channel.send
when you have TextChannel object
!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**.
ok, thanks for help again
Hello, I need help.
I'm trying to host my bot in sparked hosting, but apparently is not getting my database. I imported my database, but it catches as a file.
Does any one knows how to install the bot correctly with database in sparked host.
??
too little information
SQLite
SQLite is a file
sqlite database is a single file
are you using .db file?
YES
ooh no wonder
but then why is not getting it?
I get this error. Sparked Host
sqlite3.DatabaseError: database disk image is malformed
when I run it in my pycharm everything works, but it doesn't in the host.
why dont you use intergrated Databases they give you
cause is php
what is php
ye i am talking to him too
SQLite is super easy to understand.
ooooohhhh. Ok ok let me try that then.
I'll be back later
I got confuse. I'm just trying to master python so I havent look out of the box yet.

hey guys thank you for your time you guys take to reply.
Can you tell me which one I should chose?
I dont see it. I'm from Texas
Doesn't matters ig
But you'd choose the nearest one to the your bot's server for speed
Just take europe

im getting this error
@commands.is_owner()
async def setupAccounts(ctx: commands.Context):
await ctx.message.delete()
embed = discord.Embed(title="Accounts Info",
color=cb_color,
description="""Chase Bank offers a multitude of services when it comes to commercial banking.
We offer two different types of accounts for those who bank with us.
**ACCOUNTS**
Checking Accounts
> Chase's Checking Accounts are a smart and easy way
> to hold money that you can withdraw at any time. Money
> from Checking Accounts are not invested in any way.
Checking Accounts Rates
> $10 withdrawal fee
> $100 monthly account fee
> $100 account closing fee
> Withdraw and deposit as many times as you want
Savings Accounts
> Chase's Savings Accounts are a risk-free way to
> hold large amounts of money. Money from your Savings
> Account is subject to be invested for company purposes.
Savings Accounts Rates
> $50 withdrawal fee
> $100 monthly account fee
> $100 account closing fee
> Withdrawals are only allowed once a week""")
await ctx.send(embed=embed)```
and where is that code located?
its not nested or anything if thats what your asking
send full code mb?
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.
any idea why its saying that cus my other commands r working
could it be the is_onwer()
with such context that command should exist
Just put it on one line
is owner won't give you CommandNotFound
share the code so we can inspect it
idc
ill just reset it later and i doubt you guys will do anything
the command starts on line 235
yeah
restarting again now
to see if it didnt restart
aww fuck somebody nuked my server
xddd
Lmao
it was fast
did not take someone long 
its fine my server has like 15 people and not many channels
whoever did that just wasted time lol
the dumbass who nuked it made all the channels private
nobody got the pings 💀
So, the database it runs is MySQL.
if you can run python you can run a sqlite database
mysql is a database that requires hosting it, and connecting to the server for accessing it
sqlite is just a file, whoever has access to that file can do anything with the database
wait, idk if I was speaking to the correct guy
where you asking before some stuff from sqlite?
sqlite3.DatabaseError: database disk image is malformed
so why this comes out when I run it?
the database is corrupted
what it means?
it is not usable
it means that db is dead
are you using a previous database?
the one the I use in pycharm and it works.
try creating one from scratch
😦
if I do a replica?
u tried and async/concurrent write on it prolly
wdym by that
I make new one just like the old one?
the sqlite3 one is blocking try using async library also
that the hosting provides
what do you guys call your sqlite's database something.db or something.sqlite3?
!blocking
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.
What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:
import discord
# Bunch of bot code
async def ping(ctx):
await ctx.send("Pong!")
What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.
async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!
second
actually i call it just .sqlite
i used sqlite once and used .db it was when i was learning so idk
same
.db
which database do you guys use?
i didn't know you could call it .sqlite3 till today
Postgres
hey guys, but I do use my async
depends on use case
postgres, mongo, redis depends what i need lol
You can call it .iAmMakingTrashExtensions
if python i use postgres / mongodb
if js or ts i use something like firebase / mongo db / or some cms
I knew I should study mysql isntead of sqlite aghh.
same
fair enough
mysql just has extra stuff
sql remains same
isnt sqlite using mysql?
only place holder changes
i mean sql syntax
sure, it's sqlite
kind of, but the db browser tables are easier to work with.
it's sql
yeah corrected myself message later
there are db viewers
didn't read it, mb
yeah but what does it change which database you use
Such exist for any database
he prolly means viewers which visualise sql tables
db browser works for sqlite for sure i used it as well
i have charm professional it visualizes data for like 100 diff databases
thanks, I'm more of spanish speaker.
that's just the app you're using to view
never installed pycharm good to know
ye pycharm is cool
missed reply 😛
I love pycharm
only i dont use it
?
can I view MySQL too?
yes
not with that app
alright let me do some changer.
Sure. But not with "Browser for sqlite"
not sure if dbbrowser supports it but other apps sure
I use DataGrip, idk if it's free
jetbrains comes with a bunch of stuff out of the box thats the cool part vs code ppl will say u can install extensions and whatever but those all still take time to setup compared to out of the box support and long term support by jetbrains itself
down did u ever see anything wrong with the code that would makje the command not found
Your code works
i didn't nuke :p
the nuker was an idiot
nope maybe you did not save the file?
whats a nuker?
he banned everyone (15 people) before pinging everyone
ok bro we know 3rd time ur telling
asher u look suspicious
ok
🧐
i took over discord api 
don't leak your token next time man, we do not know who it was
it was definitely u
you know another way I can host a bot with my sqlite? besides replit?
yeah I don't have anything better to do
its meh but it's better than nothing
Thank You Asher! I'll look into it. Can't wait to release my stock/crypto market game.
I just need to start somewhere.
cant wait*
fix
Alright Thank You guys for your help!
@shrewd apex @slate swan @buoyant quail @thin raft
np
You were right!
I did db all over inside host and it work!
what you can recommend me to save back up db files incase this inccident happens again.
While calling this function console gives out an error message discord.app_commands.errors.CommandInvokeError: Command 'rec' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction and embed is not sent, what should i do in order to fix the issue?
@tree.command(name="rec", description="Records the screen for a specified duration", guild=discord.Object(id=GUILD_ID))
@app_commands.describe(duration="Video length")
@app_commands.rename(duration='duration')
async def screenrecord(interaction: discord.Interaction, duration: app_commands.Range[int, 0, 25]):
output_file = f"{outputdir}rec_{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.mp4"
fourcc = -1
frame_rate = 20.0
frames_captured = 0
screen = screeninfo.get_monitors()[0]
screen_size = (screen.width, screen.height)
out = cv2.VideoWriter(output_file, fourcc, frame_rate, screen_size)
while frames_captured < (duration * frame_rate):
with mss.mss() as sct:
img = sct.grab(sct.monitors[1])
frame = np.array(img)
frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
out.write(frame)
frames_captured += 1
out.release()
cv2.destroyAllWindows()
await find_channel("💻-screen").send(file=discord.File(output_file))
embed = discord.Embed(title="Recording has been made!",
description=f"Check it out at <#{find_channel_id('💻-screen')}>",
colour=embed_color,
timestamp=datetime.now())
embed.set_footer(text="SnoopRat",
icon_url=SnoopRat_icon)
await interaction.response.send_message(embed=embed)
await asyncio.sleep(5)
os.remove(output_file)
interaction.defer()
first
then
interaction.followup.send() where you wanted to send the msg
why? you may ask
oh ic
because my recording function is way longer than 3 seconds
