#discord-bots
1 messages · Page 116 of 1
Now I get this error: ValueError: View is not persistent. Items need to have a custom_id set and View must have no timeout
The problem is SelectionOption doesn't have a custom_id.
Do you know what I could do to fix it?
Thanks!
member.send(‘1’)
member2.send(‘2’)
You just have to define the members
if you wanna make a view persistent all of its items should have a custom_id
yeah I get that but SelectOption doesnt have a custom_id
Along with this, when I enter the font into VSCode, it shows me this
The character U+026a "ɪ" could be confused with the character U+0069 "i", which is more common in source code. Adjust settings
Anyway to make sure it scanneds U+026a instead if U+0069?
By font I mean this as a string: sᴛʀɪᴋᴇ ɪᴛ ʙɪɢ
did you add the select option to the view?
Same thing with this:
!d discord.SelectOption
Should be relatively easy to include a custom_id
just make sure it's unique
is there a way to make a certain role bypass slash commands cooldown?
I think i finally understood dicts but what do i do with the if self.name2.value == "blue":? Do I have to delete that? or with what do i have to replace that
you remove the if/elif chain since you have dicts now
what do you mean by making sure its uniqe? different label?
the string basically just has to be different
my code ```py
@bot.command()
async def mines(ctx,round_id: str):
with open("ids.txt",'a') as ids:
if ctx.author.id in ids:
pass
else:
await ctx.send("You need to login to use that!")
like this? i just dont know how to check if the value is None then if i delete the if chain
the string is different but for some reason it still gives me this error
Can I see the code
Just something like:
if self.value2 is None:
# send embed with random color
else:
color = embed_colors.get(self.value2)
# send embed using `color`
Something like this then?
class area_selection(discord.ui.Select):
def __init__(self):
options = [
discord.SelectOption(label="דרום"),
discord.SelectOption(label="מרכז"),
discord.SelectOption(label="צפון")
]
super().__init__(placeholder="בחר אזור מגורים", max_values=1, min_values=1, options=options)
async def callback(self, interaction: discord.Interaction):
print("callback")
option_name = interaction.data['values'][0]
user = interaction.user
guild = interaction.guild
roles = [role for role in guild.roles if role.name in area.values()]
for role in roles:
if role in user.roles:
await user.remove_roles(role)
elif role.name == option_name:
await user.add_roles(role)
await interaction.response.defer()
class area_selection_view(discord.ui.View):
def __init__(self):
super().__init__()
self.add_item(area_selection())
In my main file I called the area_selection_view function and did the persistent view bot but the error is from here
@sick birch
you dont have a custom_id set to the Select?
idk man thats about the extent of my knowledge lol
damn i love you bro!!! no more 200 lines of code (no homo)
DROP TABLE tablename
it's alright, thanks for tryna help lol
seems like the 'double down' works fine because I don't get timed out after doubling down
the stand button works fine as well, but if I draw 1 card then stand it will time me out
very weird results i'm getting and I have no idea how to fix it haha
super().__init__(placeholder="בחר אזור מגורים", max_values=1, min_values=1, options=options, custom_id="area_selection")
do I need to do something like this?
nope just the table name
yessir
I still get ValueError: View is not persistent. Items need to have a custom_id set and View must have no timeout
nvm fixed it by adding
self.timeout = None
in the area_selection_view
could have passed timeout=None in the init itself
how do you disable a button after its pressed? i tried self.button1.disabled = True inside the button interaction but that doesnt work and doesnt give errors
that disables the button in code,
you gotta edit the message with the current view to disable on discord
ah okay
is there an easy way or do i need to make a whole new view with disabled buttons lol
just pass your current view instance to the view kwarg
so specify that the button is disabled after interaction, then edit the message with the same view=view and itll work?
just interaction.edit_original_response(view=self)
i'm not seeing where you defined it a custom ID
[Running] python -u "c:\Users\PC\Desktop\Noas Bot\main.py"
[2022-10-29 21:40:41] [INFO ] discord.client: logging in using static token
Traceback (most recent call last):
File "c:\Users\PC\Desktop\Noas Bot\main.py", line 496, in <module>
bot.run("MY TOKEN")
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 828, in run
asyncio.run(runner())
File "C:\Program Files\Python39\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Program Files\Python39\lib\asyncio\base_events.py", line 647, in run_until_complete
return future.result()
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 817, in runner
await self.start(token, reconnect=reconnect)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 745, in start
await self.login(token)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 589, in login
await self.setup_hook()
TypeError: setup_hook() missing 1 required positional argument: 'self'
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x0000018E24179A60>
Traceback (most recent call last):
File "C:\Program Files\Python39\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "C:\Program Files\Python39\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Program Files\Python39\lib\asyncio\base_events.py", line 751, in call_soon
self._check_closed()
File "C:\Program Files\Python39\lib\asyncio\base_events.py", line 515, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed``` wtf is that
TypeError: setup_hook() missing 1 required positional argument: 'self'
i think setup_hook is missing the first self argument
OH YES
class PersistentView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label='Green', style=discord.ButtonStyle.green, custom_id='persistent_view:green')
async def green(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message('This is green.', ephemeral=True)
@discord.ui.button(label='Red', style=discord.ButtonStyle.red, custom_id='persistent_view:red')
async def red(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message('This is red.', ephemeral=True)
@discord.ui.button(label='Grey', style=discord.ButtonStyle.grey, custom_id='persistent_view:grey')
async def grey(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message('This is grey.', ephemeral=True)
class PersistentViewBot(commands.Bot):
...
async def setup_hook(self) -> None:
print("Setup hook called")
self.add_view(PersistentView())
@bot.command()
async def prepare(ctx):
await ctx.send("What's your favourite colour?", view=PersistentView())
``` doesnt work after i restart the bot
But it prints Setup hook called?
no
ah
that's the issue
for some reason your setup hook isn't even being called
perhaps you're not on discord.py version 2?
cuz i have it twice
ah
i am i think
get rid of the other one
but that prints that my bots onlinre
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.
you could print it in this setuphook too
async def setup_hook():
print(f"{bot.user.name} is online!")
try:
synced = await bot.tree.sync()
print(f"Synced {len(synced)} command(s)")
except Exception as e:
print (e)
is overwriting the other setup hook
okay wait'
exactly what i was looking for, thank you
Soo, does someone knows why this won't work?
any errors?
class PersistentViewBot(commands.Bot):
async def setup_hook(self) -> None:
print(f"{bot.user.name} is online!")
try:
synced = await bot.tree.sync()
print(f"Synced {len(synced)} command(s)")
except Exception as e:
print (e)
print("Setup hook called")
self.add_view(PersistentView())```
``` File "c:\Users\PC\Desktop\Noas Bot\main.py", line 468
async def setup_hook(self) -> None:
^
IndentationError: expected an indented block```
hey does anyone got any ideas how to do a check for if the chat is active? like if theres at least 4 active chatters currenly, theres a few ideas i have to do this but thought id ask to see if theres a btter way
when it is used, and it is successfully used without any errors
oh yeah well, its not working 🤷♂️
!d discord.TextChannel.history or on_message
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") that enables receiving the destination’s message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") to do this.
Examples
Usage...
your function needs to be indented so it's inside of the class
so what, get the last 50 msgs, check dates to see if it was in the last 5-2 mins, and ch eck if there from diff users?
ioh
its not printing
you can filter messages by using the before/after/around kwargs, but sure
read the docs
class PersistentView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label='Green', style=discord.ButtonStyle.green, custom_id='persistent_view:green')
async def green(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message('This is green.', ephemeral=True)
@discord.ui.button(label='Red', style=discord.ButtonStyle.red, custom_id='persistent_view:red')
async def red(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message('This is red.', ephemeral=True)
@discord.ui.button(label='Grey', style=discord.ButtonStyle.grey, custom_id='persistent_view:grey')
async def grey(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message('This is grey.', ephemeral=True)
class PersistentViewBot(commands.Bot):
async def setup_hook(self) -> None:
print(f"{bot.user.name} is online!")
try:
synced = await bot.tree.sync()
print(f"Synced {len(synced)} command(s)")
except Exception as e:
print (e)
print("Setup hook called")
self.add_view(PersistentView())
@bot.command()
async def prepare(ctx):
await ctx.send("What's your favourite colour?", view=PersistentView())
maybe unix timestamps works
do you have an error handler that might be eating your errors? have you made sure that the cog was loaded correctly?
the cogs seems to load correctly and there's no error handler
What are you trying to do 🤨
logs channel
you have a PersistentViewBot class but you're not using it anywhere
this is the only setup hook you have?
yes
so what do i do
use it?
I mean surely you created that class to use it right
on line 32
bot = commands.Bot(command_prefix="-", help_command=None, intents=discord.Intents.all())
is there a way to do this in response to a message instead of an interaction? when a user sends a message, the bot sends a message in a seperate channel and if i try to edit the message it tries editing the message the user sent instead of the message sent by the bot
the setup_hook for this instance is defined as ```py
@bot.event
async def setup_hook():
print(f"{bot.user.name} is online!")
try:
synced = await bot.tree.sync()
print(f"Synced {len(synced)} command(s)")
except Exception as e:
print (e)
what about that
that's the bot you're running
now i changed it to that
class PersistentViewBot(commands.Bot):
async def setup_hook(self) -> None:
print(f"{bot.user.name} is online!")
try:
synced = await bot.tree.sync()
print(f"Synced {len(synced)} command(s)")
except Exception as e:
print (e)
print("Setup hook called")
self.add_view(PersistentView())
editing someone else's message?
it tries to but it cant do that. i want it to edit the bots own message that got sent with the view for buttons
if im not wrong, if you want to edit something the bot sent you can store it inside a variable before sending it
my_message = await interaction.followup.send(". . .")
you cant
user sends a message, levels up, the bot sends a message in a seperate channel with a view containing buttons. i want to disable one of the buttons upon interaction with it. i have interaction: discord.Interaction in the init then also self.interaction = interaction so it can be sent to the children through self. if i do self.interaction.edit(view=self) then it tries to edit the message the user sent instead of its own
oh
i have it working when i use a different view from an interaction because i can use edit_original_response but that doesnt work because its not being sent in response to an interaction
hm how do you use interaction.followup.edit_message()?
I have a json file with this structure:
{
id: {
"message": "abc"
"link": "www.www.www"
...
}
id2: {
"message": "abc2"
"link": "www.www.www2"
...
}
id3: {
"message": "abc3"
"link": "www.www.www3"
...
}
...
}
I want to access each message link and channel id and every other thing via for loop in pyhon, then send every message to every channel
I tried it like this:
with open("data.json", "r") as f:
data = json.load(f)
print(data)
for channel in data:
for message in data:
print(channel)
print(message)
name = message[0]
msg = message[1]
inv = message[2]
id = channel[3]
print(name, msg, inv, id)
c = client.get_channel(id)
embed = nextcord.Embed(title=name, description=f"{msg}\n{inv}")
c.send(embed=embed)
But it's just taking the ID and for example message[0] would be i because of the "id"
how do i do that?
and, what's that? Never heard of it
im on discord.py
thats for autocomplete interactions
how does it look like? What is it?
'message' object has no attribute followup
this worked 🤔
async def testing_command(self, interaction: discord.Interaction):
await interaction.response.send_message("Test 1")
message = await interaction.followup.send("Test 2")
await asyncio.sleep(5)
await interaction.followup.edit_message(message_id=message.id ,content="Test 3")
didn't mean to ping
you stored the followup, not the response.send_message
im okay with pings
oh yeah I sent the wrong message and edited it afterwards
they are autocompletes for slash command options
oh oky
can someone take a look at this?
you should look into using dictionaries
kk
is there a way to make a certain role bypass slash commands cooldown?
!d discord.app_commands.checks.dynamic_cooldown
@discord.app_commands.checks.dynamic_cooldown(factory, *, key=...)```
A decorator that adds a dynamic cooldown to a command.
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns are based off of the `key` function provided. If a `key` is not provided then it defaults to a user-level cooldown. The `key` function must take a single parameter, the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") and return a value that is used as a key to the internal cooldown mapping.
If a `factory` function is given, it must be a function that accepts a single parameter of type [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") and must return a [`Cooldown`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Cooldown "discord.app_commands.Cooldown") or `None`. If `None` is returned then that cooldown is effectively bypassed.
Both `key` and `factory` can optionally be coroutines.
I was able to make a variation of this work. Thanks!
How can I change my bots status to DND? I forgot
Can you set notifications for a channel?
bot = commands.Bot(command_prefix="!", status=discord.Status.idle)
If I'm remembering correctly
wrong status
!d discord.Status.dnd
The member is “Do Not Disturb”.
Yea that one
idle is the yello moon one!
You right
await bot.get_channel(1034484568562081872).send(f"Welcome {user.mention} ! 👋 if you need any support [#1034471573383557261](/guild/267624335836053506/channel/1034471573383557261/)")
How would i fix this?
Fix what?
Can you send the entire function?
Yup sure
Perhaps add a print statement to see if the function is being called at all?
It works when its {member.name} but im not sure how to ping them
{member.mention} perhaps?
ill test it now, do you know have a moving discord bot status?
like changing
Like, on an interval?
yes
if you have the member object that's unnecessary. most of the time u only do that when u just have the ID
member.mention works fine
so like 1 min it will be
watching many members another 1 min watching website
ect
use tasks
How would i do that? I'm a bit new to py
some examples
how would I be able to check if a json value = 1, so then It doesnt run a command
!d discord.ext.commands.Bot.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
It's in oauth2 > url generator
The generated url at the bottom will appear if you put in a redirect url. Or select different options that don't require it
whats a redirect url
what do i put there
i made a discord bot a couple years ago and i would just select the permissions and it would give me the url
this is all new to me
I've only ever used it when making a bot on a serverless site. I'm assuming you have some scopes selected that you don't actually need
Unselect the guilds.join scope, it'll join your server when you follow the url
And you're gonna want to select the bot scope as well
Did you select the bot scope
Is it listed at the top of members, where the active members would be
no its not in the server
I've always selected applications.commands and bot then selected whatever permissions I need and have no issues with the bot joining any servers
im not getting a captcha quiz if thats relevant
That doesn't always show
ill try tio make the bot again
yea its not joining
okay wait so @mighty pilot
i took this link and replaced the id with my id, the bot joined the server
but now i run the code i get an error
What error
Hey @dapper bluff! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discord.com/developers/applications
Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!
import discord
from discord.ext import commands
TOKEN = ''
description = 'bot'
bot = commands.Bot(intents=discord.Intents.all(), command_prefix='!', description=description)
@bot.event
async def on_message(msg):
if msg == "test":
await msg.channel.send("hi")
bot.run(TOKEN)```
is that a erro from this or bot
Oh yea you need to enable priveleged intents in the developer portal
u need to enable all 3
Yup all 3 toggles
k
Because your code requests all 3
ok so
the code is working and so is the bot but
import discord
from discord.ext import commands
TOKEN = ''
description = 'bot'
bot = commands.Bot(intents=discord.Intents.all(), command_prefix='!', description=description)
@bot.event
async def on_message(msg):
if msg == "test":
await msg.channel.send("hi")
bot.run(TOKEN)```
when i say !test it doesnt say hi
no errors
u need msg.content and that's an event
You're using on_message in place of a command
no a command so no prefix
If you just say test it'll sat hi
what does @bot.X do
so what do i write
@bot.command() ?
i advise you follow a tutorial or just actually look at the docs especially if you are just starting. and then ask questions if you are stuck on something.
otherwise if ppl just keep telling u what to do you'll never learn
i know python "fluently"
i just dont know this api, so theres no need for a whole tutorial for this
just pls tell me, instead of "@bot.event" what should i puyt
then why not read docs if you know python fluently?
we aren't just going to keep spoon feeding u
1 question then ill screw off
bot is missing permissions
You need to give the bot proper permissions in the server
Usually accomplished with roles
why does the error handler not work?
i also got an exception for an KeyError but it also failed
I don't use nextcord so I can't help with that one
its just like discord.py, just tell me how you would fix it in discord.py and I will try to make something out of it
do you guys know how to do subcommands with slash commands ?
which library?
async def get_ip(ctx,user: discord.User):
if ctx.content.startswith("!get ip"):
randomIp = f"{str(randint(1,255))}.{str(randint(1,255))}.{str(randint(1,255))}.{str(randint(1,255))}"
await ctx.channel.send(randomIp,user.mention)```
how can I check if their second message was a user ping?
this doesnt work
why are you doing all this instead of just using the commands extension
i am
oh shoot wait
then why are you checking if ctx.content.startswith("!get ip"), there should be no need for you to ever do that
i was messing around with bot.event and i forgot to remove
do you want the user parameter to either be a mention or the word ip?
How can I do @command using spaces?
I would prefer !get ip @dapper bluff over !get_ip @dapper bluff
subcommands or use the name parameter in the decorator
@bot.command()
async def get(ctx,args): #if args == "ip"
like that?
ok what about the third message, how can i get that?
just make another parameter
oh thats how it works?
@bot.command()
async def get(ctx,second,user: discord.User):
if second == "ip":
if user:
randomIp = f"{str(randint(1,255))}.{str(randint(1,255))}.{str(randint(1,255))}.{str(randint(1,255))}"
await ctx.channel.send(randomIp)```
ok so this works but it errors if user is not a user
Its true I dont want it to run if user is not a User, but I would prefer if it didnt error (to keep the console clean)
so how can I check if user is a User so it wont error
if that makes sense
ill try try
man i want to seperate my 1300 lines into cogs so bad.. but i feel like something is going to break if i do 
cant install discord or discord.py (idk if theres a difference) send help
pick the first option for C++ development and install it, or alternatively skip it and downgrade to 3.10 which has prebuilt wheels for the three packages listed in your error message
downgrade to discord 3.10?
no, python 3.10
what version is the newest
python 3.11, which is what you have installed
oh calm with downgrading then
ez w now imma go figure out how to
ty for the help
back how tf do i downgrade
i just uninstall python then reinstall a older version right?
you dont have to uninstall 3.11, but it can be confusing having both versions if you dont know how to choose between the two
there any way to install 3.10 in the cmd?
with the Chocolatey package manager i guess if you have that installed, you can ask more about it in a help channel
Just ask your question
it pays off when you get things working trust me
I know it would. Feels like I JUST got all the big points down though so I don't want to tear down and go through all that troubleshooting again
i'm still struggling with my stupid bot timing me out for no reason 😭
Yea idk what's up with that. I have 2 button menus and don't have any problems with my timeouts
if i draw once then stand it will time me out after the game ends
even though the very first line of code under my stand button is self.stop()
but it works properly if i dont draw and stand straight away
doubling down works fine
Anyone know how i can have this kind of button under an embed?
Buttons (or components) are now in the 2.0a version of the library.
If you wish to use Buttons (and Selects/Dropdowns), please view the documentation for discord.ui here:
https://discordpy.readthedocs.io/en/latest/interactions/api.html#bot-ui-kit
You can also view examples in the repo: https://github.com/Rapptz/discord.py/tree/master/examples/views
Thank you
I have realised i needed to update to discordpy 2.0+, however now my code will not run. If i try the invite user command. I get this error saying unexpected 'value'
Not sure exactly what is the issue, i have a feeling its a deprecated value i used
Has await ctx() changed?
is there a way I can make praw faster in sending something from Reddit?
because right now its really slow loading images
its description not value
Embeds have never had a value argument. The fields have though. But maybe you wanted description
what exactly is slow?
after you type the command I have, the loading time for the image is slow. It will show the embed then just a loading picture for a while then after ~20-30 seconds it shows the image. I was wondering if I can just preload the images before hand maybe on_ready or smth
1.7 used to use **kwargs as the parameters for __init__ so any incorrect arguments like value= wouldnt have caused an error, but your message wouldnt have appeared either
sounds like an issue on your side? if the embed is already sent with the image attached and is just "loading" pretty sure thats a client issue, no?
Usually I would think the same but its the same with people in my server, we are all unable to see the photo until ~20 seconds then it shows for all of us
at the same time
its an embedded image link? or a discord embed with an image attached?
the command im using for it is embed = set_image(url=url) so a image link
that's weird never seen that before.
i guess since it's a url link still it would be an issue with where the image is hosted then
not sure
it varies
a shitty way to fix it would be defer the command download the img, then set the image as a file and send then
but if it takes long to load the image i would assume it takes a min to save it aswell
I wouldnt mind that, I got the resources on my hosting
dont know till I try
then yea i would suggest that.
How would I go about doing that
rather than the img sitting there loading for everyone
im new to discordpy
I would much rather it take a second without posting then suddenly showing up loaded then it just sitting there loading
?
i figured out
@bot.command()
async def set(ctx,second,user: discord.User):
how can i make an arg which is everything else
a table
You can use * to consume everything.
ok also
async def set(ctx,second,user: discord.User):
user: discord.User
How can I figure out if a message is a mention of a user
Because that works until I want a set command that doesnt relate to users
@bot.command()
async def get(ctx,second,third):
if discord.User.mentioned_in(third):
?
...no
well thats what im trying to do
because how am i supposed to know who user is
Why don't you just require a user object instead of second,third stuff?
what if i want a function that sets role name
!set rolename "hello"
well thats gonna cause an issue
i meant to reply to this
Hey, I have a question
One sec, let me find it
Hey, does someone have experience with discord.py?
If so, I have a bot, which has commands with custom prefix, I want to have the custom prefix removed and the commands should be slash-commands, since I'm to stupid to do it, I would like to know if someone can help me
Alright, you can use third.mentions to get the mentions of of the third value
discord.py 2.0a slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
Read that and you'll understand how to use slash commands.
Let me know if you're confused anywhere :)
@bot.command()
async def get(ctx,second,third):
if second == "ip":
user = third.mentions```
like this?
@hollow agate
I`m confused with slash commands, the issue is, that it's my first time using python since 1 year
and I have never done something with slash commands
What I sent literally gives you examples
It's spoonfeeding, you can't get any more than that...?
You can genuinely copy and paste the code and it'll work
If not, what are you struggling with?
@dapper bluff there's no easy way to do it, just use separate commands.
It'll make your life 100x easier
k
what about this tho
is * a table?
Table? What?
!say hello how are you today
*[1] = hello
*[2] = how
*[3] = are
etc...
thats a table
ok but how do i get the rest of the words in a message
thats what ive been trying to ask
I dont need every single word I just need the entire thing
Ex:
@client.command()
async def test(ctx, member: discord.Member, *, reason=None)```
If you use ".test @hollow agate hello how are you today"
`reason` will be `hello how are you today`
let me give u an example of what i need
!set note @dapper bluff he is a user in this server who is a user
!get note @dapper bluff
--> he is a user in this server who is a user
Let me just give you the code
I need to be able to get all of the words after the member argument
@client.command()
async def set(ctx, first, member: discord.Member, *, note=None)```
Then you have to store the note somewhere in a database and get it out of the database using the get command.
so if i print * ill get he is a user in this server who is a user
mhm
Wait- no.
ah ok thats what ive been trying to ask
If you print note you will get it.
but you defined note to None
That's if they just do "!set note @hollow agate" you can simply do
@client.command()
async def set(ctx, first, member: discord.Member, *, note=None):
if note == None:
await ctx.reply('Please provide a note!')
else:
...put the note in the database
await ctx.reply("I've added the note!")```
Consider learning basic Python before trying to do discord.py. Discord.py isn't beginner friendly at all
excuse me? I know fucking python
Im asking about the arguments in a discord.py function dumbass
This is literally basic Python, is it not?
uh no this is discord.py
😂 alright
let me show u what i have already
Hey @dapper bluff! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discord.com/developers/applications
Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!
import discord
from random import randint
from discord.ext import commands
import json
def importData(location, data):
filename = f"{location}.JSON"
old_data = extractData(location)
data = {**old_data, **data}
with open(filename, "w") as f:
json.dump(data, f)
def extractData(location):
with open(f"{location}.JSON", "r") as read_file:
return json.load(read_file)
TOKEN = ''
description = 'bot'
bot = commands.Bot(intents=discord.Intents.all(), command_prefix='!', description=description)
@bot.command()
async def get(ctx,second,user: discord.User):
if second == "ip":
ipFound = False
for id,ip in extractData("IPs").items():
if id == str(user.id):
ipFound = True
await ctx.channel.send(ip)
if not ipFound:
randomIp = f"{str(randint(1,255))}.{str(randint(1,255))}.{str(randint(1,255))}.{str(randint(1,255))}"
userData = {str(user.id):str(randomIp)}
importData("IPs",userData)
await ctx.channel.send(randomIp)
@get.error
async def get_error(ctx,error):
if isinstance(error, commands.BadArgument):
await ctx.send("https://tenor.com/view/shoebill-bird-rain-beautiful-gif-18429868")
does this look like it was written by someone who "doesnt know basic python"
the question was never about python, it was about discord.py, read the channel name
That is pretty basic code, however, knowing how to consume all via * is pretty basic Python... along with setting a variable to None.
guess what genius, the variable didnt need to be None
...but I can't argue, I don't know what you know 
A heads up... if you don't have the =None and they don't add a note, it will raise an error.
You do you, I guess
That works, but I personally wouldn't do it for a few reasons.
@get.error
async def get_error(ctx,error):
if isinstance(error, commands.BadArgument):
await ctx.send("https://tenor.com/view/shoebill-bird-rain-beautiful-gif-18429868")```
In your case, it doesn't really matter
as u can see here, i make the bot send a gif when the code errors
define "not basic" code
exactly you have no definition
you just say shit to fit youre narrative
Well then, I help people... no good deed goes unpunished 😄
Good luck with your bot! 😊
thank you
You want to take it down quite a few notches please?
Hey!
I have a purge command,
But I want it to purge all of the messages besides its own messages
How would i do something like that?
@slate swan, you can use a TextChannel.purge check! Here's some documents on it: https://discordpy.readthedocs.io/en/stable/api.html#discord.TextChannel.purge
for userId,note in extractData("notes").items():
if userId == str(user.id):
noteFound = True
warning = await ctx.send("User already has a note, would you like to override it?")
await warning.add_reaction(":white_check_mark:")
confirmation = await bot.wait_for("reaction_add", check=":white_check_mark:")```
def is_me(m):
return m.author == client.user
deleted = await channel.purge(limit=100, check=is_me)
await channel.send(f'Deleted {len(deleted)} message(s)')``` You can view this example and edit the `is_me` to your liking!
the warning message is being displayed, but no check mark is being added, why?
im using that, but i dont want it to purge bots messages
Put the warning message in a variable
then add the reaction to that variable
whats what im doing
Oh i didnt see
How have you altered the is_me?
You need to use unicode if it's not a custom emoji iirc.
simple
can i use "✅"
Yes
ok thx
Might try removing the : from the emoji name. Looks like that method takes a string too.
?tag add_reaction
This is not a Modmail thread.
ah nvm
Hello modmail.
Different server
Nevermind:
The emoji may be a unicode emoji or a custom guild Emoji.
await warning.add_reaction("✅")
await warning.add_reaction("❌")
confirmation = await bot.wait_for("reaction_add")
how can I check to which the user responded too?
There's an example here https://discordpy.readthedocs.io/en/stable/api.html?highlight=wait_for#discord.Client.wait_for
They are looking for the thumbs up but you can look for what you need.
its not reognizing check
oh wait
it doesnt help
I dont know what to put for the last parameter, or why they are using a function
I dont need a function
i just want to know which reaction the user reacted too
They are using a function because that third argument (check) is a callback. It's just the example I saw while here. Probably other ways of doing it.
What is that peice of code doing?
idk what all the api functions do
just how would it look to a discord user
You're confused on the def check(reaction, user) part, right?
i may of got it one sec
bot.wait_for("reaction_add") is going to return two values according to the documentation. The reaction object and the user object.
So, at the minimum, you need:
confirmation, user = await bot.wait_for("reaction_add")
confirmation here should be a Reaction object which you can pull the .emoji from and know which one it is. user is who clicked/added a reaction.
Beyond that, the logic is a bit more than I can help with. I've not done this with bots 
warning = await ctx.send("User already has a note, would you like to override it?")
await warning.add_reaction("✅")
def check(reaction, user):
return user == ctx.author and str(reaction.emoji) == '✅'
try:
reaction,user = bot.wait_for('reaction_add', timeout=5.0, check=check)
except asyncio.TimeoutError:
await ctx.send("Timed Out")
else:
await ctx.Send("Overriden")
importData("notes",msg)```
not workign
im getting an error
cannot unpack non-iterable coroutine object
reaction,user = bot.wait_for('reaction_add', timeout=5.0, check=check)
!d discord.Client.wait_for - You need to await it
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
elif second == "note":
print("get note called")
noteFound = False
for id,note in extractData("notes").items():
if id == str(user.id):
noteFound = True
await ctx.channel.send("[User Notes]",note)
print("here")
if not noteFound:
ctx.send("[ERROR] User has no notes.")
get note called does print, but nothing else does
No errors, just nothing happens, here does not print
Its almost like that loop is yielding the thread?
you have an error handler that eats your errors
yea i saw noticed lol
im trying to run this task every 5 minutes on the minute: 1:05 > run, 3:25 > run, every 5th minute, run. I did it for ever hour on the hour: @tasks.loop(time=[datetime.time(hour=h, minute=0) for h in range(24)]) but idk how to do it for minutes. this is what i tried: @tasks.loop(time=[datetime.time(minute=h) for h in range(5)]) but this like never runs
ping on reply please :>
that code would run at 00:00, 00:01 .. 00:04
instead of using the time param here
set the minutes to 5, and in before_loop, check the current time, and wait until the next multiple of 5
im trying to use youtube_dl and voice to stream youtube videos through the bot
but after ~3 mins it stops with this error
anyone know the cause of it?
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
Can't help you sorry
hello ive had this serverinfo code for a while but now it recently stopped working and gave error 'Guild' object has no attribute 'region'
So many str casts
Guild.region doesn't exist anymore. It was removed.
fetch = (await cursor.fetchall())[0]
the parens are important
thats dumb.
I don't think you can even change a server's region anymore?
Ah
it was something like that, wait
so like im not able to have a serverinfo command? anymore
or just region
yeah its rtc_region
Just remove the region part of the serverinfo command
I have nothing to say
..why would that be the case
word
What is ctx.member supposed to be
You didn't answer my question
What is ctx.member supposed to be? That doesn't exist
You have a param named member though
uhm?
await report.send(f"<@&1005078296729501796> {interaction.user.mention}", embed = embed, view = view)
await interaction.response.send_message(f"Please head over to {report.mention}", ephemeral=True)
await report.edit(locked = True)
yo so idk if im locking threads right but this aint working
Hello!
I am making a discord bot that checks to see if a user is staff
Code:
perms = json.load(open('perms.json', encoding='utf-8'))
def owner(ctx):
return str(ctx.author.id) in perms['OWNER_ID']
@bot.slash_command()
async def command(ctx):
if not owner(ctx):
await ctx.respond("Invalid perms")
But instead of it checking data from a .json file I want it to check if a user has a specific role in my server
How would I do something like that
!d discord.ext.commands.has_role
@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
If the message is invoked in a private message context then the check will return `False`.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
but then how would i return the error if they dont have owner?
discord.on_error(event, *args, **kwargs)```
Usually when an event raises an uncaught exception, a traceback is logged to stderr and the exception is ignored. If you want to change this behaviour and handle the exception for whatever reason yourself, this event can be overridden. Which, when done, will suppress the default action of printing the traceback.
The information of the exception raised and the exception itself can be retrieved with a standard call to [`sys.exc_info()`](https://docs.python.org/3/library/sys.html#sys.exc_info "(in Python v3.10)").
Note
`on_error` will only be dispatched to [`Client.event()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.event "discord.Client.event").
It will not be received by [`Client.wait_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_for "discord.Client.wait_for"), or, if used, [Bots](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#ext-commands-api-bot) listeners such as [`listen()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.listen "discord.ext.commands.Bot.listen") or [`listener()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog.listener "discord.ext.commands.Cog.listener").
Changed in version 2.0: The traceback is now logged rather than printed.
You can check if the error argument is an instance of the discord.ext.commands.MissingRole or not
Yes like try check if user has role if not call the missing role exception which reply's they don't have perms
Found a work around!
def owner(ctx):
role = ctx.guild.get_role(<role id>)
@bot.slash_command()
async def ping(ctx):
if not owner(ctx):
await ctx.respond("Error")
else:
await ctx.respond(f"Pong! `{round(bot.latency* 1000)}ms`")
You can try:
@commands.has_permission(administrator=True)
hm
can you send or put one of you commands on hastebin and send it here!
@crimson horizon
@client.slash_command(name="start", description="Start your journey with many partners")
@commands.has_permissions(administrator=True)
async def start(interaction: Interaction):
await interaction.response.send_modal(Modal1())
!d discord.app_commands.check
@discord.app_commands.check(predicate)```
A decorator that adds a check to an application command.
These checks should be predicates that take in a single parameter taking a [`Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction"). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure "discord.app_commands.CheckFailure") exception is raised and sent to the appropriate error handlers.
These checks can be either a coroutine or not.
Examples
Creating a basic check to see if the command invoker is you...
@bot.command(
name="play",
description="노래재생",
options= [
interactions.Option(
name="query",
description="노래이름",
type=interactions.OptionType.STRING,
required=True,
),
],
)
async def play(ctx: interactions.CommandContext, query: str):
queue = []
channel = ctx.author.voice.channel
if bot.voice_bots[0].is_playing():
queue.insert(len(queue), query)```
The HTTP client has exhausted a per-route ratelimit. Locking route for 1.0 seconds.
anyone knows why this error happen?
what this mean
it doesn't have access
how do i give it access
also what u mean by that
help
Error clearly says that the connection to 127.0.0.1 has failed, it either works different on heroku, or some information that you are giving when connecting is not coorect
The bot doesn't have access to execute that action
2FA is required for that operation
Can't tell which operation, since you only showed one line of an error
it worked before without 2fa...
What "it"?
I'm guessing that action you are executing requires 2FA for moderation to be enabled on the server
hi, how can I make my discord bot execute a command / send a message everyday? (it is hosted on an online server if this can help)
!d discord.ext.tasks.loop
@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
thank you
your bot cannot perform moderation actions in servers where 2FA is enabled if you don't have your 2FA turned on

hello, i'm quite kinda new for discord.py but since they migrated the discord.py api, can someone tell me how to not confuse two embeds using on_message(message):???
!d help
"to not confuse two embeds"? wdym?
to clarify, i am trying to create a new embed but if i try to make the func ctx, itr's not responding
try "to make the func ctx" what?
and if i say like !embed it will work but the other embed will not respond
What...
i cannot get what you are saying
let me give example :
# embed 1
@client.evemt
async def on_message(message):
if message.content.startswith('!firstembed')
embed1 = discord.Embed(title='First Embed', description='First Embed', color=0x0001)
await message.channel.send(embed=embed1)
# embed 2
@client.evemt
async def on_message(message):
if message.content.startswith('!secondembed')
embed1 = discord.Embed(title='second Embed', description='second Embed', color=0x0001)
await message.channel.send(embed=embed1)
@silk fulcrum
like that\
You're overriding the first one with the second one
wtf 🤢
Why are you making commands like that
that's like ancient 200 years ago method
And for the love of God use the discord.ext.commands.Bot to make text commands

oh?
here's an example of a basic bot, commands.Bot is discord.Client, but with more features fyi
https://github.com/Rapptz/discord.py/blob/master/examples/basic_bot.py
yes?
technically not outdated, just not very good to use unless you're making something beyond basic and have no need to use commands.Bot
well they aren't TOTALLY outdated
true
they're not outdated, theres just much much better ways to do it
alright thanks for the help, i just came back from developing discord.py bots since it's "migrated"
It's client.event not client.evemt
cliemt.evemt
bonjour il y a des français ?
Je pense que vous ne pouvez parler qu'anglais ici
!d discord.ext.commands.Group.group - then create a subgroup
@group(*args, **kwargs)```
A shortcut decorator that invokes [`group()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.group "discord.ext.commands.group") and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin.add_command "discord.ext.commands.GroupMixin.add_command").
group.group.group.command
Hey!
I am making a discord bot with a help command
Code:
@bot.slash_command(description="Sends all current bot commands")
async def helpme(ctx):
embed=discord.Embed(description=f"**SOME HELPFUL LINKS** \n\nasdfasdf", color=embedcolor, timestamp=times)
embed.set_footer(text="Page (1/5)", icon_url=ctx.author.avatar)
pages = 5
button = Button(label="▶️")
button2 = Button(label="◀️")
async def button_call(interaction):
await interaction.response.defer()
if 'Page (1/5)' in embed.footer.text:
embe=discord.Embed(description="OK")
await ctx.edit(embed=embed)
button.callback = button_call
view = View(timeout=None)
view.add_item(button2)
view.add_item(button)
await ctx.respond(embed=embed, view=view)
if botlog == True:
embed=discord.Embed(title=f"Command logging", color=embedcolor, timestamp=times)
embed.add_field(name="Command ran", value="/help", inline=False)
embed.add_field(name="Comman ran by", value=f"{ctx.author.mention} : {ctx.author.id}", inline=False)
embed.add_field(name="Where", value=ctx.channel.mention, inline=False)
await bot.get_channel(logcha).send(embed=embed)
logweb.send(embed=embed)
else:
pass
But for the button_call
I want it to check the embeds footer to see what page its on and go to the next one
Is there a way i can read the text of a footer?
hello, I'm having issues with this command, it tells me Bot object has no attribute logout, though it worked the last time I launched it
@bot.command(name='stop')
async def logout(ctx):
await ctx.message.channel.send("Bisous je m'envole")
await bot.logout()```
what library are you using
import discord
from discord.ext import commands
bot = commands.Bot(intents = discord.Intents.all(), command_prefix = ";")```
!d discord.ext.commands.Bot.close
await close()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Closes the connection to Discord.
@commands.Cog.listener()
async def on_message_delete(self,message:discord.Message):
if not message.guild or message.author.bot:
return
channel = message.channel
content = message.content if message.content else "Content Unavailable"
if not channel.type == discord.ChannelType.text:
return
cursor = self.client.db.cursor()
time = discord.utils.utcnow()
cursor.execute("CREATE TABLE IF NOT EXISTS deleted_messages (guild_id BIGINT, channel_id BIGINT, message_id BIGINT, author_id BIGINT, content TEXT, timestamp TIMESTAMP)")
cursor.execute("INSERT INTO deleted_messages VALUES (?, ?, ?, ?, ?)", (message.guild.id, message.channel.id, message.id, message.author.id, content))
print("hello")
self.client.db.commit()
cursor.close()
for fn in os.listdir("./cogs"):
if fn.endswith(".py"):
bot.load_extension(f"cogs.{fn[:-3]}")
and in the end of the cog
def setup(bot):
bot.add_cog(Logs(bot))
!d discord.Webhook.url
property url```
Returns the webhook’s url.
!d discord.TextChannel.create_webhook
await create_webhook(*, name, avatar=None, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a webhook for this channel.
You must have [`manage_webhooks`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_webhooks "discord.Permissions.manage_webhooks") to do this.
Changed in version 1.1: Added the `reason` keyword-only parameter.
What's the problem?
its not working
and saying [Running] python -u "c:\Users\PC\Desktop\Noas Bot\main.py"
c:\Users\PC\Desktop\Noas Bot\main.py:48: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
bot.load_extension(f"cogs.{fn[:-3]}")
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
I can't know what's wrong with just it's not working
.
load_extension is a coroutine
Await it
i tried
File "c:\Users\PC\Desktop\Noas Bot\main.py", line 48
await bot.load_extension(f"cogs.{fn[:-3]}")
^
SyntaxError: 'await' outside function
oh
Read dpy migration guide 2.0, seems like you just updated it and now are confused @slate swan
i will try
message.channel then the channel Attribute u wana use
i know coding but never used cogs
That's not what I mean
just ctx.channel
Traceback (most recent call last):
File "c:\Users\PC\Desktop\Noas Bot\main.py", line 434, in <module>
bot.run("my token")
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 828, in run
asyncio.run(runner())
File "C:\Program Files\Python39\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Program Files\Python39\lib\asyncio\base_events.py", line 647, in run_until_complete
return future.result()
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 817, in runner
await self.start(token, reconnect=reconnect)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 745, in start
await self.login(token)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 589, in login
await self.setup_hook()
File "c:\Users\PC\Desktop\Noas Bot\main.py", line 46, in setup_hook
await bot.load_extension(f"cogs.{fn[:-3]}")
NameError: name 'fn' is not defined
it tells u the issue
i did defined it
@bot.event
async def setup_hook():
print(f"{bot.user.name} is online!")
try:
synced = await bot.tree.sync()
print(f"Synced {len(synced)} command(s)")
except Exception as e:
print (e)
for fn in os.listdir("./cogs"):
if fn.endswith(".py"):
await bot.load_extension(f"cogs.{fn[:-3]}")
File "c:\Users\PC\Desktop\Noas Bot\main.py", line 47
if fn.endswith(".py"):
^
IndentationError: unindent does not match any outer indentation level WHAT
!indention
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
If it visually does look correct- then you are mixing tabs and spaces.
@bot.event
async def setup_hook():
print(f"{bot.user.name} is online!")
try:
synced = await bot.tree.sync()
print(f"Synced {len(synced)} command(s)")
except Exception as e:
print (e)
for fn in os.listdir("./cogs"):
if fn.endswith(".py"):
await bot.load_extension(f"cogs.{fn[:-3]}")
File "c:\Users\PC\Desktop\Noas Bot\main.py", line 47
if fn.endswith(".py"):
IndentationError: expected an indented block
you if is not in the same level as print and others
actual here it should be inside the for loop
!d discord.Interaction.followup
Returns the follow up webhook for follow up interactions.
@client.event
async def on_message(message):
if message.content == "test":
print('test')
Anyone know why this isn't working?
Sorry but this is self explanatory please read the indention embed above or lookup a tutorial on indention.
does in not print the test
thanks ok
Have you enabled the message content intent?
intents = message_content = True
ehm?
channel.webhooks
Now you are just assigning True to the variables intents and message content
How do I enable it then?
In the developer portal
intents.message_content = True
It worked thank you
👍
hey can someone help me with discord.ext.tasks ? I'm unsuccessfully trying to setup a tasks.loop
first I just tried to copy paste and edit a bit the example given in the docs
from discord.ext import tasks, commands
class MyCog(commands.Cog):
def __init__(self):
self.index = 0
self.printer.start()
def cog_unload(self):
self.printer.cancel()
@tasks.loop(seconds=5.0)
async def printer(self):
chan=self.client.get_channel(986077790296231997)
await chan.send(f"{self.index}")
self.index += 1
async def setup(client):
await client.add_cog(MyCog(client))
but it doesn't work, the bot doesn't seem to like the setup function, but I need it in order to add the cog ?
Is there a way to do something on reconnect? I don't think on_ready is called during reconnect
!d discord.on_connect
discord.on_connect()```
Called when the client has successfully connected to Discord. This is not the same as the client being fully prepared, see [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready") for that.
The warnings on [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready") also apply.
Thanks
i had a discord.py bot a year ago but now it doesn't respond to commands
i havent changed anything so has the document updated or is it just buggy
message content intent is now required
!d discord.VoiceChannel.connect
await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>, self_deaf=False, self_mute=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Connects to voice and creates a [`VoiceClient`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceClient "discord.VoiceClient") to establish your connection to the voice server.
This requires [`voice_states`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.voice_states "discord.Intents.voice_states").
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
ok ty
yellowline??
...what
ah.. this has the error.
!e
import random
x = random.randint(0.1,0.5)
print(x)
@atomic creek :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/usr/local/lib/python3.11/random.py", line 295, in randrange
003 | istart = _index(start)
004 | ^^^^^^^^^^^^^
005 | TypeError: 'float' object cannot be interpreted as an integer
006 |
007 | During handling of the above exception, another exception occurred:
008 |
009 | Traceback (most recent call last):
010 | File "<string>", line 2, in <module>
011 | File "/usr/local/lib/python3.11/random.py", line 362, in randint
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/uzalapusox.txt?noredirect
!e
print(np.random.uniform(0.55,0.8))
@atomic creek :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'np' is not defined
!e
import random
import numpy as np
print(np.random.uniform(0.55,0.8))
@atomic creek :white_check_mark: Your 3.11 eval job has completed with return code 0.
0.584142826020576
@atomic creek #bot-commands
oh, then what is this for?
Discord bot development
lmao
and doesn't work that way
!e
print(10 and 10)
@alpine cove :white_check_mark: Your 3.11 eval job has completed with return code 0.
10
thats the reasob
You can make it global by removing the copy global to line
And remove the guild kwargs in the sync function
Just be advised it may take up to 1 hour to apply
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
10 10
Delete the first line
Remove all the guild= stuff in 2nd line
Yes should be global after that
Aye
that would also work
bot ideas please 🥹
Yes, I have no knowledge of Python, so please teach me. What's wrong with the above attachment?
I'm student and i'm studying python by myself and u are expert so plz tell me whats wrong
not so soon you'll realise that most people in this channel are self taught and student as well
There's a guild kwarg in @eternal girder
Or guild_ids
In some libraries
That's for slash command
Oh, I don't know about dpy
Let me check the docs
!d discord.app_commands.CommandTree.command - it also have guild argument
@command(*, name=..., description=..., nsfw=False, guild=..., guilds=..., auto_locale_strings=True, extras=...)```
A decorator that creates an application command from a regular function directly under this tree.
I don't understand your question
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
elif arg == "ping":
if user == None:
await ctx.channel.send(f'Latency is ${Date.now() - ctx.createdTimestamp}ms. API Latency is ${round(bot.ws.ping)}ms')
I tried copying something I found online, but it says ctx.createdTimestamp doesnt exist
im also student and not expert
but that's basic python
heeeelp
@bot.event
async def on_guild_channel_delete(channel):
channel = bot.get_channel(1035829526766293043)
embed = discord.Embed(title="Channel Has Been Removed", description=f" Channel: {str(channel.name)}", timestamp=datetime.now() , color=0x4e80cf)
embed.set_footer(text=f"{channel.guild.name} | Channel System", icon_url="https://media.discordapp.net/attachments/1007641111776481371/1008627898846027836/noadgifdev.gif")
embed.set_thumbnail(url="https://media.discordapp.net/attachments/1007641111776481371/1008627898846027836/noadgifdev.gif")
await channel.send(embed=embed)
@bot.event
async def on_guild_channel_create(channel):
channel = bot.get_channel(1035829526766293043)
embed = discord.Embed(title="Channel Has Been Created", description=f" Channel: {str(channel.name)}\n Mention: <#{str(channel.id)}>", timestamp=datetime.now() , color=0x4e80cf)
embed.set_footer(text=f"{channel.guild.name} | Channel System", icon_url="https://media.discordapp.net/attachments/1007641111776481371/1008627898846027836/noadgifdev.gif")
embed.set_thumbnail(url="https://media.discordapp.net/attachments/1007641111776481371/1008627898846027836/noadgifdev.gif")
await channel.send(embed=embed)```
how do i make it tag the deleted or created channel
how do I check if someone has reacted to a reaction?
like for what
what are u trying to do w that
!d discord.on_reaction_add
discord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_message_edit "discord.on_message_edit"), if the message is not found in the internal message cache, then this event will not be called. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") instead.
Note
To get the [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Reaction.message "discord.Reaction.message").
This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.reactions "discord.Intents.reactions") to be enabled.
Note
This doesn’t require [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") within a guild context, but due to Discord not providing updated user information in a direct message it’s required for direct messages to receive this event. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") if you need this and do not otherwise want to enable the members intent.
sarthhh
@slate swan
for the created one you can do channel.mention
i was here first
like not mentioned just the name of the deleted channel
{str(channel.name)} dhd that
that's not discord.py at all
oh
ok so then how would i get ping
channel.name , will work for both
its not working sadly
bot/client.latency iirc
OH WAIYT GOT IT TYSM
how do i get client latency
client.latency ;-;
I thought you meant bot latency divided by client latency
elif arg == "ping":
if user == None:
await ctx.channel.send(f'Latency is {bot.latency}')```
so like this?
bot.latency*1000 if you want in milliseconds like normal people do yes
@slate swan nononono
What im trying to get is how long it takes for a the bot to respond to a user
so if I have 50 ping and the bot has 100 it should be 150 ms or smth
basically just user ping
you can't get your ping
I can
I can get when the message was sent and subtract it by the bots ping
The time it took for the bot to respond?
yeah you can do that
ah
!d discord.Message.created_at
It’s not accurate as the API can be slow
property created_at```
The message’s creation time in UTC.
this will tell you when the message was created
!d datetime.datetime.now this will get you current time
classmethod datetime.now(tz=None)```
Return the current local date and time.
If optional argument *tz* is `None` or not specified, this is like [`today()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.today "datetime.datetime.today"), but, if possible, supplies more precision than can be gotten from going through a [`time.time()`](https://docs.python.org/3/library/time.html#time.time "time.time") timestamp (for example, this may be possible on platforms supplying the C `gettimeofday()` function).
If *tz* is not `None`, it must be an instance of a [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo "datetime.tzinfo") subclass, and the current date and time are converted to *tz*’s time zone.
This function is preferred over [`today()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.today "datetime.datetime.today") and [`utcnow()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.utcnow "datetime.datetime.utcnow").
how do i get the message
ctx.message
ctx.message.created_at()?
yeah exactly, it will never be accurate
without braces
@slate swan await ctx.channel.send(f'Latency is {round(Date.now()-ctx.message.created_at,2)} ms')
nope
What latency is this supposed to calculate
user's latency
?
wdym ?
you can't calculate the user's latency
is that not what im doing there
not at all
You can't interact with other users device, just your pc/server and discord
nono let me put it this way
im trying to get how long it will take from, the message being sent, to the server responding
you are calculating the time it took the bot to receive the message
yes
!d discord.ext.commands.Bot.latency
property latency```
Measures latency between a HEARTBEAT and a HEARTBEAT\_ACK in seconds.
This could be referred to as the Discord WebSocket protocol latency.
just use your bots latency
await ctx.channel.send(f'Latency is {round(bot.latency-ctx.message.created_at,2)} ms')
?
its not exactly what you want but much mure convenient
await ctx.channel.send(f'Latency is {round(bot.latency, 2)} ms')
thats not what i want though
ik
its the bot's latency
i dont want the bot's latency
as said
It's still the same latency from discord to your program
How is that going to calculate the users latency
lets say the message was created at 0:05
You want the time taken for a user to send a message and discord to receive it, yes?
and the time now from the bot's perspective is 0:15
I can subtract that minus the time the message was made
and thats the latency
which is 0:10
100 ms latency
All you can see is the time between the websocket and your bot
yes thats what im trying to get
For user latency you would need access to the user's device. Which isn't a thing
lets say the message was created at 0:05
and the time now from the bot's perspective is 0:15
I can subtract that minus the time the message was made
and thats the latency
which is 0:10
100 ms latency
so if i print this
then print bot.latency()
ill get the same value?
There's no way of knowing when the user actually sends the message
there is
property created_at
The message’s creation time in UTC.Type
datetime.datetime
How?
That's the time that discord receives the message
The message’s creation
time in UTC.
Yea that's when the message is posted on discord not when it was created on their device
oh i thought every packet to the discord bot sent the creation time as a parameter, and that gets it
discord respects users privacy and doesnt reveal their time zone
u are not the only user on discord tho 
does using @default_permissions on a hybrid command also add a normal permissions check for the message based command?
dont think so
Yh I know I’m just saying it’s a dumb thing to be concerned Cavour
Over
might as well expose your IP
use @commands.check() its should work on both slash and message i think
For you, but other people may prefer keeping their location secret
Any piece to the puzzle is one step closer to not being anonymous
i think u meant anonymous
Wow yea that's the one
guess that's what I get for doing 4 things at once lmao
If message.created_at returns the time the server got the message then what’s the difference between using that and datetime.now()
I still think you are wrong
await ctx.channel.send(f'Latency is {(Date.now(timezone.utcoffset(-6))-ctx.message.created_at)} ms')
how do i get est from utcoffset
await ctx.channel.send(f'Latency is { Date.now(timezone.utc) - ctx.message.created_at} ms')
this does what I want but I need timezone.utc to be est, how do i get it
hi hi! could someone help me figure how i could upload a PIL Editor canvas directly into Discord using discord.py? 😓
Just use {client.latency*1000}
not what im trying to do
having this error when initialising my db
what's the problem with that?
if your canva is saving locally, then here's a way you could send it:
embed = discord.Embed(title="Title", description="Desc", color=0x00ff00) # creates an embed
file = discord.File("path/to/image/canva_file.png", filename="image.png")
embed.set_image(url="attachment://image.png")
await ctx.send(file=file, embed=embed)```
or you might just do await ctx.send(file=file)
without making an embed
where can I see an example of a slash command sub command?
it's pdt_locales according to docs
This is one example. There's a few different ways
async def git(ctx):
if ctx.invoked_subcommand is None:
await ctx.send('Invalid git command passed...')
@git.command()
async def push(ctx, remote: str, branch: str):
await ctx.send(f'Pushing to {remote} {branch}')
Except you define (interaction: discord.Interaction) and use interaction.response.send_message(...)
@app_commands.describe(member='The user you want to see server level for')
async def level(interaction: discord.Interaction, member: discord.Member= None):
'''Display your level on this server.'''
if member==None:
userid = interaction.user.id
icon = interaction.user.display_avatar
dname = interaction.user.display_name
else:
userid = member.id
icon = member.display_avatar
dname = member.display_name
Forgot I had some of my code on my phone. This is how I did my slash command sub commands
Looks like something in like 333 needs to be 5 or more in length 
wnhich
thanks, I already found a gist tho 😅
No problem
view=SelectView() he wants to see the code for SelectView()
async def get(ctx,arg,user=None):
if arg == "ip":
if user != None:
if user == discord.User:```
how can i do smth like this
basically checking if the third arg is a mention
I could do async def get(ctx,arg,user:discord.User=None): but that would be inconvient in some circumstances
how so?
lets say I wanted to do !get total bots
or literally any get command with 2 arguments
how do i fix guild object has no attreibute to icon_url
The program will assume the third is a mention and will error
i talked abt this last night but it was late
What should the 3rd argument be? Just any string?
yea
it doesn't need any typehints then, or : str if you want to be explicit
but I also would like commands where the third argument is a mention
yea i did that got another error
You can use typing.Union[] to indicate the 3rd arg can be one of it
what?
i just want something like i have here
obv that doesnt work, but it gives an idea
@slate swanits guild.icon not guild.icon_url
thanks that worked. do you know why it says owner : none
@sick birch
thats likely because the owner of a guild is a privileged intent that you dont have enabled
i think its the member intent that enables dpy to cache guild members
its just not in the cache
For instance typing.Union[discord.TextChannel, discord.Member] would allow you to either mention a text channel ( #discord-bots ) or a member ( @dapper bluff )
so i could do:
You can also use typing.Literal in there to be even more precise
ah
async def get(ctx,arg,arg2=None):
if arg == "ip":
if arg2 != None:
if arg2 == typing.Union[discord.User]:```
?
@slate swan you can enable it in the discord dev thing then pass it into your bot instance
No…
typing.* goes in your async def structure.
I just said thats what im not trying to do
Refer here
That makes nearly no sense to why you would do that… but you can just get the mention attribute out of it. https://discordpy.readthedocs.io/en/stable/
Take a look at the documents and you’ll find it under Message.
What?
That makes nearly no sense to why you would do that…
I dont get how this makes no sense to yall
What if I want to do !get notes @dapper bluff
but i also wanted to do !get server members
You can just make a Literal and force them to mention someone or do something else and if it’s neither of those, you check it
im asking how I can check if a string is a mention
The documents show under the Message section on how you can see if a string has a mention in it
You can probably get a message out of your second variable with it, however, I’ve never done that so I’m not entirely sure.
i clicked the link where do i go from jhere
even more why are u trying to make one cmd be used in multiple ways lol. just making it more complicated
You'd just typehint
async def get(ctx, arg, arg2: typing.Union[...]) -> None:
...
More complicated to me sure, but I want it to be less complicated to the user
It’s documents…
You can get very specific with compounding your typehints in a certain way
Click API References to read the api docs
searching through docs is such a nightmare, i dont even know what im looking for
I’m trying to help you learn to search on your own… :/
Where now????
Oh and you can use isinstance to do something depending on the type of arg2. This is what you want, yes @dapper bluff ?
is discord.User a type of instance?
Youre not helping very well
Im at message where do I go now
Its an object
It was a yes or no question
The only thing that applies to you… the mentions…?


