#discord-bots
1 messages · Page 118 of 1
cus bruv
you have to start the task
ctx
idk, __init__ if you want it to start as soon as the cog is initialized, a command if you want to toggle it
you don't need to, just throw it inside your init
sure
Question: Does anyone know why I'm not seeing my slash commands on the list?
You ran the .sync command?
Looks like all your commands are global
You might want to try using .copy_global_to
Yea does nothing
where do I put .copy_global_to
above the sync
.copy_global_to
async def sync(ctx) -> None:
fmt = await ctx.bot.tree.sync(guild=ctx.guild)
await ctx.send(
f"Synced {len(fmt)} commands to current guild"
)
return
?
@sick birch
bro please help me
!d discord.app_commands.CommandTree.copy_global_to
copy_global_to(*, guild)```
Copies all global commands to the specified guild.
This method is mainly available for development purposes, as it allows you to copy your global commands over to a testing guild easily.
Note that this method will *override* pre-existing guild commands that would conflict.
i meant this not just adding that text to the code
above your await ctx.bot.tree.sync()
Read the documentation on how to use the function
it needs to be called on your tree instance
async def sync(ctx) -> None:
copy_global_to(*, guild=None, type=None)
fmt = await ctx.bot.tree.sync(guild=ctx.guild)
await ctx.send(
f"Synced {len(fmt)} commands to current guild"
)
return```
**Its still an error can you please just help me so I can start slash commands
Have you read the documentation throughly?
It tells you exactly how to use it
The doc confused me
Which part? I'd be happy to clarify
I don't really know where to look to get my answer theres so many things I'm just trying to get my slash commands to appear
if you'll notice, copy_global_to is under discord.app_commands.CommandTree
This means that copy_global_to has to be called on a dsicord.app_commands.CommandTree instance
Luckily - you've already got that!
ctx.bot.tree happens to be an instance of discord.app_commands.CommandTree
notice how sync is also under the same class?
Yea
It also tells you the aguments the class takes
The first one, client is your client/bot instance (ctx.bot in your case). The 2nd argument is an optional, so you can ignore it if you'd like
Put together, it'll look like this:
await ctx.bot.copy_global_to(guild=ctx.guild)
That's my crash course on How To Read Documentation ™️
I'm still confused on where to find the answer to my problem tho
It's an invaluable skill, and learning how to do it efficiently will supercharge you as a developer, and allow you to focus on new features than fighting with the language/library/framework you're using
I've just given it to you, see the message above this
Though I would highly recommend against copy pasting it and moving on
fmt = await ctx.bot.tree.sync(guild=ctx.guild)
Get rid of this?
I'd recommend you take your time, analyze each part, and make sure you're 100% sure what's going on before you proceed, since this is fundamental. If you've got questions I'd be more than happy to answer them
No, you still need to be syncing
You just need to copy all of your global commands to a guild, then sync those copied commands with Discord
Reason being global commands can take up to 1 hour to propagate
async def sync(ctx) -> None:
await ctx.bot.copy_global_to(guild=ctx.guild)
fmt = await ctx.bot.tree.sync(guild=ctx.guild)
await ctx.send(
f"Synced {len(fmt)} commands to current guild"
)
return```
**Is this a good final result?**
Sure. Sounds good, though it still seems you're worried more about the final result than the intermediates, which are far more important 😄 I can't force you to of course, but just make sure you understand before moving on
Okay thanks
I just want to test out my slash command
I can totally understand that - but if you don't get comfortable with problem solving and documentation skills, it'll only get harder. Not meant to discourage you, of course, just friendly advice you can keep in mind
I got an error
Let's see it
File "C:\Users\dynam\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 986, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\dynam\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 199, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'client'```
Code:
```@client.command()
async def sync(ctx) -> None:
await ctx.bot.copy_global_to(guild=ctx.guild)
fmt = await ctx.bot.tree.sync(guild=ctx.guild)
await ctx.send(
f"Synced {len(fmt)} commands to current guild"
)
return```
Is that the whole error? Looks like parts are cut off
I'll re try
File "C:\Users\dynam\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 190, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\dynam\Documents\predictor\main.py", line 210, in sync
await ctx.bot.copy_global_to(guild=ctx.guild)
AttributeError: 'Bot' object has no attribute 'copy_global_to'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\dynam\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1347, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\dynam\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 986, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\dynam\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 199, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Bot' object has no attribute 'copy_global_to'```
is full error
so no ctx.bot.tree.sync? just ctx.bot.tree
and all good
Leave the sync as it is
The line above, the copy global to part, it should be ctx.bot.tree.copy_global_to
right now its' ctx.bot.copy_global_to
Notice the difference? it can be a bit hard to spot
"await cannot be used as an expression"
Full traceback, please
It happens. May not have saved all the way
One issue tho "The application did not respond"
For every slash command I do
Can I see the pastebin of the entire code?
yea
I've lost the link as I rebooted my computer
For which command specifically did it not respond?
All 3
Hmmm
It should at least work for the login one
Try doing print statements in each, see if they get called
Yeah, for instance
@client.tree.command(...)
async def login(...):
print("Login command was called!")
yea
Do that for all 3, run your slash commands from discord, see what happens
I'm unfamiliar with slash commands
Is this right?
async def login(ctx):
print("Login command was called!")```
Don't change any existing code
if none of the commands responded, wouldnt there have been more tracebacks in the console?
yea there was
Just add the print statement as the first line in your slash command functions
It would be helpful to see them otherwise we're just taking a shot in the dark as to what the issue is
alright one second
File "C:\Users\dynam\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 851, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "C:\Users\dynam\Documents\predictor\main.py", line 51, in balance
user_info = collection.find({"user": user})
AttributeError: 'list' object has no attribute 'find'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\dynam\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\tree.py", line 1240, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\dynam\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 876, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "C:\Users\dynam\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 869, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'balance' raised an exception: AttributeError: 'list' object has no attribute 'find'```
What are you trying to do here? Check if the user_info exists?
Or get the index of it?
I did /balance and that was the error
Yeah, but what is the purpose of that line?
user_info = collection.find({"user": user})
What's it supposed to be doing?
find the user
Ahh, did you remove the database connection code?
I think collection is supposed to be something from your database, yes?
yea
Is it MongoDB?
mhm
Could you include the code? Remove any sensitive information like database URLs and login passwords
you mean add this?
cluster = MongoClient(mongo_url)
db = cluster['']```
Is that all your database connection?
yea
Well it looks like you're assuming collection is a MongoDB object, when it's just a regular list
So you'll have to change all of that to accomodate for it
i am doing this but it just exits the app evereytime..
name = input("\033[31mClick any key to return to menu")
except KeyboardInterrupt:
os.system('cls')
print(x)
BTW print(x) is just something it re prints out
im trying to make it reprint x but it just closes the prompt
someone???
how do you convert message input (with wait_for command) into a str?
It's a string by default
msg = await bot.wait_for("message", ...)
print(type(msg.content)) # <class 'str'>
but yeah i'm using .content now so there's no problem
How do I get the "guess" command to work
Hey @granite plume!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
Message is the object
does anyone know a way to shuffle music playlists? wavelink docs dont seem to have a command for it
We don't help with music bots per rule 5, sorry
oh ok
!e
code
!e
print ("hi")
!e
import wikipedia
user = input("Search here")
result =wikipedia.summary(user, sentences= 2)
print(result)```
@last belfry :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 | ModuleNotFoundError: No module named 'wikipedia'
#bot-commands
yo anyone down to help me
OHHHH thanks
How would I be able to record audio in voice channels through a bot?
only js libs capable of that. no py libs that I know of are actually able to maintain something like that
damn
So you dont think anything can be done with this :/, my js is limited would be a pain in the ass
none of that is able to record audio
They really do hate pycord in here
thats just vc channel related stuff and playing audio
nobody likes pycord

