#discord-bots
1 messages · Page 359 of 1
@discord.app_commands.command(name="kick", description="kicks a member from the server")
@discord.app_commands.default_permissions(kick_members=True)
async def kick(self, interaction, member: discord.Member, *, modreason=None):
await member.kick(reason=modreason)
conf_embed = discord.Embed(title="Success!", color=discord.Colour.green())
conf_embed.add_field(name="Kicked", value=f"{member.mention} has been kicked from "
f"the server by {interaction.author.mention}.", inline=False)
conf_embed.add_field(name="Reason", value=modreason or "No reason provided", inline=False)
await interaction.response.send_message(embed=conf_embed)
!code 🗣️
whats the issue
am trying to make slash cmd for kick
but somn wrong about mod reason
checks out but you should definitely use this py from discord import app_commands
makes your code look much cleaner, like when you do py from discord.ext import commands
that is when i do simply app_commands
oh. slash commands dont take * because they're already given
now i dont cuz am using discord.app_commands alrdy
just remove the asterisk and typehint mod reason to a string
also when i use it it says unused lol
lemme c
|| (even the docs use it) ||
yeah because you're not using it
you're supposed to change the stuff using discord.app_cmds to just app_cmds
both same thing right ?
Using module aliasing is purely personal preference
cuz it worked with discord.app_command
was just abt to say that
oh ur back
did this
still somn wrong with mod reason
back to your question btw
i removd asterisk
then ?
how do i typehint mod reason to a string ?
modreason: str
good. the asterisk defines i think positional arguments, but in dpy its used to take everything after a certain argument. not sure. maybe solstice can add
its not needed for slash commands because the inputs are already separated
probably poor explanation im ngl
It's worth mentioning that as written, this throws away several protections already made by the built in /kick
lemme try

