#discord-bots
1 messages Β· Page 342 of 1
I will look into it too thanks
Typically cache is just a common data structure like dict or list, unless you're caching remote database
In that case you would use redis
i have no idea what is remote database, but like, my plan is to it store the database imported from my macro Cog, that imports from ctx.bot.database, so my local database is kept into a cache function along with the ids
You can easily store that in a dictionary
yeah i read a doc from real python related to cache
right
seems like dicts works like cache in python
kinda like that
you can use lists too but your use case..dictionaries are way easier to implement
yeah
also how do i check if a user by their ID have admin permission of a guild by it's ID?
@commands.has_permissions(administrator=True)
put it right after @bot.command()
this ensures that the specific command can only be used by an admin
i'm not doing it in bot, but in a custom library i'm making for macros
so @commands.has_permission won't work for me
https://pastes.dev/yhiZkhGNGh
i need to use the guild id to gather the guild as an object
as you can see, here i have a cache with the guild id and user id
i need to use the guild id to gather the guild as an object
then verify the user permission using their id
the most i got to was command_count = len(client.commands) which does the regular commands but not the tree commands and if i do command_count = len(client.tree.commands) then it dont work
for p in pathlib.Path("./modules").glob("**/*.py"):
p.load_extension(p.as_posix()[:-3].replace("/", "."))
self.load_extension(f"modules.{module[:-3]}")```
``` p.load_extension(p.as_posix()[:-3].replace("/", "."))
^^^^^^^^^^^^^^^^
AttributeError: 'WindowsPath' object has no attribute 'load_extension'```
Why are you doing p.load_extension
Put the arg into self.load_extension
ModuleNotFoundError: No module named 'modules.goods'; 'modules' is not a package```
how do I send a message in a specific channel in a specific server?
how do i check if a member have a certain guild permission, in my case admin perm?
like, this command only returns the guild permissions, but i have no idea how to check a certain permission
member.guild_permission()
len(client.commands) how do i do this but with tree commands?
Just send the message to the channel ID that you want the message to be sent
Does it still work if the bot is in multiple servers?
yeah, chanel ID is unique
If you want to check for the specific "Admin" role you could use the has_role method or just use the memeber.guild_permission.administrator to check if the user has admin permissions
this this the correct way to do it?
await client.get_channel(channel_id).send(message)
I would recommend storing the channel ID in a different variable and then call that variable with the .send(message)
But yes, it's correct :D
alright
I linked CommandTree.get_commands not CommandTree.commands π€¨
And for the command count of both prefix and app comands, you can just add them together
what type of command is used for feedback?
(like the popup type, where you can enter information in a text box)
i think ive seen it somewhere, but i dont quite remember where.
You're probably talking about discord.ui.Modal
!d discord.ui.Modal
class discord.ui.Modal(*, title=..., timeout=None, custom_id=...)```
Represents a UI modal.
This object must be inherited to create a modal popup window within discord.
New in version 2.0.
Examples...
and...
to send any of the information to an entry?
where would any of this data go if someone were to add an entry?
i was looking at the example on the Github, and i see all it does is pop up, but any of the data just, goes nowhere...
i would assume that i would need to throw the response to a file, or some sort of DM at that point...
the example is like a suggestion box, but the suggestions just go to a paper shredder.
They goes into the .values attribute of the modal in the on_submit method

its jus textinput.value
That's weird π«€
na its more ergonomic tbh
class MyModal(ui.Modal):
bob = ui.TextInput(label="bob")
async def on_submit(self, interaction):
await interaction.response.send_message(f'u set bob as "{self.bob=}"')
so, but thats just.
oh....
flowery
so, essentually i need to make it so {self.bob=} is on another await, where i can have the bot ether write to a file, or dm me?
id rather it dm me, or message in a specific channel since the bot is on only one server, and wont be used for anything else
So, i took this from the Github... what im after, is taking essentially the response from the feedback portion of the code, right?
class Feedback(discord.ui.Modal, title='Feedback'):
# Our modal classes MUST subclass `discord.ui.Modal`,
# but the title can be whatever you want.
# This is a longer, paragraph style input, where user can submit feedback
# Unlike the name, it is not required. If filled out, however, it will
# only accept a maximum of 300 characters, as denoted by the
# `max_length=300` kwarg.
feedback = discord.ui.TextInput(
label='What do you think of our Slash Commands?',
style=discord.TextStyle.long,
placeholder='Type your let us know here...',
required=False,
max_length=400,
)
async def on_submit(self, interaction: discord.Interaction):
await interaction.response.send_message(f'Thanks for your feedback, {self.name.value}! I have let `nalathethird`, my creator, know what you think of me!', ephemeral=True)
async def on_error(self, interaction: discord.Interaction, error: Exception) -> None:
await interaction.response.send_message('Oops! Something went wrong.', ephemeral=True)
# Make sure we know what the error actually is
traceback.print_exception(type(error), error, error.__traceback__)
so, i would do something along the lines of,
await interaction.response.send_message(self.feedback.value)
to uhhh... a guild channel?
Fetch a channel and send a message to it? 
essentially, yea...
maybe in embed format?
id rather it come directly to me, as im the only one coding it, but i could throw it into our genchat for admins only.
guess i could also make it almost a way for members to report a user as well if they are breaking rules, TOS, or anything like that
idk how to do it like what do i actually put
Hi guys, made a bot for discord and when I give the command my bot doesn't send any messages in the chat. I programmed it so that when I tag him in chat he sends a message and he sends that message, but when I give a command the bot doesn't show any signs of life.
Any message or error in the terminal?
no
Send the codebase & any additional errors if there
py-cord unxpected keyword url
Can I send it right here?
the code is too big
send the command then
is that the full codebase?
yeah
token and prefix are in config.json
First I did it the way you said and it didn't solve my problem either.
Because you have no token in the script?
The script needs to load the token or else it won't work
but the script had a token, the bot still didn't send a message in the same way
You don't even have import json in the script so how are you loading the token
Oh my god, I sent the wrong code, I'm sorry
You're never starting the bot there
send the correct one then xd
Do what?
like what do i actually put for it to say the amount
Someone help
canβt help without knowing what the problem is
first thing, discord.ui.Button, the b has o be capitalized im pretty sure
Question, can custom emojis be used in slash command descriptions?
No
can anyone tell what is error here? Keyerror? How should I resolve it?
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
doubt resloved
#1207959062940221472
Can anyone help?
what your bot doing?
features
working
Not an option, only local host
Or trial periods on amazon aws, ms azure, digital ocean
okay
Auto-roles system
I mean, if you have an old working device (mobile phone will work). You can use that to host your bot
how to host on mobile phone?
π
Get an app that lets you run Python π
Or you just pay 5$ month and get a proper vps
5 dollar is a fortune
It's going to be one less pizza for you
I'm broke to afford that too
Can even sell that phone ππ
Then hosting a bot is not your problem
yeah
With a group like this, is it possible to have a sub-group in a group so the command could be something like stats user info
import discord
from discord.ext import commands
import datetime
class Stats(commands.Cog):
def __init__(self, bot):
self.bot = bot
stats = discord.app_commands.Group(name='stats', description='All commands related to statistics.')
@stats.command(name = 'member-count', description = 'Gives the amount of members in the server')
async def member_count(self, interaction: discord.Interaction):
await interaction.response.send_message(f"Server Member Count: {interaction.guild.member_count}")
@stats.command(name = 'user-info', description = 'Gets information about a certain user.')
async def user_info(self, interaction: discord.Interaction, member: discord.Member = None):
member = member or interaction.guild.get_member(interaction.user.id)
embed = discord.Embed(title = "User Info").set_author(name = member.name, icon_url = member.avatar.url if member.avatar is not None else "")
embed.add_field(name = "Created At", value = f"<t:{int(member.created_at.replace(tzinfo=datetime.timezone.utc).timestamp())}:F>", inline = False)
embed.add_field(name = "Joined At", value = f"<t:{int(member.joined_at.replace(tzinfo=datetime.timezone.utc).timestamp())}:F>", inline = False)
await interaction.response.send_message(embed = embed)
async def setup(bot):
await bot.add_cog(Stats(bot))
Iirc it is but what's the point
lirc?
Google?
i couldnt find it
oh
is there an event for when a button is pressed?
disnake.on_button_click(interaction)```
Called when a button is clicked.
New in version 2.0.
!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.
oh thanks
okay so, do Message discord object have guilds?
i need to gather guild id from discord.Message
!d discord.Message.guild
The guild that the message belongs to, if applicable.
how do i send discord message from my bot using discord.Message?
cus i'm using listener
He guys, I encounter an issue with discord bot created with python. I try to make a form application with the discord.ui module.
I pop ups nicely but clicking on the button to submit nothing in the error logs console. just on discord message something happends try again later.
class ApplicationModal(Modal):
def __init__(self):
super().__init__(title="Guild Application")
self.add_item(TextInput(label="What is your ingame name?", custom_id="ingame_name"))
self.add_item(TextInput(label="What is your motivation to join us?", custom_id="motivation", style=discord.TextStyle.long))
self.add_item(TextInput(label="What legacy level are you?", custom_id="legacy_level"))
self.add_item(TextInput(label="What is your gameplay time a week?", custom_id="playtime"))
self.add_item(TextInput(label="What gameplay do you like the most to play?", custom_id="favorite_gameplay", style=discord.TextStyle.long))
async def callback(self, interaction: discord.Interaction):
try:
# Create an embed with the user's responses
embed = discord.Embed(title="New Application", color=discord.Color.blue())
for item in self.children:
embed.add_field(name=item.label, value=item.value, inline=False)
# Fetch the channel where the results should be sent
results_channel = await bot.fetch_channel(results_channel_id)
# Send the embed with the application results to the channel
await results_channel.send(embed=embed)
# Respond to the user's interaction confirming the application was received
await interaction.response.send_message("Thank you for your application!", ephemeral=True)
except Exception as e:
# If anything goes wrong, log the error
print("Failed to send application result: {}".format(str(e)))
# Send a follow-up message to the user if the initial response has already been sent
await interaction.followup.send("There was an issue with your application. Please contact the server admin.", ephemeral=True)
class ApplicationButtonView(View):
@discord.ui.button(label="Start Application", style=discord.ButtonStyle.green, custom_id="start_application")
async def button_callback(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_modal(ApplicationModal())
modal's callback is on_submit, not callback
!d discord.ui.Modal.on_submit
await on_submit(interaction, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Called when the modal is submitted.
Thanks I'll have a look!
Works like a champ thanks !
oki
anyone have a ticket bot code
.
You mean to the channel that message was sent? you can use message.channel.send
ty
it doesnt work btw
You need to fix the db
nah like when i do the t!ticketsetup it says u didnt respind
I have a question, I have made logs inside of my bot, but im trying to make it use webhooks, I got that part down.. but for each event would I actually have to make a webhook for each event..? Or how can I make it like check for multiple webhooks or something.. im just confused on how I could do this..
Because each event can have their own channel... is what im saying, which there are 19 events
Can you group some of the events together in categories?
I technically could
you should do that. if that's not possible it's fine to send all logs to one channel
Its like this, but then you click on message events, and it will have multiple options
but really you should be using log aggregation software (which discord is not)
ah these aren't logs related to your bot
no no
i mean, you still could use log aggregation software
it would give better statistics
but most bots just send these in webhooks
yes
but, im wondering how to store all 19 webhooks or something?
because you would have to store the webhook if im not wrong?
19 webhooks? why not just one?
you should make 4 channels for these, 4 webhooks instead
19 channels does not seem ideal
but if you wanted to do that yes you would have to store them. put them in a database for instance
hm
would each webhook have their own name and stuff?
Nah ^
Im just trying to think, cuz some idiots like to have there stuff seperated in like multiple things... but personally I just have 1 channel for all logs.. so this issue wouldn't be for me, but some people are weird, so im just trying to think the best way to do tho..
Wait, i could add a button where it will say, Message Events Channel, then all 4 will go there, you enable or disabled it using yes or no maybe. Then I could just use 4 webhooks like Robin said
allow customization. i think the default option of 4 channels for what you've sent in that screenshot is good, but also add an option for people to set custom channels on an event by event basis
Im thinking of just having a button for the channel, but the button for now will just toggle on or off maybe? Then it will ask what channel when you click the channel button, or something, then those events will use that webhook
meaning max 4 webhooks
Like changing these buttons to Disabled or Enabled, then have a button named {eventname} Log Channel, they click it, then they just send what channel, when you enter that channel, it will create the webhook then. Then it will store that webhook, using max 4 webhooks like robin mentioned..
which will require a whole rework on my logs lol
what I would do is have 4 categories like u do, and then 4 webhooks (4 channels) and all the events inside each category will be enabled by default but users can disable/re-enable specific events or even the whole category.
len(client.commands) how do i do this but with tree commands?
here Ill show you what I did
this isnt done, but an example of what I have done so far.
@quick gust(sorry for ping)
Basically this is my idea so far, which is kinda working really well some how. But if a webhook is deleted, it will make a new one.
Video:
There's no such thing as a tree.commands (discord.app_commands.CommandTree.commands)
seems to be working well, what's the issue?
No issue right now, this is just me updating it to use webhooks
Which I think is going pretty well so far now.
right right
That's inside of a Cog, no?
Sorry, my bad
len(client.commands) how do i do this but with tree commands?
How'd I use an art asset for a rich presence game activity?
I tried
act = disnake.Activity(
name=";help",
state="x",
details="x",
assets= {
"large_image":"key1",
"large_text":"text1",
"small_image":"key1",
"small_text":"text2"
},
type=disnake.ActivityType.playing,
)
but it doesnt show the assets or the details
(Using disnake, following this page: https://docs.disnake.dev/en/stable/api/activities.html#activity)
For disnake you should go to the actual support server for it, unless someone here can help, but you are better off in the legit help server than here.
Oh, I didn't realize there was an official -- many thanks
Np
Hello, I am needing assistance in this bot, the language is in python and it is called a verification bot
someone has paid me $5 to make this bot work and give it to them and i am somewhat new to coding
what this bot does apparently is when you verify with it through a qr code, it will send a custom message everywhere possible,
I have got it running before but was stuck on the qr code part, if someone can help me please do so
He @golden portal maybe you know this? It works fine for 10 min then it says something wrong. When i fully restart the bot it works again for few minutes only. Its hosted on GCP but local same issue. There is no error in the logs only inside discord the message interaction failed.
- bot is online, other functions work
without code i can only assume
what does "doesnt work" mean
I need a ticket bot, anyone have one?
Real
What type
I got ones tailored towards the game rust if u want
it's here somewhere.
Nth much, just have 3 buttons. General Support, Civilian Report & Stafff report
Aight
no such file or directory
the file on the desktop
just use the change dir command which is cd
I am not sure where is the desktop in macos
but it could be called desktop
use cd desktop
man im so lost
i just want to use a bot that makes videos for me
could you be so kind as to type out the commmand to run the file if its on my desktop
wait it says permission denied now lol
Hello, I am needing assistance in this bot, the language is in python and it is called a verification bot
someone has paid me $5 to make this bot work and give it to them and i am somewhat new to coding
what this bot does apparently is when you verify with it through a qr code, it will send a custom message everywhere possible,
I have got it running before but was stuck on the qr code part, if someone can help me please do so
IF THIS BOT IS MALICIOUS PLEASE TELL ME
chmod 777 *
it's most likely malicious lol stay away from it
run this command in terminal
thank you
did that fix it
so chmod 777* then ./main.py
@drifting arrow u got one?
first command: chmod 777 *
second command: python main.py
lmk if that doesn't work
oh, ok
i just wanted to get it working because i was paid, and the guy said he would pay me more if i could help him get other bots working
I have one
https://github.com/RejectModderss/TicketSystem
Just make sure to change everything in it to work for your server :)
Discord Ticket System made in Discord.py. Contribute to RejectModderss/TicketSystem development by creating an account on GitHub.
omg tyyy
np lmao
every single one i have seen is .js, and i dont know js so even when they tell me wht to edit i fail
Thats fair, I made this ticket system public for others cuz most are in JS.
I did get it from another person, but I made it like 10x better because they person who gave it to me, he made it for 1 ticket only, i made my have unlimited amount of tickets, you just gotta know what you are doing I guess lol
ohh
Theirs was lowkey ass, so I made theirs better, but its not the best ticket system, but it works lmao
:)
Does buttons n everything, on startup it loads the old buttons so you don't have to re run the ticket command to get the embed up
/nix/store/xf54733x4chbawkh1qvy9i1i4mlscy1c-python3-3.10.11/bin/python3: can't open file '/home/runner/ticccc/main.py': [Errno 2] No such file or directory
did you get everything off the repo?
mhm
wait lemme get vs code rq
I use pycharm, but vs code will work too
whts py charm lol
discord.errors.LoginFailure: Improper token has been passed.
it shows the errror...
oh lol
im getting "NameError: name 'roleid' is not defined"
then define it?
yk where it is
.......
Bro, replace roleid with the fucking role id
Like what? π
if you read what the important notes say, you would know this...
Where has it been used π
bro does not know python 
uhhh
it still dont work π’
@vapid parcel i have failed
I can tell
but I have no time to help you. I have to update other things on my end, if you can read basic instructions then you will know how to make it work.
I currently have that exact source running on my server. and multiple other servers. So its not the source, its just you man.
ik its me
im dumb dw
PS C:\Users\mr_fa\Downloads\TicketSystem-main> & C:/Users/mr_fa/AppData/Local/Programs/Python/Python311/python.exe c:/Users/mr_fa/Downloads/TicketSystem-main/TicketSystem-main/main.py
2024-02-17 22:33:52 INFO discord.client logging in using static token
SFRU Tickets Bot has logged in successfully.
Everything has been loaded.
Bot_Admin has been loaded.
Error_Handling has been loaded.
Ticket Buttons added!
2024-02-17 22:33:54 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: 5b53b6bb5305fbbf0cf2d826f84cca1c).
SFRU Tickets Bot is ready to recieve commands.
fixd
kk
does it use / cmds or prefix
ok ima go test it
Why only have slash commands? Why only have prefix? Have both, HYBRID!!
lmao fr
.
whts the prefix
!
uhh the buttons dont work
?
they do nth
Bro, just simply read what I have said on the repo
im not gonna help you with something really simple...
ok
update: i have failed
len(client.commands) how do i do this but with tree commands?
Bro has asked this before 
and i didnt get an answer
hello
I was trying to fix a problem in nextcord. trying to create a kick command
@commands.has_permissions(kick_members=True)
@client.slash_command(description="Kick a member", guild_ids=[TESTING_GUILD_ID])
async def kick(interaction: Interaction, member: nextcord.Member, reason: str = "No reason provided"):
await member.kick(reason=reason)
await interaction.send(f"{member.display_name} has been kicked.")
but seems like its not working, anyone with or not with the kick permission can kick
I saw this Note that this check operates on the current channel permissions, not the guild wide permissions. in the docs
could be the reason?
there's no need to be so aggressive to people. If you can help, then help. If you can't, then just don't say anything
I understand your frustration but you don't have to take it out on them
if its a slash command it should be await interaction.response.send_message(f"{member.display_name} has been kicked.")
if it was a regular prefix command then it would be interaction.send
thanks for the feedback, but what about my permission problem?
its supposed to be after the command
@client.slash_command(description="Kick a member", guild_ids=[TESTING_GUILD_ID])
@commands.has_permissions(kick_members=True)```
even after doing that, it didn't work
you cant make permissions before the command is made
probably @commands.checks.has_permissions(kick_members=True)
wait
i sent the same thing oops lol
i just realized you are using nextcord
idk how to use nextcord at all
i needed to manually check if he has
if interaction.user.guild_permissions.kick_members:
that how I fixed my problem
alr mb, it was just annoying cuz I was focused on something and he kept pinging.
How many requests can webhooks have per second?
Bots get 50 per second, im guessing 50 per second for webhooks too?
not sure exactly how much but webhooks have a much larger rate limit
Its seems false because everyone is having an issue with it..
https://discord.com/channels/336642139381301249/1208540459903746078
This is where I am asking currently, but some are having the same issue, so maybe its a discord thing right now..?
Issue fixed, I wasn't checking for old webhooks I guess, it would make a new one each time. Issue finally fixed cuz im a lil slow 
anyone know this this isnt hiding it like it's supposed to
like ||GatosT001||
Is it in a field's name? If yes, markdowns are not supported there
What if someone get to know about my discord bot's token? It will steal my data? Is it harmful to me?
They just get to run the bot and do pretty much everything you can do with it (except for the app settings)
Anyone knows the value of
discord.Intents.all(), as in integer
!d discord.Intents.value 
The raw value. You should query flags via the properties rather than using this raw value.
Ikr i just didnt want to install dpy or any other wrapper right then
You can look at the Discord docs, they have a section explaining on how to calculate it
tbh it's just a bunch of bitwise operation, like (1 << 15) is MESSAGE_CONTENT, (1 << 14) is DIRECT_MESSAGE_TYPING so just combine them to get the intents value
https://discord.com/developers/docs/topics/gateway#list-of-intents
!e ```py
print(bin(1 << 15 | 1 << 14))
print(1 << 15 | 1 << 14)
@golden portal :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 0b1100000000000000
002 | 49152
Oh lol, gotta look at docs thankie
Does anyone know how I can have to fields in each row?
embed.add_field(name="Level", value=profile['level'], inline=True)
embed.add_field(name="XP", value=profile['xp'])
embed.add_field(name="Wallet", value=profile['wallet'], inline=False)
embed.add_field(name="Bank", value=profile['bank'], inline=True)```
I want it Level XP Wallet Bank
try removing inline=True from Bank
Looks exactly the same
The inline=Falsein Wallet causes anything after to go to the next one. But if I do inline=False in XP then it'll cause XP to not be in the same line as Level
you (technically) cannot have 2 columns
but (practically) you can create an empty field with invisible characters
https://stackoverflow.com/questions/66485287/how-to-make-a-discord-embed-with-only-2-columns
its in discord.js but im sure you will get the point
guys i have a question im tryin to make a ban command on my discord bot but it isnt workin
@bot.command()
@commands.has_role("Owner/Mod") # Import has_role
async def ban(ctx, member: discord.Member, *, reason):
if reason is None:
reason = f"This user was banned by {ctx.message.author.name}"
await member.ban(reason=reason)
did i do something wrong?
cuz it isnt workin when i try the command
Intents enabled? Do you have the role?
Which ones
The @bot.command() decorator goes below the role check btw
... for real?
I just said it goes before.. switching two lines shouldn't be that complicated..
bro i js started coding
i learned the bascics of python
but im still new to coding in general
oh
I said. Switching. Two lines...
how do you host these discord bots?
VPS, paid
Iβve been running it on my laptop 24/7 but looking in to ways to use a vps to host it
Unsure of how though
it worked thanks
Heya, Would the .has_role() work with say 2 roles?
!d discord.ext.commands.has_role
@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check) that is added that checks if the member invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
If the message is invoked in a private message context then the check will return `False`.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole) if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage) if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure).
Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole) or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage) instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure)...
if you want the user to have both roles then you have to put the decorator twice, if you want the user to have at least one of them then you can use .has_any_role() check
Checking this one.
https://fallendeity.github.io/discord.py-masterclass/checks/#has_role
https://fallendeity.github.io/discord.py-masterclass/checks/#has_any_role
A hands-on guide to Discord.py
There it is!
I was looking for this guide for so long. β€οΈ

While you're here.
Can I intercept this MissingRole error and do something else instead?
you mean you want to raise your own error?
Not even to be honest.
More like:
@commands.has_any_role()
if not: do something else
you can, but not with the decorator
Also, im confused now.
@bot.command() @commands.has_role("x")
<- as per your guide.
#discord-bots message But this has it the other way around?
you would have to check if user has roles inside the command and then you get to use if statements
Okay, not the end of the world π
Im still exploring what's possible and what's not
well im still confused how the order of decorators changed something here
Im thinking of a thing that will auto press a button and flush the toilet. can anyone help me?
a discord bot
it will be
first I was thinking to be with a command /flushtoilet but no
a camera should be attached
yeah i get it, reading the guide i sent will most likely reveal most of secrets discord.py holds
and it will somehow determine if it needs to press the button now
When I'm done
like that google ai
u watched it ?
Yeah, It's really good, not sure if you wrote it but thanks in any case β€οΈ
well its written by few others but yeah i have my contribution in this project too
Now, last thing.
I'm passing in a set to the has any roles. should I make it a tuple instead?
cz as of now it's not working π But maybe I must do the snowflake thing? (still need to learn about that)
it doesnt take set nor tuple
it takes x amount of arguments
.has_any_roles(123, 456, 789)
so you can do py roles = {1, 2, 3} @has_any_roles(*roles)
Ah. *
!e py print(*{1, 2, 3})
@slate swan :white_check_mark: Your 3.12 eval job has completed with return code 0.
1 2 3
yup you can do that
does the @commands.has_any_role() still work above that?
If I have a
@commands.has_any_role()
@app_commands()
does anybody know how to get the last message that a user sent in the current channel?
about discord bots
Get the channel object and loop through the message history, and check the user IDs
bruh im never asking gemini to generate code again
everything is giving errors ill just do it myself
thankss
i get it like "channel = message.channel.id" right?
i started coding discord bots yesterday so i dont know much
!d discord.TextChannel.history
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator) that enables receiving the destinationβs message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history) to do this.
Examples
Usage...
!d discord.ext.commands.Context.channel
Returns the channel associated with this contextβs command. Shorthand for Message.channel.
hmm
also where can i find a list of commands/functions or stuff like "message.content"/"message.send"
class discord.Message```
Represents a message from Discord.
x == y Checks if two messages are equal.
x != y Checks if two messages are not equal.
hash(x) Returns the messageβs hash.
No such thing as message.send btw
oh i meant message.channel.send
okay thank you
yeah just check the docs for that, its all documented
Hey,
Im looking to send a message to a specific channel when bot is online. (Same as lancebot has to dev-log for instance.)
However I'm struggling to see where to put this message or how to implement this.
I tried at the end of setup_hook but get_guild() returns None and therefor get channels returns None. Any suggestions?
get_guild just gets it if it exists in cache ideally u would want use fetch
!d discord.ext.commands.Bot.fetch_guild
await fetch_guild(guild_id, /, *, with_counts=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild) from an ID.
Note
Using this, you will **not** receive [`Guild.channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.channels), [`Guild.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.members), [`Member.activity`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.activity) and [`Member.voice`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.voice) per [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member).
Note
This method is an API call. For general usage, consider [`get_guild()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.get_guild) instead...
server = bot.get_guild(id) or await bot.fetch_guild(id)
also bot also has a get_channel and fetch_channel methods so if u have the channel id ur good to go
yo asher
hello π
I have a command that has a pretty long cooldown (10 hours) after its invoked once. but it also has the possibility to error (if the user isnt registered to the bot).
i was thinking of using before_invoke to see if they are registered or not, but im not entirely sure how to use it. you got an example?
(im using disnake)
!d discord.ext.commands.Context.reset_cooldown
No documentation found for the requested symbol.
What?
brother im using slash commands
why not reset the cooldown of the command if say the command was invoked but an error other than cooldownerror occurred u can check in the error handler for a specific error using isinstance and if in this case say its not registered exception then reset the cooldown
Oh π
how would I reset the cooldown?
But for app commands it should be the same, cause app commands cool downs are managed by libs too
async def on_slash_command_error(
self, inter: disnake.ApplicationCommandInteraction, error: commands.CommandError
) -> None:
if not isinstance(error, commands.CommandOnCooldown):
inter.application_command.reset_cooldown(inter)
here is an example
I do have that, but I think it's where I run it or how I run it that it doesnt exist yet.
run it in on_ready with a flag variable of some sorts or u can have it as a one time task using tasks.loop and bot.wait_until_ready()
bot needs to start before actually being able to send a message
count seems appropriate for this
thank u
π
onready works a charm, thanks!
aight cool make sure to have a boolean along with a if guarding it btw on ready can fire multiple times over a bots lifetimes (everytime the gateway reconnection occurs)
like this?
self.onready_ran = False
if not self.onready_ran:
# send embed
self.onready_ran = not self.onready_ran
yeah u would set the guard in the bot constructor
the initial value
yeah. Got it underneath self.synced in the init
yeah
anyone know how to fix this
2024-02-18 21:43:51 ERROR discord.ui.view Ignoring exception in view <ticket_launcher timeout=None children=3> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label='β’ Support' emoji=<PartialEmoji animated=False name='π·' id=None> row=None>
Traceback (most recent call last):
File "C:\Users\mr_fa\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\view.py", line 427, in _scheduled_task
await item.callback(interaction)
File "c:\Users\mr_fa\Downloads\TicketSystem-main\TicketSystem-main\views\buttons.py", line 25, in ticket
return await interaction.response.send_message(f"Ticket category '{ticket_category_name}' not found!",
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\mr_fa\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\interactions.py", line 774, in send_message
raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before
Don't respond to an interaction twice with interaction.response
ey this is how i did mine
also what are you making your bot do
im lost on ideas
on_ready can be called multiple
times, also not sure but get_channel
might return None when it's not
cached so eventually you could fetch
the channel I guess 
Hi
bot%2Fexts%2Futilities%2Flogging.py lines 19 to 21
await self.bot.log_to_dev_log(
title=self.bot.name,
details="Connected!",```
`bot%2Fbot.py` line 41
```py
async def log_to_dev_log(self, title: str, details: str | None = None, *, icon: str | None = None) -> None:```
%2F
If anyone has an idea about this https://discord.com/channels/267624335836053506/1208879184324075651
His code can be found here https://paste.pythondiscord.com/5WAA
I don't know much about discord bots and threading.
anyone have a twitch n youtube notification working in dpy?
or how to set one up maybe?
I have a really scuffed twitch one
uses dpy?
yeah if it works, then ill take it lol
i can fix it up dw π. I just can't find a WORKING one... and I kinda just don't wanna go through the pain of having to actually get one working...
Ok just letting u know I made it 2 years ago before I learned how to use databases so it stores all the stuff in a json file
Thereβs a twitch cog in there
Good luck
yes if its not the real thing.
Ok
which it clearly isnt π
Oke
Hi
Hello
What are you capable of doing
Wdym
What the
for number in range(1, 9999999999999999999999999999999):```
Beceause if I use a while thΓ© f8 buttons does not work
If you have an alternative
Sorry, but code looks very poorly structured, and even more poorly written. Threading and using asyncio at the same time is not a very good idea. I advise modulated project structure, where your API runs as separate service from bot
And I highly suspect that "autofarmer" is something that violates ToS thereby you can't expect help on it
Okay
why wont my slash command show up even though command tree is synced π
Sometimes you just gotta restart discord
See above.
And it takes some time for discord to push it through.
So give it at tops an hour.
yeah had to restart discord
Perfect:)
Also, pro tip, (learn from my mistakes lol)
If you spam sync to get it to show up youβll get rate limited ππ»
@commands.is_owner()
@cog_ext.cog_slash(name="admin", description="Admin Commands")
async def admin_group(self, ctx: SlashContext):
await ctx.send_help(ctx.command)
#subcommands
@admin_group.sub_command(name="load", description="Load a Cog")
async def load_cog(self, ctx: SlashContext, extension: str):
await self.bot.load_extension(f"cogs.{extension}")
await ctx.send(f"Loaded {extension} Cog")
now what is the problem in this code
AttributeError: 'CogCommandObject' object has no attribute 'sub_command'
What library is this
I think these should be listed in message.attachments as well, check it
solve mine pls
oh alr
You never answered my question
I answered it is discord.py
Sry I am not different accounts on windows and phone
Okay
What is cog_ext then
There's no thing as SlashContext either
That is not discord.py but a very outdated library
Discord.py now supports all functionality
Oh
So get rid of that
What to do now?
Bro my bot in dpy only
I am rewriting all commands to slash command
To i thought to discord_slash
It's in discord_slash technically
If you have it imported it's that
Yea I just imported it
That library does not work
So what should I do
Yes
How to do what to install?
A hands-on guide to Discord.py
is there an event for message publishes? if so what is it
there is not
but then how does some bots send log msgs for that
maybe i missunderstood what you mean message publish
do you mean when you click publish message on announcements channel?
yes
well its not an event
class Administration(commands.Cog):
"""This Cog is for the Administration of the Bot"""
admin = app_commands.Group(name="admin", description="Admin commands")
def __init__(self, bot: commands.Bot):
self.bot = bot
@commands.is_owner()
@admin.command(name="load", description="Load a cog")
async def _load_cog(self, interaction: discord.Interaction, extension: str):
await self.bot.load_extension(f"cogs.{extension}")
await interaction.response.send_message(content=f"Loaded {extension} cog successfully.", ephemeral=True)
my command is not showing

!d discord.Message.publish there is method to publish a message but i dont see how to receive an event when it does that
await publish()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Publishes this message to the channelβs followers.
The message must have been sent in a news channel. You must have [`send_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.send_messages) to do this.
If the message is not your own then [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages) is also needed.
hm, ig btw i also have 1 more question
then ask it
if i have on_message_delete, that only detects a single deleted msg right.does it detect bulk msg deletes or should i use on_bulk_message_delete
or on_raw_bulk_message_delete
?
put the admin var under def __init__
Did you add the cog to the bot?
Also check that you're syncing the commands
How do you have spaces in slash command
isn't there a flag?
iirc yes, lemme check
!d discord.Message.flags
Extra features of the message.
New in version 1.3.
!d discord.MessageFlags.is_crossposted
Returns True if the message was crossposted from another channel.
@dense swallow
are you supposed to look for message edit and check if it has that flag?
no you can listen to the on message event and check if it has that flag
then how does that make you get when it was published
mh I'm unsure, i should test some things to tell
the Bot says message created though
which is different than when it was published
Use discord.Attachment as the annotation for a parameter in your command
class Confirmer(View):
def __init__(self, ctx, timeout):
self.ctx = ctx
self.button = Confirm_Button(id)
self.callback = self.button.callback
super().__init__(timeout=timeout)
self.add_item(self.button)
self.add_item(Cancel_Button(id))
i am not sure if above code is right or not, but i am trying to do is fit the code below into the view class.
I'm unable to do callback in code provided above.
view = ConfirmView(ctx=ctx, timeout=15)
cancel = Cancel(id=f"{id}")
confirm = Button(label="Confirm", emoji=tick, style=discord.ButtonStyle.green, custom_id=f"{id}d")
view.add_item(confirm)
view.add_item(cancel)
confirm.callback = callback
Is there a way to set a disabled state for ui.Button?
Set it's disabled attribute to true, or in decorator
i personally use "Luckiest Guy" but for the style your going for, I wouldn't use it in this case.
if you look up google fonts, adobe fonts, or like dafont.com, you can find some unique ones there and use them
would they support special characters tho?
i think so
You can use falloff font
Fancy fonts typically don't support everything and are just for latin, digits and basic symbols, sometimes cyrillic
With falloff font normal symbols will be rendered as expected, the "weird" ones will get rendered as falloff. Might look ugly but it's users fault for including those goofy ahh αͺ βΈ» ( Ν‘Β° ΝΚ Ν‘Β°) or whatever
Oh so it will work if using falloff?
What font does discord use?
I think they have their own font
imma just
do username instead of display names.
display names is just causing to many issues atp 
Depends on what you mean by "special character"
the Noto family of fonts intends to support most of the unicode
view.add_item(DownloadButton(label=f"Download media", url=url, style=discord.ButtonStyle.blurple, row=0, emoji="β¬οΈ"))
doesn't seem to apply the color, any idea why?
hi, i have a discord bot running on aws. it was able to handle 700-800 people easily. but now i want it to handle 10k+ people smoothly. i have never used aws paid tiers before. can someone guide me?
url button types cannot have a color
I see
about setting up a paid instance or bot design?
how do u get message from a channel? is there just one method, the channel.get_partial_message ?
theres also fetch_message, but i need to get the reactions from the msg, but get_partial_message.reactions doesnt exists
A partial message doesn't have the information of the message its ID is pointing to
It's for you to work with messages when you have their ID but don't want to fetch them
any methods that have any info?
Fetch the message
ok but it said it didnt have .reactions
What said that?
So im working on a command to print the names of the members having a certain role in the server and when I make my bot iterate through the contents of ctx.guild.members, the only member it can find is the bot itself even when there are other people in the server
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.
no, ill go and check it
ive enabled it but the output is still the same
async def members(self, ctx, *, role1: discord.Role):
role = discord.utils.get(ctx.guild.roles, name=f"{role1.name}")
l = []
if role is None:
await ctx.send(f'There is no "{role1}" role on this server!')
return
for member in ctx.guild.members:
if role1 in member.roles:
l.append(f"{member.mention}({member})")
print(member)
await ctx.send(f"{member.mention}({member})")
if len(l) == 0:
await ctx.send(f"Nobody has the role {role1}")
else:
res2 = "\n".join(l)
print(res2)
embed = discord.Embed(title=f"Members in {role1.name}", description=f"{res2}", colour=discord.Colour.blue())
embed.set_footer(text=f"Requested by {ctx.author.name}", icon_url=ctx.author.avatar.url)
await ctx.send(embed=embed)```
this is the command
can you put print(ctx.bot.intents.value) in the members' command?
see what it prints
3276541
you didnt turn on members intents in code
i have this in my code
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="g!", intents=intents)
oh ye so a separate 1 for members too?
thanks
its working perfectly fine now, tysm
welcome
I hosted my discord bot on EC2 instance. My bot going offline again and again. Like 5-6 times in a day. I don't know what to do. I just running the script again to make it online. But it's too tedious. What should I do?
Is there anyone who would like to build a discord bot with me?
yeah, I am interested
Can I dm you then?
sure
async def on_message(self, message):
banned_words = ["shit"]
print(message.content)
for word in banned_words:
if word in message.content.lower():
await message.delete()
await message.channel.send("That is a banned word!")
await self.bot.process_commands()```
I created this event to delete banned words but it seems like the bot cant see any messages. I have also enabled all intents via
intents = discord.Intents.all()
make a script that runs your bot and auto restarts if it crashes :P
in all seriousness though you should check the logs to fix the error instead of relying on these workarounds
can someone tell me what the issue could be?
guys
i forgot how to show picture using embed
what is the property of discord.Embed that allows me to show picture?
how do i make colorless embed
i tried doing the usual method and using the color that the background is but the little line still shows but when on other bots it doesnt
okay guys what is the difference between thumbnail and image from discord.Embed ?
Can you show us an image?
fixed
Thumbnail is small and at the right. Image is big and at the bottom
i see
hello all, can someone help me? i made a script so that when people write the words "classe, !, salon" it deletes the message for them and the bot responds for 5 minutes before deleting the message but it doesn't work... and i don't have any errors if possible please help me. thank you very much.https://pastebin.com/qtg9sHgB
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
can anyone send some repos link of cool discord bots? (related to coding is good)
other is also fine
!src
Is it unable to read messages for you as well?
Anyone knows how to in discord.py disable select menus?
I put print messages to see where the error comes from but in fact I have the impression that it doesn't detect the messages to be deleted...
I made a similar event and it seems like the bot is unable to detect the messages at all.
Why? I'd managed to do it on another code but this is impossible...
Idk why either, im having the same issue.
hey gys
guys
can somebody help me i want to make a discord server small discord server
are u sure u have enabled the message content intent in the developer portal aswell?
Yes
100% sure, checked the toggle and discord.Intents.all() in my code
Is there a way to make a /say command and /edit command where the bot sends a message and if you use /edit (message ID) it will give you the existing message in your message bar and let you edit it
all i need now is help on polishing my code:
https://github.com/HirukaRogue/RP-Utilities
like, to improve performance
i'm planning to make a releasing patch
i also need make it to make it have quality
for attract people to engage with my bot
It isn't, it's only in 1 server too
hm
I have these lines setup to check your own event rewards and event points, it works fine when you use /balance (discord tag) but for normal /balance and /rewards it gives me the same errors message
Anyone know what I need to change?
Interaction object does not have .author it has .user instead
So just change .author to .user? Sorry I'm pretty new to pythong and coding in general
!d discord.Interaction.user
The user or member that sent the interaction.
π
d.py is not consistent

