#discord-bots
1 messages · Page 117 of 1
I cant answer a question with a yes or no if it cant be answered with a yes or no as it doesnt make sense on its own
You read it
& check if the argument has a mention and boom. That’s your check
I’m not trying to spoon feed. You need to learn how to read the documents and I’m trying to get you to the point where you don’t have to ask these questions.
Try to make a check and tell me where it goes wrong.
I FUCKING READ THE DOCUMENTS YOU ANNOYING ASSHOLE
I’m not going to give you the correct answer, but I’ll help you through it
<@&831776746206265384>
Start by getting your message set…
Once you get your message attribute set, you can then use the .mentions attribute
What tf is a message attribute?
Ctx is your message attribute basically
!mute 269990152368029697 2d This is the second time you've been extremely rude to someone trying to help you. Change your attitude before returning or you'll be banned.
:incoming_envelope: :ok_hand: applied mute to @dapper bluff until <t:1667344270:f> (2 days).
He should learn how to do basic Python and read documents 😅
…but I guess it’s not that basic
Eh, their usecase could be considered semi-difficult
Fair, this case is pretty interesting
From what I gather, they wanted something like: typing.Union[typing.Literal[...], ...]
And then a few if/elifs with isinstance checks
I don’t know why they disliked the idea to type hint it though
He kept saying that it wasn’t what he wanted to do 
Probably because it errors out, and they wanted more of an if/else approach
people tend to like LBYL over EAFP
Most documents may depend on a few paradigms so it's not really basic
Fair, it’s much easier with Union or Literal
right you are
What does LBYL and EAFP mean?
Oh well, in two days we’ll see what he has 
LBYL: look before you leap - traditionally an if/else approach:
can_do_something: bool = ...
if can_do_something:
do_something()
else:
error()
EAFP: easier to ask for forgiveness than permission:
try:
do_something()
except:
error()
ah i see, interesting terms
that's just what they're called ¯_(ツ)_/¯
I've actually never seen the usage of them lol
Not the specific terminology, no. But the concept is quite common
yep
E.g "would it be better for me to use an if/else here or a try/except?"
"Should I use try/except with dict [] notation, or use .get()?"
That's actually a prime example of the difference
I always use LBYL but it always depends on the use case
Do you always raise errors?
I never seem to raise errors
If the operation you want to do doesn't raise errors, then LBYL is the better approach (e.g .get())
It just depends really
Unlike [] notation which does raise errors, where you'd use EAFP
[] doesnt always have to raise an error e.g via indexing
You could probably write __getitem__ in such a way that it behaves like .get(). Probably not recommended, but you can do all sorts of funky stuff
!e ```py
foo: list[str] = ["foo", "bar", "baz"]
if buffer := foo[3:]:
print(buffer[0], "shouldnt")
if buffer := foo[2:]:
print(buffer[0], "yes")
@pliant gulch :white_check_mark: Your 3.11 eval job has completed with return code 0.
foo yes
did an oopsie with my slice but you probably see what I mean
[ ❌ ] Failed to load cog: cogs.user.customizeation
Error log: Extension 'cogs.user.customizeation' raised an error: KeyError: 'serverid'
[2022-10-30 20:10:53] [ERROR ] discord.ext.tasks: Unhandled exception in internal background task 'game_simonsays_creation'.
Traceback (most recent call last):
File "C:\Users\kaelm\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\tasks\__init__.py", line 239, in _loop
await self.coro(*args, **kwargs)
File "C:\Users\kaelm\PycharmProjects\SimonSays\cogs\games\simonsays\gameCreation.py", line 50, in game_simonsays_creation
guild = self.bot.get_guild(int(guild["_id"])) or self.bot.fetch_guild(int(guild["_id"]))
TypeError: '_asyncio.Future' object is not subscriptable```
anyone know why?
TypeError: '_asyncio.Future' object is not subscriptable
ive never seen this error
what is guild?
looks like you're re-assigning
is there any way i can make it so when i do my command ">>avatar @" it can give a download link to the avatar?
fixe
use display_avatar.url
nvm
alr
what will that do?
just return avatar url?
well i wanna try and make it send a download link kinda how it shows display name, seen it before just wondering if its possible
to download the avatar
https://menmenmenmenmenmenmenmenmenmenmenmenmenmen.men/HGq1As53 why is my var none? the guild does exist so. loop ^
fixed by doing guildVar = self.bot.get_guild(int(guild["_id"])) or await self.bot.fetch_guild(int(guild["_id"]))
but now i cant do guild.members i get <discord.utils.SequenceProxy object at 0x0000027FB9177430>
what are you trying to do with guild.members?
if self.bot.user not in guild.members
since i wasnt sure if you can get a guild when not in so was just confirming
copiolet gave me that so might be wrong, i forget if its self.bot.user
i was just testing that to see if it was none or what
my code isnt running at
if self.bot.user not in guild.members
You might want to check the len() of it instead
without any error
just check if guild.me is not None
o
.
one more question
games = await self.bot.database.games.find({"guild_id": guildVar.id, "game": "simon_interactive"}).to_list(None)
check = True
while check:
for game in games:
if game['status'] == 'running':
check = False
break
if game['status'] == 'queueing':
check = False
break
print(5)
if check == False:
continue```
i got this to get all games with the guild ID and game type, im trying to do it if any of them are status = running or queueing, continue the loop (theres a bigger loop that this code is in)
is th ere a btter way to do this as that way dosnt work bc it just while's forever
for guild in guilds
games = await blah blah blah
i need to continue the for guild in guilds loop if one of the two game statuses are true
got it
Hey, I have a question, is anyone familiar with this issue?
my discord bot grabs the role id and saves it into a database.
first message before restart, second message after restart
after the restart the role_id is broken, before its not
https://cdn.discordapp.com/attachments/961280961079836732/1036450771052544070/unknown.png
Hey @young pendant!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
you set a minimum amount of values the user can specify to 5 but you never passed in 5 or more options
I cant find any mistake I have made in the code, it would be nice, if someone could help me
that’s not right because it errors before it even sends the view. look at trace back
I asked him earlier to send his code for the view but he just resent the same img , pretty sure he just copied someone else’s code
also just read that wrong . I see what ur saying now
literally just did a test on my bot and got the exact same traceback setting the min values to higher then the amount of options
since channel.history wont take a timestamp for after/before, anyone know how i can convert unix / timestamp to datetime obj
Hi Guys! Does anyone know a way to check if a user has a role, but with a list of roles?
uh prob a btterway but one way is
check = false
for role in roles
if role in user.roles
check = true
lmao
sure
role_ids = (123, 456, ...)
if any(role.id in role_ids for role in member.roles):
# do something
thank you!!
Usually I'll create a utility function in my projects:
def has_any_role(member: discord.Member, roles: list[discord.Role]) -> bool:
return any(role.id in role_ids for role in member.roles)
The name may clash so you might want to change that if possible
Or just use the built in check if that's desirable
can you help me?
thanks 🙂
Code would be helpful
Hey, I have a question, is anyone familiar with this issue?
my discord bot grabs the role id and saves it into a database.
first message before restart, second message after restart
after the restart the role_id is broken, before its not
https://cdn.discordapp.com/attachments/961280961079836732/1036450771052544070/unknown.png
there
i'm guessing the issue is:
for x in self.roles_of_team[guild_id]:
val = val + f"<@&{x}>\n"
x is a tuple
you could try f"<@&{x[0]}>"
okay, thanks
doesn't work 
@sick birch , its pretty weird, when I type in /change_team_role TEAM
the bot grabs the ID and saves it in role_ids.db
/info https://cdn.discordapp.com/attachments/1006964148296487022/1036465156605083658/unknown.png
restart of bot
/info https://cdn.discordapp.com/attachments/1006964148296487022/1036465437539569714/unknown.png
it's doing this stil with x[0]?
did you replace all instances of x with x[0] or just one?
the only reason it does not ping team is because of this stupid ","
normally the id should be <@&id>
x is a tuple and it's being converted to a string
if id was an actual id, which it's not in this case
async def info(self, guild_id):
embed = discord.Embed(title="Info", color=discord.Colour.from_rgb(64, 118, 227))
if self.roles_of_team[guild_id] != [] and guild_id in self.team_roles.keys():
val = ""
for x in self.roles_of_team[guild_id]:
val = val + f"<@&{x}>\n"
embed.add_field(name="Teamrolle:", value=f"<@&{self.team_roles[guild_id]}>", inline=False)
embed.add_field(name="Rollen:", value=val)
return embed
elif self.roles_of_team[guild_id] != []:
val = ""
for x in self.roles_of_team[guild_id]:
val = val + f"<@&{x}>\n"
print(x)
embed.add_field(name="Teamrolle:", value="keine Rolle festgelegt", inline=False)
embed.add_field(name="Rollen:", value=val)
return embed
you changed x both times, yes?
You need to makesure inside of init_roles that you flatten your record from the SELECT query
self.cursor.execute(f"SELECT id FROM roles WHERE guild_id = {guild.id};")
for role_id in self.cursor:
self.roles_of_team[guild.id].append(role_id[0])
``` Like, can you print `role_id[0]` here?
To make sure it's either not a tuple or is one
Because this issue only happens when you reset meaning it has to be in here right?
yeah, both x changed to 0
what do you mean by that?
little confused
When you restart the bot the issue appears, this mean either you populate your cache INCORRECTLY which causes your roles_of_team to become dict[int, list[tuple[int, ...]]] when you actually want dict[int, list[int]]
The other issue that could be happening is you actually mutating the cache with incorrect data which I don't see from a scan
So your query must've produced a tuple
how do I fix it?
Well first of all confirm it
Just a question, its my first time working with python since one year, what do you mean by print role_id[0]
?
I have not worked with discord.py for one year
@pliant gulch
Just do print(role_id[0]) as what I assume it’ll be a debug.
It’ll give us the first value of role_id in the database
@hollow agate are you still there?
Yep!
I printed the ID of the role TEAM which is not displayed properly after restart
(905095402448101406,)
I`m getting this
if the , would not be there, this bot would work
Ah! Okay
That’s a tuple, you just have to remove it… it’s been a very long time since I’ve done this, so let me eval and test it before giving you a wrong answer 😂
np, thanks for helping me
You’re welcome! Allow me ~10 mins
yeah, no problem
How are you storing the ID?
Maybe it can be easier to remove the tuple from the storing method rather than remove it when we fetch it
Should I send you the code?
Sure!
What line are you storing/committing the ID?
Where do you store the IDs? lol
That commits the creation of the database (i think)
you mean, when I used the /change_team_role command?
Line 100 - 109 is the part where the bot grabs the id from the role
Got it, there can you put a small debug and just print(role.id)?
Along with that, is this what printed when you did print(role_id[0])? (Make sure to include [0])
Perfect, so that's normal
Yep, but after restart, this is not the case
What happens before and after a restart?
Hm
info command is from 119 - 143
I would recommend to fetch it straight out of the database?
the weird thing is, I have a /add_role command for the rollen
Both times, the role twitch mod is being display properly
Okay, welp just do this in the info command
role_id = (905095402448101406,)
a = int(role_id[0])
Just convert the role_id to an int with [0] to forcefully remove the tuple
I lied, do this @young pendant
try:
a = int(role_id[0])
except:
a = int(role_id)```
If it's not a tuple, what I sent previously would've failed
I know it's not the best/most correct solution, but it does work
Where do I put it exactly? @hollow agate
Erm
async def info(self, guild_id):
embed = discord.Embed(title="Info", color=discord.Colour.from_rgb(64, 118, 227))
try:
a = int(self.team_roles[guild_id])[0])
except:
a = int(self.team_roles[guild_id])
if self.roles_of_team[guild_id] != [] and guild_id in self.team_roles.keys():
val = ""
for x in self.roles_of_team[guild_id]:
val = val + f"<@&{x}>\n"
embed.add_field(name="Teamrolle:", value=f"<@&{a}>", inline=False)
embed.add_field(name="Rollen:", value=val)
return embed
elif self.roles_of_team[guild_id] != []:
val = ""
for x in self.roles_of_team[guild_id]:
val = val + f"<@&{x}>\n"
print(x)
embed.add_field(name="Teamrolle:", value="keine Rolle festgelegt", inline=False)
embed.add_field(name="Rollen:", value=val)
return embed
elif guild_id in self.team_roles.keys():
print("just teamrole")
embed.add_field(name="Teamrolle:", value=f"<@&{a}>", inline=False)
embed.add_field(name="Rollen:", value="keine Rollen festgelegt")
return embed
else:
embed.add_field(name="Error", value="Es sind keine Rollen für diesen Server festgelegt.")
return embed```
I think that should work
I didn't try to understand what's going on in the code, but that's the gist
Did it work?
Yeah, the only issue I have is that the bot needs to assign the role TEAMto a user automaticly if the user has the role Twitch Mod the bot does not do this right now but the info command works fine
For this, I would do a loop
Its a bot for Category roles
Team is a category and the twitch mod is a normal role
if user has twitch mod, give him team role
@bot.command()
async def mute(ctx, member:discord.User = None, reason = None, *, time):
time = humanfriendly.parse_timespan(time)
if reason is None:
await ctx.send("Please write the reason!")
return
if time is None:
await ctx.send("Please mention the time like 1d 1h 1m!")
return
if member is None:
await ctx.send("Please mention the member you want to mute")
return
if member == ctx.message.author:
await ctx.send("You cant mute yourself!")
return
await member.edit(timed_out_until=discord.utils.utcnow()+datetime.timedelta(seconds=time))
await ctx.send(f"{member.mention} קיבל מיוט\n סיבה: {reason}")```
```discord.ext.commands.errors.MissingRequiredArgument: time is a required argument that is missing.```
but if i do that time = None so it cant be cuz time is an int so what do i do
Can you explain why you can’t time=None?
cuz then it shows that error
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: expected string or bytes-like object
@hollow agate thanks again, I'll get some sleep now cough 6:30 am here cough
Haha you’re welcome!
Have a good one
You too!
Did you make a if time == None check?
The code will fail if you don’t have that check at the top of the command
That works too
it didnt work
Send the code
@bot.command()
async def mute(ctx, member:discord.User = None, reason = None, *, time = None):
time = humanfriendly.parse_timespan(time)
if time is None:
await ctx.send("Please put the time!")
if reason is None:
await ctx.send("Please write the reason!")
return
if time is None:
await ctx.send("Please mention the time like 1d 1h 1m!")
return
if member is None:
await ctx.send("Please mention the member you want to mute")
return
if member == ctx.message.author:
await ctx.send("You cant mute yourself!")
return
await member.edit(timed_out_until=discord.utils.utcnow()+datetime.timedelta(seconds=time))
await ctx.send(f"{member.mention} קיבל מיוט\n סיבה: {reason}")```
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: expected string or bytes-like object
Put time is None above the time = thing
what
& you have two if time is None:
@bot.command()
async def mute(ctx, member:discord.User = None, reason = None, *, time = None):
if time is None:
await ctx.send("Please put the time!")
return
time = humanfriendly.parse_timespan(time)
if reason is None:
await ctx.send("Please write the reason!")
return
if member is None:
await ctx.send("Please mention the member you want to mute")
return
if member == ctx.message.author:
await ctx.send("You cant mute yourself!")
return
await member.edit(timed_out_until=discord.utils.utcnow()+datetime.timedelta(seconds=time))
await ctx.send(f"{member.mention} קיבל מיוט\n סיבה: {reason}")```
Copy that and it’ll work
You’re welcome :)
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'User' object has no attribute 'edit'
@hollow agate
when im trying to mute
which is weird
oh okay
User is for global things like getting their ID or whatever
Member is for server things like timing them out or editing their roles
You're welcome :)
it would be more correct to do member: Optional[discord.Member] = None or If you don't want to import typing member: discord.Member | None = None (only for python >= 3.10)
could you show your SelectView class
my bad, the Select class
hm
what does the error code mean
you must have atleast 5 options to fulfil the max-values parameter
but in your case you have commented out the other 4
so do i get rid of the # in front of the discord.selectoption
yes
alr i will try
what does this error mean?
can someone please help?
code?
i wonder what would "no such file or directory" mean
@slate swan sent you the code in dms
how do i add the file
that the file you're tryna open doesn't exist
sarth 🛐
@slate swan any fix to it ?
what file is your boost command in?
eevee 
now that depends on what you are trying to do, how would i know
The bot uses slash commands
i tried doing it and it showed so
it has many commands in the main.py but it can't be run
CommandNotFound is raised when a prefix command does not exists
unless you're using some stinky fork
in config.yaml , the prefix is $
and that's what I used
no u
i used a slash commands , it didn't worked , then i used a $ command
i dont see anything wrong
still it didn't work
line 64
what was the errror when you used it as a slash
it responded nothing
long time, how u been
😔 school, high school is nerve-wrecking 😭 you're quite familiar already
well that file does not exist, and your interpreter wont lie
it seems like a logic issue from your side
check if the file exists or not, if it doesnt, make your code do that
?
yeah that sucks, im done with school and took a drop lol
show the boost command code
wtf fr?
😔 sad to know
not only boost , it's happening with every command , al the code of the bot is located in the file I sent you
it does exist
ye it is
didn't you take it this year?
then you entered the wrong path
did and didnt score too well, i was getting some colleges but not a good branch
async def play(ctx: interactions.CommandContext, query: str):
queue = []
if not discord.VoiceClient.is_connected():
await discord.connect()```what's wrong?
module 'discord' has no attribute 'connect'
i think you mean to use <some_channel>.connect
understandable 😔 feels shit
look
thats not how slash command work wtf
pip install pycord
you gotta type / wait for a menu to popup
and select boost from there
!d discord.VoiceChannel.connect you need a VoiceChannel object, you can get it via bot.get_channel(channel_id)
await connect(*, timeout=60.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 "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 "discord.Intents.voice_states").
yes I know it dosent show anything
oh wait that's py-cord
more like cursedcord
@slate swan
but....but....py-cord is love 😭
the menu isn't popping up
right, I'll be off, will complete my episode :pepecry:
are you using bluecord or something by chance
once it pops up , ig il be able to run all commands
bluecord
yeah thats the issue
use the actual discord mobile client
ok
il be in the actual discord mobile Cline tin a min
ah.. can u tell me eg?
im gonna shoot you 
@bot.command(...)
async def foo(ctx: ...):
if not ctx.voice_client.is_connected():
channel = bot.get_channel(channel_id) or await bot.fetch_channel(channel_id)
await channel.connect()
go ahead 😔 living is pointless too
average CBSE student
💀
thank you very much!
i'll try them!
,
import discord
import interactions
bot = interactions.Client("mybottoken")```
discord-buttons-plugin 0.1.2
discord.py 2.0.1
discord-py-interactions 4.3.4
pycord 0.1.1
should i have to delete discord~~?
if not ctx.voice_client.is_connected():
channel = bot.get_channel(channel_id) or await bot.fetch_channel(channel_id)```
this one has the error
Then what's the error
How can I check if the bot gets kicked/banned in a guild?
you can just know if your bot was removed, not if it was kicked or banned
!d discord.on_guild_remove this event
discord.on_guild_remove(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild") is removed from the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").
This happens through, but not limited to, these circumstances...
okay thanks
Does the bot have to be in a voice channel to see others connect and disconnect from it?
no
uhm, so what would I use?
units = pdt.pdt_locales['en_US'].units? I'm not sure that will work
isnt the library documented?
it is
but i have no idea what the heck that is
and how to read that
after seeing this i can gladly say i make good documentation
so minimalistic and beautiful 😻
parsedatetime.pdt_locales.pdtLocale_en
is what you need mb
the heck is this tho?
yeah, that beautiful that I could only find the thing I needed in source code
had to dig a lil bit
yeah, almost
and docs say this
("source code" link)
maybe it's just me dumb
no idea how that works
what is this library meant to do?
parsedatetime :lmao:
I just use it's Calendar
and locales (regret it now)
pep8 loves this library
yes
ok im outta here

wow wtf
same question
there is literally nothing in the __init__.py file of this lib (version, author & license), I might want to rewrite it myself, or it's just going to be a torture lol
me2 :kms:
just write your own library at this point of time
me is 2 lazy for that
ill just edit this shit
if it's even possible...
good luck with that
i mean what on earth is rfc822
it's not on pypi
not in any of my files on my PC
but only in it
how does RoboDanny use this shit
wtf
i just chose it because RoboDanny used it
and it worked
until today, when I switched back to windows
maybe that is the problem
Windows 10 = shit?
bruh, my song in the bg: "You made me a psycho, a psycho"
@slate swan i found a secret way
monkeypatching ?
like, you take a monkey, and it patches your bugs, very cool strategy, you need to try it
rfc822 is only for python 2.x
letss goo
just stop working on that feature, easy
on what feature 
whatever used that library
What are you even trying to do?
The initial action from which this error came is initialising my database
well, I parsed the time arguments with it
in commands like giveaway for example
!pip durations-nlp
!pip time-str
consider these
ok, thx
I will do that later, I'm too tired
actually im not tired I just wanna play my sweet Portal 2
datetime.strftime(format)```
Return a string representing the date and time, controlled by an explicit format string. For a complete list of formatting directives, see [strftime() and strptime() Behavior](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior).
!d datetime.datetime.strptime
classmethod datetime.strptime(date_string, format)```
Return a [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") corresponding to *date\_string*, parsed according to *format*.
This is equivalent to:
```py
datetime(*(time.strptime(date_string, format)[0:6]))
``` [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "ValueError") is raised if the date\_string and format can’t be parsed by [`time.strptime()`](https://docs.python.org/3/library/time.html#time.strptime "time.strptime") or if it returns a value which isn’t a time tuple. For a complete list of formatting directives, see [strftime() and strptime() Behavior](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior).
Because this doesn't use human readable rather a C standard format
it dies
*does
%m %H %I is human readable?
Heres an example from parsedatetime ```py
result = p.parse("tomorrow")
parseDate() is a helper function that bypasses all of the
natural language stuff and just tries to parse basic dates
but using the locale information
result = p.parseDate("4/4/80")
parseDateText() is a helper function that tries to parse
long-form dates using the locale information
result = p.parseDateText("March 5th, 1980")
These are obviously human readable, where as strptime isn't
@silk fulcrum Are you doing py from parsedatetime import pdtLocales or ```py
import parsedatetime
import parsedatetime as pdt
Try the first one I showed
ok, gonna try when get back home
Alright
ofc
thanks for trying to help
then you aren't a human
You must read books entirely in hexidecimal
binary im afraid

Binary is too long so unless you want have a very large book length wise hexidecimal would be better
They both can do about the same thing anyways
I'd much rather prefer to work with hexidecimal rather than binary to store data when programming as well
make your own new computing system
I recently just read:
00110000 00100000 01100110 01100001 01100011 01110100 01110011 00100000 01100001 01100010 01101111 01110101 01110100 00100000 01100001 01101110 01101001 01101101 01100001 01101100 01110011
it roughly translated to:
110000 facts about animals
the fact that you wasted more bytes in sending that message than how much they actually are
class Giveaway(commands.Bot):
def __init__(self, bot):
self.bot = bot
@bot.command()
@commands.has_permissions(manage_channels = True)
async def create(self, ctx, mins: int, *, prize: str):
embed=discord.Embed(title="New Giveaway!")
embed.add_field(name="Prize", value=f"{prize}")
end=datetime.datetime.utcnow() + datetime.timedelta(seconds=mins*60)
embed.add_field(name="Ends At", value=f"{end}UTC")
embed.set_footer(text=f"Ends {mins} min from now!")
my_msg = await ctx.send(embed=embed)
await my_msg.add_reaction("🎉")
await asyncio.sleep(mins*60)
new_msg = await ctx.channel.fetch_message(my_msg.id)
users = await new_msg.reaction[0].users().flatten()
users.pop(users.index(bot.user))
winner = random.choice(users)
embed2 = discord.Embed(title="Winner!", description=f"{winner.mention}")
embed2.set_thumbnail(url=winner.avatar_url)
embed2.add_field(name="Prize", value=f"{prize}")
embed2.set_footer(text="Giveaway Ended!")
server = ctx.message.guild
await ctx.send(f"{winner.mention}", embed=embed2)
await winner.send(f"You won the giveaway in {server.name} !")```
```discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: create() missing 1 required positional argument: 'mins'
and i did mins]
the
discord.ext.commands.errors.BadArgument: Converting to "int" failed for parameter "mins".
heck is this
what
giveaway system
why are you passing a bot instance to a Bot object?
the
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot 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
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
It looks like you need to convert what the user inputs into an integer. Just because it's numbers doesn't mean the program sees it as int
Are they enabled on the developer portal and do you have intents specified in your code?
And does the bot have proper permission in the server
yup theyre enabled on portal
what intents have to be specified?
Whatever it needs for your situation
Depends on what you need
hello , how to create an ephemeral message ? i tried
@bot.command()
async def message_invisible(ctx):
print("running")
await ctx.
send("Text", ephemeral=True)
but it doesn't work :/ it displays running but that's it
Slash commands are better anyways imo
you can send ephemeral messages only while responding to an interaction (eg. you're in a slash command, user command, message command, button callback, modal callback, select callback function body)
Like autocorrect for your bot lol
tbh i dont even know what intents are, im kinda new to them. they got added in between my discord.py hiatus and all my bots died a tragic death
so how do i do that ? i'm not familiar with discord API :/
Read the docs link at the bottom here it should help you understand intents
intents are sort of permissions that you have to ask to Discord to let your Bot use certain APIs endpoints
you need to transform your prefix command to a slash command
what library are you using
import discord
from discord.ext import commands
import os
from PIL import Image
from random import *
When the
This doesn't tell what library you are using, might be discord.py 1.7.3, might be discord.py 2.x, might be disnake[discord], might be pycord
Rip
Use pip freeze and see
i'm pretty sure its discord.py
What version of dpy
the latest one
ok so
Do pip show discord.py @drifting cypress
TypeError: __init__() missing 1 required keyword-only argument: 'intents'
not sure what intent i need
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot 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
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
it shows a lot of numbers but the first one is 20.0.2
It should be labeled
wth 20.0.2
He's from the future
try to do print(discord.__version__)
1.7.3
send what you've done so far
if im trying to print a list of all users in my server, how do i exclude all bots ?
not just the bot in which im executing the cmd
cool, you need to update the lib to a version >= 2
ik its something simple, but idr the right wording
oki , thx
just dropped those in the code block in my bot's code
the command is pip install -U discord.py
As expected
id_list = '\n'.join([f' - **{m.name}** *({m.id})*' for m in ctx.guild.members if m != ...])
send the code
and it says im missing intents from an __init__()
whats the correct ending to that...
k
You didn't pass the intents into the intents argument
What exactly are you trying to achieve
import discord
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
client = discord.Client()
client = commands.Bot(command_prefix=">", intents=intents)
@client.event
async def on_ready():
print("{0.user} is online!".format(client))
to print a list of all ids and names of users in the text channel
i alrdy got it working, im just trying to filter bots
Why tf you have 2 clients, remove the first one
Why are you having both Client and Bot
Then it's if not m.bot
💀
ah...
Done , so now i can use interactions ? how do i do so ?
alr got rid of the top one
cheers, nice easy fix for once lol
still bugged because a bot that worked perfectly fine a year ago has to be broken as hell now
Because everything get updated
0.0
Downgrade dpy and it will work fine, but many features will be unsupported
guys I use disnake so I can't help you more than that with slash commands, 
well yeah but ive been struggling with my limited knowledge of python and very limited brain power to get this thing online
Extend it and it'll be easier for you to understand all this and get help
If dpy 1.7 was relatively ok for beginners, 2.0 is totally not beginner-friendly
hellnah
If you are looking to work with interactions in my opinion the most beginner friendly library is Disnake
Agreed
🦶
it's still on alpha
its a VVIP package
oh
talking about slash commands
gimme some slash command implementation ideas for my wrapper 
is it a discord api wrapper?
yeah
You need sync methods or event processing or smth (slash commands are done through gateway right?)
slash commands can work thru both gateway and rest ( because they are part of the interactions )
you recieve a "INTERACTION_CREATE" payload if you're using gateway
Imo 2.0 makes more sense than 1.7 but I also wasn't making bots in 1.7
Ah yes that's what I thought
im talking about the command constructor tho, like discord.py implemented CommandTrees which people dont seem to prefer
What don't people like about command trees?
Personally I would just put them all together, fetch list of current commands, compare them and sync ones that were updated
its just redundant
one reason for that can be it gives better control
i mean it would if i understood it
but again, disnake provides full control with the basic bot class only too
Yea kinda but I prefer redundant lmao. From the little bit of disnake api that I've looked at it looks more user friendly on the code side
i think the major benefit of the command tree is code decoupling from the client, but of course lib users dont care about that
async def message_invisible(ctx):
print("running")
await interaction.response.send("Text", ephemeral=True)
still not working with / prefix :/
ephemeral responses can be created only for interactions
Changing the prefix won't make it a slash command
you dont even have interaction defined there
There's some changes you need to make to convert it to a slash command
how do i create a slash command then ? 😭
🤓
i googled it and it says discord.py does not support slash commands
There's some helpful resources. it's a handful of things you need to change
Outdated
I find it annoying that that forum still comes up as top result in a Google search
I was going to send it
If I seperate my stuff out into cogs, I'm assuming anything that uses a view needs that view to be in the same cog right?
thats upto you, personally i keep things that do same kind of thing in single cog independent of the features they use
So I could have my views in one cog and the command that uses them in another without troubles?
in theory yes, but you should take care when referencing things from other extensions, particularly making sure they're loaded
if you dont think you'll need to hot-reload your view classes, you can put them in a regular module (.py) and import it in your extension
I was planning to put everything into regular modules and import them into the main file, so I should also import them into the other cogs that will use pieces of it is what you're saying
yeah thats fine
Alright. Wish me luck lol I'm sure everything is going to go exactly as planned 
ayo disnake worked
it is certainly supposed to, why wouldn't it 💀
cuz discord.py didnt
in what way huh
couldnt figure out intents
could have asked here, or just used !intents 
more like disnake has the same class for intents 💀
intents in both the libraries are accessed in the same way
¯_(ツ)_/¯
done it 180,000 times lol
disnake seems to be easier for beginners/low skilled programmers (me lol) and more akin to the older version of discord.py i used to use
in discord.py the intents kwarg is now required
disnake doesnt do that maybe
as my bot gets more complex i'll prolly move back over but for now this is fine
I mean...... 💀
tbf the point of requiring intents= is precisely to inform you of its existence
disnake is just a fork anyways
right
and breaking bad tutorials, so you bot never runs until you apply your brain
disnake is literally a fork, I don't see how's it "easier" to use
youtube tutorials 🛐
does disnake have a warning for starting a commands.Bot without message_content?
a.doesnt require intents
b. worked for my bot
yeah
yep, warnings in disnake are really nice from what i have seen
pip install discord discord.py discord.py-interaction discord.ui py-cord nextcord disnake[discord] 
oh yeah they went hard on those warnings
https://github.com/DisnakeDev/disnake/blob/v2.6.1/disnake/ext/commands/bot_base.py#L154-L162
disnake/ext/commands/bot_base.py lines 154 to 162
warnings.warn(
"Message Content intent is not enabled and a prefix is configured. "
"This may cause limited functionality for prefix commands. "
"If you want prefix commands, pass an intents object with message_content set to True. "
f"If you don't need any prefix functionality, consider using {alternative}. "
"Alternatively, set prefix to disnake.ext.commands.when_mentioned to silence this warning.",
MessageContentPrefixWarning,
stacklevel=2,
)```
disnake[discord] is another cursed name to write
who suggested that after all
it means install disnake with discord requirements
ew
just like discord[voice] works
!pip discord-disnake
installs this package alongside
cursed
https://pypi.org/project/discord2 cursed you say?
the sequel
thats just pycord under the hood
unruly 😭
I don't remember how many times you've said the same thing 💀 pricks every time
the love for pyc0rd it eternal
weird
you should study really 💀
lmao thanks for reminding i have 2 mock tests on 6th
average JEE aspirant
self.bot
thanks
@bot.command()
@commands.has_permissions(ban_members=True)
async def ban(ctx, member:discord.Member=None,*,reason=None):
if not member:
await ctx.reply("בבקשה תתייג מישהו!")
return
if member.top_role >= ctx.author.top_role:
embed3=discord.Embed(color=discord.Colour.red(),
title="Ban System", description="למשתמש יש גישות מעלייך, לא אפשרי לתת לו באן!")
await ctx.reply(embed=embed3)
return
await member.ban(reason=reason)
await ctx.reply(embed=discord.Embed(title=f"{member.name} קיבל באן \n איש צוות: {ctx.author.name}", description=f"סיבה: **{reason}**"))
@ban.error
async def ban_error(ctx, error):
if isinstance(error, commands.CheckFailure):
await ctx.reply("אין לך גישה לתת באן..")```
and if someone that his role is higher then me trying to ban me it says error
```discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
like how do i do that if the bot has perm then the bot can ban not the member
did you enable ban permissions on discord developer?
yes
i wanna do that if the bot has perm to ban then it will not the member
Check that the bot has the permission in your sever settings, and that the bot has a role higher than the member you are trying to ban
like
I think the role hierarchy affects it
Ah, I see, I just skimmed your message and read the error
when i am trying to ban someone that his role is biggeer then mine it sent but if his role higher then my it shows the error
Then his role is probably higher than the bot's
yeah I didn't
and when someone that his role higher then me AND higher then the bot so it shows that error
Nextcord better
You could add checking for that missing permissions error in your handler
@ban.error
async def ban_error(ctx, error):
if isinstance(error, commands.CheckFailure):
await ctx.reply("אין לך גישה לתת באן..")
elif isinstance(error, commands.MissingPermissions):
await ctx.reply("no perms")
Is that Hebrew?
¯_(ツ)_/¯
(╯°□°)╯︵ ┻━┻
🧢 nextcord for life
Where do you live?
Bro 💀 that's so random 🤣
bruh I just wanna go to your place and talk
Anyway how far you squirt
Let's keep it civil and random personal questions are weird.
lol
Whatever that was, it's not appropriate.
Water guns are inappropriate?
its funny tho
true
This is a Discord bots channel. Please stay on topic.
I live in Ohio
Are overrated self bots >>>
from discord.ext import commands
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
@bot.command()
async def test(ctx):
await ctx.message.reply("test")
bot.run("tol")
I hope that works
I'm on my phone rn so I cant check
class SlashBot(commands.Bot):
def __init__(self) -> None:
super().__init__(command_prefix=".", intents=discord.Intents.default())
async def setup_hook(self) -> None:
self.tree.copy_global_to(guild=discord.Object(id=12345678900987654))
await self.tree.sync()
bot2 = SlashBot()
@bot2.tree.command(name="ping", description="...")
async def _ping(interaction: discord.Interaction) -> None:
await interaction.respond("pong",ephemeral=True)
When i use the ping command i have the following error :
discord.app_commands.errors.CommandNotFound: Application command 'ping' not found
but if i remove the "ephemeral" part it works , but i'm trying to get it to reply with an ephemeral message , anyone have a fix for that ?
Can anyone tell me how to get server list
Thru jishaku
from nextcord.ext import commands
bot = commands.Bot(command_prefix="!", intents=nextcord.Intents.all())
@bot.command()
async def test(ctx):
await ctx.message.reply("test")
bot.run("tol")
What package are you using?
Looks like discord.py, but Interaction objects don't have respond methods
Can anyone tell me how to get server list
Thru jishaku
yea its discord.py
Interaction objects don't have a respond method. To respond with a message, you use interaction.response.send_message()
don't know why you didn't get an error for that
already did that but got the same error , i'll retry just in case
yep , still getting the same error
did you run() your bot2 afterwards? CommandNotFound would imply that your ping command wasnt correctly synced with discord
ok umm i can't get discord.py/disnake on my laptop because it says I have to get VisualStudio 14.0. Do I have to?
it works on my PC
yep , at the end of the code bot2.run(TOKEN) but also running bot.run(TOKEN)
Can anyone tell me how to get server list
Thru jishaku
only one of those lines will work, since run() is a blocking method
jeez
i want to know the jsk command
Which will return all the servers list in which my bot is
Jsk kinda new 4 me
jishaku doesnt have a dedicated command for that, but you can evaluate python code with jsk py, giving you the _bot variable to access your bot instance
if you want to run both bots on the same event loop, you could write a single main function and start both using gather(): ```py
async def main():
async with bot, bot2:
await asyncio.gather(
bot.start(...),
bot2.start(...)
)
asyncio.run(main())```
so there's no way i can have command (bot = commands.Bot(command_prefix=PREFIX, description='',intents=discord.Intents.all()) and slash (bot2 = SlashBot()) at the same time ?
do you actually need both bots though?
or rather are you using the same token for bot and bot2?
not really XD just trying to learn discord's API and trying to include as much as possible
yes
then you dont actually need bot2
oki thx
jsk py
e = []
for guild in bot.guilds:
try:
if guild.owner.id not in e:
e.append(guild.owner.id)
except:
pass
await ctx.send(f'{len(e)}/{len(bot.guilds)}')
This is my cmd in jsk but the bot wont reply
e = []
for guild in bot.guilds:
try:
if guild.owner.id not in e:
e.append(guild.owner.id)
except:
pass
await ctx.send(f'{len(e)}/{len(bot.guilds)}')```
did you include your bot's prefix in front of jsk?
and jishaku specifically provides the _bot variable, the leading underscore is necessary
Ohh k
use filters
@cedar smelt i just saw your bio, im trying to use flask with vue, can you help me?
jsk py
e = []
for guild in bot.guilds:
try:
if guild.owner.id not in e:
e.append(guild.owner.id)
except:
pass
await ctx.send(f'{len(e)}/{len(bot.guilds)}')```
you wanna check how many unique guild owners you bot has>
How can i check if a role already exists on a server, and if it exists the bot moves it on top of all the other existing roles and add it to the user who used the command
!d discord.Guild.roles check if the role is in the list
property roles```
Returns a sequence of the guild’s roles in hierarchy order.
The first element of this sequence will be the lowest role in the hierarchy.
and if it exists the bot moves it on top of all the other existing roles and add it to the user who used the command
bot can move roles only till its top role, not above that
yo
some guy told me its better to use / prefix
instead of "!", is that true ? for a discord bot
Slash commands have extra features that text commands don't
Like autocompletes or ephemeral response
I mean yeah or you could use hybrid commands if you use discord.py
Dont, theyre annoying to invoke over using actual slash commands
Hello!
I am making a discord bot with cogs:
Code:
class Owner(commands.Cog):
def __init__(self, bot):
self.bot = commands.Bot = bot
times = datetime.now()
embedcolor = 0xf47fff
def owner(ctx):
perms = json.load(open('modules/assets/config/perms.json'))
return str(ctx.author.id) in perms["OWNER_ID"]
@commands.slash_command(description="Gives a target staff")
async def givestaff(self, ctx, target:discord.Option(discord.Member, "Who am I making staff?")):
if not owner(ctx):
embed=discord.Embed(title="Insufficient perms", description="It seems you don't have permissions to use this command", color=embedcolor, timestamp=times)
await ctx.respond(embed=embed, ephemeral=True)
else:
pass
But if not owner(ctx) + embedcolor + times
Is error saying it is not defined... How would I fix that?
All the methods in the cogs need to take self as the first argument, and you would reference it as self.owner(...)
i heard that discord was only making people use / commands
what are hybrid commands
class Owner(commands.Cog):
def __init__(...) -> None:
...
def is_owner(self, ctx: commands.Context) -> bool:
...
@commands.slash_command(...)
async def givestaff(self, ...) -> None:
is_owner = self.is_owner(...)
for instance
(this was meant for @slate swan )
Hey quick question
guess this is kinda like a command but, im doing a on message event and need to check if the message is something like "simon says change your status to {online/dnd/etc}. How do i
- do the check for the multiple statues of online, dnd, etc
- check what one they choose
i could just do a bunch of elif status to online, etc but itheres prob a btter way
thanks i fixed it!
also by any chance is it possible to prevent my code from creating a __pycache__ folder when I run my bot?
the easiest way i can think of is split it by spaces and get the last word
status = text.split(" ")[-1]
as the name says it combines two prefixes one is slash and the other is whatever you want
hey!
I have a command
perms["STAFF_ID"].append(......)
How would I make a command that removes there id from that .json file?
thanks
async def unban(ctx, *, member):
banned_users = ctx.guild.bans()
member_name, member_discriminator = member.split('#')
for ban_entry in banned_users:
user = ban_entry.user
if(user.name, user.discriminator) == (member_name, member_discriminator):
await ctx.guild.unban(user)
await ctx.channel.send(f"Unbanned: {user.mention}")
im getting an error in this code
File "c:\Users\foodi\Desktop\DiscordBot_Files\discord_bot.py", line 63, in unban
for ban_entry in banned_users:
TypeError: 'async_generator' object is not iterable
why?
async for ban_entry in baned....
line 3 ctx.guild.bans() must be awaited
heyyyyy, asher
tired, now I'll head out
addios
bai bai
dont use lucas unban cmd
@bot.tree.command(name="clear", description="Clears number of messages")
@commands.has_permissions(manage_messages=True)
@app_commands.describe(amount = "Please put an amount to clear")
async def clear(interaction: discord.Interaction, amount : int):
await interaction.channel.purge(limit=amount)
await interaction.response.send_message(f"{amount} messages cleared.")```
```discord.app_commands.errors.CommandInvokeError: Command 'clear' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
what do i do instead of interaction.channel.purge then
Your interaction took too long to respond
Defer the interaction and respond with a followup

!d discord.InteractionResponse.defer
await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
This is only supported with the following interaction types...
interaction.response.send_message instead of that
like it is clearing the messages
but not showing the message
Thank you one more question
What about “Simon says set your custom status to (x)”? Since I can’t get the last word if it’s a sentence
!e ```py
sentence = "Simon says set your custom status to (x)"
print(sentence.split()[-1])
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
(x)
Is it just me not understanding questions or it's that hard to understand
use the -1nth index
!e ```py
sentence = "Simon says set your custom status to this won’t work"
print(sentence.split()[-1])
@indigo pilot :white_check_mark: Your 3.11 eval job has completed with return code 0.
work
lol
!e
print("hi")
!e
class Questions(commands.Cog):
def __init__(self, bot: commands.Bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
print('Soru yüklendi')
@commands.command()
async def sync(self, ctx) -> None:
fmt = await ctx.bot.tree.sync(guild=ctx.guild)
await ctx.send(f'Synced {len(fmt)} commands.')
@app_commands_command(name="Daneme", description="soru sor oruspu")
async def questions(self, interaction: discord.Interaction, question: str):
await interaction.response.send_message('Sonunda başardın 2 gündür dc.Py eğitimi alıyorsun cahilsin')
async def setup(bot):
await bot.add_cog(Questions(bot), guilds=[discord.Object(id=1023275954388336660)])
.so discord.py slash command
Here are the top 5 results:
how do i make a slash command be avilable only to a perm
@app_commands.has_permissions(manage_messages=True)``` ?
.remove(value) or .pop(index)
anyone know how i can do this?
Sarth answered that question
well that dosnt work as i shown below lmfao
@bot.command()
@commands.has_permissions(ban_members = True)
async def ban(ctx, member: discord.Member, *, reason = None):
await member.ban(reason=reason)
ban = discord.Embed(title=f":hammer: Banned {member.name}!", description=f"Reason: {reason}\nBy:{ctx.author.mention}")
await ctx.message.delete()
await ctx.channel.send(embed=ban)
await member.send(embed=ban)
im writing this code rn but im only able to ban someone by mentioning them. how can i make it so that there are multiple ways to ban them, whether by mentioning them, writing down their name, or copying their discord ID?
here is the code.
@app_commands.has_permissions(manage_messages=True)``` ? for slash commands?
That should work tho
Are u getting any errors while trying to do it with the id?
nuke can u help?
it might be app_commands.checks.has_permissions
why, does that code there not work?
which code ? also thanks!
i want to make it so that just writing chillman would ban them
the code u sent
and no it doesnt work
??
I said you took too long to respond
^
error?
!d discord.Guild.get_member_named
get_member_named(name, /)```
Returns the first member found that matches the name provided.
The name can have an optional discriminator argument, e.g. “Jake#0001” or “Jake” will both do the lookup. However the former will give a more precise result. Note that the discriminator must have all 4 digits for this to work.
If a nickname is passed, then it is looked up via the nickname. Note however, that a nickname + discriminator combo will not lookup the nickname but rather the username + discriminator combo due to nickname + discriminator not being unique.
If no member is found, `None` is returned.
Changed in version 2.0: `name` parameter is now positional-only.
whats the thing to wait again, async.wait(5)? i forget
await asyncio.sleep(5)
and why dont u use slash cmds
it handles that for u
ah thanks
File "C:\Users\dynam\Documents\predictor\main.py", line 20, in <module>
tree = app_commands.CommandTree(client)
File "C:\Users\dynam\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\tree.py", line 134, in __init__
raise ClientException('This client already has an associated command tree.')
discord.errors.ClientException: This client already has an associated command tree.
PS C:\Users\dynam\Documents\predictor>```
umm
yo quick one more question, how do i check a members status and custom status?
ohh
!e ```py
sentence = "Simon says set your custom status to this won’t work"
print(" ".join(sentence.split()[7:]))
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
this won’t work
u need to make a task loop
like
!d discord.Member.status for online idle etc
property status```
The member’s overall status. If the value is unknown, then it will be a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)") instead.
yeah that works, thanks
!d discord.Member.activities for playing , custom activities etc
The activities that the user is currently doing.
Note
Due to a Discord API limitation, a user’s Spotify activity may not appear if they are listening to a song with a title longer than 128 characters. See GH-1738 for more information.
ah ty
code: https://paste.pythondiscord.com/haxivizuqo
Can someone help me please?
The bot already has a tree
commands.Bot has a commandTree assigning by default
if member.status == discord.Status.online:
this is right, right?
yes
ah thanks
Okay, but the only way @tree.command is not an error is when I have treeapp_commands.CommandTree(client)
Once I remove that @tree.command is an error
use @bot.tree.command
I'm using client
client.tree.command then
error?
edited.
It works but the slash commands don't show up
you gotta sync your commands too
!d discord.app_commands.CommandTree.sync
await sync(*, guild=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Syncs the application commands to Discord.
This also runs the translator to get the translated strings necessary for feeding back into Discord.
This must be called for the application commands to show up.
I wanna make the bot my own way
im like practicing coding
ah
yea
does that also use the discord ID?
How do I do that the docs confuse me
bot.tree.sync
!d discord.Guild.get_member if u want with id
get_member(user_id, /)```
Returns a member with the given ID.
Changed in version 2.0: `user_id` parameter is now positional-only.
nope
where do I put that?
!e
user = bot.get_user(986703977313865838)
user.activities
@indigo pilot :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'bot' is not defined
ok i dont know how this bots eval works just ognna ask lmao
does this just return a str of there status? or
since its all activiies, for playing, watching, etc im not sure
I have a column in a database table that is type json, would it be better to use Postgres's built in functions for making changes to the json or importing the json object to python and making my changes there?
Sounds like a #databases question to me.
!d discord.Activity list this object
class discord.Activity(**kwargs)```
Represents an activity in Discord.
This could be an activity such as streaming, playing, listening or watching.
For memory optimisation purposes, some activities are offered in slimmed down versions:
• [`Game`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Game "discord.Game")
• [`Streaming`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Streaming "discord.Streaming")
what if it isnt a game th o? a normal users discord status isnt anything
its a custom activity object then
!jsk py
guild =_bot.get_guild(811284392156725339)
a = guild.get_member(842859032628822057)
abc = a.activities
abc.name
oops
so how would i fit banning by ID into my command?
@commands.has_permissions(ban_members = True)
async def ban(ctx, member: discord.Member, *, reason = None):
await member.ban(reason=reason)
ban = discord.Embed(title=f":hammer: Banned {member.name}!", description=f"Reason: {reason}\nBy:{ctx.author.mention}")
await ctx.message.delete()
await ctx.channel.send(embed=ban)
await member.send(embed=ban)
why does this not work tho
what are the erros
discord.ext.commands.errors.MemberNotFound: Member "chillman" not found.
but if i tag them like @hard seal
You should use a converter if you're using discord.py
memberconverter?
mention and id should work, name not tho
id doesnt
Forget about what I have said
wait id worked
but i want it so that it bans by name
.
It can accidentally ban someone with the same name
how do i incorproate that into my code
well yeah but i just want to add that j in case
i would help u but i gtg
its ok ill figure it out
hey, if I want to upload text to a free online source like pastebin and then be able to edit it with a python script. any suggestions for what I could use?
does the pastebin have an API?
well then you can read the pastebin first, then create a new one with edited content
thats all you can do
i have something else reading the pastebin so I cant rlly
well then use a pastebin that allows you to edit the content lol
im trying to send a discord inv created from a bot to a twitch overlay.
I thought the best way would be to upload the inv to a text host and just add that as a browser source for the stream
its literally a single line of text though 🥲
Why not store it locally then
use a gist
cause its someone elses stream
"stream"?
twitch stream overlay
that looks promising. thanks
whenever i use
\033[39m when i open the program it just does ←[39m
Does anyone know a fix to this?
the unicode for ansi is \u001b
what does that mean?
is it a bad idea to use os.stat on File to get file size?
is it a heavy blocking call?
it's the escape unicode character. It's what you use with ansi, that's what you want to achieve right?
I just want it to be colorful
shouldn't be the case
what should be colourful?
the text
I have a print statement
print("\033[39mRunning")
but thats what is shows
oh, then use the colorama module
then you'll have to use the escape character (\u001b) to get the ansi formatting
it's unicode, you literally just copy and paste that to the left of the opening bracket
doesnt work.
does this still
fwiw 39 won't get you anything either
it gives white
it's 40-47 for background, and 30-37 for foreground
then why bother using ansi? Printing normally will get you the same result




0
29
1
python, discord, nextcord