also was my explanation faulty
Prefix commands use the * because at the start it's just one giant string and dpy has to parse them. The * means "parse the rest as one parameter". This isn't needed for slash commands as discord sends these as individual already parsed arguments
thanks solstice 
also now my slash isnt even showing up lol
Basically what you said but expanded a bit with what's happening under the hood. This also means all slash command parameters need to be typehinted
can you explain more what your issue is?
what do you mean by "a sec it showed up at least but its not there"
try resyncing your commands or refreshing any cogs
screenshots would also be pretty helpful for this sort of stuff
got it
refresh worked
but i think now reason is being a necessary arg
i want it to be an option and if no reason
it will auto send
no reason specified
i have alrdy coded like that but whn it came to slash
it bcm compulsory
how do i change@discord.app_commands.command(name="kick", description="kicks a member from the server")
@discord.app_commands.default_permissions(kick_members=True)
async def kick(self, interaction, member: discord.Member, modreason: str):
await member.kick(reason=modreason)
conf_embed = discord.Embed(title="Success!", color=discord.Colour.green())
conf_embed.add_field(name="Kicked", value=f"{member.mention} has been kicked from "
f"the server by {interaction.author.mention}.", inline=False)
conf_embed.add_field(name="Reason", value=modreason or "No reason provided", inline=False)
await interaction.response.send_message(embed=conf_embed)
show me your slash command arguments
because you removed the = None
!code also pretty important
?
the same place you did before
but now str is thr
# it makes your code more readable```
Typehints and defaults are two separate parts of a parameter declaration
what is typehint lol
they're not mutually exclusive
something: Hello # this is a typehint```
You also can (and probably should) use the Optional typehint in combination with this
when you do something: something_else, that : is a typehint
whaat this word
i lerant in math
mutually exclusive and exhaustive
our teacher told this like 1000 times and v wr giggling over thr cuz she literally told this for every qs
lol
have you played minecraft before
ye
cracked
since am not so creative minecraft wasnt for me
but yes i did like the game tho
do you know about the two bow enchantments, Infinity and Mending?
and how they can't be put on the same bow?
nop
i just know to cut trees
lol
also still now it says mod reason is requiredd
show your slash command arguments again
(just the arguments. not the whole thing)
mb
lol
async def kick(self, interaction, member: discord.Member, modreason: str = None):
try syncing your commands again
what does this mean ?
you're using slash comamnd lol. do you not know what syncing is?
not really
lol
refresh discord ?
thats part of it
also this type command worked
and it became optional
but then the embed didnt show up
!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.
what is this now ?
have you never seen a traceback before?
commonly called "errors"?
so whats the problem?
programming hard
idk lol
embed not showing
i tried defer so now the bot is still thinking lol
but the mmber got kicked lol
i just want the mbed to wurk lol
show your most recent code
!code | and please for the love of god use this
im gonna go for a walk soon
lol
got it ? any mistakes ?
went alrdy ??
hm
?
Hey guys, I am using discord.py and autocomplete for the options since they are more than 25, I am just wondering why if nothing is typed, it doesn't load any options by default
Only when I type at least one letter
show how you coded it
async def maps_autocomplete(interaction: discord.Interaction, current: str) -> List[app_commands.Choice[str]]:
speedrun_maps = ['Abduction Avenue', 'Abducted Avenue', 'Behold the Gold', 'Burrito Bonanza', 'Cannon Climb', 'Cannonball Chaos', 'Construction Climb', "Crab's Landing", "Don't Be Jelly!", 'Floor Flip', 'Humble Stumble', 'Ice Caramba', 'Icy Heights', 'Jungle Roll', 'Lava Rush', 'Lost Temple', 'Monopoly Rush', "MrBeast's Dangerous Traps", "MrBeast's Warehouse", 'NFL Scramble', 'Over & Under', 'Paint Splash', 'Pivot Push', 'Race For Eternia', 'Space Race', 'Sping Go Round', 'Stumble Cove', 'Stumble Trouble', 'Super Lava Slide', 'Super Paint Slide', 'Super Pivot Slide', 'Super Slide', 'Super Waterpark', 'Tile Fall', 'Tornado Temple', 'Turtle Tumble']
return [
app_commands.Choice(name=speedrun_map, value=speedrun_map)
for speedrun_map in speedrun_maps if current.lower() in speedrun_map.lower()
]
@bot.tree.command(name="submit-time-trial", description="Submit an entry into the Time Trial Competition!")
@app_commands.check(check_cc)
@app_commands.autocomplete(speedrun_map=maps_autocomplete)
@app_commands.describe(speedrun_time = "Please enter your speedrun time in MM:SS:MS format", video = "Please enter the link to your speedrun video", speedrun_map="Enter the map you are submitting for.")
async def speedrun(interaction : discord.Interaction, speedrun_time : str, video : str, speedrun_map : str):
await interaction.response.defer(ephemeral=True)
My friend has a JS bot with similar use of autocomplete but theirs show default options when nothing is typed
try this ```py
if not current:
return [app_commands.Choice(name=speedrun_map, value=speedrun_map) for speedrun_map in speedrun_maps[:25]]
return [
app_commands.Choice(name=speedrun_map, value=speedrun_map)
for speedrun_map in speedrun_maps if current.lower() in speedrun_map.lower()
]
gotcha, thank you so much! Let me try
You should probably always be capping at 25 just in case even a search yields more
It worked! And yes that's true
How would I go about doing this? Would something like this work?
if not current:
return [app_commands.Choice(name=speedrun_map, value=speedrun_map) for speedrun_map in speedrun_maps[:25]]
return [
app_commands.Choice(name=speedrun_map, value=speedrun_map)
for speedrun_map in speedrun_maps if current.lower() in speedrun_map.lower()
][:25]

Thank you both a ton 
did your issue get solved?
yes ofc
i used author instead of user
i think its user for slash cmds instead of author perhaps ?
@upbeat otter
you should probably check permissions before kicking someone
like hierarchy
among other things but 
am admin
This lets anyone with the kick members permission kick anyone else underneath the bot, with no tracking or auditing, and bypassing the server's 2FA requirements
That seems cool
the one which i did ??
pulling out all stops
which covers the first part of my sentence, but none of the rest
what r u gys saying ?
yes now say there is another guy with a higher or similar perm i can kick them out as long as the bot is highers than either of them
are u saying it to me ?
yes
so my code can let anyone kick ?
kinda
but how come
anyone with that perm can kick anyone else that the bot could kick, even if they themselves shouldn't be able to
because you're not checking anything
@discord.app_commands.default_permissions(kick_members=True)
eg. a mod could kick another mod with the same role, using the bot
yeah but now say there is a guy with manage_server perms now i can still kick him out (i am the guy with kick_perms)
if the bot is higher than both of us
ohhh
When someone kicks someone else in the normal discord flow, discord performs several checks. Not only do they have the perm, but it also checks the server's 2FA policy and the hierarchy. Your code does none of that
then how do i solve that ??
use the built-in kick
then ?
That's the unironic correct answer
check for role heirarchy
ummm
role positions basically
how do i do that
!d discord.Role.position
The position of the role. This number is usually positive. The bottom role has a position of 0.
Warning
Multiple roles can have the same position number. As a consequence of this, comparing via role position is prone to subtle bugs if checking for role hierarchy. The recommended and correct way to compare for roles in the hierarchy is using the comparison operators on the role objects themselves.
You will also never be able to verify 2FA settings without every mod authorizing your bot through oauth. There's no functional reason to do this in a bot at all
how do i code that to the bot ?
so allow kicking only when role lower than commands author
how do i code it
like what shud i type in ?
the tutorial guy did this for kick
this too ^^ (but since this is prolly a smol bot it seems kinda irrelevant ig, fine for smaller pet projects)
I'm willing to bet a large sum of money that this tutorial guy had no idea what they're doing
i thot it had brains
uhh okah
wait gys just come back down
get the authors role with highest position
and same with the guy being kicked
stop stop lets come back
then compare
i wanna ask what does my bot do now ?
am thought it would allow ppl to kick othrs if they have kick members perm switched on
isnt that what my bot is gonna do ?
Read this carefully
Discord checks 3 things. Your bot checks 1 thing
hierarchy, 2fa
It's in that sentence
lol
got it
now next
how do i do it
and as I have said, these things already exist in something people already have
and implementing it yourself is going to range from annoying to impossible
thats quite a bit of selective reading 💀
lol mb
now how do i do it ?
haha this was it
Telling you now that you are not going to bother with the 2FA bit
ye please
the code lines for it was what i wanted.
lol
Maybe one question worth asking is why do you want people to use this instead of the built in /kick they already have and works great
whats the point then, u just seems to copy pasting lines of code from few of us or a few tutorials and patching stuff up, what are u learning?
okah now that is thr
prolly just satisfaction of being able to accomplish some particular feature or functionality thats often quite motivating i believe
am learning little by little
like this part am doing it for the first time
then i can do for ban and unban
by learning this one
like that
ye
You can do this with other pieces of the api that aren't sensitive and aren't eroding security protections people rely on, but you do you
also i did not come to master python or stuff
just making a small bot for my server
a part time hobby if u wanna say
huh ?
but how will me giving u lines of pre made code help with that i did already said the logic behind it isnt it more interesting if you figure out how to do it from there?
i also pointed out which particular attributes you need to check
People already have a /kick, but you want to make a /kick to learn something. People already can make channels, send messages, modify settings, and a billion other things that aren't as sensitive or protected so why not just implement those
so why dont you try or atleast attempt to solve the issue by yourself once before looking for a solution
it is interesting but then am not familiar with python at atll
and i shud invest a lotta time in it
rn i dont think i have thaaaaat much time
cuz i have othr stuff to study
i mean if u dont wanna waste ur tym or help i dont mind
i will prbly ask sum1 else or just if no1 helps at the end figure it out myself like how u told me in the first place lol
imo ur just doing stuff with little to no goal
but i dont know
i havent did this at once also
i think u dont get it
lmao
why not try to figure it out yourself first? its fun too like a puzzle ||with less than 1000 peices||
umm
in one way or the othr yea
Free time go to yt tutorials
copy paste code is what am literally doing rn
lol
but now i can make embeds cuz i have done in first time by copying
and i did it alone for my ping command altho i sneek peaked a bit
lol
!d discord.Interaction.user
The user or member that sent the interaction.
i dont think u get my point
!d discord.Member.roles
property roles```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role) that the member belongs to. Note that the first element of this list is always the default [‘@everyone](mailto:'%40everyone)’ role.
These roles are sorted by their position in the role hierarchy.
tell me a program that you are proud of writing as a beginner
nyways thanks for ur tym ig
i will figure it out by trial and error or some referrals lol
i think i do because i was in the same position as you
oh wow
also like solstice said
y the shit am i even making kick and ban and unabn etc stuff what all thr
imma think outta the box and do somn different
it makes no sense
lol
wasted my tym lol
at the end of the day you should do whatever you feel like, as long as you're learning on the way
fair
Re-implementing things is fine as a learning exercise. But when you do so and actively make security worse on a server you probably should be re-implementing something else
lol yea
ye sommn not related to security perhaps
perhaps i can create a game
but i think its too complex for a beginner like me
maybe just start with basic python
uwu
i tried that 2 yrs ago
lol
4got aftr i went to boarding school where electronic devices were not allowed for 2 whole yrs
lol
like a bit i tried
copy pasting is only good in the short term of things it rlly doesnt help in the long term of things like imagine you have this super unique issue only to your project youre kinda just done there
to learn how to use something is to have more ideas on how to make something new
lol yes and no
fair
ive had issues where even gpt cant help me and i had to quit the project and learn the basics
i dont think i have the patience
tbh
but thats just me
oh
oh so now u a pro ?
nope far from it
where would I start to make a code check if someone received a certain role?
Coding isn't easy, it takes time + dedicated learning + personal experimentation and exploration
far
inside a command? or you want to do some stuff when someone is assigned a role
whenever someone is assigned the role and the bot is active
no command associated
How would I make it run without a command
do I just skip the command part and go to async def ...
Ill let you know what I need to accomplish
alr
lovely if you have any questions remember we're still here to help you!
How do i check every user in the guild instead of a single one?
one doubt
i can use prefixes in my server right
like i dont want slash cmds
discord will lemme do that right ?
also i dont plan to make my bot private
i will be only thr in 1 or 2 servers max
Yes, you only need message content for prefix commands to work
cool
this event will be dispatched whenever any of the members update their profile
^^
cud u share me a good video to learn basics perhaps ?
There aren't really good video's regarding this topic. Best way to learn is to see other code or ask here.
Best is to keep it simple and not ask broad questions.
Asher
breh
i dont need the best
just to get some hang of the basics
rest i will learn by trail and error
lol
|| (ask your question) ||
can anyone share me a video link to learn the python basic the fastest way
i do not need like the best of the best
just to get a hang of the basics
rest i shall learn from trial and error or by seeking help frm othr ppl
pls share me a link ?
also if there is any specific vid abt discord.py basics
better
ur back from walk ? lol
there arent really any good dpy videos, like the guy said.
for python, theres loads upon loads upon loads of tutorials online. most i presume are cash grabs, but there might be some good ones out there
yep. here to help now 
care to suggest some so that i can stop asking my stupid dumb doubts here
lol
I don't have one, it's just an old friend lol
I was regular here a year ago or so
ohh alr
idk. freecodecamp? i used websites to train my python skills and learn new things
https://codeabbey.com - this is a good one, but its centered around problems. its the one i used.
https://codewars.com - this one is good as well for learning python basics.
these r all practice sites ?
idk to write a signle line lol
then learn. and learn by doing
thanks will 
sarth feeling old (ancient)
sup boss
does anyone know how to make a code so that if i put a command in a specific channel it sends messages that you cant use the command in that channel ?
stop commands being used in a channel with a command?
so like if i have 2 commands (!hello and !bye) i want that !hello cant be used in a specific channel
only thing i can find is this ```default_invoke = bot.invoke
async def new_invoke(self, ctx: Context):
if ctx.command:
if 'cypher_ascend_a':
return
await self.default_invoke(ctx)
bot.invoke = new_invoke```
Yea use a check
if ctx.channel.id = 12455493993:
return await ctx.send("you can't run the command in this channel")```
==
i have this code ```@bot.group()
async def cypher_ascend_a(ctx):
file_1 = discord.File(r'C:\Users\Luuk\Pictures\Cypher setup\ascend\A site\cypher A site ascend.png', filename="cypher ascend-a one-way.png")
embed = discord.Embed()
file_2 = discord.File(r'C:\Users\Luuk\Pictures\Cypher setup\ascend\A site\cypher ascend-a one-way.png', filename="cypher A site ascend.png")
embed = discord.Embed()
embed.set_image(url="attachment://cypher ascend-a one-way.png")
embed.set_image(url="attachment://cypher A site ascend.png")
await ctx.send('Aline yourself under this line in the generator and aim at the spike in the sky to get this heaven one-way')
await ctx.send(files=[file_1])
await ctx.send("Jump and throw")
await ctx.send(files=[file_2])
await ctx.send(embed=embed, file=file)
if ctx.channel.id == 1234540499390431252:
return await ctx.send("you can't run the command in this channel")``` but get the following error return await ctx.send("you can't run the command in this channel") ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ SyntaxError: 'return' outside function
maybe you have to fix your indentation
send me a screenshot of this function
you put it outside function
indent the second last line.
that's basic python bro
and wtf is with that code
😭why are you sending different messages
bc its sending a picture with a text

you mean this:
await ctx.send(files=[file_1])
await ctx.send("Jump and throw")
await ctx.send(files=[file_2])
await ctx.send(embed=embed, file=file)
if ctx.channel.id == 1234540499390431252:
return await ctx.send("you can't run the command in this channel")```
you can send that in one message
it bc its 2 images with 2 diffirent text inside one command
you can still send them as 2 embeds in 1 .send()
what the fuck is a group
!d discord.ext.commands.Bot.group
@group(*args, **kwargs)```
A shortcut decorator that invokes [`group()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.group) and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin.add_command).
damn
idk how so i messed around and this worked
you can set the embeds param
embeds=[embed1, embed2, ...]
but will it send the text in the same order as now ? bc now i have a text, image, text, image
sending 5 seperate is not ideal
basically a ratelimit every time you use the command
what does ambigous variable mean ??
you can noqa it if you want
means the name is too short
i mean the name makes no sense
its for tic tac toe
also why -1 1 2, and not 0 1 2 ?
lineups are better understood through videos ngl
idk lol
ai made this code for me lol
yeah but when im in game i want to be able to send a command and than check a few photo's
examples/views/tic_tac_toe.py lines 66 to 68
X = -1
O = 1
Tie = 2```
so you dont have to watch a video

hmm
this is what i did
is thr any other thing for edit_message
Cannot find reference 'edit_message' in '() -> InteractionResponse'
this warn comes
are you using pycharm
ye
typical pycharm error
lol
ignore it
its so you can call sum() on a line and if its 3 it means its 1 who wins and if its -3 its 2 that wins
interesting
also now interactions is unresolved
red flag error
ai aint smart to code my tic tac toe ?lol
or idk if its my prb
just keep the screenshots? or does it do more?
well i want o make that but than for every agent, so if i have to cearch for every agent for every map on every site it takes a long time that why i want to make the commands like that
I will not help if you're just generating code through AI. Hopefully someone else does
nvm got it
ah I see alright
okah
so that command is what i wanna use in a channel for only that agent, but i dont know how to block the other commands in that channel. So you won't have different picutres of different agent in the same channel. If that makes sens
so you wanna constrict a certain something to a certain channel using a command?
you'll need a database for that then
i guess so, that only a few commands can be send in a specific channel
were can i find the right info to learn about a database for that ?
#databases probably has some good pinned chats
oh damn I am looking through this channel's pins and the misinformation in there hoes hard 🔥
like?
well it was the like old slash libs (2020ish pins)
yeah should probably be unpinned
tbh other pins hold info that was relevant but isn't anymore lol
Or the two gists from Deleted User
everyone loves Deleted User
@bot.listen()
async def on_member_update(before, after):
staffrole = discord.Guild.get_role(1155546749117669376)
if staffrole in on_member_update(before, after):
print("zaddy")
TypeError: Guild.get_role() missing 1 required positional argument: 'role_id'
could use some help
you're using a base class which doesnt have any details. think of it like a blank state
also your command repeats itself so it doesnt go anywhere
dw it happens lmao
ah yes let's not help them and instead tell them how bad their code is
Is being shitty to people a way to help them learn
*editing your rude message doesn't change anything

but yeah good point. i see what you mean
in an argument with friends so kinda pissy
in a case like this its best you dont help for a bit and let someone else take over
youre doing this voluntarily remember


Anyone got any docs you’d recommend for starting with discord bots?
Thanking you muchly
np
Hello anybody able to help, I'm looking for a script I could add to my python script for mentioning members username in an embedded message upon them receiving certain roles
!d discord.Member.mention
property mention```
Returns a string that allows you to mention the member.
!d discord.Member.roles
property roles```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role) that the member belongs to. Note that the first element of this list is always the default [‘@everyone](mailto:'%40everyone)’ role.
These roles are sorted by their position in the role hierarchy.
!d discord.Embed
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
x == y Checks if two embeds are equal.
New in version 2.0...
@slate swan this is all you need, pretty much
thank you been trying to figure this out all day lol
why does it say i dont have message content intent enabled even though i have all intents enabled?
I even added the intent.message_content = True just to be sure but it still doesnt work
MissingMessageContentIntentWarning: Message content intent is not enabled. Prefix commands may not work as expected unless you enable this. See https://docs.nextcord.dev/en/stable/intents.html#what-happened-to-my-prefix-commands for more information.
nextcord 
show your commands.Bot definition
i think nextcord renamed that to discord.Bot
show where you defined your Bot
# for dpy
import discord
from discord.ext import commands
intents = discord.Intents.all()
bot = commands.Bot(command_prefix = '?', intents = intents)```
should look smth like this
I've been using nextcord for years now and i also have a different bot with the same things so that cant be and I really dont want to switch back to d.py just because of some silly error
why are you removing the help command
also whats the silly error that you dont want to return to dpy because of
i dont know if its still the same as it was a few years ago but you had or still have to remove it to make a custom help command
depending on what your help command is, i dont think you have to remove it to make a custom one
its nothing with dpy but rather the error i just had again
its just that im way more familiar with nextcord
Print dict(bot.intents) somewhere please
discord.ext.commands.on_command_error(ctx, error)```
An error handler that is called when an error is raised inside a command either through user input error, check failure, or an error in your own code.
A default one is provided ([`Bot.on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.on_command_error)).
AHA there we go
how to take input as a txt file
example /give dskfjsdkfssssss.txt
the txt is uploaded
parameter: discord.Attachment
to my laptop
can i get the whole command im kinda new
bot.tree.command(name="give")
@app_commands.describe(txt = "Give Txt FIle")
async def say(interaction: discord.Interaction, txt: discord.Attachment):
like this?
yep
ok thx
@slate swan i can add an execption if i can read the txt its txt file if it gives error its not right
i can do it like tht no?
@slate swan another thing when u get the attachemnt
is it downloaded in my laptop
like in the folder of python code?
I don't really know since I never used them but probably yeah
ill try it
and to the second question, they arent afaik
afaik?
oh shi mb
@slate swan and another how do i check name of the file in the attachment
class discord.Attachment```
Represents an attachment from Discord.
str(x) Returns the URL of the attachment.
x == y Checks if the attachment is equal to another attachment.
x != y Checks if the attachment is not equal to another attachment.
hash(x) Returns the hash of the attachment.
Changed in version 1.7: Attachment can now be casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str) and is hashable.
thx
@slate swan the attachment
dosent download
@slate swan
so download file is await save(fp, *, seek_begin=True, use_cached=False)
it shows this tho
@bot.tree.command(name="add")
@app_commands.describe(file = "Give The txt combo")
async def say(interaction: discord.Interaction, file: discord.Attachment):
file_name = file.filename
await file.save(fp, *, seek_begin=True, use_cached=False)
whole code (basically trying to downlaod the txt file from attachments)
it says fp not defined
the signature shown in the documentation has different syntax rules than what you would write when you're calling that function
so how to download the file?
you need to open a file to save it to first
how?
file.save()
dosent work
i dint give any response where does it download?
i want it to download to the file where bot.py is loacted
ya, you need to pass either a file object or a filename for dpy to save it to
you er, cant call instance methods on the class directly
if you don't need to physically write the file to disk, you can use an in-memory file instead: ```py
import io
@bot.command()
async def command(ctx, attachment: discord.Attachment):
file = io.BytesIO()
await attachment.save(file)
data_bytes = file.read()
data_text = data_bytes.decode("utf-8")
await ctx.send(f"The attachment contains:\n{data_text}")```
its the same with /slash command
@bot.tree.command(name="add-stocks-free")
@app_commands.describe(file = "Give The txt combo")
async def say(interaction: discord.Interaction, file: discord.Attachment):
file = io.BytesIO()
===========================================
same?
0|bot | Traceback (most recent call last):
0|bot | File "/path/to/venv/lib/python3.11/site-packages/discord/client.py", line 441, in _run_event
0|bot | await coro(*args, **kwargs)
0|bot | File "/root/Events/logging.py", line 216, in ModLog
0|bot | if not entry.target.is_timed_out() and entry.before.timed_out_until:
0|bot | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
0|bot | AttributeError: 'AuditLogDiff' object has no attribute 'timed_out_until'```
discord.py v2.3.2
yo how to add this kinda message into embeds
```
your text here
in the deescription
well you can see the error
ai coding 
I have no idea about this maybe Leonardo or others can help
SO WHY DO YOU REPLY IF YOU DON'T KNOW ABOUT IT?
@pale zenith
class discord.AuditLogDiff```
Represents an audit log “change” object. A change object has dynamic attributes that depend on the type of action being done. Certain actions map to certain attributes being set.
Note that accessing an attribute that does not match the specified action will lead to an attribute error.
To get a list of attributes that have been set, you can iterate over them. To see a list of all possible attributes that could be set based on the action being done, check the documentation for [`AuditLogAction`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AuditLogAction), otherwise check the documentation below for all attributes that are possible.
iter(diff) Returns an iterator over (attribute, value) tuple of this diff.
Read this carefully, that error is intended.
You need to use hasattr or getattr, probably.
!d g hasattr
hasattr(object, name)```
The arguments are an object and a string. The result is `True` if the string is the name of one of the object’s attributes, `False` if not. (This is implemented by calling `getattr(object, name)` and seeing whether it raises an [`AttributeError`](https://docs.python.org/3/library/exceptions.html#AttributeError) or not.)
ok
!d discord.Member.display_name @swift siren
property display_name```
Returns the user’s display name.
For regular users this is just their global name or their username, but if they have a guild specific nickname then that is returned instead.
before is an instance of discord.Member
I am trying to get my discord bot to update an embedded message with their @ under the correct category depending on what they are checking in for, However the code works fine but the bot isn't updating the embedded message with @ username when that role is assigned, could someone tell me what is missing or wrong with the code please.
I got it thank you
@pale zenithIs it possible to make commands.HelpCommand hybrid?
Nah
the send_mapping one?
how to download a file given in attachment (slash command) download to folder of bot.py
yo nobody les go
i tried in the morning nothing worked
The file is a parameter right?
class discord.Interaction```
Represents a Discord interaction.
An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.
New in version 2.0.
I looked through it the file.save(fp) dosent work some error
I'll show later I closed my pc
Well i don't know how to do it or is it even possible since i couldn't find anything regarding it
Guys is bot-hosting.net good for hosting bots?
You can try doing interaction.message.attachments[0].save but i doubt it's gonna work since slash command don't have a message attached to it
Anyone here? Hello?
Don't know never used or heard of it
If it's a free hosting then the are probably not good
Anyways how much space is required for a python bot?
I have 1 GiB Storage
And 250MiB Memory
Since free hosting use share ips which causes frequent rate limiting issues
As a rule of thumb, anything that markets itself as a "discord bot host" is a scam because "discord bot hosts" don't exist. There are just hosts where you run processes
Their privacy policy is also scummy
It has VPS
Depends on what your bot is doing and how much traffic it is handling
I want it as a automod bot
You should run your bot and profile it, it's impossible to accurately estimate the resources you'll need from just a one sentence description
Ohk
And how much servers ot will be in? And amount of users
Anyways anyone can help me with some code?
Just post your issue and if anyone knows the solution they will tell u
I need a code where I have a file named BadWords.txt and the bot scans the message and if the message contains any word from the list(i used line by line for each word) it will delete it and dm a warning and also show a embed.
Or you can try sending a response with the attachment then use attachments[0].save() on that response to download the file
What have u done so far
Wdym my code?
I have done anything a average bot has and it's online and working and I need a command for that
Yeah and what have u wrote for the specific feature u mentioned above
We are not here to write your code just to help if you have an issue with your existing code
I wanna use on_message with @bot.event for this
I am
And it's not working AT ALL
Ok wait
except discord.errors.Forbidden:
print("I don't have permission to delete messages or send DMs.")
@bot.command()
async def hello(ctx):
await ctx.send('Hello!')
Bruh i couldn't copy it
Wait
This is covered by the native automod system in discord, with far more flexibility and far less instability than relying on a specific bot
Is it possible to connect automod with the bot like bots like Wick have?
Your bot can make automod rules yes
Which then discord takes the responsibility of processing
Any code example for it maybe?
Hmm
Tbh what are automod rules? I'm new to automod
There's a good article from discord one sec
Basically anything a human could do to configure automod, a bot can as well
Hey folks, i need in help my bot development
DM pls if there is anyone to help with this project
For both folks, it's almost always better to get help in a public place where incorrect or bad answers can be reviewed by multiple people
Is there way i can get emoji or emoji id from server which isn't into my bot guilds?
Answer - discord.PartialEmoji worked
!d discord.ext.commands.Bot.get_emoji
get_emoji(id, /)```
Returns an emoji with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
should use this one
@bot.tree.command(name = 'give-file', description="Gimme The txt file")
@app_commands.describe(txt = "Txt")
async def say(interaction: discord.Interaction, txt: discord.Attachment):
split_v1 = str(txt).split("filename='")[1]
filename = str(split_v1).split("' ")[0]
if filename.endswith(".txt"): # Checks if it is a .csv file
await txt[0].save(fp="DISCORD BOT/{}".format(filename)) # saves the file
so im trying to download the file sent in /slash command and it gives an error
Traceback (most recent call last):
File "C:\Users\RedApple\AppData\Roaming\Python\Python312\site-packages\discord\app_commands\commands.py", line 828, in _do_call
return await self._callback(interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\RedApple\Desktop\DISCORD BOT\bot.py", line 121, in say
IndexError: list index out of range
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\RedApple\AppData\Roaming\Python\Python312\site-packages\discord\app_commands\tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\RedApple\AppData\Roaming\Python\Python312\site-packages\discord\app_commands\commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\RedApple\AppData\Roaming\Python\Python312\site-packages\discord\app_commands\commands.py", line 846, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'give-file' raised an exception: IndexError: list index out of range
And the error?
oh
thts the error
range error \o/
i just wanna download the file in bot.py folder
or change the txt file into a list
but downloading is better
is 121 the filename?
split_v1 = str(txt).split("filename='")[1]
filename = str(split_v1).split("' ")[0]
``` this looks weird to me lol
i searched google
no the file i gave was lol.txt
i replaced the message.attachment to file cuz thts the attachment
Controversial opinion, but fuck stackoverflow
lol
tht error too
await save(fp, *, seek_begin=True, use_cached=False)
this
i prolly wrote it wrong can u show how to write ti
is it like py await file.save(fp, *, seek_begin=True, use_cached=False)
hold up
I wasnt putting checks in. just saving a simple file if it uploaded
@app_commands.command(name="savefile", description="Saves a file!")
async def savefile(self, interaction:discord.Interaction, file:discord.Attachment):
await interaction.response.send_message("File attached!")
print(file.filename)
filepath = f"C:\\Users\\Declan\\Desktop\\discordbots\\testbot\\files\\{file.filename}"
await file.save(fp=filepath)
so "file.filename" returns the files name, in my test I used an image called "cabeldrawer.jpg", it returned that.
The file path is where you want the file to be saved to. In this case locally to my code
as well as what to save it as
Oh thx
how can i send an image? i'm using this format:
@client.tree.command(name="prof", description="Sends an image")
async def prof(interaction: Interaction):
await interaction.response.send_message()
can i even send an image this way?
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, silent=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
you can do it using
...send_message(file=discord.File('filepath'))```
ty
is code geass worth watching?
the animation is kind of outdated by now
very yes
!traceback | whats the full 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.
you mean the whole file?
because i dont get any errors
in the terminal
nvm it just suddenly started working
terminal errors lmao

Need help
how can i get a bot to join the vc and play some audio?
with what
!d discord.ext.commands.Bot.voice
No documentation found for the requested symbol.
class discord.VoiceChannel```
Represents a Discord guild voice channel.
x == y Checks if two channels are equal.
x != y Checks if two channels are not equal.
hash(x) Returns the channel’s hash.
str(x) Returns the channel’s name.
So Im trying to make views persistent using data from Django ORM
class TicketBot(commands.AutoShardedBot, View):
def __init__(
self,
initial_extensions: list[str],
**kwargs,
):
super().__init__(**kwargs)
self.initial_extensions = initial_extensions
self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
def load_persisted_data(self):
objects = PersistentView.objects.all()
for obj in objects:
print(f'adding {obj.guild_id}, {obj.channel_id}')
self.add_view(CreateTicketView(obj.guild_id, obj.channel_id))
print('view added!')
async def on_ready(self):
await self.change_presence(activity=discord.CustomActivity(name='👀 Watching Tickets'))
print(f'{self.user.name} is ready')
tracemalloc.start()
async def setup_hook(self) -> None:
for extension in self.initial_extensions:
await self.load_extension(extension)
self.executor.submit(self.load_persisted_data)
print("Cog modules are ready")
async def cleanup(self) -> None:
print("Cleaning up...")
await self.close()
print("Clean up complete")
but it seems views are not properly added as view outputs nothing. Any ideas?
!d discord.VoiceChannel.connect | @gusty berry
await connect(*, timeout=30.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>, self_deaf=False, self_mute=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Connects to voice and creates a [`VoiceClient`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceClient) to establish your connection to the voice server.
This requires [`voice_states`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.voice_states).
that doesnt show anything about the view? interaction failed arises from when you dont give a .response. to the current interaction
oh well, i mean i print out something by clicking the button in my view, but after restart it doesnt stay persistent and therefore there is no output
here is my view for clarification
def persist_view(guild_id, channel_id):
PersistentView.objects.update_or_create(
guild_id=guild_id,
channel_id=channel_id,
)
class CreateTicketButton(discord.ui.Button):
def __init__(self, guild_id, channel_id):
self.parser = JSONParser(guild_id, channel_id)
super().__init__(
label=self.parser.get_language(),
style=discord.ButtonStyle.success,
custom_id=f'persistent:create_ticket_{uuid4()}'
)
async def callback(self, interaction: Interaction[ClientT]) -> Any:
print(f'Creating at {interaction.channel.name}!')
class CreateTicketView(discord.ui.View):
def __init__(self, guild_id, channel_id):
super().__init__(timeout=None)
self.guild_id = guild_id
self.channel_id = channel_id
self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
self.setup_view()
self.add_item(CreateTicketButton(self.guild_id, self.channel_id))
def setup_view(self):
print('Setting up view!')
self.executor.submit(persist_view, self.guild_id, self.channel_id)
Well. I'm geting an issue like that
I literally tired every way it has to be easy to fix but I didn't find any solution I would be very happy if you help.
your UUID probably needs to be in your database too, otherwise you'd be generating a random custom ID each time
doesnt exist any more
deprecated and replaced with regular dpy
oh okay, ima try that out
or perhaps, maybe you dont really need a UUID in your custom ID? once a view is sent, it can be associated with a message ID which will help dpy associate components by (message ID, custom ID)
so i just save message_id as well to my db?
TypeError ?
sure, if you do that then you won't need a globally unique custom ID
class MyView(discord.ui.View):
@discord.ui.button(..., custom_id="my-view:my-button")
async def my_button(self, interaction, button): ...
@discord.ui.select(..., custom_id="my-view:my-select")
async def my_select(self, interaction, select): ...
bot = commands.Bot(...)
bot.add_view(MyView(), message_id=1234)
bot.add_view(MyView(), message_id=5678)``` here, both buttons/selects share the same custom ID but can be distinguished by the message they're attached to
well how would I pass it to the view
the thing is I am creating that view from task
Here I use the view in the class where all the logic lays for creating ticket threads in a forum
And 2nd/3rd image is how my task executes it
is this pycord? if so, the forum thread returned by create_thread() has the same ID as the message that your bot sent, so you can store that and later re-supply it in your add_view() call
no, it is just vanilla discord.py
can someone look for this code im tryna figure out where is the mistake
not sure what you mean by mistake, but tkinter is a synchronous/blocking lib which means it will stop your bot from running until you close out of your GUI
well yeah, it returns the message, so essentially I can call product_thread.message.id but how do I pass it at the same time in the view arg as I am creating the thread?
!d user installed
NumPy user guide
This guide is an overview and explains the important features; details are found in NumPy reference.
Getting started
• What is NumPy?
• Installation
• NumPy quickstart
• NumPy: the absolute basics for beginners...
i suppose something like this wont work
ergh yeah, you'd have to assign it after creation
or i just send view separately?
though your view doesn't really need the message ID
well how do I add it to the db then? cuz im adding it to a database at the first time view is created
at the setup_view
class CreateTicketView(discord.ui.View):
def __init__(self, guild_id, channel_id):
super().__init__(timeout=None)
self.guild_id = guild_id
self.channel_id = channel_id
self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
self.setup_view()
self.add_item(CreateTicketButton(self.guild_id, self.channel_id))
def setup_view(self):
print('Setting up view!')
self.executor.submit(persist_view, self.guild_id, self.channel_id)
or I just add it beforehand?
i was just thinking what if i can make a pannel and asked chat gpt it showed me that code so i continued with that code which module i can use for that type of usage like kick or ban
I wouldnt recommend on relying on chatgpt too much, it has outdated info, always look up to the docs
its a bit weird to persist them in init given that you're going to remake those view objects at startup
oh well, yeah that is kinda weird
yea chatgpt made me suffer alot
i just began to coding discord bot for a month and im looking every source i foun
btw what can i do to make a window like the code i gave but it needs to work ofc ...
i guess simplest option would be to add the message_id parameter to your setup_view() method, then only call it after you've sent your view: py view = CreateTicketView(...) thread, message = await forum.create_thread(..., view=view) view.setup_view(message.id) (might also be worth renaming it to .persist_view(message.id))
thanks a lot for help, ill try that
im trying to use user apps and when logging into my but it just gets stuck on shard validating
[2024-04-30 21:18:43] [INFO ] discord.gateway: Shard ID 0 has connected to Gateway (Session ID: 4437c13a60e1848795783ca0d53527e4).
@app_commands.command()
@app_commands.allowed_installs(guilds=False, users=True)
@app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
async def useable_only_users(interaction: discord.Interaction):
await interaction.response.send_message("I am only be installed to users, but can be used anywhere.")
its a complex topic, tkinter and dpy both have their own event loops which can't run in the same thread (at least, not without some .update() shenanigans)
https://tkdocs.com/tutorial/eventloop.html#asyncio
is this in a cog? it looks like self is missing from that snippet, but it's not clear from that alone what your bot is stuck on
ty maybe i will look back at this at the future
thanks 😭
forgot all about it the cog itself
Is there anything to get sticker url like discord.Emoji.url
me loving that ts still doesn't work 
I think i tried but didn't work
elaborate
Function should be below decorators
Vice versa
Let me double check if it returned none or something
???? it already is
half ass ss , mb
Every line with @ is decorator and async def is you're defining function
im aware that's why I questioned u
You have commands.command below function
those are two different commands
^^
Sorry mb
you're fine
Anyone else having issue with logging in bot?
have you set-up logging?
aha nvm
yeah there's an issue rn
Welcome to Discord's home for real-time and historical data on system performance.
Taking me 6-7 reconnects to login finally
if i understood correctly, i need to do something like this:
class CreateTicketView(discord.ui.View):
def __init__(self, guild_id, channel_id):
super().__init__(timeout=None)
self.guild_id = guild_id
self.channel_id = channel_id
self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
def setup_view(self, message_id):
print('Setting up view!')
self.executor.submit(persist_view, self.guild_id, self.channel_id, message_id)
self.add_item(CreateTicketButton(self.guild_id, self.channel_id, message_id))
async def _create_products(self, channel: discord.ForumChannel):
for product in self.data['products']:
try:
print(product)
product_utils = self.ProductModeUtils(product)
print(product_utils.title, product_utils.description)
print(channel.type)
view = CreateTicketView(self.data['guild'], channel.id)
thread, message = await channel.create_thread(
name=product_utils.title,
embed=CreateEmbed(
title=product_utils.title,
description=product_utils.description
),
view=view
)
view.setup_view(message.id)
but it doesn't add button item
Oh yeah it's returning None because bot is not in guild maybe something like discord.PartialEmoji would work?
tias
has the randomized custom ID been replaced in CreateTicketButton?
oh wait, the add_item() call should be in init
the creation of your components should happen separately from the database persistence so you can skip the excess queries when you're re-adding your views at startup
yeah
class CreateTicketButton(discord.ui.Button):
def __init__(self, guild_id, channel_id, message_id):
self.parser = JSONParser(guild_id, channel_id)
super().__init__(
label=self.parser.get_language(),
style=discord.ButtonStyle.success,
custom_id=f'persistent:{message_id}'
)
async def callback(self, interaction: Interaction[ClientT]) -> Any:
print(f'Creating at {interaction.channel.name}!')
but back to the thing, if i keep it in __init__, how do I get message_id ?
this would be impossible without re-editing the components after the message is already sent
^ custom IDs don't have to be globally unique, a static custom ID combined with message ID in your add_view() call on startup is sufficient to distinguish views from each other
@hushed galleon discord.Sticker.url
?
I want to get sticker url like a partial emoji url
ofc
i found a yt video explaining it
You could use something likd systemd, pm2, screen, etc.
i'll see if it works
https://discord.com/developers/docs/reference#image-formatting-cdn-endpoints
doesnt seem like dpy can format a partial sticker for you but it seems easy to do it yourself, as sticker urls are always in the form https://cdn.discordapp.com/stickers/{id}.png
do you automatically get the active dev badge or do you have to apply to something?
And can i upload these links as a emoji in server?
Claim from here and must have admin in one community enabled server
You don't have to wait if your bot's global was used before last 24H
If you're using it now then you'll be eligible after 24H
i've been making bots for days i just didnt have my server as a community so i changed it like 2h ago
Just visit website and it'll show your eligibility status
bro i just put in some random shit and i got the badge 😭
xD 🤣
That means you were already eligible
it was a dead server tho
hasnt been used in 2 years
As long as your bot is not dead works
fair enough
@app_commands.command(name='avatar',description="view a user's avatar")
@app_commands.describe(user_id="user id to avatar")
async def avatar(interaction: Interaction, user_id: str = None):
if user_id is None:
user = interaction.user
else:
user = await interaction.client.fetch_user(user_id)
embed = discord.Embed(title=f"{user.name}'s avatar",color=0xffffff)
if user.avatar is not None:
avatar_url = user.avatar.url
else:
avatar_url = user.default_avatar.url
embed.set_image(url=avatar_url)
await interaction.response.send_message(embed=embed)
embed is not accessible if user_id is None
you defined embed in the else scope so it doesnt carry over
got there before me 
You've associated it in else: only
I'm slow typer to avoid typos maybe even before you
i am as well considering im on my phone and the text was squished

I code on my phone

await connect(*, timeout=30.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>, self_deaf=False, self_mute=False)
this is the command for joining a vc. idk how to check if the user is in a vc and how to feed this command which vc to join
foul behaviour
!d discord.Member
class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild).
This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User).
x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User) instances too.
x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User) instances too.
hash(x) Returns the member’s hash.
str(x) Returns the member’s handle (e.g. `name` or `name#discriminator`).
Jk jk but I'm on phone rn too that's why I'm slow typing
!d discord.Member.voice
property voice```
Returns the member’s current voice state.
this to check if he's in a vc?
discord.Member.voice returns true if connected
discord.Member.voice.channel returns voice channel of user
I got there before you
member 🗣
You had to check it smh
answer was wrong because users cant be in a vc 🗣🗣


But it is more helpful after correction
Better than yours
ok i got that working. now how do i feed the channel_id to the connect command?
await connect(*, timeout=30.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>, self_deaf=False, self_mute=False)
discord.Member.voice.channel.connect()
oh its that simple
Whilst Y'all are racing to "help" you're missing key information
Enlighten me
Member.voice is VoiceState | None, meaning it can be None, you'll need to check for that before trying to access .channel (which can also be None)
I thought we were having heathy competition
Server has strict rules against music bots like this btw
No one knows
If I ping a mod they will?
That could be my personal class too?
Weird argument
That's not the full code?
Fam we all know what wavelink is
like this no?
if member.voice:
That is one way, sure, yep
I wouldn't like to take a exit from here
This means they have a voice state in your cache, which likely means they're in a VC
It's helpful for me
RuntimeError: PyNaCl library needed in order to use voice?
Did you install your library with the voice addon? That is required and outlined in the "Getting Started" in the documentation
E.g.
python -m pip install -U "discord.py[voice]"
It also installs a bundled version of libopus for you (for Windows users)
also every time i add a new command i have to kick the bot and add him back for it to update
Mac user since birth
Nvm....
is there an easier way like to make it update in the code?
Disconnect from vc
I don't recall asking you?
no
That has no solution
Please let OP speak.
i mean from the server. i use @client.tree.command(name="ping", description="Izpiše, koliko pinga ima bot.") for commands
Ah you're syncing slash commands on startup
client = commands.Bot(command_prefix="$", intents = discord.Intents.all())
You could make a sync command and do it that way, especially since syncing on startup can incur nasty ratelimits
so how should i go about it. idm rewriting the code
I wrote something about this, one moment
https://about.abstractumbra.dev/dpy
It's a fair bit of reading but it teaches you all about how syncing to discord works
There's also an example message command to make syncing easier
can it? i thought the endpoint was ~2/30s plus a separate limit of 200 new commands daily, excluding updates to existing commands
They're restarting every 20 seconds and syncing globally by the seems of it
Global syncing sure be a vicious ratelimit
if i just add Umbra's Sync Command to my code it'll sync itself?
Not at all
Hence I said you should read the pages
They explain how this all works
...all of them?
oh, referring to this? i would have suspected their discord client needed to be reloaded, rather than a sync rate limit
Just switching to a new channel and back works (sometimes) in that case
it isnt so bad. i tried learning rust and making a bot there. the manual is..... lets just say long. ITS WAY TOO LONG.
But what I'm saying is, if they're restarting the bot all the time to update the code, but syncing globally in setup_hook or on_ready then it's gonna get hit by the mean ratelimit
Yeah the Rust book is dense
making a bot in rust is such a pain
I tried writing this to be simple but convey the important stuff
bless you
@client.event
async def on_ready():
await client.tree.sync()
await client.change_presence(activity=discord.activity.Game(name="SimulIDE"))
print(f"{client.user.name} je povezan!")
i've had client.tree.sync() there from the beginning but it never really did anything. i'm still not done reading so ig i'll understand later
Only if you understand why and have an alternative
Like it's likely not gonna be an issue for a smalltime bot or anything, but since I tailored this to the average user I had to mention the issues
The sync command example is just what I use and share with ppl in the dpy server to use since it covers most cases of use and is pretty user friendly
when ?tag ass in here
The brashness we use in dpy wouldn't fly here
that's a new word
in the command body there are many examples of how you can sync the command tree. are they necessary? why cant i just always sync all global commands to discord with !sync or $sync in my example?
yeah you can, they are for different situations
you can. .tree.sync() takes an optional guild id argument and if you leave it out you sync commands globally
@wanton current whats the thing for an app cmd tree?
|| talking about umbras cmd ||
ohh
app_commands.CommandTree
It doesn't take an id
!d discord.app_commands.CommandTree
class discord.app_commands.CommandTree(client, *, fallback_to_global=True)```
Represents a container that holds application command information.
isnt it an object with an id? cant remember off the top of my head
A Snowflake is not an id