then show it
Owp sorry nevermind it got fixed I think I just forgot a comma lol but I have another now
With a /buy command
I get this error
so basically you can only once do interaction.response.send_message(...) if you try to do it two or more times on the same interaction you will get this error
if you want to send another message use interaction.followup.send(...)
Alright thank you alot, but now im getting this error, do follow up messages not need a delete after command to delete them?
It only happens for follow up.send
!d discord.Webhook.send
await send(content=..., *, username=..., avatar_url=..., tts=False, ephemeral=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., view=..., thread=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message using the webhook.
The content must be a type that can convert to a string through `str(content)`.
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) object.
If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) and it must be a rich embed type. You cannot mix the `embed` parameter with the `embeds` parameter, which must be a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) objects to send.
Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) instead of `InvalidArgument`.
look like you cannot put delete_after in followup.send
you have to delete it manually
Oh wow that really sucks
Is there no other way to code this? but with delete message
!e import random def fair_coin_method(): return random.choice(['H','T']) ctr = 0 for x in range(100): curr = fair_coin_method() + fair_coin_method() if curr != 'HT': ctr+=1 print(ctr/100)
@still raft :white_check_mark: Your 3.12 eval job has completed with return code 0.
0.74
OMG
my?
@torn panther
Did you throw it for me
you could try interaction.channel.send() and then you can use delete_after
.
.
How can i ping in embed a channel?
you can but only in certain parts
How can I do this when I click a button because a Select should come up? How does that work? (in py-cord)?
df is the activity type for custom
activity=discord.Activity(name=βrewrite because yes", type=4),
nvm I got it
anyone knowss how to make ur bot run while ur pc is off
even though i'm rarely using my discord bot, every time i call it, why do i get this error? i think the rate limit reset time might be calculating incorrectly, but im not 100% sure
get a vm or a server from one of the cloud providers like digital ocean, gcp, azure etc
are u sure ur code is not making any unnecessary requests can you show code for the command or operations your trying to run
Nah rate limit is pretty correct, except it's assigned to your IP and apparently there are many people using discord API on this IP
which one do you recommend add me
Hey guys, how do you add a Cog class to a discord bot that inherits from commands.Bot? for example
class MyBotCog(commands.Cog):
def __init__(self, bot: commands.Bot):
self.bot = bot
@commands.command(name='roll')
async def roll(self, ctx: commands.Context):
print("rolling...")
random_number = str(random.randint(1, 6))
await ctx.send(random_number)
using self.add_cog in the MyBot in the __init__ method of the class containing the implementations for the botdoesn't seem to be working
no like the past message before the rate limit was sent an hour before, which should be more than long enough for a reset to occur
Are you using some hosting service
you add an
async def setup(bot):
await bot.add_cog(Cog(bot))
inside the cog and call bot.load_extension("cogs.cog") on setup_hook
actually, i solved the issue by adding await and moving it into setup_hook.
Thanks!
np
my main bot runs on docker, it has poetry so i have no issue with requirements
but i am making a secondary bot for self propose and its not letting me download a package
Is this inside docker
i just want to download disnake on it...
Global packages on linux are very messy to my experience
this is ubuntu
Virtual environments are isolated Python environments, which make it easier to keep your system clean and manage dependencies. By default, when activated, only libraries and scripts installed in the virtual environment are accessible, preventing cross-project dependency conflicts, and allowing easy isolation of requirements.
To create a new virtual environment, you can use the standard library venv module: python3 -m venv .venv (replace python3 with python or py on Windows)
Then, to activate the new virtual environment:
Windows (PowerShell): .venv\Scripts\Activate.ps1
or (Command Prompt): .venv\Scripts\activate.bat
MacOS / Linux (Bash): source .venv/bin/activate
Packages can then be installed to the virtual environment using pip, as normal.
For more information, take a read of the documentation. If you run code through your editor, check its documentation on how to make it use your virtual environment. For example, see the VSCode or PyCharm docs.
Tools such as poetry and pipenv can manage the creation of virtual environments as well as project dependencies, making packaging and installing your project easier.
Note: When using PowerShell in Windows, you may need to change the execution policy first. This is only required once per user:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
do you know how i could possibly install disnake? i would rather do that
Make a venv and install it there
what command do i use in a ubuntu vps?
nvm, got it thanks
@weak tendon
still need help
With what you need help?
You need to run the script in venv too
And your pm is probably setup incorrectly
Do not use it, there's systemctl
A learning guide for the discord.py bot framework written by members of our community.
Also there's always docker, I highly advise to use it instead
Can i manually stop select menu after interaction just like buttons?
Yes
Hey I was wondering how you can like show the discord user in an embed?
What is the command?
Thanks alot btw it fixed it and the rest I was able to figure out :D
!d discord.Embed.set_author
set_author(*, name, url=None, icon_url=None)```
Sets the author for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Can someone tell me, what should I learn before making discord bots?
what should i do to fix this?
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: JSONDecodeError: Expecting value: line 1 column 1 (char 0)
im trying to load data from a json file and as per my knowledge its a valid json.
- all the basics of python
- python OOP
- a little bit of asynchronous programming knowledge
What IS python OOP
Object Oriented Programming in Python
Ok, so can u tell examples, python hardest basics
seems like there's something wrong in the json file, pls share it if you can
!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.
{"768074971213725706": {"1": "hi"}}
this is all the data i have in my json file rn
What IS that numbers
my discord id, im trying to make a reports system
Did you edit the file and didn't save it?
No
Wait how you keep bot online then?
if i dont close the file after dumping, will it not save the data?
You need to run the bot with its token, not MongoDB token
What IS The MongoDB for?
it works for me
weird
You use json.load(file obj)
Being a database, it's used to store data
Like store bot?
https://paste.pythondiscord.com/N5KQ
this is my code as of now
with open("ok.json", "r") as f:
data = json.load(f)
do any of you know of any program which logs the command usage, active users, and a bunch of other stats? and shows it on a web server with graphs and shit? I remember seeing something like that but I can't remember the name...
which is what im using but it shows the jsondecodeerror
its weird since ive made 2 projects before using json and ive never encountered something like this
Try loading with r+
IS there in GitHub good discord bots? I noticed that I learn by reading codes, when I don't understand a Part, I Will learn what It means
I dont get the same error anymore but now im getting a key error and for some reason its creating a new entry when i try to enter data using the same key
Does it print data correctly?
yeah but i make it print before re-entering the data
You missed r+ in first one too matey
And for json.dump r+ should work too, if doesn't then try w+
dump is working fine as of now
and load as well
Can I ask y bro.? Do you know anything abt Pydroid 3 in mobile?
Fk alr np np
ig ill just remake the code, i cant find the error π
i dont think loading with r+ does that
That shouldn't even be possible, idk why it's doing that
Something wrong with the if-else statement then
That's what I thought too but the member.id is already in data
So why is it going wrong π
@shrewd fjord :white_check_mark: Your 3.12 eval job has completed with return code 0.
{'1': 3}
Wha
Well yeah it just switches to latest assigned one, not sure if same for json tho
It aint merging, its just using the 2nd latest one something like variable
a=1
a=2
>>>a
2
it is, when loading a json file python converts it to a dict
and the json file itself is not supposed to have duplicated keys
Yeah i was unsure of that
some witchcraft is going on
Idk how to use any db except mysql
!pip aiosqlite
!pip asqlite
the former is better
Both uses a db like file
(file.db, file.sqlite, file.sqlite3)
Okay
!indent
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
Thank you :D
The command works as intended but it always does that sending command for 5 seconds
And then turns into this
But it does excecute the right command but with just an extra line of that
And i dont even get an error message in the console, what am i doing wrong here?
the issue was that the key cant be an int value so it was automatically converting it to a str, thats why the if-else statement was going wrong
Thanks
Called it π
Hello there , I'm considering to get a hetzner dedicated server to host my bot. It's not a heavy bot though but I need 100% uptime. Any suggestions?
if message.channel.id == target_channel_id:
lfg = "lfg"
bot_message = await message.channel.send(lfg)
if message.id != bot_message.id:
await bot_message.delete()
print("LFG guide reposted")```
I'm trying to check if the last message was posted by the bot or not, but it wont work, can someone help?
@client.event
async def on_message(message):
if message.author.bot:
print("it\'s a bot !")
else:
print("it\'s not a bot !")```
try to use this logic
Hey,
I am looking for a solution that will allow me to send a message "notification" on discord at a given date: for example, in 3 months at a given time. How to approach this, what to use? Celery, RQ or something else?
How can I fix the pixilation around the profile picture, the circle that I am using. Is there a way to fix that? I am using pil.
Code: https://paste.pythondiscord.com/YHOQ
image:
Increase the resolution of the images π«
(don't resize them too much)
how?
@vapid parcel
Don't resize them to the point that they become pixelated π«
That pfp quality is the result I'd expect if I resize an image to 120x120px
alr, ill change it when I have the time, I couldn't really tell if it was pil or just me ig.
what would be a recommend size?
Heavy in what terms? Have you monitored memory and CPU usage
Can Someone give me BASIC discord bot 'background.
Im meaning ready-coded thing, like It has already responses.py and that stuffs.
( I only read by reading codes, so when ill have them, ill 'translate' them and understand The lines by Step by Step. )
Can send in dms, / GitHub, send link If GitHub.
(Note: skemers, I won't download pip install trash, All I can pip install IS pip install discord or It was pip install discord.py anyways, If someone can Help and give on dms.
Ik there's few on GitHub, but idk If virus, and etc.. I won't understand them
**I Will fill The
TOKEN =
or
DISCORD_TOKEN =**
120x120px
If It makes Image to size, you should use The recommend size as size + extra. ( when bigger gets smaller, quality gets little better )
Someone Help π
at that point just read up https://github.com/Rapptz/discord.py/blob/master/examples
Okay
So I download this as zip?
( My goal IS to Make own DC bot, but at first I need to learn Make commands like )
!Ban userid / @user
you dont really have to download it, each example is just 1 file, you can just read the code and try it out
each file covers a concept that the library offers
Okay..
IS this skem? It has hash to
Linus, MacOS, windiws
Like checks files?
from the looks of it, it's disnake so it's not dpy
Your link was better!π
Did you Make that
The github
er no that's the official discord.py examples
Sorry but how old are you? Your way of making sentences suggests you are either not native english speaker or a tos breaker
Yeah that's not very basic but it's a full project with a database, dependencies control tools and deployment tools
It's not heavy, in terms of both memory and cpu, just need close to 100% uptime
And don't wanna get rate limited sharing same IP with 100 others
You will not, VPS has unique IP assigned to it
And I doubt you need a dedicated server, virtual will do
Dedicated is a whole personal machine, they are typically more powerful (hence more expensive) and are meant for higher load than a basic discord bot. As long as its CPU and memory usage does not exceed limits
So vultr vps or hetzners works ig ?
There are a bunch of recommendations in #965291480992321536 pins
While VPS is a virtual machine inside another big machine. It has its own part of resources of that big machine and own IP
Oh ic, thanks
!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.
Hey guys! I'm currently facing a small issue with my bot. It claims that it can't find the categories even though the category ID is already stored in the database. Could someone please help me out? I'd really appreciate it!``` ```py
class CreateTicketSelect(discord.ui.View):
def __init__(self):
super().__init__()
@discord.ui.select(
custom_id="ticket_select",
min_values=1,
max_values=1,
placeholder="Select a category for your ticket",
options=options,
)
async def ticket_select_callback(self, select, interaction):
category_name = select.values[0]
category = discord.utils.get(interaction.guild.categories, name=category_name)
if category:
guild_id = interaction.guild.id
category_id = category.id
channel_id = None
await db.create_ticket(guild_id, category_id, channel_id)
overwrites = {
interaction.guild.default_role: discord.PermissionOverwrite(view_channel=False),
interaction.user: discord.PermissionOverwrite(view_channel=True, read_message_history=True, send_messages=True),
interaction.guild.me: discord.PermissionOverwrite(view_channel=True, read_message_history=True, send_messages=True),
}
channel = await category.create_text_channel(name=f"{interaction.user.display_name}", overwrites=overwrites, topic=interaction.user.name)
embed = discord.Embed(
title="Ticket Created",
description="Support will be with you shortly.",
color=discord.Color.green()
)
await channel.send(embed=embed, view=CloseTicket())
await interaction.response.send_message(f"I've opened a ticket for you at {channel.mention}", ephemeral=True)
else:
await interaction.response.send_message("I π« find the specified category.", ephemeral=True)```
!d discord.ui.ChannelSelect Don't get me wrong but you can literally use this
class discord.ui.ChannelSelect(*, custom_id=..., channel_types=..., placeholder=None, min_values=1, max_values=1, disabled=False, row=None, default_values=...)```
Represents a UI select menu with a list of predefined options with the current channels in the guild.
Please note that if you use this in a private message with a user, no channels will be displayed to the user.
New in version 2.1.
So this is my code for getting multiple options when using /fruit but I would like the display names of the fruits to have capital letters and space for example apple displaying as Apple Pie how can I do this?
Is there a way for that? cuz I've seen other bots with spaces and capital letters in their options
https://github.com/Rapptz/discord.py/blob/master/examples/app_commands/transformers.py#L80-L89 use the typing.Literal way instead
examples/app_commands/transformers.py lines 80 to 89
# In order to support choices, the library has a few ways of doing this.
# The first one is using a typing.Literal for basic choices.
# On Discord, this will show up as two choices, Buy and Sell.
# In the code, you will receive either 'Buy' or 'Sell' as a string.
@client.tree.command()
@app_commands.describe(action='The action to do in the shop', item='The target item')
async def shop(interaction: discord.Interaction, action: Literal['Buy', 'Sell'], item: str):
"""Interact with the shop"""
await interaction.response.send_message(f'Action: {action}\nItem: {item}')```
With Enum you cannot do it
Either use app_command.choice or typing.Literal
Literal is easy imo
Yo catty sup
Yeah tried those when following some videos but never worked for me always got some errors but ill try again maybe im just missing commas
Hii π
ty
