#General Help
1 messages ยท Page 12 of 1
yes
Cant find what i needed, I am trying to make a bot stats command basicly, but dont know how id get the amount of servers its in, the ping ect
^^^
thx
servers: len(bot.guilds)
ping: bot.latency
ty, Where would i find more infomation on this for other aspects of it such as non related bot info but server info like member count server name ct
ect*

uhh
are you looking for a server info or bot info command?
or both
both
you gotta realise you have to read the docs and create a template for it like an embed or a string with the info
I know, I just dont know what part of the docs to check
thats all im asking
well look through the docs and see if you can find what you need
also yeah that exists
lets say i want the guilds's profile
if you can't find something then ppl can help here
you kinda just search, read a bit and go "is this what i need?" and then try it out. You gotta read it carefully and try to understand the info it tells you. Theres multiple ways of doing something
@bot.command()
async def stats(ctx):
await ctx.send('My ping is bot.latency')
It just sends it as a normal message not showing its ping, adding it as {bot.latency} dosent change it
needs to be an f-string
f'{bot.latency}' btw
await ctx.send(f"My ping is {bot.latency}.")
b!rtfm pyc icon_url
ok nvm
cuz in dpy u have
message.author.avatar_url
but thats not a thing in pycord
i tried searhcing for an alternative
avatar.url
but pycord only got .avatar
is that a thing?
yes
yea nvm
xd it happens
avatar is https://docs.pycord.dev/en/master/api.html#discord.Asset which has a url attribute
oh alr thanks
dont wanna be mean but try looking into: https://www.w3schools.com/python/
Im sorta new to python but i actually struggled 60% way less due to checking this out for a bit and looking at the examples
agreed, its best to learn python before jumping straight into a not so easy library
Yeah, I dont mind but i agree foolish can seem insulting xD
alright
thanks
we're happy to help you learn but its always better to try learning the language
doesnt't works
discord bot making is fun but no need to run before you crawl
what doesnt work?
^^ gotta be a bit more specific than that
it isn't showing anything
is this right btw
@gilded widget since it seems u know what ur doing
you have to round it
is it possible that the bot responds to a slash command while pinging the user
await ctx.respond('๐ Pong! ' + format(round(bot.latency, 1)))
list_of_files = []
for i in range (0, 8):
list_of_files.append(discord.File(f"image_{i}.jpg", filename=f"image_{i}.jpg")
await ctx.channel.send(files=list_of_files)
Thanks
Thanks
might not work 100% but should be close
._.
code?
wait
@bot.slash_command(guild_ids=guild_id)
@option("fds", description="Choose if the user have to get upranked or downranked", choices=["uprank", "downrank"])
async def rankfgh(ctx, member: Option(discord.Member)):
moderator = get(member.guild.roles, id=896705950742880310)
await member.add_roles(moderator)
await member.edit(nick=f"ในใซใตใใ | {member.name}")
channel = bot.get_channel(937062067825942549)
embed = discord.Embed(title=f"{member.name}", color=0x3264a1)
embed.add_field(name=f"{member.name} is now a mod", value="cvb")
await channel.send(embed=embed)```
add this around it
```python
code
```
done.
hm
btw
i have a balance command
currently it is run by doing /bal or ?bal
however i want to run by /balance or ?balance as well
is it possible to do this in a quick and clean way
without having to copy paste the code and make it from bal to balance
i tried making it so name = 'bal' or 'balance' but that doesnt work i guess
set your option like this:
@option("fds", discord.Member, description="Choose if the user have to get upranked or downranked", choices=["uprank", "downrank"])
and the function signature:
async def rankfgh(ctx, member: discord.Member):
@gilded widget py if get_images_from_backend(prompt): list_of_files = [] for i in range (0, 8): list_of_files.append(discord.File(f"image_{i}.jpg", filename=f"image_{i}.jpg") break await ctx.channel.send()
This isn't right, right?
bridge
was there an error?
Concept
in other words?
you didnt add the files to the send but otherwise it should work?
Cause the loop hasn't been break, ctx.send comes under it right?
It's saying invalid syntax for break.
Nothing...
if you want another way you can try this
yes, not sure why you'd need a break statement, get rid of that?
@bot.slash_command(guild_ids=guild_id)
async def rankfgh(ctx, member: discord.Option(discord.Member),fds:discord.Option(str, 'fds', choices = [discord.OptionChoice(name="uprank", value="uprank"),discord.OptionChoice(name="downrank", value="downrank")])):
pass
oh wait you want both options
yes
yeah you shouldn't and im not sure if you can crossmix the option types
not what i meant but still helpful
for example
didnt you want slash and prefix command?
i want /bal and /balance to do the same thing
yeah looks like you want aliases
works thanks
^^
you cant do that with slash commands
alias is the word
true
unless you create a different command with the same code
can i do it with normal ones tho?
is the await in a async function?
prefixed? yes
how
Yes
are you sure you indented it right?
async def dallemini(ctx, prompt):
await ctx.respond("Please wait... โณ/nIf it doesn't upload your images then something went wrong, in that case, try again in some time.", ephemeral = True)
if get_images_from_backend(prompt):
list_of_files = []
for i in range(0, 8):
list_of_files.append(discord.File(f"image_{i}.jpg", filename=f"image_{i}.jpg")
await ctx.channel.send()
when you define the decorator for the prefix command put aliases=[your aliases here] in the decorator
bad habit tbh
and use bridge_command
yea ik it is thats why i asked
but sometimes u gotta do what u gotta do
trust me lmfao
@desert dagger
i once wrote spaghetti code then had to refactor it 3 times
i mean whats an alternative
does the console say anything specifically?
and how can i do "if uprank ..."
Just this
one sec
okk
i dont really see a syntax error
can you change files=list_of_files to something like "test" then run code
The whole code.
i guess u gotta use ctx.reply or ctx.respond
or else ull have to do ctx.message.channel.send i think
I don't think that will make a difference
?
idk i might be trippin
No, default ones run fine with pycord
whats the error?
...
if fds == "uprank"??
ok this might be hard to answer
but either way
is there a way for the bot to recognize that a command has been typed
for example
i currently have an event listener that adds xp to the user on_message
however this doesn't work with slash commands
since slash commands dont count as messages
how can i overcome this?
you probs could just add it in the code or use a custom event
how
thx
When I remove for loop for files it works.
is there an on_command thing or what
alright
so something is not right with the loop
oh wait
on_application_command and on_application_command_completion
why do you loop thru 0,8?
there is also on_interaction
mhm
Cause there are 8 files, tho I didn't baronkobama wrote
yeah
maybe try adding a print to see whats stored in the array
alright
I can't run the command until that error ah
@gilded widget
Can you help?
why this no work
ctx.message.created_at.second
AttributeError: 'NoneType' object has no attribute 'created_at'
its here tho
Why am i getting, Unknown event GUILD_APPLICATION_COMMAND_INDEX_UPDATE.
@bot.command()
async def ping(ctx):
await ctx.send(f'My ping is ' + format(round(bot.latency, 1)))
Is it possible for the builtin autocomplete to ONLY show Threads?
or am I hard-stuck on ALL channels?
Did it give the roles?
Is it possible to manually create a command using initialising, not through the decorator
yes
because you NEED to respond to the command.
Then add await ctx.respond('I have given the roles')
or whatever msg u want
^^^
anyone know?
need more information than just that.
but the embed isn't sending too
I gave the code and the error, what more do u need lol
Try change channel.send to ctx.send
what does format() do?
no because it have to be in channel
the format is adding the latency im p sure
await ctx.send(f'My ping is {round(bot.latency, 1)}')
its still going to send in that channel
try this instead.
alr
What is it with ".joined_at"
If i ping a user (with the command, everything works fine and i am able to access .joined_at. however if i use the command with a ID, i am able to access every other attribute in the video except ".joined_at"
you are misusing format (hence why I asked)
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: can only concatenate str (not
"float") to str
are you sure you are using the line I send ? ๐ค
Yeah
otherwise add str() around the round()
1 sec
it really shouldn't need that, but ๐คท
Thanks, It worked without this part just messed up a bit lol
let me guess, you still had the + in? ๐
yes xD
async def get_images_from_backend(prompt):
async with aiohttp.ClientSession() as cs:
async with cs.post(backend_url, json={"prompt": prompt}) as r:
rjson = r.json()
if r.status_code == 200:
json = rjson
images = json["images"]```
```py
Traceback (most recent call last):
File "/home/runner/Quasar-1/venv/lib/python3.8/site-packages/discord/bot.py", line 993, in invoke_application_command
await ctx.command.invoke(ctx)
File "/home/runner/Quasar-1/venv/lib/python3.8/site-packages/discord/commands/core.py", line 357, in invoke
await injected(ctx)
File "/home/runner/Quasar-1/venv/lib/python3.8/site-packages/discord/commands/core.py", line 134, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: FileNotFoundError: [Errno 2] No such file or directory: 'image_0.jpg'````
What would i do to make the bot delete '!say Hello' once its sent the message
What's wrong here?
Do want a timer? like deleting it after 2 secs when send?
Just want to delete after the bot sends the input
await ctx.send('Hello', delete_after=2)
wouldnt this just delete after 2s, and not after its sent
you want to delete it instantly?
basicly yeah
await ctx.message.delete()```
Add this after ctx.send
alr
async def say(ctx, message):
if ctx.author.guild_permissions.administrator:
await ctx.send(message)
await ctx.message.delete()
else:
await ctx.respond('You do not have the correct permissions for this')``` dosent seem to delete tho
So i'm working on github for now and I have this piece of code which half my discord bot depends on (it gives the code access to the project files to find a specific json file). This piece of code currently doesn't work because I'm running it with github (heroku) and I don't know the github file path. so my question is: what is the github file path.
Ahh
await ctx.send('Hello', delete_after=0.1)```
just do this
Would this still work if i had it as, await ctx.send(message, delete_after=0.1)
cause its not hello im sending, Its the input after !say
Yes, it should
Alright
I mean it works but it deletes the bots message instead of the members
Oh you wanna delete the authors message?
yeah, sorry
How would i do that?
is it like ctx.author.delete or smth?
This should have worked, what error did it gave?
No error, It works but deletes the bot message instead of the authors
@slender lintel
Trying doing this
await ctx.message.delete(ctx.message)
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Message.delete() takes 1 positional argument but 2 were given
Dosent delete it
await message.delete()```
do this, don't add ctx
that's what I told at first. They said it isn't working
I changed it back to this, then gave the bot admin to see if thats the issue now if i do !say Hello it will say Hello then if i do !say Hi it will say Hi Hello
Whys it saying all the messages??
idk
bruh
what's the problem?
Ill show you what im trying to do
ok
async def say(ctx, message):
if ctx.author.guild_permissions.administrator:
await ctx.send(message)
else:
await ctx.respond('You do not have the correct permissions for this')```
I want the !say (message) to delete after the bot sends the input
doesn't ctx.message.delete work?
ye it does
?
It deletes the bot's message, I want to delete the members command
You were told
no, do it before you send the bot message
@slender lintel did it work?
Nope dosent delete it
async def say(ctx, message):
if ctx.author.guild_permissions.administrator:
ctx.message.delete()
await ctx.send(message)
else:
await ctx.respond('You do not have the correct permissions for this')```
does the bot have the permisison to delete messages
add await before ctx.message.delete
Its got admin
alr
This deletes it but its back to sending multiple messages so Hi Hello
Like it keeps sending forever?
ill show u 1 sec
async def say(ctx,*, message):
```Do this too
it wasn't that you told me but thanks for trying to help me
It was kind of me.. but sure
Send the traceback for it.
i whas to stupid to name a variable the same that i wrote it
do you have a bot.event detecting a message containing "hi"?
Your command is like an echo command.
How can I delete all but two roles not?
I dont
Correct
How it sends 'Hi' and "Hello", when you didn't used 'Hi'?
Exactly, I typed !say hi then it sends
Hi
Hello
Hi
hello
Bruh wth
that's weird
:(
@bot.command()
async def say(ctx, *,args):
if ctx.author.guild_permissions.administrator:
await ctx.send(args)
await ctx.message.delete()
else:
await ctx.send("You do not have the correct permissions for this.")```
Change your code to this and try again.
remove all roles from a user but only two roles not
'Args is not defined'
remove all roles and then add those two roles
replace args with message
async def say(ctx, *,args):
``` did you do this?
yes
Just copy paste what I sent above
nvm
im dumb it changed cos ctrl z
xD
:|
worked or not?
Thanks! After all this its worked xD
await member.remove_roles(member.roles)
theoretically i think that will work
then you can add the other two after you want to
doesn't works
async def dm(ctx,member: discord.Member,*, message):
if ctx.author.guild_permissions.administrator:
await member.send(message)
await ctx.delete()
await message.respond("I have dmed them!", ephemeral=False)```
How would i delete the !dm (user) (message) for this one? It keeps not working on every one lol
probs bc member.roles is a list
What is a Github repository's file path? (i'm using os.chdir("FILE_PATH") to give a file access to a json file)
@sleek grove remove the everyone role then try removing all the others w the previous code
anyone know?
i don't know what you mean
every user has a hidden 'everyone' role, remove that and then remove others w your code
amay work
try await member.remove_roles(member.roles[1:])
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'respond'
@bot.command()
async def dm(ctx, member: discord.Member, *, message):
if ctx.author.guild_permissions.administrator:
await member.send(message)
await ctx.send("I have dmed them!")
await ctx.message.delete()
should work
didnt work
this is the same isnt it
isn't working
Thats not deleting it though...
oh
only user sees it i didnt notice u set to true
Ill give that a try
hm i go to bed bb
bye
Why whenever i add the else:
await ctx.respond('You do not have the correct permisisons') it always gives me error expected expression
File "C:\Users\jackd\Documents\Felbcord Py\main.py", line 53
else:
^^^^
SyntaxError: invalid syntax
@slender lintel
I dont get the 'I have Dmed them'
but it does dm
think this cld be bc when the dm is sent then the ctx is taken as being in the users dm so you may want to find a way to ensure that the 'i have dmed them' is sent in the orginal channel e.g using its id
or you could change the order around
Traceback (most recent call last):
File "C:\Users\jackd\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 344, in invoke
await ctx.command.invoke(ctx)
wym?
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'respond'
this too
probably wrong but ctx informs of the channel and what not but it might be that when the dm is sent then the ctx changes to the user's dm rather than original channel so then the 'ctx.respond' won't work as desired. like i said i am 85% sure what i'm saying is wrong but a theory xd
alr
im dming my alt with it so i know if it goes wrong
if being interpreted the positive indicator of 'i have dmed them' cld be given and then the actual sending of dm cld fail
surely
im trying now
anyways whyilst i'm here, how can i take in '1d' as two separate arguments e.g. '1' as a single and 'd' as another
dosent dm anymore
instead of havinf to type '1 d'
yh so error is with the respond i ebelive then
Would changing it to ctx.send work?
@slender lintel may not b exactly what you want but maybe try and ephermal message of 'user.mention +{message} with ctx.send
ygm
I was using slash commands but then i thought it may be better using normal commands (no idea why), Should i be using slash?
import re #if you haven't already
separated = re.split("(\d+)", "1d") #replace "1d" with your variable
alright ty
Nah luckily i just spammed ctrl z XD
Btw, Why do sometimes my slash commands just disappear?
And i need to restart the bot for them to re-appear
is it an issue on my side or a discord issue or what?
sometimes every slash command for every bot disappears so i reload discord for that
Probably just my discord bugging out then :(
bye
probably discord bugging out. Discord bugged out for me a few moments ago so it might be a problem with a discord server (not the server you chat in)
or it might be that you bot got run twice and ended up registering 2x commands
happens to me alot
I restarted my bot and it seems to be fine, May just be my discord bugging out Again
ye
Also do you know how i would have a different line in my message so, ```@bot.slash_command(name="ping", description="Info about bot")
async def ping(ctx):
await ctx.send(f'My ping is ' + format(round(bot.latency, 1)))
The i want to have like another line for my amount of guilds but it would give errors, is there a way to do it so itll have another line when sent
ty
What do i do to get the other type of /
like what on my keyboard lol
isn't there one above the enter key?
thats backspace
if you don't find it, you could just do Ctrl+C or Ctrl+V
you prolly have a different keyboard layout
yep
is there a key next to your Z? (on the left)
Oh yeah i see that
\
ooh ty
to save stuff use Ctrl + S
@bot.slash_command(name="ping", description="Info about bot")
async def ping(ctx):
await ctx.send(f'My ping is ' + format(round(bot.latency, 1))
what did i mess up there it says ( is not closed
nvm fixed it lol
One message removed from a suspended account.
you can make them persistant
?tag ex
Bot examples: https://github.com/Pycord-Development/pycord/tree/master/examples
Slash command/context menu examples: https://github.com/Pycord-Development/pycord/tree/master/examples/app_commands
Buttons, dropdowns example: https://github.com/Pycord-Development/pycord/tree/master/examples/views
One message removed from a suspended account.
I think so
how do i give my bot an about me?
set an application description in the dev portal
ty plun
Since the current version of jsk doesnโt support pycord, canโt I just downgrade a version till it works with pycord?
I use jsk and it does support it.
how would i make commands server only rather than dm/server?
getting same error with PycordUtils as well
ImportError: cannot import name 'PartialMessageable' from 'discord.channel'
why this no work
ctx.message.created_at.second
AttributeError: 'NoneType' object has no attribute 'created_at'
https://docs.pycord.dev/en/master/api.html#discord.Message.created_at
its here tho
message does have a created_at attribute
then why is it saying ctx.message is nonetype
Can you show your code
@bot.listen()
async def on_application_command(ctx):
if ctx.author != bot.user:
user_egg_id = ctx.author.id
if bool(mongo.users.find_one({'user_id':user_egg_id})) == False:
mongo.users.insert_one({'user_id':user_egg_id, 'balance':0, 'xp':10, 'level':1, 'last_message':ctx.created_at.second, 'employment':"unemployed"})
event listener that looks for slash commands
if a slash command is entered and its the users first time using a slash command
it creates a new database entry in mongodb
the database entry includes many properties but the issue i have is with the 'last_message'
i want it to record when the slash command was used
and hence ctx.created_at
File "C:\Users\jackd\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 993, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\jackd\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 354, in invoke
await self.prepare(ctx)
File "C:\Users\jackd\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 285, in prepare
self._prepare_cooldowns(ctx)
File "C:\Users\jackd\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 270, in _prepare_cooldowns
raise CommandOnCooldown(bucket, retry_after, self._buckets.type) # type: ignore```
Whys my bot sending the command cooldown error to console and not chat?
@commands.cooldown(1, 300, commands.BucketType.user)
async def say(ctx, message):
if ctx.author.guild_permissions.administrator:
await ctx.send(message)
else:
await ctx.respond('You do not have the correct permissions for this')
@bot.event
async def on_application_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
await ctx.respond(error)
else:
raise error```
my slash commands are disappearing after using once
does someone know what could be the problem
your event decorator is inside command
you need to put it outside
wym?
@bot.slash_command(name="say", description="Repeats input")
@commands.cooldown(1, 300, commands.BucketType.user)
async def say(ctx, message):
if ctx.author.guild_permissions.administrator:
await ctx.send(message)
else:
await ctx.respond('You do not have the correct permissions for this')
@bot.event
async def on_application_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
await ctx.respond(error)
else:
raise error
this is how it should be
Alr
whats ur code
its big can't share here
the start of the command ur talking about
@core.slash_command(name="confess")
@commands.cooldown(1, 30, commands.BucketType.user)
async def confess_slash(self, ctx :discord.ApplicationContext):
"""Confess to your heart's content '-'"""
modal = confess_modal(self.bot)
await ctx.send_modal(modal)
i dont think im qualified enough to ans i guess
guys, is it possible to subclass Bot and define slash commands inside this subclass?
https://guide.pycord.dev/popular-topics/subclassing-bots
I tried to follow this guide, but it seems the command isn't registered
Subclassing is a popular way of creating Discord Bots. Explore how you can create a Discord bot by subclassing.
i think so but it isnt recommended in any way, shape, or form
ok, sad
as I understand, preferred way to do something like this is to create a cog subclass and create a bunch of slash commands inside it using @commands.slash_command
after that you can just load this cog using bot_object.load_extension(f'cogs.{your_cog}')
is this correct?
this is the most common way to do it to organize commands into sensible groups
sometimes you dont need all this and you just simply require a @bot.slash_command decorator in the main file
in my opinion, cogs are too powerful to use it just for just one slash command
at the same time, I want to have opportunity to do something like:
from custom_bots import RoleBot
bot = RoleBot()
bot.run('TOKEN')
hence why i mentioned this
I understand, but, eh
changing behavior of an object is a bit strange for me
prefer to work with classes
ok, summing up, I need to use cogs, if I want to get some kind of modularity
?
yes
thank you
dont forget to read up on cog documentation so you know how to make and load one properly
had read this thing
https://guide.pycord.dev/extensions/commands/cogs
Cogs, often known as modules or extensions, are used to organize commands into groups. This is useful
yep thats good
i think a week?
understood; thank you again for the explanation
its a discord thing btw if you were wondering
this looks the same as my current code
https://guide.pycord.dev/getting-started/rules-and-common-practices/#subclassing
in that case, somebody must delete or edit this paragraph, lol
All about the rules and common practices for coding a Discord bot
i meant making commands in subclasses of bot
?
you need an error handler
this is the only thing that is described as "good practice" in the guide
this is not a claim to you, but to slightly crumpled docs
also your error handler definition is inside of a function
might wanna remove a few levels of indentation
i do
i think
async def on_application_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
await ctx.respond(error)
else:
raise error```
ook
How do i fix this? My cooldown is having the cooldown on every guild so, for eg i have a cooldown on my test server and its the cooldown on my actual one too
like it isnt seperate cooldowns
b!rtfm pyc ApplicationContext
discord.ApplicationContext
discord.ApplicationContext.bot
discord.ApplicationContext.cog
discord.ApplicationContext.command
discord.ApplicationContext.delete
discord.ApplicationContext.interaction
discord.ApplicationContext.invoke
discord.ApplicationContext.respond
discord.ApplicationContext.selected_options
discord.ApplicationContext.send_modal
show entire code
Ig buckettype.user will have a cooldown on that user for all guild 
quick question: i am using alpha version, whenever changes in the code has been committed in repository, do they update automatically in my pc too? or i need to update it
then what?
i tried applicationcontext.interaction
but to no avail
@lucid cove i restarted it a lot of times but it still doesn't work
maybe you are multihosting
idk then it used to happen to me
and you dont notice
i just restart the bot and its fine
ok
nope i checked it
no
you mean restart the server?
yes
quick question: i am using alpha version, whenever changes in the code has been committed in repository, do they update automatically in my pc too? or i need to update it
not working..
idk then
have you tried ctx.interaction.message?
yes its a nonetype
try store the respond message to var, then var.message?
but the processes that my code is doing are supposed to be on_message
in other words if i take var.message.datetime it would already be too late
cuz i have to wait for the bot to reply first before doing anything with the code
anyways i think i'll just skip cuz i think there is no solution to this issue
moving on
im trying to implement buttons
and i get this error
_tkinter.TclError: unknown option "-label"
for this
btn1 = Button(
label = "lorem ipsum",
style = discord.ButtonStyle.primary
)
fixed now ?
well first you have to fix the event indentation
Pepega
It's from a video it's right
Most probably not, you'll need to update it manually
I remember seeing the github files for this bot and I saw a restriction on it being used outside of PyCord
so i think you can't rly use it outside this server
So why not make it private 
guess i'm wrong then
Is there a way to set the online status of a bot (the Online, DND, Away, Invisible thing, not the custom playing game status)
use bot.change_presence and use the status parameter
i.e. bot.change_presence(status=discord.Status.idle)
How would I set my bot to a database so it remembers roles
Is there any tutorials
The basic is pretty much the same as how to make a crud
Theres a ton of tutorial of making a crud on yt
alr ty
is this good
Yes ig
is it confusing to make a database
No, you can learn the basic mysql
On w3
is that hard
https://brucedev.medium.com/storing-data-in-python-discord-bots-discord-py-pycord-d370689624b is this good too
You are making a super cool Discord bot, and now you need to store data. You probably tested out tutorials for storing data in JSON filesโฆ
its a different database
yo is there a way to make interaction.response reference the user / message
Good for learning yes
for learning, wym?
just use mongodb
does that work w pycord?
that shouldnt matter
yes it does
but u should ask does it work with python not with pycord
ook
ok so I tried to create a new thread but discord threw a pissy fit and errored like 6 times then ratelimited me for 5 minutes but anyway
I think group commands (text-based) are completely broken
I think the logic that is being used for slash groups is being applied to regular text-based group commands. See below example:
from discord.ext import commands
class ExampleCog(commands.Cog):
def __init__(self, bot: commands.Bot):
self.bot = bot
@commands.group(name="foo", cls=commands.Group) # I tried the cls= to see if it would fix the issue. Spoiler alert, it didn't.
async def foo(self, ctx):
await ctx.reply("foo")
@foo.command(name="bar", cls=commands.Command) # cls= doesn't fix here either
async def foo_bar(self, ctx):
await ctx.reply("bar")
def setup(bot):
bot.add_cog(ExampleCog(bot))
Trying to bot.load_extension(ext) yields this:
Traceback (most recent call last):
File "C:\Users\Nexus\PycharmProjects\bumpr-v6\venv\lib\site-packages\discord\cog.py", line 715, in _load_from_module_spec
spec.loader.exec_module(lib) # type: ignore
File "<frozen importlib._bootstrap_external>", line 883, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "C:\Users\Nexus\PycharmProjects\bumpr-v6\cogs\main.py", line 12, in <module>
from .queue import Job
File "C:\Users\Nexus\PycharmProjects\bumpr-v6\cogs\queue.py", line 112, in <module>
class QueueCog(commands.Cog):
File "C:\Users\Nexus\PycharmProjects\bumpr-v6\venv\lib\site-packages\discord\cog.py", line 251, in __new__
parent = lookup[parent.qualified_name] # type: ignore
KeyError: 'queue'
(Error traces back to the bottom of this function in cog.py: https://h.nexy7574.cyou/pkKtU88f39.py)
I re-installed pycord from git, same issue
Actually should i open an issue on github for this
You seem to be massively naive about the difference between sql relational and nosql databases, saying one is trash is completely false
For more advanced things, you almost have to use relational databases, NoSQL is good for very small, flat data
thats the exact reason i said sql is trash
How exactly is it trash?
So what is the best database for me to use?
guess hastes are dangerous now
It depends on your use-case, but ignore "bRUH", he doesn't know what he's talking about
alright
You could give SQLite a stab
by use case what do u mean by that?
alr, aiosqlite?
Like what you're trying to do @slender lintel
Yeah, that will run async
Like i wanna save roles for eg a mute command i dont want them to bypass by leaving then joining
i wanna save roles
(don't use the sqlite3 module that's built in to python, it'll block your event loop)
If you're just storing a few roles for a mute command, you might not even need a database
You're the one throwing a hissy fit but okay
Like if the amount of data you're storing is very small, like < 100 elements, you can probably just store it locally in a json file tbh
well eventualy it would be more than that, just dont know what yet
Your lack of understanding of it doesn't make it ass, if you took more than 30 seconds to learn how it works you'll realise how naive and dumb you're being
Thanks but im going to listen to skeeza.
It's very easy to store a file with 100 discord ids now, so why not try that and if/when things require growth you can look into databases
How would i store it with discord ids?
(if you're using JSON don't forget all keys have to be strings, so enjoy repeatedly casting)
You can do something like this:
import json
# Save
with open('discord_ids.json', 'w') as file:
json.dump(file, <data>)
# Then when you want to load it
with open('discord_ids.json', 'r') as file:
data = json.load(file)
so id put the bottom code below each command needing it, and is there somewhere i can learn more about this to understand it better?
You'll probably want to have a function that saves and loads the id, but you can load it on startup and attach it to the client object
You can do something like this:
import json
# Then when you want to load it
with open('discord_ids.json', 'r') as file:
data = json.load(file)
client = discord.Bot(...)
client.muted_people = data
<command to mute people>
client.muted_people.append(<new_person>)
# Save
with open('discord_ids.json', 'w') as file:
json.dump(file, client.muted_people)
If you look up loading and saving with json in Python you'll most likely find something online
so for
oops
didnt mean to enter lol
No worries
so for example,
async def mute(ctx, member: discord_member, reason)
await member.add_roles('rolename')
bot.muted_people = data
with open('discord_ids.json, 'w') as file: json.dump(file, bot.muted_people)
Try this:
bot = discord.Bot(...)
with open('discord_ids.json', 'r') as file:
bot.muted_people = json.load(file)
@bot.slash_command(name="mute", description="e")
async def mute(ctx, member: discord_member, reason):
await member.add_roles('rolename')
bot.muted_people.append(member.id)
# Save
with open('discord_ids.json', 'w') as file:
json.dump(file, bot.muted_people)
Would i add the #save part below each command needing to store data
If you're ever updating the list, you'll want to update the list in memory (the bot.muted_people) and the permanent list, for when the bot gets restarted or dies (in the file, the json.dump bit)
wym? (sorry)
You're storing a list in 2 places, once permanently (in the file, which will be stored on your computers storage) and one for easy access, in memory, which is the variable (bot.muted_people)
The bot.muted_people list will get cleared when the bot dies right? Since it's just a variable, which is why we store it in the file, but to access the file everytime is slow and bad, so we keep a handy list in a variable
alr
Wouldnt this raise bot object has no "..." attributes"?
What would i have to do to connect to a youtube channel? like i want to create a /ytsearch command to search for any youtube channel total views, subs ect
or just one particular channel if i cant do any
probs search for the youtube api if it exists
also
Think they have the official api
how can i move commands that accept arguments to different files
Cogs
is it legal to do something like this? (the last line disturbs me)
class CustomCog(discord.Cog):
bot: discord.Bot
async def some_stuff(self, ...):
...
def __init__(self, bot, *args, **kwargs):
self.bot = bot
self.some_stuff = self.bot.listen('on_ready')(self.some_stuff)
Yeah don't do that
I'm a little unsure about what you're asking, so this may be completely wrong, but you might be looking for
if __name__ == "__main__":
<code>
@deep timber
Why does this happen (It happens no matter what im installing)
pip isn't listed in the PATH
How would i fix that?
Try python -m pip install <package>
Yeah ive been usin that instead, dont know if theres any disavdamtages to it
no, vs code
I want to run the bot. After that, anytime I run test.py, the test function will run and a notification will be sent.(not to run the bot again and not to do anything)
well replit itself is the disadvantage
oops i misread the text LOL
lol
Im using the youtube data api to get youtube channels total veiws subs ect
?
lol
should I do this if I want some_stuff to be done when self.bot gets on_ready event?
class CustomCog(discord.Cog):
bot: discord.Bot
def __init__(self, bot):
self.bot = bot
@discord.Cog.listener("on_ready")
async def some_stuff(self, ...):
...
What is some_stuff, but probably yeah
Just set a boolean for if on_ready has fired before
Since it can run more than once
stop
I know about that
but can't understand a point to create a flag
CustomCog will create views, which can live longer than a bot session, what's why I'm trying to do this
body of some_stuff function, defined inside of CustomCog
Yeah no shoot haha
summing up, this should work, right?
friends how to take a parameter with slash?
can you show the full code used
well it says line 51
yes but it doesn't really help
no never.
Basically, my other repl got found. The bot was token logged & the person started pinging everybody in my announcements channel. So i've had to fork it to another account & I reset the token. I've also changed the token in the code. Before, all this code was working, but now that i havetransferred it to the new account, i seem to be getting this error.
[found out it was a server admin]
can you show just in case
this was all working before
uhh, the import?
yes
uh....
now this is strange
that looks like pyscript to me
no, im using pycord
pycord is a package
ah but
im using python
so youre probably right
but im not sure what these errors are
ยฏ_(ใ)_/ยฏ
could somebody please help me
as soon as i transfer it to another acc
im getting all these errors
which means it cant be a problem with the code
but a problem with the libraries or smthn
hey?
someone
pls
;c
i mean... it's pretty hard for us to troubleshoot stuff hosted on replit because the user lacks control
How can you download files (ex. recorded voice channel) to local storage? All the examples I see just upload them to a discord channel
Attachments: https://docs.pycord.dev/en/master/api.html#discord.Attachment.to_file
voice: might need more context
can you show your code?
I was following this: https://guide.pycord.dev/voice/receiving/
Pycord tries to keep the recording of audio as simple and easy as possible, to keep making Discord
specifically
files = [discord.File(audio.file, f"{user_id}.{sink.encoding}") for user_id, audio in sink.audio_data.items()]
this you can upload in a channel using something like await channel.send(f"finished recording audio for: {', '.join(recorded_users)}.", files=files)
but I would just like to save the files to local storage
hmm hold on
Hey so ive connected the youtube data API to my code but how would i make a slash command find any channels stats?
ok i think i got it
in this case, audio.file is a bytes object; to save it to a file, we open the file we want in bytes mode, i.e. py f = open("path/to/audio.format", "wb") f.write(audio.file) f.close()
await def ytsearch(ctx, channel)``` So what would i add after this? Channel meaning the channel name to find stats for
Th yt api is confuising me
Hey u got any idea about my issue above?
https://developers.google.com/youtube/v3/quickstart/python might be a good place to start
this example follows requesting a channel's info
thanks
;c
await def ytsearch(ctx, channel)
await ctx.channel.respond(channel.list)``` Is this right? I am having trouble understanding it
I want to set a custom asyncio event loop.
discord.Client has an attribute for it but ext.commands.Bot does not. how can i set one for commands.Bot?
ahh I see thanks!
it should? commands.Bot inherits from discord.Bot which inherits from discord.Client
e
i think you skipped a couple steps... navigate to the code sample the page tells you about and review it
alr
Should it be a gitihub page?
github*
no it's on the site
Its showing request stuff and thats just confusing me, I just want it through a slash command
i couldnt find on docs but if i can set then np
also im actually trying to run bot on a multiprocessing process which doesnt want to work (no event loop in thread-2) so i tried to give it a loop
which actually still didnt change anything
it tells you how to get there
- Go back to the documentation for the API's channels.list method.
https://developers.google.com/youtube/v3/docs/channels/list- In the "Common use cases" section, click the code symbol for the first listing in the table.
Its making it into a slash command thats confusing me tho
well you need to understand how to even make the request before using it in a slash command
extra info:
when creating bot, in init, i passed in loop=asyncio.new_event_loop()
and its still the same error
well yeah i watched a video on it, I understand it but dont understand the slash command side
what in particular? it shouldn't be that different
after the await def ytsearch((my args))
then is it like request = or ctx.respond(request=)
idk what your ytsearch function does
but you're looking for ctx.respond
which generally takes a string, an embed, a file or whatever else
I am trying to search for any channels stats
so what does ytsearch return
It would be an regular message with the subs and total veiws of requested channel
so you should assign that to the variable instead
e.g. result = await ytsearch(...)
then you can await ctx.respond(result)
so then must i do the request but instead of request = its result =
alright
await def ytsearch(ctx, channel):
result = await ytsearch(...)
await ctx.respond(result)``` this right?
your original await def ytsearch((my args)) wouldn't be valid code, because def is used to define a function
oh
I havent defined it anywhere else/inside a different command
How do I create a paginated embed?
use the pages extension https://guide.pycord.dev/extensions/pages/paginator-basics
Should i send my entire code, But for the unrelated parts?
and id remove api key
sure
print(sys.version)
import discord
from discord.ui import Button
from discord.ext import commands
import logging
from googleapiclient.discovery import build
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('discord')
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')
handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
logger.addHandler(handler)
bot = commands.Bot(command_prefix='!', intents=discord.Intents.all(), debug_guilds=[965533467557371944,933803468815204372,964126154774679582])
@bot.event
async def on_ready():
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name='Over The Felbcord'))
print('Connected to bot: {}'.format(bot.user.name))
print('Bot ID: {}'.format(bot.user.id))
api_key=(my api key is normaly here)
youtube = build('youtube','v3', developerKey=api_key)
@bot.slash_command(name='ytsearch', description ="Finds yt stats of channels")
await def ytsearch(ctx, channel):
result = await ytsearch(...)
await ctx.respond(result)
``` The rest of the code, the code i removed was mostly just commands not related to this
@crimson coral
how do i get discord.ext.pages?
from discord.ext import pages
async def ytsearch(...) outside the command, and remove the await def ytsearch(ctx, channel): line
await def ytsearch(ctx, channel):
result = await ytsearch(...)
await ctx.respond(result)``` so this?
oops
async def ytsearch()
result = await ytsearch(...)
await ctx.respond(result)```
sorry that one i meant
is that correct
again, define it outside of the command
you don't want to recreate the function every time someone uses the command
@bot.slash_command(name='ytsearch', description ="Finds yt stats of channels")
result = await ytsearch(...)
await ctx.respond(result)```
close enough, just... make sure you actually write the rest of the function
Wym? what else should i add?
is it possible to make a slash command arg disabled for a specific occasion?
don't think so
hm
is it possible to change the input type depending on the value you put in the arg before the arg you want to change the input type in?
nope
Yeah, am i right i need to add the channel.list stuff
the best you could do is some manipulation with autocomplete to check previous args
im confused sorry
all good
is it possible to make so autocomplete doesn't work and it doesn't send the "no options" thingie to discord?
autocomplete results aren't enforced, they can ultimately input anything they want in there
but that's the closest you can get to the behaviour you want
alright, thank you
is this right?
all good
well just give it a try and see what happens... i guess
why do i now think im doing it wrong :/
well you gotta try first
ImportError: cannot import name 'PartialMessageable' from 'discord.channel' (C:\Users\petru\Desktop\Simple-Scoreboard-Main-v1\.env\lib\site-packages\discord\channel.py)
i broke it
I have another question, if you set the input type to int, can there be made exceptions so you can also put a specific string too?
you've mixed multiple libraries together, uninstall any discord-related libs (pycord, dpy, disnake etc) and reinstall py-cord==2.0.0rc1
nope
discord didn't design slash commands/options to be flexible across types like that
yeah...
working, thanks
all good
I'm guessing the latest library is not compatible without slash commands?
Sori but i suggest you learn the basic for this language first
W3 a great free resource for learning it btw ^
But if prepared to pay would recommend the Udemy course Python zero to hero by Jose Portilla or something like that
tbh, if you don't wanna do courses, because i sure as hell didnt, just start with small projects
make small little things and use your resources to understand things
if that doesnt work though courses are a good way to understand it
How to get bot in flask server
True, hands on learning is amazing
Read part 3 of this.
I'm not sure why you would want to do this unless you are transferring the bot to repl.it or something.
It is not necessary to have flask and uptime robot if you are running it on your own PC or other server that does not go offline after x amount of inactivity.
Parth 3 of that ^
I just need to pass the bot from main somehow
I dont think you want to have the from main import bot. That leads to circular imports causing problems
And you can pass it through the function?
The more complex way to fix it is by putting all the code in main into a function and doing
if __name__ == __main__:
myFunc()
Outside the function at the bottom of the file.
I'm not super familiar with how it works so that the best I can give you. :/
I just want to work with the bot through the site.
if i want to run flask and discord bot at once, can i not multithread the discord bot and have to multithread flask?
Hi
i need help with a userinfo command, buttons
Error: ```py
File "c:\Users\darkm\OneDrive\Desktop\Skyler v1\cogs\miscellaneous.py", line 32, in b3_callback
await interaction.response.edit_message(embed=more)
NameError: free variable 'more' referenced before assignment in enclosing scope````
b3 = Button(label="More Informations", emoji="")
async def b3_callback(interaction):
await interaction.response.edit_message(embed=more)
b3.callback = b3_callback
view = View()
view.add_item(b3)```
you need (content=embed)
A okey
Thanks
await interaction.response.edit_message(content=more)
NameError: free variable 'more' referenced before assignment in enclosing scope
What? They're sending an embed, why would it be sent as content?
Share your code.
b3 = Button(label="More Informations", emoji="")
async def b3_callback(interaction):
await interaction.response.edit_message(content=embed)
b3.callback = b3_callback
view = View()
view.add_item(b3)
more = discord.Embed(
description=
f"""
>  *3*User Name:**_ _ `{user.name}#{user.discriminator}`
>  **User ID:**_ _ `{user.id}`
>  **Status:**_ _
>  **Join position:**_ _ `{str(members.index(user) + 1)}`
>  **Account Created:**_ _ <t:{round(user.created_at.timestamp())}:R>
>  **Joined Server:**_ _ <t:{round(user.joined_at.timestamp())}:R>
>  **Roles:**_ _ [0]
>  **Emojis:**_ _ [0]
>  **Emojis Animated:**_ _ [0]
""",
color=0xed455b)
more.set_thumbnail(url=has_avatar)
more.set_footer(text=f"{user.name}#{user.discriminator} || {user.id}")```
Do you realise that you're creating the embed after the response and not before
why do i get an error that create_text_channel is not defined
nvm im dumb
wait no its not working still
b!rtfm create_text_channel
I couldn't find a documentation with the name create_text_channel! Maybe you used to command wrong? Correct Usage: <prefix>rtfm <docs> [<term>] (eg. b!rtfm py cool)
List of Documentations you can search:
python
pycord
discord.py
yarsaw
nextcord
disnake
b!rtfm pyc create_text_channel
Read the docs.
How do you prevent Greedy from trying to get members from a word without a tag, like I use greedy to get members for massban, and it keeps getting members from the reason
What's Greedy
How can i make that only author can use a button?
I've tried this out, and it's not working
audio.file is a discord.sinks.core.AudioData object
it seems to have a write method, but I can't figure out how to use it
not what I was looking for... this is weird
I would download the file from the message that it sends, but if the file is too large it won't be able to send in the first place
yes
the problem is in the channel.send() method you can just pass in a file
that is, a discord file object
and you got audio from sink.audio_data.items()?
yup
if I print the type of audio from sink.audio_data.items() it says it's an AudioData object
so the question boils down to just: how do you download a discord.File object
well it's the other way round
you don't download a discord.File, you convert data into it
oh I see
what about audio.file
oh let me check
i'm trying - it's being a bit weird
sometimes I have to wait to start/stop recordings or they don't work
that's exactly what we want
it's just the module it's from
the original code snippet i provided should hopefully work
ah okay
TypeError: a bytes-like object is required, not '_io.BytesIO' - I think I need to convert it, just not sure of how to/what format
i'm pretty sure I can do io.BytesIO(data)
what about audio.file.getbuffer()
like this?
yeah
that worked, thank you so much!
eyy nice
can anyone help me with making my bot create channels
how to i get the pfp of someone?
discord.Member.avatar.url
What are you trying
I just want a button that when its pressed it makes a channel
What are you trying
oh right
I followed the button tutorial
and was trying to replace where the bot sends a message with an async def that makes the channel
Code?..
bot.guild?
i think i was trying discord.Guild too
idk where i got it from but i tried bot.guild too ig
How do you add the unix timestamp to an embed?
!rtfm pyc timestamp
b!rtfm pyc timestamp
interaction.guild
Also you dont to make another function under interactikn
im blanking so badly right now, how do you get the bot to turn a channel id like 881891840746475570 into #help-rules
#help-rules
i tried that in an embed and it didn't work
where in the embed
title
b!rtfm pyc category
discord.CategoryChannel
discord.CategoryChannel.category
discord.CategoryChannel.changed_roles
discord.CategoryChannel.channels
discord.CategoryChannel.clone
discord.CategoryChannel.create_invite
discord.CategoryChannel.create_stage_channel
discord.CategoryChannel.create_text_channel
discord.CategoryChannel.create_voice_channel
discord.CategoryChannel.created_at
b!rtfm pyc timeout
def server_confirm_roles(server: Guild, way: Optional[str]) -> List[discord.Role] | List[str] | List[DictConfig]:
TypeError: unsupported operand type(s) for |: '_GenericAlias' and '_GenericAlias'
This is a python version error isn't it?
or am I doing something wrong
are you using 3.10?
that syntax is only supported on 3.10
ah, that would be why, yeah, the server i'm running my bots on is python3.8-3.9, I'd have to install python3.10 from source
hmm how do i get _ctypes for 3.10.4