Alright I'll guess ill make it in js
thanks
🥴
like why
ctx.send_modal interaction.response.send_modal
I currently have this code: ```py
class AnswerQuestion(discord.ui.Modal, title='Give a Quote'):
answer = discord.ui.TextInput(
label='Response',
placeholder='What is your response?',
max_length=2000,
)
async def on_submit(self, interaction: discord.Interaction):
db = await aiosqlite.connect('database.db')
cursor = await db.execute('SELECT * FROM questions WHERE question_message_id=?', (interaction.message.id, ))
rows = await cursor.fetchone()
freelancer = interaction.client.get_user(rows[1])
embed = discord.Embed(title="New Response!",
description=f"Your question for {interaction.user.mention}'s project has been answered! \n\n{self.answer.value}",
color=discord.Color.orange())
embed.set_footer(text=interaction.user, icon_url=interaction.user.avatar.url)
embed.timestamp = datetime.now()
await freelancer.send(embed=embed)
for item in self.children:
item.disabled = True
await interaction.message.edit(view=self)
await interaction.response.send_message("Successfully answered their question!", ephemeral=True)
await db.execute('DELETE FROM questions WHERE question_message_id=?', (interaction.message.id, ))
await db.commit()
await db.close()``` My question lies in the ```py
for item in self.children:
item.disabled = True
await interaction.message.edit(view=self)``` section. How could I disable the button that opens the modal? I cannot use what I currently have as `self` is defined as the Modal and not the button's stuff... This is how I send the Modal via the button: Opening the modal's code is: ```py
class AnswerQuestions(discord.ui.View):
def init(self):
super().init(timeout=None)
@discord.ui.button(emoji='📨', label='Reply', style=discord.ButtonStyle.grey, custom_id='questions:1')
async def reply(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_modal(AnswerQuestion())```
is this dpy?
Seems like
It is, yes.
i mean since ur sending a modal
inside the button. use bot.wait_for for modal submit then disable button there
idfk i don't use view's for reasons like this. does dpy have "low level components"?
That would result in me not being able to have a persistent button
otherwise you will need to find a way to get the component after submitting the modal
Yeah, I've been trying to get it via a message ID (I'm storing everything anyways), so I'm not sure
When I restart the bot, it would break the wait_for
oh ye true
I'm just super lost on what I can try that I haven't tried already 😂
a janky way would be to use asyncio.sleep
!d discord.ui.Modal.on_submit
await on_submit(interaction, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Called when the modal is submitted.
in the button callback and set it to 5 mins. i think thats timeout limit for modals?
I don't think Modals have a timeout
by default no

but you can set it.
Ahh, gotcha
does anyone have the removerole order? dm me pls
removerole order?
I just figured this out for regular buttons a couple days ago. Give me a few to feed my daughter and I'll hop on the computer and show you how I did it. Are you trying to disable just that button or the whole menu?
By "I figured it out" I mean I asked here and played around with the answers people gave me until something finally worked
await interaction.followup.edit_message( message_id=interaction.message.id, view=self)```
i put that inside the code for my button and it disables the button after interaction
guys whats the command to do that if a mod to action like mutes a member it will send the action in a channel ?
!d action
ok isnt that
this won't work. he needs a way to get the button after submitting the modal
from inside the modal view
thought he was trying to disable the button that creates the modal?
oh he wants the button disabled after the modal is submitted not after the button is pushed?
yeah cause what if the user clicks the button and doesn't actual send the modal, then they no longer have access to the button
then theyd have to pop up another button lol
but yea i see
so could you pass the interaction into the modal with interaction: discord.Interaction then specify self.interaction = interaction in the modal and use self.interaction.followup.edit_message() inside the modal response?
how would u pass interaction into the modal tho? you can't pass anything into .send_modal
guys how do i tag the action member
like the member that used to command
mute, so how do i get the moderator
author.mention
thanks!
the way i passed a message interaction into my view was in the send command. so send_modal(AnswerQuestion(myview))?
huh. .send_modal only takes a modal object
what u can do is. somehow store the id of the message containing the button and after the modal is submitted use View.from_message
wish i had more time to try it out for myself but i gotta head to work. seems like there should be a way to pass it through without needing to store it
this is why I don't like views at all lol
yea theyre tricky thats for sure
disnake has low level components where
@Cog.listener()
async def on_button_click(self, inter: disnake.MessageInteraction):
if inter.component.custom_id == "asfdasf":
....
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: type object 'datetime.datetime' has no attribute 'timedelta'
whatt
yea ive noticed that disnake tends to make shit easy for people lol
its datetime.timetdelta
@bot.command()
async def mute(ctx, member: discord.Member = None, time = None, *, reason='No reason!'):
channel = bot.get_channel(1035829526766293043)
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
if time is None:
await ctx.send("Please put the time!")
return
time = humanfriendly.parse_timespan(time)
await member.edit(timed_out_until=discord.utils.utcnow()+datetime.timedelta(seconds=time))
await ctx.send(f"{member.mention} Got muted\n Reason: {reason}")
embed = discord.Embed(title="Member Muted", description=f"**Muted:** \n{member.mention}({member.name}) \n **Moderator:** \n {author.mention}({author.name})\n **Time:** \n {time}\n **Reason:**\n {reason}", color=0x1d2a3d)
embed.set_thumbnail(url=ctx.member.avatar)
embed.set_footer(text=f"Requested by {ctx.author.name}", icon_url=ctx.member.avatar)
await ctx.channel.send(embed=embed)```
```discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: type object 'datetime.datetime' has no attribute 'timedelta'
lmfao
typo but datetime.timedelta not datetime.datetime.timedelta
thats what i did
.
also remove your = None if its a required argument.
how did you import it?
did u import datetime from datetime?
from datetime import datetime
thats why
importing like that ur doing datetime.datetime.timedelta
so what do i do
from timedelta import datetime
no lol
remove ur import or
from datetime import datetime, timedelta
discord.utils.utcnow()+timedelta(seconds=time)
does anyone wanna make a bot together or am i going to make 1 alone 🥲
quack
thanks!
what kind of Bot would you like to do
general bot
- mod
- fun
- idk
Mod bots can be pretty labor intensive
wdym "labor intensive"
isnt that for every bot lol
I mean sure it always could be long if you make it do a lot. But there's a lot of moderation to be done in a server
¯_(ツ)_/¯
at this point i wouldn't even make a mod bot, discord's automod taking over tbh.
True. I hope they do it justice
true
My shortest one is like 50 lines aside from a dict. Just posts a random fact every day
lol
u wanna make like just a general bot
not auto mod or stuff like that
- Music
- Economy?
- Level
thats all i got idk
music denied
🤣
¯_(ツ)_/¯
I've already made a pretty intense level bot
welp idk if u want to join
https://prod.liveshare.vsengsaas.visualstudio.com/join?DDC37F95E276DF9F4817DE8B910798EC6253
Build with Visual Studio Code, anywhere, anytime, entirely in your browser.
You could make cogs for something like redbot
🤣
i never learnt cog 💀
what
you don't need to learn cogs, thats just basic python
..?
you create a subclass of commands.Cog with command objects inside it
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'author' is not defined
ctx.author
oh thanks
L

It would be better to use GitHub
how
that's why you don't share live code sessions publically
i mean i dont have anything in it anyway lol
they can access everything in the opened folder
including your token, if you have any
nice
im about to make 1 lol
idc if it get used
Well, you upload your Bot code and contributors that wants to contribute will opens pull requests (they'll clone your repo and modify your Bot code locally) but it's a little bit complex because you need some rules and checks (and idk if non premium user can have checks, maybe they're only for teams)
anyone can use checks using github workflows
too complicated
Nice
You say that... until some troll gets your bot rate limited or reported lol
alt.exe
yeah, any offense with the bot will be considered to be done by you
ill use my friends account :~troll:
@bot.command()
async def mute(ctx, member: discord.Member = None, time = None, *, reason='No reason!'):
channel = bot.get_channel(1035829526766293043)
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
if time is None:
await ctx.send("Please put the time!")
return
time = humanfriendly.parse_timespan(time)
await member.edit(timed_out_until=discord.utils.utcnow()+timedelta(seconds=time))
await ctx.send(f"{member.mention} Got muted\n Reason: {reason}")
embed = discord.Embed(title="Member Muted", description=f"**Muted:** \n{member.mention}({member.name}) \n **Moderator:** \n {ctx.author.mention}({ctx.author.name})\n **Time:** \n {time}\n **Reason:**\n {reason}", color=0x1d2a3d)
embed.set_thumbnail(url=ctx.author.avatar)
embed.set_footer(text=f"Requested by {ctx.author.name}", icon_url=ctx.author.avatar)
await ctx.channel.send(embed=embed)```
and its sending the embed in the currect channel and not the channel i did channel = bot.get_channel(1035829526766293043)
channel.send , not ctx.channel.send
remove the ctx
ohh
my bad lol thanks!
@slate swan oh hi

go vscode
@bot.command()
async def mute(ctx, member: discord.Member = None, time: int = None, *, reason='No reason!'):
channel = bot.get_channel(1035829526766293043)
ETA = int(time.time() + {time})
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
if time is None:
await ctx.send("Please put the time!")
return
time = humanfriendly.parse_timespan(time)
await member.edit(timed_out_until=discord.utils.utcnow()+timedelta(seconds=time))
await ctx.send(f"{member.mention} Got muted\n Reason: {reason}")
embed = discord.Embed(title="Member Muted", description=f"**Muted:** \n{member.mention}({member.name}#{member.discriminator}) \n **Moderator:** \n {ctx.author.mention}({ctx.author.name}#{ctx.author.discriminator})\n **Time:** \n <t:{ETA}:R>\n **Reason:**\n {reason}", color=0x1d2a3d)
embed.set_thumbnail(url=ctx.author.avatar)
embed.set_footer(text=f"Requested by {ctx.author.name}", icon_url=ctx.author.avatar)
await channel.send(embed=embed)```
```discord.ext.commands.errors.BadArgument: Converting to "int" failed for parameter "time".```
the time that user provided wasnt an integer
i did !mute the mention and 1m
That isn't an integer
Use some datetime parsing lib or this converter #discord-bots message
Import it 🤓
from discord import Converter
import Converter
import Converter the what
ImportError: cannot import name 'Converter' from 'discord' (C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord_init_.py)
What about paying more attention to imports that are in my code
discord.ext.commands.Convertor
do i import that or
Yk what
class TimeConverter(discord.ext.commands.Convertor):
!pypi parsedatetime or smth
I forgor the lib
oh thanks!
no idea
hmm....
I have no idea
I think you may have to ask in the discord.py server
Are you trying to make it happen all at once? If so you'll have to loop to make it go back over your if statements
Or are you triggering it twice
@bot.command()
async def mute(ctx, member: discord.Member = None, time: str = None, *, reason='No reason!'):
channel = bot.get_channel(1035829526766293043)
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
if time is None:
await ctx.send("Please put the time!")
return
time = humanfriendly.parse_timespan(time)
epochEnd = pyTime.time() + time
await member.edit(timed_out_until=discord.utils.utcnow()+timedelta(seconds=time))
await ctx.send(f"{member.mention} Got muted\n Reason: {reason}")
embed = discord.Embed(title="Member Muted", description=f"**Muted:** \n{member.mention}({member.name}#{member.discriminator}) \n **Moderator:** \n {ctx.author.mention}({ctx.author.name}#{ctx.author.discriminator})\n **Time:** \n <t:{epochEnd}:R>\n **Reason:**\n {reason}", color=0x1d2a3d)
embed.set_thumbnail(url=ctx.author.avatar)
embed.set_footer(text=f"Requested by {ctx.author.name}", icon_url=ctx.author.avatar```
What's the problem
Not everyone can just understand your problem by saying why is it not working
also no errors
They explained below that post lol
Round it
oh okay
I meant round the time
!d discord.utils.format_dt use it
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.11)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
oh wdym where
you'll just have to pass the datetime in
Yeah, that's easier 🫠
epochEnd = pyTime.datetime() + time
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
epochEnd = datetime.fromtimestamp(time.time())
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'float' object has no attribute 'time'
time there is an float
not the time lib
so what do i do
discord.ext.commands.errors.MemberNotFound: Member "shj" not found.
what can i write to help that
@message.error
async def message_error(ctx, error):
if isinstance(error, commands.MemberNotFound):
await ctx.send("Please mention a member!")
discord.ext.commands.errors.MemberNotFound: Member "sh" not found.
now it is sending it but shows an error
no way they rounded the screen shot 😭😭😭🤣🤣😂😂😂
!d discord.TextChannel.purge
await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=None, bulk=True, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.
You must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") to delete messages even if they are your own. Having [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") is also needed to retrieve message history.
Changed in version 2.0: The `reason` keyword-only parameter was added.
Examples
Deleting bot’s messages...
purge don't accept positional arguments
It does, self can be passed positionally or with its name
okimi use sm common sense they r obviously not talking about self 😆
I'm not okimii? I'm correcting the persons statement as self can be passed positionally and it's an argument in the method, no?
How do we receive voice
self can be passed if its a function, not a method
you'll have to use a fork like pycord or nextcord, discord.py doesnt support that
what
?self can be passed if you use it like discord.TextChannel.purge(...) ( as a function)
but not if you use it as <a discord.TextChannel object>.purge(...) ( as method )
!e ```py
class Foo:
def bar(): ...
print(type(Foo.bar), type(Foo().bar))
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
<class 'function'> <class 'method'>
ok
Going by the terms lol
I use disnake
disnake doesnt have voice support either ( from when i checked it for last time )
It doesn't exist yet
hi noid
Hi snipy, long time no see👋
voice recv support?
yeah
a lot of others do tho
.
bruz
use dpy-toolbox (works with discord.py)
dont check the source code tho its poorly written
Download link: https://pypi.org/project/dpy-toolbox
meh its so unprofessional, but anyways yeah it works as long as it works
yep ik
i just realised that you're the author, hope you stub your toe
yea I'm kinda low on testers
I thought I'd use the opportunity
i wanna do that if a member writes the command and the name it will send to the staff channel and will add a reaction of vi and x which thats what it is doing but how do i do that if a staff member clicks on vi it will change the name of the member to the name he chooses, and if on x it will send to the member that the name didnt approve?
@bot.command(aliases=["Name"])
async def name(ctx, name: str = None):
Cha = bot.get_channel(695217470641799218)
embed=discord.Embed(title="שינוי שם", description=f"{ctx.author.mention} רוצה לשנות את השם ל {name} ! מאשרים?")
if name is None:
return await ctx.send("בבקשה תציין שם !")
else:
await ctx.send("השם נשלח בהצלחה, נעדכן אותך!")
moji = await Cha.send(embed=embed)
await moji.add_reaction("✅")
await moji.add_reaction("❌")```
Where in these commands should be located json.dump?
async def open_acc(user):
users = await get_bank()
if user.bot is True:
return
if str(user.id) in users:
return False
else:
users[str(user.id)] = {}
users[str(user.id)]["wallet"] = 100
write_json("bank.json", users)
return True
async def get_bank():
users = load_json("bank.json")
return users
you will have to store the message id along with the member id who requested the access to changing the name. you can use the on_raw_reaction_add event to check when a reaction is added to a message (You will need intents for this which are enabled in the default intents) . You can then check the message id with your stored ids and if there is a good match then you can do further processing
wow tysm!!
welp i can help if you're working on a rewrite or something cause it seems pretty much messed up
yea ik
I'm bad at structuring things
!e
try:
1 / 0
except ZeroDivisionError as error:
if error == ZeroDivisionError:
print("a")
@rustic onyx :warning: Your 3.11 eval job has completed with return code 0.
[No output]
Why the check if youre only catching one specific error? Either way the logic isnt right, you're checking if error an instance of ZeroDivisionError is equal to the ZeroDivisionError class object
For things like that you would use isinstance
!e
print(1 == int)
@primal token :white_check_mark: Your 3.11 eval job has completed with return code 0.
False
!e ```py
int = 1
print(1 == int)
@cloud dawn :white_check_mark: Your 3.11 eval job has completed with return code 0.
True
👽
True
def convert(time):
pos = ["s", "m", "h", "d"]
time_dict = {"s" : 1, "m" : 60, "h" : 3600, "d": 86400}
unit = time[-1]
if unit not in pos:
return -1
try:
val = int(time[:-1])
except:
return -2
return val * time_dict[unit]
@bot.tree.command(name="giveaway")
@app_commands.describe(giveaway_time = "What time should the giveaway end? 1s/1m/1h/1d")
@app_commands.describe(prize = "What the prize should be?")
async def create(interaction: discord.Interaction,prize: str, giveaway_time: str):
time=convert(giveaway_time)
date=datetime.now() + timedelta(seconds=time)
utc_time= calendar.timegm(date.utctimetuple())
giveawayEmbed=discord.Embed(title=f"🎉 **{prize}** 🎉",description=f"> **Ends:** <t:{utc_time}:R>\n"
f"> **Hosted By: {interaction.user.mention}")
msg=await interaction.channel.send(embed=giveawayEmbed)
await interaction.response.send_message(f"Successfully created giveaway in {interaction.channel}!", ephemeral=True)
await msg.add_reaction("🎉")
await asyncio.sleep(time)
giveawaymsg=await interaction.channel.fetch_message(msg.id)
users= await giveawaymsg.reactions[0].users().flatten()
users.pop(users.index(bot.user))
winner=random.choice(users)
endEmbed=discord.Embed(title=f"🎉 **{prize}** 🎉",description=f"> **Ends:** <t:{utc_time}:R>\n"
f"> **Hosted By:** {interaction.user.mention}\n"
f"> **Winner:** {winner.mention}")
await giveawaymsg.edit(embed=endEmbed)
await giveawaymsg.reply(f"🎉 **Congratulations {winner.mention}!** 🎉")```
and when i try to make the time 1m it shows 2 hours
and then after a couple of mins it shows that error
discord.app_commands.errors.CommandInvokeError: Command 'giveaway' raised an exception: AttributeError: 'async_generator' object has no attribute 'flatten'
users = [user async for user in (await giveawaymsg.reactions)[0].users()].flatten()
Aka I don't recommend using await like this.
.flatten is no longer a thing
and you placed it incorrectly
still shows 2 hours
discord.app_commands.errors.CommandInvokeError: Command 'giveaway' raised an exception: TypeError: object list can't be used in 'await' expression
i suppose you want something like this?
users = [user async for user in giveawaymsg.reactions[0].users()]
What did you want to do with flatten?
its taking whpever reacted
still two hours:(
discord.app_commands.errors.CommandInvokeError: Command 'giveaway' raised an exception: IndexError: list index out of range
Theres no reactions
I actually made something like this with time and I just forced the user to input a ranged int (0, 86400) and let the choose the prefix like days, minutes etc and if it is over a year convert it to just 1 year.
@command(name="mute", description="Mute a certain member.")
@describe(
member="The member that is going to be muted.",
length="Amount of time to mute the member.",
unit="Unit of time.",
reason="Why this member is getting muted."
)
@choices(unit=[
Choice(name="Days", value=86400),
Choice(name="Hours", value=3600),
Choice(name="Minutes", value=60),
Choice(name="Seconds", value=1)
])
async def moderation_mute(
self, interaction: Interaction,
member: Member,
length: Range[int, 1, 2419200],
unit: Choice[int],
reason: str = "No reason specified"
) -> None:
second_amount = sec if (sec := length*unit.value) < 2419200 else 2419200
dt = datetime.now().astimezone() + timedelta(seconds=second_amount)
await member.timeout(dt, reason=reason)
await interaction.response.send_message(
f":ok_hand: Muted {member.mention} for `{reason}` until <t:{int(dt.timestamp())}:F>"
)
How i can update my discord bot
Open the file in word and edit the text.
i need help
how do i make my bot give someone a role after they do a command
@bot.command()
async def register(ctx):
embed = discord.Embed(
description=
f"**You Have __Successfully__ Registered As {ctx.author.mention}\n\nHave Fun Playing And Good Luck.**",color=0xfc0303)
await ctx.send(embed=embed)```
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
do i put role name await add_roles(*here, reason=None, atomic=True)
@bot.command()
async def register(ctx):
embed = discord.Embed(
description=
f"**You Have __Successfully__ Registered As {ctx.author.mention}\n\nHave Fun Playing And Good Luck.**",color=0xfc0303)
await add_roles(*roles, reason=None, atomic=True)
await ctx.send(embed=embed)```
@bot.command()
async def register(ctx):
embed = discord.Embed(
description=
f"**You Have __Successfully__ Registered As {ctx.author.mention}\n\nHave Fun Playing And Good Luck.**",color=0xfc0303)
await add_roles(*roles, reason=None, atomic=True)
await ctx.send(embed=embed)```
like that?
how sorry for bothering im new to python
@bot.command()
async def register(ctx):
embed = discord.Embed(
description=
f"**You Have __Successfully__ Registered As {ctx.author.mention}\n\nHave Fun Playing And Good Luck.**",color=0xfc0303)
await add_roles(community, reason=None, atomic=True)
await ctx.send(embed=embed)```
like this?
!d
You have to use get to get the role then use the role object not just the name
can u give exapmple
Any object with id property works as far as I know
so id = idhere
@bot.command()
async def register(ctx):
embed = discord.Embed(
description=
f"**You Have __Successfully__ Registered As {ctx.author.mention}\n\nHave Fun Playing And Good Luck.**",color=0xfc0303)
await add_roles(name=community, reason=None, atomic=True)
await ctx.send(embed=embed)```
That's an indentation error. Fix your indents
That's a familiar code highlight colours
HUH
VSC
Oh ok
What is the error
Make the indent in the same level as the above line
@bot.command()
async def register(ctx):
embed = discord.Embed(
description=
f"**You Have __Successfully__ Registered As {ctx.author.mention}\n\nHave Fun Playing And Good Luck.**",color=0xfc0303)
await add_roles(name=community, reason=None, atomic=True)
await ctx.send(embed=embed)```
ok
got that now
Hi I wrote this code back in 2017
string = [k,a,b,c,d,e,f,t,g]
for z in string:
await client.edit_message(message,z)
This doesnt work anymore so after reading the documentation i tried this:
string = [k, a, b, c, d, e, f, t, g]
for z in string:
await message.edit(z)
but i get the error
TypeError: edit() takes 1 positional argument but 2 were given
anyone know why ?
How do I fix
content = z
@naive briar can u help when u get a chance
thx !
its await ctx.author.add_roles()
?
How do I make it so It gives them a role I want
Do you have role ID?
Yes I have the Id for the role
!d discord.Guild.get_role
get_role(role_id, /)```
Returns a role with the given ID.
Changed in version 2.0: `role_id` parameter is now positional-only.
Do I put it above or somthing
Above giving the role yes
Ok
Why pip install discord.py don't work ?
giving invlaid intax what wrong wit it
like that?
are you getting an error?
does someone know why my bot cant send embeds? It doesnt show up any errors
no, you need a guild object and role_id should be replaced by the role id
how do i get a guild object
You can't code by copypasting every fricking thing and not understanding what that is
i can do other stuff just getting into discord.py
pretty much not copying pasting everything i wrote the whole code to this bot just stuggleing with a few things
ctx.guild.get_role(role_id) to get a role from the guild where the command was run, if you want to get a role from another guild where your Bot is in you need to get/fetch the guild with the Bot object
ye bc its adding a role
but ok
And that's programming term you gotta be familiar with to work with dpy
ctx.guild.get_role(1036640310643662848)
await ctx.author.add_roles() that will work right?
thats what i have down
like i said im learning dpy
What python knowledge you got
You basically can't learn it if you don't know how functions work, because dpy is literally based on functions and OOP
you're not adding anything
add role = before ctx.guild.get_role
Then add role between the () in add_roles
i had the same problem, my discord bot doesn't work anymore cuz i updated discord.py so better to check the discord version
role name or id
??
do i put the id or the role name
the id
add role = before ctx.guild.get_role(103...
role = ctx.guild....
ohhh
💀
Add the id between the ()
oops
role is not a keyword argument
lmao
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
and you don't need to get the full role object, you can use discord.Object
!d discord.Object
class discord.Object(id, *, type=...)```
Represents a generic Discord object.
The purpose of this class is to allow you to create ‘miniature’ versions of data classes if you want to pass in just an ID. Most functions that take in a specific data class with an ID can also take in this class as a substitute instead. Note that even though this is the case, not all objects (if any) actually inherit from this class.
There are also some cases where some websocket events are received in [strange order](https://github.com/Rapptz/discord.py/issues/21) and when such events happened you would receive this class rather than the actual data class. These cases are extremely rare.
x == y Checks if two objects are equal.
x != y Checks if two objects are not equal.
hash(x) Returns the object’s hash.
you could use this put the role id, that what i got from this conv
ik that
but idk what to put now bc he said i cant use what nuke told me
says ctx undefind
does python say ctx is not defind?
no the error is that
if not from python than ignore it
python is the lang not the ide
U forgot the id
Between the ()
ik
dam i hate when this happen
bruh
uhh ctx doesn't exist outside the function
you should put that in line 13
huh
Add the role = ... into the function instead of ctx.guild.get_role() that u already have
why my bot does not send the embed?
look you need to get the role first than pass it to add_roles than done
looks fine to me, any errors?
No, it simply does not work
try printing something before sending the emed and make sure your bot can send embeds
if the console is empty than the cmd or event did even started
where do I see if my bot can send embeds? I gave him admin permissions
if so then he should send embeds
try the method that i gave you
ok
or/and put your bot in debugging mode and watch the logs
here is the full code, im using an event handler because i will make more advanced stuff, also cogs
the main porpoise is to verify the list, if the object is not in the list, will raise the error and send an embed helping how to use the command properly
but it doesnt make sense why cant send
i am not sure but i think its should be commands.Cog.command, do u mind if you tried that?
wait ignore my message
hm
Do you have any on_mesage event?
I dont think so

sure, I have
damm
oh okay that looks fine,
the problem is only with the embed, because i tried to replace the embed only with a phrase, and worked
Does the command work at all or just not throw the error
when i removed the embed, the message was send
the problem is with the embed, only
do I need to import something specific?
!d discord.Embed
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
x == y Checks if two embeds are equal.
New in version 2.0...
have you tried creating another embed?
I don't think the Embed object takes the name kwarg 
yeah, everything
I even coppied an old embed from other project
oh that true, but should it raise an http/request error tho?
Try taking the name off the embed. Did you mean title instead?
if this was the problem, please ban me from the server
He probably have an error handler that ignores it if the error doesn't show
Hmm
yeah
okay try putting discord.py in debugging mode and it will say if trys to send embed i don't remember how exactly but it won't hurt if you tried
i think its bot.run(TOKEN,debug=1)
ok
you can and sometimes its so useful
I'm prob going to use it a ton now that I know it exists
!d discord.ext.commands.Bot.run
run(token, *, reconnect=True, log_handler=..., log_formatter=..., log_level=..., root_logger=False)```
A blocking call that abstracts away the event loop initialisation from you.
If you want more control over the event loop then this function should not be used. Use [`start()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.start "discord.ext.commands.Bot.start") coroutine or [`connect()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.connect "discord.ext.commands.Bot.connect") + [`login()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.login "discord.ext.commands.Bot.login").
This function also sets up the logging library to make it easier for beginners to know what is going on with the library. For more advanced users, this can be disabled by passing `None` to the `log_handler` parameter.
Warning
This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns.
Rip
!d discord.ext.commands.Bot.run
run(token, *, reconnect=True, log_handler=..., log_formatter=..., log_level=..., root_logger=False)```
A blocking call that abstracts away the event loop initialisation from you.
If you want more control over the event loop then this function should not be used. Use [`start()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.start "discord.ext.commands.Bot.start") coroutine or [`connect()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.connect "discord.ext.commands.Bot.connect") + [`login()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.login "discord.ext.commands.Bot.login").
This function also sets up the logging library to make it easier for beginners to know what is going on with the library. For more advanced users, this can be disabled by passing `None` to the `log_handler` parameter.
Warning
This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns.
i think you should add log handler?
must be log handler
log_handler = True?
no, add streamhandler
ok
hold sec
import logging,sys
handler = logging.StreamHandler(sys.stdout)
#code
...
bot.run(TOKEN,log_handler=handler)
stream handler is better, cuz you don't need to save the logs
ok thnks
the problem now is that im using cogs, and to import cogs from the new discord.py library, must be a coroutine, and to start the client, i used client.start instead of client.run '-'
client.start doesnt have log_handler, i dont think so
and client.run is not a coroutine
oo bruh
at least that is what i searched online, because when trying to use cog, it said that i must use await
f"> **Last Archive:** '<t:{int(s_channel.archive_timestamp.timestamp())}:F>' if '<t:{int(s_channel.archive_timestamp.timestamp())}:F>' else 'Not archived'}\n\n"
you are using ' instead of ", try replacing it
where xD
f"> **Last Archive:** "<t:{int(s_channel.archive_timestamp.timestamp())}:F>"if "<t:{int(s_channel.archive_timestamp.timestamp())}:F>" else "Not archived"}\n\n"
@white citrus
This is talking about the } after not archived I believe
It says single close brace
like everything need await
i tried using embed in the main code, and worked
know i think that the problem is with the cog
i will try also printing something at the console after the embed
yeah then the else is not anymore an else
@shadow vigil I might have figured out
look, there is no ctx parameter