lemme read up on snowflakes rq
do you have any good suggestions of where to read about them?
It's essentially anything in dpy with an .id attribute
But yeah that's the docs thanks willi
just rechecked after some faffing around with http.request() and realizing i couldnt get the response headers with status 200, but yeah the endpoint ratelimit for my test bot is still 2/30s
Even for global? I sync globally twice and my bot halts the command for like 5 minutes waiting for it
@client.command()
async def sync(ctx: commands.Context) -> None:
synced = await ctx.bot.tree.sync()
await ctx.send(f"Synced {len(synced)} commands globally.")
well is there anything bad with this? i skipped like 90% of the code
@bot.listen()
async def on_member_update(before, after):
staffrole = server.get_role(1155546749117669376)
if staffrole in on_member_update(before, after):
print("All staff have been assigned a team.")
don't know what I did wrong here
AttributeError: 'NoneType' object has no attribute 'get_role'
This syncs globally, so all servers the bot is in will see it's defined global commands
Is it a multiguild bot?
no
What's the server in the code here?
Then you may just want non global commands and syncing
the guild the bot is in
ive set up a variable for it
wonder if you got a different ratelimit, or dpy's waiting longer than usual... let me check with 3 sync calls
Where?
You can't define it before the bot starts running, which I assume you have
Just use before.guild maybe? Since before is a Member object
i think i fixed it since im facing a new error
@client.command()
@commands.guild_only()
@commands.is_owner()
async def sync(ctx: commands.Context, guilds: commands.Greedy[discord.Object], spec: Optional[Literal["~"]] = None) -> None:
if not guilds:
if spec == "~":
synced = await ctx.bot.tree.sync(guild=ctx.guild)
else:
synced = await ctx.bot.tree.sync()
await ctx.send(
f"Synced {len(synced)} commands {'globally' if spec is None else 'to the current guild.'}")
like this?
TypeError: argument of type 'coroutine' is not iterable
if staffrole in on_member_update(before, after):
Again there's a bunch of cruft you don't need here
The spec is unnecessary and the guilds parameter too
This is my fault for spoonfeeding you this code I'm sorry
You cannot call an event callback like this. I'm a bit confused on what you're trying to do?
Im wanting the bot to check whenever someone in the guild receives 'staffrole'
This is the correct event to do so but can you show the full code relating to this error?
@bot.listen()
async def on_member_update(before, after):
server = bot.get_guild(1000824509869346827)
staffrole = server.get_role(1155546749117669376)
if staffrole in on_member_update(before, after):
print("All staff have been assigned a team.")
Hello Link can you help me ?
Why are you calling the function defining this code?
You may just want to check if staffrole in after.roles: or even better, after.get_role(staff_role_id)
I can certainly try, just ask your question
You know selenium ?
This may be the wrong channel for that
Yes i know but what is the channel ?
sorry I don't know ¯_(ツ)_/¯
@bot.listen()
async def on_member_update(before, after):
server = bot.get_guild(1000824509869346827)
staffrole = server.get_role(1155546749117669376)
if staffrole in after.roles:
print("All staff have been assigned a team.")
like this?
Try it :)
such as?
This just means someone with the staff role did any kind of update to their member
What you can do is add an and to this if and check that staffrole not in before.roles
huh, it seems on the second call, my reset-after header jumped to 1min: x-ratelimit-bucket: 3e32a240d3716487d7d8f6dae6c54f6b x-ratelimit-limit: 2 x-ratelimit-remaining: 0 x-ratelimit-reset: 1714515853.730 x-ratelimit-reset-after: 59.538 and when testing with dpy, it slept in the second call after receiving 200, rather than before the third call...
i noticed
i changed 1 command from n4 to join and even tho i used $sync and $sync ~ the /join command still wont appear and the /n4 is still there?
random guess, can you try reloading your client (Ctrl+R) and see if it appears?
where would I add that? after check if they have it?
in the same if statement
ty
i’m going to make a antinuke module in for user apps wish me gl
Dpy sleeps early to prevent the 429, but also handles missing it and skipping to 429 since discord is known for variadic ratelimit
thank you ive done your solution and it worked
Glad I could help
Could you help me with something else regarding to the same thing?
ask away
I need this same command to assign a role to the member that received the staffrole and for it to rotate between 5 roles each time
async def leave(interaction: Interaction):
member = interaction.user
this is how i get member to equal the user's id. how can i make member equal the bot's id?
sounds about right, it just seemed weird for it to sleep on the trailing end of the request before returning... i guess that means the start of subsequent calls will take effect more promptly so it seems more intuitive?
@bot.listen()
async def on_member_update(before, after):
server = bot.get_guild(1000824509869346827)
staffrole = server.get_role(1155546749117669376)
if staffrole not in before.roles and staffrole in after.roles:
print("Staff member has been assigned a team.")
how would I check which user it was the staffrole was assigned to?
after
How can i check for emojis in discord.Message?
For discord emojis, you'd look through the content using an emoji regex, like <a?:(?P<name>[a-zA-Z0-9_]{2,32}):(?P<id>\d+)>
.
nah
Use bin
how
Not Unicode i want PartialEmoji
binhelp
!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.
Command 'tehee' raised an exception: InteractionResponded: This interaction has already been responded to before
https://paste.pythondiscord.com/LVPQ
You can only respond once. If you need to defer, you should use interaction.followup.send after that
@bot.tree.command(name='perfil', description='Olhe seu perfil')
async def estatisticas(interact: discord.Interaction):
name = interact.user.name
user = interact.user
fundo = Image.open("per.png")
tet = Image.open("tet.png")
imagem1 = await user.avatar.read()
icone = Image.open(io.BytesIO(imagem1))
icone = icone.resize((600, 600))
tet_resized = tet.resize(icone.size)
tet_mask = tet_resized.convert("L")
icone.putalpha(tet_mask)
capa = Image.new("RGBA", (1800, 670), (0, 0, 0, 0))
capa.paste(fundo, (0,0))
capa.paste(icone, (100, 140))
draw = ImageDraw.Draw(capa)
fonte = ImageFont.truetype("RobotoMono-Bold.ttf", 20)
draw.text((275, 250), f"{name}", font=fonte)
buffer = io.BytesIO()
capa.save(buffer, format="PNG")
buffer.seek(0)
await interact.response.send_message(file=discord.File(fp=buffer, filename="perfil.png"))```
Why does a png square appear around the circle?
I just wanted the avatar to be in the shape of a circle, I didn't think it would be so complicated...😭
!d PIL.Image.Image.paste - you need to set the mask with your mask image to get rid of it
Image.paste(im, box=None, mask=None) → None```
Pastes another image into this image. The box argument is either a 2-tuple giving the upper left corner, a 4-tuple defining the left, upper, right, and lower pixel coordinate, or None (same as (0, 0)). See [Coordinate System](https://pillow.readthedocs.io/en/stable/handbook/concepts.html#coordinate-system). If a 4-tuple is given, the size of the pasted image must match the size of the region.
If the modes don’t match, the pasted image is converted to the mode of this image (see the [`convert()`](https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.convert) method for details).
Instead of an image, the source can be a integer or tuple containing pixel values. The method then fills the region with the given color. When creating RGB images, you can also use color strings as supported by the ImageColor module.
am I using bot correctly for user apps?
class Main:
def __init__(self, registrate: CommandRegistrate, bot):
self.bot = bot
self.session_manager = SessionManager()
interaction = await self.bot.wait_for("interaction", check=lambda i: i.message.id == follow_up_message.id and i.user.id == interaction.user.id, timeout=60)
I didn't understand correctly, could you explain in more detail? (I'm using the translator)
How can i upload emoji/sticker using https://cdn.discordapp.com/stickers/1175496747712249927.png format
is there way to have sub choices for slash command? so i select choice and new choices related to that choice will appear?
so you want to download a sticker's image and reupload it as an emoji? its a CDN url so you can make a GET request to it with aiohttp without any auth headers or whatever
dpy's sticker objects also have a read method, but its not documented for some reason... you might find that easier to work with but it requires an extra http request: py sticker = await client.fetch_sticker(...) image_bytes = await sticker.read()
for slash commands or select menus?
neither support sub options, but in the case of slash commands you could theoretically return different autocompletion options based on what they selected in a previous option
that actually possible?
i think it might look something like:
https://discordpy.readthedocs.io/en/stable/interactions/api.html#discord.app_commands.Command.autocomplete
https://discordpy.readthedocs.io/en/stable/interactions/api.html#discord.Interaction.namespace ```py
@bot.tree.command()
async def pet(interaction, genus: Literal["Feline", "Canine"], breed: str):
await interaction.response.send_message(f"Details for {breed}: ...")
@pet.autocomplete("breed")
async def pet_autocomplete_species(interaction, breed: str):
genus: str = interaction.namespace.genus
if genus == "":
return [Choice(name="Please select a genus!", value="no-choice")]
elif genus == "Feline":
breeds = ["Ragdoll", "Persian", "Bengal"]
else:
breeds = ["Labrador", "Pug", "Dalmatian"]
return [Choice(name=breed, value=breed) for breed in breeds]```
cant recall if genus would get set to an empty string or None if the user were to try typing in the breed before the genus...
@naive briar hey, you told me to set the mask with the mask image, is that right?
ico.paste(icone, (0,0), mask=icone) I used the command and as expected it gave an error, how should I do what you said?
What's the error?
i tried what you got there but didn't work, so I tried their example:
@app_commands.command(name="fruits", description="Get information about a fruit")
async def fruits(interaction: discord.Interaction, fruit: str):
await interaction.response.send_message(f'Your favourite fruit seems to be {fruit}')
@fruits.autocomplete(name="fruit")
async def fruits_autocomplete(
interaction: discord.Interaction,
current: str,
) -> typing.List[app_commands.Choice[str]]:
fruits = ['Banana', 'Pineapple', 'Apple', 'Watermelon', 'Melon', 'Cherry']
return [
app_commands.Choice(name=fruit, value=fruit)
for fruit in fruits if current.lower() in fruit.lower()
]
but it say this:
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.new_command' raised an error: TypeError: unknown parameter: 'fruit'
a full traceback would be more useful, but im guessing you passed an unknown parameter name in your @autocomplete() decorator?
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.
does your command have a fruit parameter?
oh wait, this snippet was pasted in a cog right?
both methods would be missing self in that context