prob is that
Yes
ctx paramter? wdym exactly
yes i know
there is, at the beginning of the handler
if and else is not in the f string how can i fix that
okay so did it work?
lol ik, no sm
hey im making a bot that doesn't do anything he just lives and i need to him be online 24/7 also he has no code or anything like that theres a way to make this? free
There's no free hosting, check #965291480992321536
send it
If you're comfortable DMing me your token I'll run it without code on my machine
There will be periods of 2-3 minutes of downtime throughout the day though as I'm currently having weird internet outages
hello , i'm having a little problem:
await interaction.response.send_message("pong",components=[Button(label="Hey there!"), Button(label="Hi!")])
and it says "NameError: name 'Button' is not defined"
what should i import to get the button method ?
(tried google but haven't found any aswers)
class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.
New in version 2.0.
thx
how do i make it so u can only use the command in one channel?
can someone help me with something
what is it
try:
name = input("\033[31mClick any key to return to menu")
except KeyboardInterrupt:
print(x)
time.sleep(5)``` whenever i use this it just closes the application
i dont know why
do u open it in cmd or vsc to see the error
cmd
no error?
no error
hmm
just this it just closes it
if ctx.channel.id == channel id
# the rest of the code
else:
pass
kk
Did u press enter?
yeah
Thats correct tho
it just closes it when i click enter but i want it to reprint x
Then add print(x) below input
ok
works ty
@grand willowwait but now it just makes the program stop
like it works but then after it prints the program closes
Yes correct
i dont want it to close though
I want it to stay open so I can continue running commands inside it
so u mean like
def main:
input("Menu")
input("Press any Key to return to the Menu")
main()
wdym
bc this
\033[39m ╔═╗┌─┐┌\033[36m┐┌┬┌─┐
\033[39m ╚═╗│ ││\033[36m││││
print(x)```
thats what x really equals
i don't see any issue with the value of an variable
!e ```py
x = """
\033[39m ╔═╗┌─┐┌\033[36m┐┌┬┌─┐
\033[39m ╚═╗│ ││\033[36m││││ """
print(x)
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 |
002 | [39m ╔═╗┌─┐┌[36m┐┌┬┌─┐
003 | [39m ╚═╗│ ││[36m││││
works like any other thing
Yeah ik
im doing this
name = input("\033[31mClick any key to return to menu")
os.system("cls")
print(x)
except KeyboardInterrupt:
time.sleep(5)``` so it should print x but also still let me use the cmd prompt but instead it just closes
so it works but soon as i enter another command it closes
Yeah it doesnt let u do anything cuz theres nothing to do after it
well your code is completed why would it continue later
The code ends there
well i want it to but idk how
this is my full code right here
import sys
import os
import time
os.system("color")
os.system("cls")
x = """
\033[39m ╔═╗┌─┐┌\033[36m┐┌┬┌─┐
\033[39m ╚═╗│ ││\033[36m││││
"""
print(x)
Info = """
"""
command = input('''
╔═[\033[39m\033[36m]
╚═➢ ''')
if command == '1':
os.system ("cls")
print(x)
print(Info)
elif command == "":
os.system ("cls")
print(x)
elif command == "exit":
exit()
try:
name = input("\033[31mClick any key to return to menu")
os.system("cls")
print(x)
except KeyboardInterrupt:
time.sleep()
so how do i make it return to print(x) and it still lets me run the command 1
@slate swan@grand willow
one possible solution is function recursion
but how is this related to a discord bot
im new so i dont know how
becuase im trying to make something
its a currency bot
so how do i do a function recursion
so can u help or no?
Hello guys how do i black list role from discord.py commands ?
blacklist a certain role?
yeah so he cant use commands of bot
just make commands moderator-only
depends on what you want though
I'd honestly just add a global check
is this the channel for discord.py?
discord.py and bot dev related libraries yes
okay, i'm having struggles with installing discord.py 2.0
i'm new to this and saw a youtube tutorial
he told me to put this in terminal, I've downloaded python and everything I need
jusst use pip install discord.py it will install 2.0
it says pip isn't recognised as an internal or external command, operable program or batch file
!minusmpip
When trying to install a package via pip, it's recommended to invoke pip as a module: python -m pip install your_package.
Why would we use python -m pip instead of pip?
Invoking pip as a module ensures you know which pip you're using. This is helpful if you have multiple Python versions. You always know which Python version you're installing packages to.
Note
The exact python command you invoke can vary. It may be python3 or py, ensure it's correct for your system.
just using pip is not recommended
yes
May need to correct your path to the pip package
where do I find the pip package
There's easy tutorials on the internet, that's going to probably be your best resource for that
i would recommend installing 3.10 since some of discord.py's dependencies dont have prebuilt wheels for python 3.11 (yet), meaning you would have to additionally install 6 gigabyte C++ build tools to compile them
if you're getting the installer from python.org, look for 3.10.8 (latest) in the downloads page, and in the installer make sure pip is included with it
Right, I will try to delete 3.11 and install 3.10 then
I did actually do that but it still didn't work
perhaps itd be better for you to click the recommended install instead, rather than touching any of the options
afterwards you'll get a py command that you can use in place of python, e.g. py -m pip install discord.py
@keen vault try python3 -m pip install discord.py
If not, uninstall all your Python downloads and reinstall the newest version with pip
What's your definition of "practical"?
what i just said. sorry for not adding it to og message
depends on your level of python skill. Discord.py is not really an easy library so I'd say intermediate python
hm. are there better ways to make discord bots?
This is more of a limitation on Discord APIs part
wtf is this
Most wrappers have the same issue
but arent bots becoming more fun now with like embeds and actual buttons and stuff
That's subjective
lol fun to look at
i enjoy the intuitiveness to it
If you find it fun, and you've got the prerequisite and motivation, go for it!
what are those bots usually coded in though?
Though discord bots get dry after a while. I haven't done any in months
i find it fun but im a weirdo. i yearn for knowledge
just discord.py? or are there other languages and libraries out there
discord.py if python discord.JS if Node
Those are the 2 biggest competitors
ive tried both, i prefer python
now, unbiased, which one's more efficient and user-friendly
Sure. Plenty. After the Great Abandonment ™️ many of these other libraries have gotten the spotlight
Python. Unbiased, really
discord.JS is more "low level" (that is, closed to the API)
More control, less user friendliness
python is easier but ive seen websites that offer serverless hosting that use their own syntax based on node.js
I generally dislike the discord bot market
ive noticed a LOT of bots are kinda half made and their support servers arent much help
very true
mee6 sucks
mee6 is the worst bot
like even the popular ones, if youre trying to do something one off with it they dont want to help because its not something they can copy paste from the chat above
yeah
ive been to yagpdb server countless times with a question and they tell me it cant be done, just for me to spend a weekend figuring it out on my own and it actually works
a big reason i started making and hosting my own stuff
isnt yagpdb dedicated for like developers n stuff
and its super complicated to the average discord user to... calibrate? because of just how many options are given n stuff
its a good free resource imo because they offer a lot of stuff without premium like custom commands with code and auto mod and stuff
discord bots are in a dry spot right now until discord implements more features
we need select in modals, and better usage for the role select menus, etc...
or more people need to get creative lol
not really all the current select modals and UIs are so limited
wym more usage for role select menus
thats all it is, a full list of roles, members, etc. you can't specify or limit them.
oh i see, like filters
reason i ask is my level bot features a split tree role assignment system
yea exactly, imagine a filtered role select
Hey @young pendant!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
Hey, I'm getting an error when using my /info command
Error: https://paste.pythondiscord.com/isevofabod
Py.File: https://paste.pythondiscord.com/ayihezupiq
Can someone help me?
!d discord.ext.commands.Bot.case_insensitive
Whether the commands should be case insensitive. Defaults to False. This attribute does not carry over to groups. You must set it to every group if you require group commands to be case insensitive as well.
@hollow agate Can you help me? 
Sure
if self.roles_of_team1[guild_id] != [] and guild_id in self.team_roles1.keys():
There's something wrong with this, I can't read your code because it's literally impossible to
prolly an invalid id or some sorts
hmm, weird
is there a sub-subcommand in slash commands?
i found a workaround no need to dive into that tonight
all i use is sub cmds anymore lol
how would that work with sub commands in hybrid commands?
i assume this is with hybrid_group?
why does this return a user object, but in a list form with no commas? much confusion
pardon?
object.__repr__(self)```
Called by the [`repr()`](https://docs.python.org/3/library/functions.html#repr "repr") built-in function to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form `<...some useful description...>` should be returned. The return value must be a string object. If a class defines [`__repr__()`](https://docs.python.org/3/reference/datamodel.html#object.__repr__ "object.__repr__") but not [`__str__()`](https://docs.python.org/3/reference/datamodel.html#object.__str__ "object.__str__"), then [`__repr__()`](https://docs.python.org/3/reference/datamodel.html#object.__repr__ "object.__repr__") is also used when an “informal” string representation of instances of that class is required.
This is typically used for debugging, so it is important that the representation is information-rich and unambiguous.
idk why it returns that though.. even the docs say you should be able to use that to pull a user obj from reactions then mention that user. which you cant do with that repr
Does anyone here know how to use sqlite and wouldnt mind helping me?
but its also for a discord bot, i dont know where the problem is
i mean, idc where anything is discussed, but you may get better/quicker help there
The list can contain an unknown amount of Member | User objects, when you print the list the reprs would be used to display the object as a string
why cant i mention it then?
if its being pulled as an object
You can?
!e
class Foo:
def __repr__(self) -> str:
return "<Foo object!>"
print([Foo() for a in range(11)])
@primal token :white_check_mark: Your 3.11 eval job has completed with return code 0.
[<Foo object!>, <Foo object!>, <Foo object!>, <Foo object!>, <Foo object!>, <Foo object!>, <Foo object!>, <Foo object!>, <Foo object!>, <Foo object!>, <Foo object!>]
i get 'list' object has no attribute 'mention'
because you cant mention a list, it has no such attribute, you must iterate through each User or Member and mention them since a list object is a mutable container type thats the opposite of an array as it can store various types
its a list of 1 user so would i use result[0].mention?
Yep!
thanks
Do know it can raise an error
one thing at a time lol
You can use, LBYL or EAFP, depends on what you're doing
are you using sqlite3?
it doesnt seem like ur awaiting your db call
should i?
ofc
use aiosqlite
Also, you shouldn't be using f-strings, it's bad practice
sqlite3 is blocking which is bad so you'd want to use like asqlite or aiosqlite or something
it has the same syntax as sqlite
I wouldn't recommend asqlite
you can use ? for the key
but apart from that yes you shoudlnt
*shouldnt
I don't like to expect errors so I prefer LBYL always lol
I also prefer it depending on my situation
is this not counter intuitive???? reactions[0].users already returns a list of users?
i don't believe that exists on .users
it should
no?
Flatten isn't a thing there anymore
dpy so shit im sorry
its an async iterator*
thanks
Big words I should know more about
Do know an actual async iterator object doesn't exist but if a certain object has the need requirements it would be considered one
https://docs.python.org/3/glossary.html#term-asynchronous-iterator
while an async generator is an actual thing
!e
import asyncio
async def bar():
yield 1
async def main():
print(bar())
asyncio.run(main())
@primal token :white_check_mark: Your 3.11 eval job has completed with return code 0.
<async_generator object bar at 0x7f0861c8a8d0>
use next
So async generator is the object but the need for the object is an iterator 
but i'll raise if the gen is empty
small words are better, don't worry about it
Hard agree. Lol
some wise dude once said if you can explain something to a child, then you've mastered it
or something like that idk i dont read
bruh
clearly i have not mastered it :p
yea its a saying and more or less true
iterator* an iterator implements a __next__ and can implement __iter__, while a generator implements __iter__, send, "throw", close and can implement __next__
fr on jah
I rarely use gens
Yea this is actually a pretty widely used belief. I have spent some time at a pretty difficult school and I'm horrible with remembering terms and all my tests I would describe what the answer is because I'd blank on the words and I'd get full credit lol
!e
myGen = (i for i in range(20))
print(myGen)
print(next(myGen))
@alpine cove :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | <generator object <genexpr> at 0x7f2485d881e0>
002 | 0
you should feel embarrassed
?
a gen implements next
Best of luck with that. Catch you later
It can
yea u said it didnt
where
i could you could call it a
next gen
🥁
lmfao
mfw when then funny comes back to me once a month
bruh you edited ur message even more embarrassing
at least admit your mistakes
I wont because I'm not incorrect?
I'm not here to help 5yr olds like you just forget it
Please respect other server members and re-read our #code-of-conduct & #rules if you need to.
A generator can be an iterator not vice-versa, they're both different objects that have different behavior, saying
but i'll raise if the gen is empty
would be incorrect as it's a async iterator and not a generator as it doesnt implement certain methods making it a generator
yea got it
yea I usally dont work with fancy asnyc iterators...
I'll loom into that tho thx
there is no difference between an async gen and an async iter right?
There is!
or to be more precised there is no async gen
for more info look in
https://docs.python.org/3/library/collections.abc.html
point taken
you all have experience in different bots for runescape servers with eco and all that
this is specifically for discord bots
i’m trying to figure out how to make a economy bot in discord to mimic runescape wallet
hey can somebody tell me how to piece this together?
@bot.tree.command(name='support')
async def support(interaction: Discord.Interaction):
@commands.has_role('verified')
async def create_channel(ctx):
channel_name=(f"help--{ctx.author.name}")
guild = ctx.guild
existing_channel = discord.utils.get(guild.channels, name=channel_name)
if not existing_channel:
print(f'Creating a new channel: {channel_name}')
await interaction.guild.create_text_channel(channel_name)
What are you trying to do
hmmm
import discord
from discord import app_commands
from discord.ext import commands
#intents = discord.Intents.default()
#intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
@bot.event
async def on_ready():
print(f'We have logged in as {bot.user}')
try:
synced = await bot.tree.sync()
print (f"Synced {len(synced)} command(s)")
except Exception as e:
print (e)
@bot.tree.command(name='support')
async def support(interaction: Discord.Interaction):
@commands.has_role('verified')
async def create_channel(ctx):
channel_name=(f"help--{ctx.author.name}")
guild = ctx.guild
existing_channel = discord.utils.get(guild.channels, name=channel_name)
if not existing_channel:
print(f'Creating a new channel: {channel_name}')
await interaction.guild.create_text_channel(channel_name)
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.errors.CheckFailure):
await ctx.send('You do not have the correct role for this command.')
#bot.run('...')
im trying to figure out what is missing and what is supposed to be taken out
ive been working on this all afternoon
so i need to put something after the async def support(interaction: Discord.Interaction):?
im trying to let users make a help channel that includes their name in the channel
All I see are syntax errors
.. Do you know how functions work? This is basic python
import discord
from discord import app_commands
from discord.ext import commands
#intents = discord.Intents.default()
#intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
@bot.event
async def on_ready():
print(f'We have logged in as {bot.user}')
try:
synced = await bot.tree.sync()
print (f"Synced {len(synced)} command(s)")
except Exception as e:
print (e)
@bot.tree.command(name='support')
@commands.has_role('verified')
async def create_channel(ctx):
channel_name=(f"help--{ctx.author.name}")
guild = ctx.guild
existing_channel = discord.utils.get(guild.channels, name=channel_name)
async def support(interaction):
if not existing_channel:
print(f'Creating a new channel: {channel_name}')
await interaction.guild.create_text_channel(channel_name)
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.errors.CheckFailure):
await ctx.send('You do not have the correct role for this command.')
#bot.run('...')
i changed it around no existing_channel and channel_name is lit up
yeah i know basic python
but how does that look so far
this runs
but im getting an error in the server when i try to invoke the command
You aren't responding
support doesn't have a decorator
