#discord-bots
1 messages · Page 123 of 1
i personally use 120 chars limit
129
I do whatever pycharm tells me to do ool
*lol
oh yea thats pycharms limit
yep
i hate pycharm for reasons
and I hate u :((((((
helpp
sarth what's the appropriate channel to ask about pep-8 here? yesterday someone told me it's inappropriate to ask here :/
jk but why tho?
oof
tyyyy
dont care
issue? errors/logs anything?
like no errors but i said there
understandable I wouldnt care either
https://paste.pythondiscord.com/fekihoxata
thats my giveaway code and when i do the end command its sending a winner but in the create command it does nothing it doesnt edit the message to py endEmbed=nextcord.Embed(title=f"🎉 **{prize}** 🎉",description=f"> **Ends:** <t:{utc_time}:R>\n" f"> **Hosted By:** {interaction.user.mention}\n" f"> **Winner:** {winner.mention}")
bc its just sending a winner but does nothing w the real giveaway
pycharm just makes my life harder
well its making mine easier
its vsc
vs is weird af
visual studio code
add print statements to see till what part of your code it gets executed
turn on yo linter to strict mode
i did that and it doesnt connect each other
true
who is coder need help
Nobody
Ask your question
whats the code for add user id permission to use bot command?
Please elaborate
like @commands.is_owner()
Which library are you using? And are you using a slash command?
If it's discord.py I can help, idk about the other libraries
check dm
I don't do dms just ask here. I'm no python master so if I can't help someone else can and you don't have to repeat your questions
def check_if_it_is_me(ctx):
return ctx.message.author.id == 85309593344815104
@bot.command()
@commands.check(check_if_it_is_me)
async def only_for_me(ctx):
await ctx.send('I know you!')
@mighty pilot
Do you want it to only work for you or only work for a server permission level
work with anyone
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
If you want it to work with anyone then why are you asking about how to restrict it to just you
If you wanted a permission level restriction or role restriction etc you could use a check like sarth said here
If you want it to only work for you I'd just do an if ctx.author.id == 45676432567876788
I guess the check_if_it_is_me is a thing too but idk why you'd prefer to make more lines unless you want an error raised if it's not you
it was in the docs lol
Yea I read that. It's interesting that it exists but I am a simple man and prefer a short if line lol
same
!venv
Virtual Environments
Virtual environments are isolated Python environments, which make it easier to keep your system clean and manage dependencies. By default, when activated, only libraries and scripts installed in the virtual environment are accessible, preventing cross-project dependency conflicts, and allowing easy isolation of requirements.
To create a new virtual environment, you can use the standard library venv module: python3 -m venv .venv (replace python3 with python or py on Windows)
Then, to activate the new virtual environment:
Windows (PowerShell): .venv\Scripts\Activate.ps1
or (Command Prompt): .venv\Scripts\activate.bat
MacOS / Linux (Bash): source .venv/bin/activate
Packages can then be installed to the virtual environment using pip, as normal.
For more information, take a read of the documentation. If you run code through your editor, check its documentation on how to make it use your virtual environment. For example, see the VSCode or PyCharm docs.
Tools such as poetry and pipenv can manage the creation of virtual environments as well as project dependencies, making packaging and installing your project easier.
Note: When using Windows PowerShell, you may need to change the execution policy first. This is only required once:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
not everyone bruh
.
There's like 7 answers if you just read up the channel lol
i have to rewrite code everytime when i want to add more user id lol
Why not restrict it to a role then just add that role to people
def check_if_me(id):
if id == 85309593344815104:
return True
else:
return False
@bot.command()
async def only_for_me(ctx):
if check_if_me(ctx.author.id) == True:
await ctx.send("I know you!")
Maybe something like this
dont override inbuilts
use _id or user_id instead
I'm running with a problem here.
async def filter_user(ctx,bot, m):
return(m.author == ctx.author
# Author of message is command runner
and m.channel.id == ctx.message.channel.id
# Message is on the same channel than context
and not m.reference
# Mention is not a reply reference
and len(m.content.split(' ')) == 1
# Message contains one element
and ((m.content.isdigit() and await search_id(bot, m.content))
# Message contains a User ID without a mention
or (len(m.mentions) == 1
and not m.content.replace(
f'<@{m.mentions[0].id}>', ''))))
# Message contains a mention without any other content
async def select_subject(ctx, bot):
while True:
response = await bot.wait_for(
"message",
check=lambda message: head(
await filter_user(ctx, bot, message) for _ in "_"
),
)
print(response.content)
So this is supposed to print response.content if user sends a message that matches filter_user() conditions. The conditions are: user either have to write a message with nothing more than a mention, or nothing more than a valid user id.
It worked well with m.content.isdigit() but I wanted to enhance it to perfection by turning it to async so it can filter just valid IDs or mentions instead of digits and mentions.
But this new thingie doesn't filter anything anymore :o
And I don't get where my problem comes from :o
EDIT: Here's what search_id() does btw:
async def search_id(bot, arg):
try:
return await bot.fetch_user(arg)
except:
return False
ever heard of ctx.bot lol
where do you see ctx.bot? XD
You don't need to pass the bot object, the context object holds it
ohhhh okay i didn't know it
!d discord.ext.commands.Context.bot
The bot that contains the command being executed.
Thank you for this info I really appreciate and it will enhance my work. Although my question isn't answered 😊
Can you please help me on it? :D
async def greet(ctx, member: discord.Member = None):
# Im not sure whether it'll raise if an invalid is is provided
if member:
return await ctx.send(f"Greetings {ctx.author.mention}")
ctx.send(f"Greetings {member.mention}")
bruh
whats the issue lol?
Oh I think you missunderstood my question i probably didn't explain it well
basically I have a condition that always return True for a reason I don't understand :o
I wrote it above
Issue is when I turned my check function asynchronous and added a bot.fetch_user() to the conditions
why the function... what is it used for?
It's used to control the integrity of the answers
I'm making a questionnaire, so when you run the command a questionnaire starts, and the bot will answer multiple question one by one and take the answers that matches certain conditions
is there a function to convert a path string ("cogs/moderation/ban.py", "cogs\moderation\ban.py") to a importable string (to use in bot.load_extension)("cogs.moderation.ban")
ping me if answering please
si when the bot asks for "Who do you want to greet" I want rather a valid ID or a mention, but I don't want "cat684834384343" or "hi @cerulean folio " to work
Actually, I'll try to refine my question:
can the check kwarg of bot.wait_for('message', check=my_checking_function) be an async function or it makes the code not working properly. If it's the case, can you explain me why?
async def is_member(ctx: commands.Context, string: str) -> Optional[discord.User]:
if not ctx.guild:
return
s = string.strip("<@>")
if not (m := ctx.guild.get_member(s)):
return
return m
that should do the job
async def is_user(bot: commands.Bot, string: str) -> Optional[discord.User]:
s = string.strip("<@>")
if not (m := (await bot.fetch_user(s))):
return
return m
actually no wait it wont
^ This is my question, forget about the one above it's not well explained I apologise 
async def is_member(ctx: commands.Context, string: str) -> Optional[discord.User]:
if not ctx.guild:
return
s = string.strip("<@>")
if not s.isnumeric():
return
if not (m := ctx.guild.get_member(int(s))):
return
return m
I think that does
This checks if it's a guild member, not if a string is a valid id.
async def search_id(bot, arg):
try:
return await bot.fetch_user(arg)
except:
return False
this does and it works well
async def is_user(bot: commands.Bot, string: str) -> Optional[discord.User]:
s = string.strip("<@>")
if not s.isnumeric():
return
try:
return await bot.fetch_user(int(s))
except: # idk the exception
return
oh gotcha
exceptions on this are discord.NotFound and discord.HTTPException
check should be a normal function, not a async function
At least that's what I've been told
thx
AH so that's why it isn't working !
tyyyyy all for helping me and sorry for confusing explainations of my problems haha
.
where do you want to import it to?
bassically i have this but it only works on unix
await self.load_extension(os.path.splitext(entry.path)[0].replace("/", "."))```
Why don't you use from cogs.moderation.ban import *?
cause its in a loop
async def load_extensions_from_folder(self, folder, recursive=False):
with os.scandir(folder) as it:
for entry in it:
if entry.is_dir():
if recursive and entry.name != '__pycache__':
await self.load_extensions_from_folder(entry.path, recursive=True)
elif entry.is_file():
if entry.name.endswith(".py"):
await self.load_extension(os.path.splitext(entry.path)[0].replace("/", "."))```
Oh then your problem interests me as well, I didn't know we can import modules this way
you didnt know about bot.load_extension?
Apparently
No I just use python import
I can't use something if I don't need it / don't know it exists, I don't see what's funny in that ^^
no it's few lines. I just use those __init__.py files and everything is working
oh yeah forgot
Oh right
how to ignore server id using discord.py?
@discord.ext.commands.check(predicate)```
A decorator that adds a check to the [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or its subclasses. These checks could be accessed via [`Command.checks`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command.checks "discord.ext.commands.Command.checks").
These checks should be predicates that take in a single parameter taking a [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context"). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure") exception is raised and sent to the [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") event.
If an exception should be thrown in the predicate then it should be a subclass of [`CommandError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError"). Any exception not subclassed from it will be propagated while those subclassed will be sent to [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error").
hey can any one tell me
how can i get the image the persone sends with the command
And store it in mongo db
Text or slash command
Totally personal preference, but many users (many whom I know) like slash commands because of a cleaner way of invocation
Doesn't matter much for a Private bot tho
You cannot store images in JSON??? (MongoDB)
so where can i do it
You should store it on the file system (HDD/SSD)
better i ask for link of image
Yea, u should instead save the image link, but the link would be invalidated if the person deletes the image
The image can be deleted
thats there issue
in case image cant be loaded i will show the error
If u r sending the image in an Embed, it won't show the image
but embed has the option to show image
what u mean the deleted img u mean
I mean, if u delete the image it won't show up in the embed
ofc that wont
-_-
without the correct link how can it
Just telling
There have been many instances of people saying the image not loading and after ages they check the image link and be like: Image has been deleted, sorry for bothering
oke oke
i made a welcome bot
how does it look as user interface
pls egnore the embed
What do you mean?
what
Please stop spamming the command
i'd personally use a command group called welcome with channel and message as subcommands instead
using slash commands would be even better because they provide autocompletes for channels
okee
i will work on it
good luck w/ that
I have no idea how to ask the question so... I am going to describe the problem
I have been teaching myself python by writing a discord bot
everything was working fine.
then suddenly, my bot starts hanging when atttempting to connect, and I never get the "on_ready" response
error in the console?
`import discord
import vars
import responses
block_words = ["uwu", "Rama", "omnitype"]
diceResult = []
diceResultMsg = "Your Results is"
intents = discord.Intents.all()
TOKEN = vars.DISCORD_TOKEN
client = discord.Client(intents=intents)`
'@client.event
async def on_ready():
print(f'{client.user} is now running')'
no error either
is that all the code you got?
nope, there are many stuff that can get triggered before on_ready like on_message or on_connect etc
here is the dump of the main bot code...
`import discord
import vars
import responses
block_words = ["uwu", "Rama", "omnitype"]
diceResult = []
diceResultMsg = "Your Results is"
############# To Do ###############
1. complete Roll diceRequest any 4d6 etc
2. roll percentage diceRequest
3. roll with advantage or disadvantage
4. check percentage vs skill
5. store skill numbers
6. parse character sheet for skill numbers
7. check skill using skill name
intents = discord.Intents.all()
TOKEN = vars.DISCORD_TOKEN
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print(f'{client.user} is now running')
@client.event
async def on_message(msg):
if msg.author != client.user:
for text in block_words:
print(f'Checking for {text}')
testtext = str.lower(text)
print(testtext)
if testtext in msg.content.lower():
print(f'{text} found')
await msg.channel.send(f"{msg.author.display_name} said {text}. That's a bad word.")
######## check if message is a command ########
if msg.content.lower().startswith("!"):
#remove command operator and store key data
cmdTxt = str(msg.content)
cmdUser= msg.author.display_name
cmdTxt = cmdTxt[1:]
print(f'{cmdTxt} command Sent By {msg.author.display_name}')
##############################
######## Roll Command ########
##############################
if cmdTxt.startswith("roll") or cmdTxt.startswith("r"):
print(f"cmdTxt")
await responses.rollCommand(msg,cmdTxt,cmdUser)
elif cmdTxt.startswith("skill") or cmdTxt.startswith("s"):
await responses.rollCoC(msg,cmdTxt,cmdUser)
elif cmdTxt.startswith("song"):
print(f"{cmdTxt}")
await responses.songOfPeople(msg)
elif cmdTxt.startswith("helpme"):
print(f"{cmdTxt}")
await responses.helpMe(msg)
else:
print(f"I dont know what the heck they are talking about")
client.run(TOKEN)`
just after the variable is defined
hm you sure that you are in the correct directory? is the code saved?
wait you are running the bot wrong way, you run it using python bot.py lol
not ./bot.py
pip install discord.py doesnt work
what's your python version
my friends
if its 3.11 you need to install visual c++ tools or just use python 3.10 ( or anything above 3.8)
oh ill check w him
whats the commant to check version?
3.9.1
python -V
TY
i see and what's the error you get when trying to install discord.py?
don't see an error?
python ./bot.py is getting me errors now
Then what is it
'2022-11-05 10:35:09 INFO discord.client logging in using static token
Traceback (most recent call last):
File "D:\Python Coding\Clackula\env\lib\site-packages\discord\http.py", line 801, in static_login
data = await self.request(Route('GET', '/users/@me'))
File "D:\Python Coding\Clackula\env\lib\site-packages\discord\http.py", line 744, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 401 Unauthorized (error code: 0): 401: Unauthorized
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "D:\Python Coding\Clackula\bot.py", line 69, in <module>
client.run(TOKEN)
File "D:\Python Coding\Clackula\env\lib\site-packages\discord\client.py", line 828, in run
asyncio.run(runner())
File "C:\Python39\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
return future.result()
File "D:\Python Coding\Clackula\env\lib\site-packages\discord\client.py", line 817, in runner
await self.start(token, reconnect=reconnect)
File "D:\Python Coding\Clackula\env\lib\site-packages\discord\client.py", line 745, in start
await self.login(token)
File "D:\Python Coding\Clackula\env\lib\site-packages\discord\client.py", line 580, in login
data = await self.http.static_login(token)
File "D:\Python Coding\Clackula\env\lib\site-packages\discord\http.py", line 805, in static_login
raise LoginFailure('Improper token has been passed.') from exc
discord.errors.LoginFailure: Improper token has been passed.
Exception ignored in: <function _ProactorBasePipeTransport.del at 0x0000021EB937E550>
Traceback (most recent call last):
File "C:\Python39\lib\asyncio\proactor_events.py", line 116, in del
self.close()
File "C:\Python39\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Python39\lib\asyncio\base_events.py", line 746, in call_soon
self._check_closed()
File "C:\Python39\lib\asyncio\base_events.py", line 510, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed'
anyone know why this is returning "This application did not respond." with no error -> https://paste.pythondiscord.com/xahareqexo
the token was wrong
You didn't respond to the interaction
i dont understand why it was working then stopped.... the token was fine... ok I will reset the token and swap it out
discord.ApplicationContext
pycord 
ikik
still shows
do you see something like this below?
you're using 3.11 lol, click on it and choose 3.10
this happens when you download multiple python versions on same device
I dont know how I screwed that up, but I really appreciate your help. Somehow i buggered my token.
ah so it does work now?
it connected with almost everything commented out.... now to uncomment
yes it works

thank you
will the time.sleep() function pause the whole bot or just the function if in an async function?
You are awesome
how I can fix this
u install discord.py
I don’t know what is this ERROR
with discord.py buttons how do i make it so that when you click the button once you cant click it again
!d discord.ui.button
@discord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)```
A decorator that attaches a button to a component.
The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View"), the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") you receive and the [`discord.ui.Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button "discord.ui.Button") being pressed.
Note
Buttons with a URL cannot be created with this function. Consider creating a [`Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button "discord.ui.Button") manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.
disable the button and edit the view
How do i download discord py
it says syntax error
@shrewd apex
it keeps saying syntax error
get the tools from the given link
get python and set python in ur system vars set the path
im new to python so idk what ur rlly talking about
then learn pytho before attempting a discord bot
i already know most of it
wow

i js dk what u mean by set the path
i want my bot send a embed via my command and each embed has randomised numbers ik how to make a embed js not the randomised numbers
anyone know how to do this?
!d random.randint
random.randint(a, b)```
Return a random integer *N* such that `a <= N <= b`. Alias for `randrange(a, b+1)`.
tysm
Type exit() first, then install discord.py
thx
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)
pip install discord.py
msg.author will give you the Member/User that created the message
wait is that a command?
so what does it have to do with a moderator?
Help me
import discord
from discord.ext import commands
print('Коги запущены')
class User(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def хелп(self, ctx):
await ctx.send("работает")
def setup(bot):
bot.add_cog(User(bot))
hello
so i wanna do that it will let a command be on two channels and idk how to
if ctx.channel.id != 1008759406177026068 or 1005776398507581490:
if ctx.channel.id not in (1008759406177026068, 1005776398507581490):
!or-gotcha
When checking if something is equal to one thing or another, you might think that this is possible:
# Incorrect...
if favorite_fruit == 'grapefruit' or 'lemon':
print("That's a weird favorite fruit to have.")
While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.
So, if you want to check if something is equal to one thing or another, there are two common ways:
# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
print("That's a weird favorite fruit to have.")
# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
print("That's a weird favorite fruit to have.")
tysm!
ik this is dumb and hard to explain but like how would i make it so if i did !frost dragon it would tell me the price of it
i don't want to make a separate command for everything on the list
i don't want to make a separate command for everything
like u mentioned here
hes saying main command being frost, then make subcommands dragon, witch, troll etc
youll end up needing to make a command or sub command for anything you want to be user input
U can do this then search for the item in the list if not then say Invalid item or whatever
is there a way to run both discord both and WebSocketApp?
ofcourse just make sure to use an async websocket like aiohttps ( discord.py uses that too )
what about websocket-client?
is that a python library?
yes
does it have async support?
no fix, self botting is against tos
k well fixed it myself
so I can't find any documentation that says it does this but does discord limit attached images to 670*670?
I'm trying to send a 3072 * 3072 image in an embed and it keeps downscaling it
hello everyone! is anyone knowledgeable about making a "custom command" command
i don't think the img dimensions are the issue but the size of the attachment itself
yeah that's what I thought
i did read somewhere tho that they are typically downscaled to around the size u mentioned
rip
Traceback (most recent call last):
File "/home/deusopus/.local/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1240, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/deusopus/.local/lib/python3.10/site-packages/discord/app_commands/commands.py", line 876, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/deusopus/.local/lib/python3.10/site-packages/discord/app_commands/commands.py", line 865, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'web-links' raised an exception: TypeError: Embed.add_field() got an unexpected keyword argument 'url'
what is your expected output?
Embed.add_field(url=x) isnt a thing
titles and authors
or using markdown in description and field values
if you want it to be added in a field value this would be the method ```py
<Embed object>.add_field(name="name", value="text to appear other stuff")
thanks
btw you can do something along the lines of this: '[Text](url)' if you want to get a hyperlink inside of your embed description :-)
so for me I have:
f'[Invite Me]({invite}) | [Support Server]({support})'
(invite and support are just strings)
and it looks like this in the embed:
Forgot where it goes but Embed(url=...) is there too, but that's probably in the title which was what sarth was referencing
yessir it appears as hyperlink on the title
so i put inline= True if i want them as a list?
inline=True adds the field in the same row
i don't understand how i can make a button to give a role but i can't use that as a template to post an embed
where did everybody go?
i think its redundant to post an embed with a button anyway. i should forget about that
i should try to figure out how to put a button on an embed instead
You can't put one on an embed but you can put them under - in the same post as the embed
If you know how to give a role, just put that code in the button code block
Discord.member.add_role
Anyone know why I'm not getting any tracebacks when interactions fail
Are you talking about it just saying error when you use an interaction
No
Like in my terminal, I'm getting no traceback
It says this interaction failed, but then I have to figure out why with no traceback
I'm talking about the when interactions failed are you talking about seeing that in discord
You need to set a response for the interaction with interaction.response
What does your interaction do
Its with every time any interaction ever fails
No matter what I'm doing, I never get a traceback in my terminal
What does your interaction do
Never mind
You need to send a response to the interaction otherwise it'll tell you it failed in discord. But if you have it set to do something like add a role (for example) it'll still do that
Yeah, I know
I'm telling you. It says "this interaction did not respond" because of a code error. Whether its an undefined variable or a type error, I never get a traceback
can you guys help me with some basic python
I am sending a response, but it's never reaching that line because of an error before it. But I'm not getting a traceback to find that error in the code before the response
Let's see the code
You could use print() to see what you're getting to trigger
I know
That's what I've been doing. But it's really annoying to put print statements all over to narrow it down the line thats causing it when I could just get a traceback. So I'm asking why it's not giving me a traceback. Does anyone else have that problem?
It's probably an error inside something you're assigning that it doesn't actually see as an error. You could enable the debug mode
How can I use enumerate() so that I can replace … in my field name with the warning number -> so it looks like this: Warning #1:.
cursor = db.INFRACTIONS.find({"suspect": member.id})
warns_embed = discord.Embed(colour = 0x2f3136)
warns_embed.title = f"Here are {member.name}'s warnings:"
async for doc in cursor:
mod = self.bot.get_user(doc["mod_id"])
warns_embed.add_field(name = f"Warning #...:", value = f"**Punishment ID:** {doc['_id']}\n**Moderator:** {mod}\n**Reason:** {doc['reason']}")
await ctx.respond(embed = warns_embed)
#❓|how-to-get-help might be better for off-topic help
Sounds like you have the wrong role ID assigned to that button
does anyone know how to fix this im trying to install easy pil
embed=discord.Embed(color=0xe68600)
^
IndentationError: expected an indented block after function definition on line 6 ```
help please
your py version?
!indent
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
How do I make a slash command parameter not required?
Like here I want the reason parameter to be entirely optional
@bot.tree.command(name="kick", description="Kick a member")
@app_commands.checks.has_permissions(kick_members=True)
async def kick(interaction: Interaction, member: discord.Member, reason: str):
3.11
typehint to Optional[str] or give a default value
eh?
Changing type hints doesn't work
typing.Optional```
Optional type.
`Optional[X]` is equivalent to `X | None` (or `Union[X, None]`).
Note that this is not the same concept as an optional argument, which is one that has a default. An optional argument with a default does not require the `Optional` qualifier on its type annotation just because it is optional. For example:
```py
def foo(arg: int = 0) -> None:
...
``` On the other hand, if an explicit value of `None` is allowed, the use of `Optional` is appropriate, whether the argument is optional or not. For example...
anyone know how to fix?
some of aiohttp's dependencies (specifically multidict, yarl, and frozenlist) dont have prebuilt wheels for python 3.11, which means you need to either:
- download the build tools as linked somewhere above your error message - on windows its the VS build tools, specifically "Desktop development for C++" which will be 6GB - or;
- downgrade to python 3.10, which has the prebuilt wheels
is there a list of all the types of interactions? i know there's buttons, but is there anything else?
the exact types are documented in the discord API
https://discord.com/developers/docs/interactions/receiving-and-responding#interaction-object-interaction-type
that includes application commands (slash and context menu), autocompletes, and modals
don't see anything relating to buttons in there?
buttons fall under the MESSAGE_COMPONENT type
if you mean you wanted a list of different components you can add on messages, there's only buttons and select menus
what's a select menu look like?
is this in context to any api wrapper you're using like discord.py? or are you intending to use the API directly
no i'm using discord.py
then their documentation would be a helpful source as well
Wait select menus can have roles now?
What else can you select?
Last time i checked it was only text
wdym
it seems like you're selecting more than just plain text?
Roles and users and channels
hm thinking about it i havent seen those member counters before, but perhaps thats part of the select option
yeah but their docs don't give that image you just provided
!d discord.ui.RoleSelect
fair enough
class discord.ui.RoleSelect(*, custom_id=..., placeholder=None, min_values=1, max_values=1, disabled=False, row=None)```
Represents a UI select menu with a list of predefined options with the current roles of the guild.
Please note that if you use this in a private message with a user, no roles will be displayed to the user.
New in version 2.1.
channels & users too
oh i didnt notice the "RoleSelect", huh
looks like they're new types for select menus
iirc it doesn't really show all the roles of a guild
and i was here thinking i just shared a normal picture of select menus
but i downloaded desktop dev for c++
you just downloaded the build tools? or do you mean you already had it before
btw i would suggest a help channel for this (#❓|how-to-get-help)
no i vx intaller and download vs build tools then modified it with the c++ thiing
Hi people ! On my journey to recode my bot to a cleaner and smarter code and logic, I wonder how you guys would code a message with buttons other than this because it looks so... bulky :o
import discord
import asyncio
from discord.ui import View
async def select_game(ctx, bot):
class GameView(View):
def __init__(self):
super().__init__(timeout=None)
self.value = None
@discord.ui.button(label='Genshin', style=discord.ButtonStyle.blurple)
async def genshin_callback(self, interaction, button):
if interaction.user == ctx.author:
self.clear_items()
await interaction.response.edit_message(content='Game selected: Genshin', view = self)
self.value = 'Genshin'
self.stop()
@discord.ui.button(label='Roblox', style=discord.ButtonStyle.blurple)
async def roblox_callback(self, interaction, button):
if interaction.user == ctx.author:
self.clear_items()
await interaction.response.edit_message(content='Game selected: Roblox', view = self)
self.value = 'Roblox'
self.stop()
@discord.ui.button(label='Honkai', style=discord.ButtonStyle.blurple)
async def honkai_callback(self, interaction, button):
if interaction.user == ctx.author:
self.clear_items()
await interaction.response.edit_message(content='Game selected: Honkai', view = self)
self.value = 'Honkai'
self.stop()
@discord.ui.button(label='IDV', style=discord.ButtonStyle.blurple)
async def idv_callback(self, interaction, button):
if interaction.user == ctx.author:
self.clear_items()
await interaction.response.edit_message(content='Game selected: IDV', view = self)
self.value = 'IDV'
self.stop()
@discord.ui.button(label='Other', style=discord.ButtonStyle.blurple)
async def other_callback(self, interaction, button):
if interaction.user == ctx.author:
self.clear_items()
await interaction.response.edit_message(content='Game selected: Other', view = self)
self.value = 'Other'
self.stop()
view = GameView()
msg = await ctx.send('What **game** is it?', view = view)
def check(m):
return (m.author == ctx.author) and (m.content.lower() == 'cancel') and (m.channel.id == ctx.message.channel.id)
tasks = [asyncio.create_task(view.wait()),
asyncio.create_task(bot.wait_for('message', check=check))]
done_tasks, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
if tasks[1] in done_tasks:
return False
else:
return str(view.value)
for this i'd consider using a button subclass to store the value OR a select menu which seems more appropriate here, alongside an interaction_check, and a cancellation button which is a bit simpler to implement than waiting on a "cancel" message
Looks like all your buttons do about the same thing?
I would use a subclass and conditionally edit the message/value
Ah... since I wanna improve my OOP I'll try my best to understand all these :D
Also I don't know if there's select menus on discord.py since it's no longer supported :(
can someone help me
That's a redundant question just ask what you came to ask
that hasnt been the case for a while now, it resumed development at least 8 months ago, perhaps a bit longer
ohhhh really? that's so cool :D
Yea there's most definitely select menus lol
not to mention it already had select menus before danny initially stopped
so all those new fancy menus and pop up windows where you can write something etc...?
modals yeah, those are in dpy 2.0
Yea select menus. Modals. Buttons.
Okay then I'll do what you and robin asked me with subclasses just to practice OOP and then make dropdown menus.
I have to subclass the class Button from discord.ui?
yeah
alright i'll try rn :D
the interaction.author == ctx.author part is one you can do in the view's interaction_check() method
Isn't there a thing specifically for that in __init__? Interaction check I believe? Edit: I'm dumb that's exactly what you meant
@client.command()
async def me(ctx, wink):
get = await client.get_user() #gets the message author id, then returns the dm channel id
await get.send(wink)
def solid_list(mode, user=None):
if mode == "read":
with open("users.txt", "r") as E:
return E.readlines()
else:
with open("users.txt", "a") as E:
E.write(f"{user}\n")
return solid_list(mode= "read")
@client.command()
async def register(ctx):
solid_list(mode="write", user=ctx.author)```
This is an unfinished command that I don't know how to finish, it was basically me trying to make a list command that would add a person to a list when they triggered the command in a text file and dm a specific user id that such person was added to that list, the user id would be able to view this text file list with another command and be able to take off persons as he sees fit but I dont know what to add so could someone show me
@slate swan
Ok so I was trying to make a command when triggered adds the user who triggered the command to a list, this list will contain their name and will be stored by the bot, along with that I would like the bot to dm another user telling them that someone used the command and was added to that list.
Additionally I would like to be able to view this list with another command that would display the list in a text file of some kind or just in plain discord text.
that's pretty simple. on command executution store the user, dm the specific person all inside the cmd that is used
then make another cmd to just pull the data from the list
you guys wanna see some pretty useful data?
2 players in server - 7.9 minutes play time, 3.2 play sessions
3 players in server - 13.9 minutes play time, 4.6 play sessions
4 players in server - 18.4 minutes play time, 6.2 play sessions
5 players in server - 14.0 minutes play time, 5.3 play sessions
6 players in server - 33.4 minutes play time, 6.7 play sessions
10 players in server - 8.1 minutes play time, 2.0 play sessions```
averaging play time and play sessions across the amount of people who use one of my bots in each server
seems to strongly suggest social interaction hugely drives bot usage, competition or whatever
Ok so... I read some sources about classes and subclassing. I get the idea but it's very overwhelming for me because years ago I got complitely traumatised and blocked by a teacher reagarding object oriented programming (it was a nightmare) and I really have a big struggle starting to use them. Here's my attempt that failed:
class GameButton(Button):
def __init__(self, ctx, style, value, game, content, view):
super().__init__(style=style, label=value)
self.value = value
self.game = game
self.content = content
self.view = view
async def callback(self, interaction, ctx):
if interaction.user == ctx.author:
self.clear_items()
await interaction.response.edit_message(content='Game selected: Genshin', view = self)
self.value = 'Genshin'
self.stop()
I'm not sure what I'm doing tho 
You're on the right track. the callback takes 3 arguments: self, interaction, button
You could do something like button.label and check the label, and send a message depending on that
content=f"Game selected: {button.label}", pass this into your await interaction.response.edit_message(...)
you also never actually define a button. unless im missing something here
@commands.hybrid_command("purge")
@commands.has_permissions(manage_messages=True)
async def purge(self, ctx: commands.Context, msg_num: int):
if not ctx.author.guild_permissions.manage_messages:
await ctx.send("You don't have permission to delete messages!")
return
await ctx.message.channel.purge(limit=msg_num, check=lambda _: True)
await ctx.send(f"Attempted to purge {msg_num} message(s)")
calling this gives the following error: https://paste.pythondiscord.com/ehejujevip
no clue what the actual issue is because you have a error handler
and the error handler is erroring lol
oh ok
also what are u checking for in the lambda?
@bot.event
async def on_command_error(ctx: commands.Context, e: commands.CommandError):
if isinstance(e, commands.MissingPermissions):
await ctx.reply("Unable to perform command- check your permissions!", ephemeral=True)
elif isinstance(e, commands.MissingRequiredArgument):
await ctx.reply("You're missing a required argument!")
else:
await ctx.reply("An unexpected error occurred!", ephemeral=True)
raise e
^ this is the error handler
yea remove ur error handler so u can get a proper error
nothing, just tryna delete the last x messages
why have what?
if ur trying to send a file. u need the path of the file
yes but i need to generate the path
huh?
so just save the file to a location
im getting erros with the r'' format
no clue what that means
can i send you the code, and see if you can figure out my problem
x = message.content
x = x[2:]
yt = pytube.YouTube(x)
t = yt.streams.filter(only_audio=True).first()
out_file = t.download(output_path='C:\Users\Ethan\PycharmProjects\YoutubeBot')
base, ext = os.path.splitext(out_file)
new_file = base + '.mp3'
os.rename(out_file, new_file)
time.sleep(10)
directory = ???
directory = str(directory)
await message.channel.send(file=discord.File(directory))
os.remove(directory)
i need to add the new file name to the end of \YoutubeBot
what's the bests way to host your bots?
u already have the file. out_file why rename and do extra stuff
what's the best hosting service
i need to add r' to the front
how would I type that?
but once ive done that it says it isnt formatted correcly
but why? all ur doing is sending a file after downloading then deleting it
it says its formated as "r'directory'" instead of r'directory'
i learned a lot today from the discord.py github examples
cause im using my directory and it need r'' for some reason
now i have embeds with buttons! yay!
if you can show me a way to not need that that would also work
r' is the file pointer btw
what is the problem maybe i can help
these guys are tough nuts sometimes
ill just tell you how to do it so you dont lose sleep
x = message.content
x = x[2:]
yt = pytube.YouTube(x)
t = yt.streams.filter(only_audio=True).first()
out_file = t.download(output_path='C:\Users\Ethan\PycharmProjects\YoutubeBot')
base, ext = os.path.splitext(out_file)
new_file = base + '.mp3'
os.rename(out_file, new_file)
time.sleep(10)
directory = ???
directory = str(directory)
await message.channel.send(file=discord.File(directory))
os.remove(directory)
ur using pytube right?
yes
inside of out_file, u can already define a filename
sorry, i dont understand
ok ill try that
os.remove(f'path_to_download/{yt.default_filename}`)
im not gonna write it all out for you. you already know how, just use the docs.
aighty
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)
^ this is the error i get after removing the handler
what should i do?
post your code to that shared space and ill look at it
anybody know why some slash commands are persisting in the menu when i have removed them from the bot
?
do i need to reset the token and log in again?
did you sync your commands afterwards
yeah
supposed to be instant but they do still take some time in some instances ive seen
gotcha
yeah because i run this every time in every bot
import discord
from discord import app_commands
MY_GUILD = discord.Object(id=935395948727779328)
class MyBot(discord.Client):
def __init__(self, *, intents: discord.Intents):
super().__init__(intents=intents)
self.tree = app_commands.CommandTree(self)
async def setup_hook(self):
self.tree.copy_global_to(guild=MY_GUILD)
await self.tree.sync(guild=MY_GUILD)
intents = discord.Intents.default()
client = MyBot(intents=intents)
@client.event
async def on_ready():
print(f'Logged in as {client.user} (ID: {client.user.id})')
print('------')
that's kinda my boilerplate more or less
nope rule number 6. if you would have read the rules
deleted
dmed you a server that is tech savy and allows such advertisements
yes, thank you very much
hey
how do you guys do
Traceback (most recent call last):
File "/home/deusopus/.local/lib/python3.10/site-packages/discord/ui/view.py", line 425, in _scheduled_task
await item.callback(interaction)
File "/home/deusopus/Desktop/get_og.py", line 43, in get_mod
await interaction.response.edit_message(view=self)
File "/home/deusopus/.local/lib/python3.10/site-packages/discord/interactions.py", line 787, in edit_message
raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before
how do you prevent this erros
is it the self.value=...
do i need to set that to False after the interaction?
you're responding to an interaction twice which you can't do
it would be helpful to see the code of that view
You can get around that by sending the first response as a response, and any subsequent message as interaction.channel.send()
As long as you're not trying to use ephemeral
if you don't mind here it is...
class button_view(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
self.value = None
self.timeout = None
@discord.ui.button(label = "Get OG Status, Now!", style = discord.ButtonStyle.green, custom_id = "role_button")
async def get_mod(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
if interaction.user.get_role(985708739392839720) is None:
role = interaction.guild.get_role(985708739392839720) or await interaction.guild.fetch_role(985708739392839720)
await interaction.user.add_roles(role)
await interaction.response.send_message(f"I have granted you {interaction.guild.get_role(985708739392839720)}!", ephemeral = True)
else:
await interaction.response.send_message(f"You already possess {interaction.guild.get_role(985708739392839720)} or HIGHER!", ephemeral = True)
self.value = False
self.get_mod.disabled = True
await interaction.response.edit_message(view=self)
@client.tree.command(guild=MY_GUILD, name = 'get-og-status', description='Get OG status!')
async def launch_button(interaction: discord.Interaction):
await interaction.response.send_message(view = button_view(), ephemeral=True)
Thanks in advance
so interaction.channel.send(view = button_view())
It looks like the problem is your edit_message() line where if they already have the role it tries to send the view again. I don't think you can do that with an ephemeral message for 1. And 2, you shouldn't need to since you never self.stop() so the original buttons should still work after they've been interacted with
Also, to make it easier on yourself, you could just use {role} instead of {interaction.guild.get_role()} inside your text lines since you've already grabbed the role
Not exactly
It would probably still give you the error. If you want to edit that response you should send it with something like msg = interaction.response.send_message() then edit it with msg.edit(view=view)
now why do you have to make the command a variable? im just curious
Makes it easier. iirc the other way is to grab the message by ID then edit it that way. I also just found this though
!d discord.InteractionResponse.send_message - it doesn't return the message, so no, you can't edit that way
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
Whatttt that's wack
await interaction.response.send_message(view=None)
This should work then to edit it?
!d discord.Interaction.edit_original_response
await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the original interaction response message.
This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit "discord.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if the message sent was ephemeral.
Why does it always seem like there's 7 answers that might work but only one of them does lol
Back to the shadows I go 
hmmm
this one works?
tell me about it. i know what you mean'
this edits the first interaction response sent
only the interaction response
is this what you mean?
class button_view(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
self.value = None
self.timeout = None
@discord.ui.button(label = "Get OG Status, Now!", style = discord.ButtonStyle.green, custom_id = "role_button")
async def get_mod(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
if interaction.user.get_role(985708739392839720) is None:
role = interaction.guild.get_role(985708739392839720) or await interaction.guild.fetch_role(985708739392839720)
await interaction.user.add_roles(role)
await interaction.response.send_message(f"I have granted you {interaction.guild.get_role(985708739392839720)}!", ephemeral = True)
else:
await interaction.response.send_message(f"You already possess {interaction.guild.get_role(985708739392839720)} or HIGHER!", ephemeral = True)
self.value = False
self.stop()
self.get_mod.disabled = True
await interaction.edit_original_response(view=self)
@client.tree.command(guild=MY_GUILD, name = 'get-og-status', description='Get OG status!')
async def launch_button(interaction: discord.Interaction):
await interaction.response.send_message(view = button_view(), ephemeral=True)
Send it see if it works
It should
Should work with ephemeral messages even
Traceback (most recent call last):
File "/home/deusopus/.local/lib/python3.10/site-packages/discord/ui/view.py", line 425, in _scheduled_task
await item.callback(interaction)
File "/home/deusopus/Desktop/get_og.py", line 37, in get_mod
await interaction.user.add_roles(role)
File "/home/deusopus/.local/lib/python3.10/site-packages/discord/member.py", line 1014, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
File "/home/deusopus/.local/lib/python3.10/site-packages/discord/http.py", line 738, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
missing permissions
i need to reinvite with proper permissions this time
manage roles
send messages
what permissions does it need anybody know?
nope
gdmit
Are you talking with yourself
not anymore 😉
Also manage users maybe
And you can't manage a user that is above the bot in the member hierarchy
And you also can't manage roles above the bot's highest role in the role hierarchy
ahhh
so maybe it doesn't work since im admin and the role is lower than that
so what roles does it look like it needs just send messages
and manage roles
manage messages
read message history
use slash commands and thats it
i wonder if that's enough or too much
i got bot and application.commands scopes
@mighty pilot what is rename every member code
that stuff doesn't work
if i have OG status as admin it tells me that i have that role already
but if i don't have OG role it says application didn't respond and the traceback says permissions error
Is that role above the bot's role
let me check
yeah that was part of it. but it still not disappearing according to my tester
!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.
@naive briar do u know nextcord
yup
hey
i am working on embed and i want to add user name in title
the user who use the command
i want him to see a sample embed with his user name
What's the problem you're having
i am trying to add
member: discord.Memeber along with ctx
but it thrown error
What's the error
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'builtin_function_or_method' object is not subscriptable
!d discord.Member.nick
The guild specific nickname of the user.
Call the method
i am
can u show u the code
Can I?
sorry can i
if you paste your code, say what you want it to do vs what it actually is doing and any errors you get all in 1 message then people will be able to help you much more easily :)
oke sir
actuly i am myself confuse with code coz there are many commands now
wait let me send it as soon as possible
in this i am trying to get the username of the person who send the command message
and put that message in dict title3
but its showing me eorro
!d discord.commands.ext.Context.author
!d discord.ext.commands.Context.author
Union[User, Member]: Returns the author associated with this context’s command. Shorthand for Message.author
this is the user/member who sent the command
okke
here i am trying to send the embed the user asked for with deserd title ,description etc
but what if the user has not passed any of two feilds
how cany send the resut in both the case
1: when user provide title and description
2: when user skiped one of the feilds
without any error
Set defaults to the params
what is params
but what if he want to skip it
..that's why you set defaults
A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
okee
how to put the embeds in one message?
its a list so it sends as a list and more than one message
I barely understand what you're saying
@commands.command()
async def kicks(self, ctx, arg=None):
user_limit = arg
if arg == None:
async for kicks in ctx.guild.audit_logs(action=discord.AuditLogAction.kick):
em1 = discord.Embed(title="Kicks", description=f'{kicks.user.mention} kicked {kicks.target.mention}')
await ctx.send(embed=em1)
else:
async for entry in ctx.guild.audit_logs(action=discord.AuditLogAction.kick, limit=int(user_limit)):
em = discord.Embed(title="Kicks", description=f'{entry.user.mention} kicked {entry.target.mention}')
await ctx.send(embed=em)
since discord.AuditLogAction.kick is a list i want it to be sent in one single message
Add the embeds to a list, then send one message at the end
use the embeds kwarg instead of embed
discord.embeds?
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
See the embeds keyword argument? It takes a list instead of one Embed
where should i use embeds argument?
^ in the send method
use the
embedskwarg instead ofembed
Traceback (most recent call last):
File "C:\Users\unfge\Desktop\TEST Bot\testbot\lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "c:\Users\unfge\Desktop\TEST Bot\Cogs\errorhandler.py", line 28, in on_command_error
raise error
File "C:\Users\unfge\Desktop\TEST Bot\testbot\lib\site-packages\discord\ext\commands\bot.py", line 1347, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\unfge\Desktop\TEST Bot\testbot\lib\site-packages\discord\ext\commands\core.py", line 986, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\unfge\Desktop\TEST Bot\testbot\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: ValueError: embeds has a maximum of 10 elements.
have you tried reading the error
it sends that error when the embed has 3 elements
how do you know that
i know how many people i have kicked from the server
whats the code of rename every member in server
I trust discord.py more than you
I'm not gonna give you code
and why do you need this?
cuz im making discord bot
obviously
cool
it two message not one
just Answer the question then, why do you need this
cuz i want to rename everyone in my server
wow really you want to do X because you want to do X
kk nvm u wont give it
w.... .. ....
property members```
A list of members that belong to this guild.
!d discord.Member.edit
await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., timed_out_until=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the member’s data.
Depending on the parameter passed, this requires different permissions listed below...
really
@upbeat gust
@client.command(pass_context=True)
async def rall(ctx, member: discord.Member, nick):
await ctx.message.delete()
for member in list(client.get_all_members()):
try:
await member.edit(nick=rename_to)
print (f"{member.name} has been renamed to {rename_to}")
except:
print (f"{member.name} has NOT been renamed")
print("Action completed: Rename all")
this is why im asking ju
???
Does anyone know how to get all channels in a certain category
Like:
category:
channel-1
channel-2
channel-3
for channel in category:
print(category)
output:
channel-1
channel-2
channel-3
property channels```
Returns the channels that are under this category.
These are sorted by the official Discord UI, which places voice channels below the text channels.
.
Thanks bro
from discord.ext import commands
import discord
from replit import db
class create(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
@commands.cooldown(1, 1, commands.BucketType.user)
async def create(self, ctx):
await ctx.send(ctx.channel.id)
db[f'{ctx.channel.id}'] = 'created'
await ctx.send(db[f'{ctx.channel.id}'])
async def setup(bot):
await bot.add_cog(create(bot))
it only does
await ctx.send(ctx.channel.id)
wondering what am i doing wrong
Replit moment
No idea, do you have logging?
i dont have an error handler
and there is nothing in the log
the only output is the channel id
aight i figured it out
the value inside db[] must be a string
so str(f'{ctx.channel.id}') works
but f'{ctx.channel.id}' is a string
its an integer
an f-string is a string
???
i mean the datatype of the id
>>> type(f'{123}')
<class 'str'>```
yep, but in this context it's being placed into an f-string, so it's a string
:/
lemme try
how is that any different
also, you could just do str(ctx.channel.id)
you could also just use a real db
oo ya
i think the JSON returned from the API is actually a string too
ids are ints
oo its strings
i assume they were talking about the discord api?
json limits keys to strings, not values
how is the api even relevant here
i have no idea what this guy is on about
yeah, idk either :P
from discord.ext import commands
import discord
from replit import db
class create(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
@commands.cooldown(1, 1, commands.BucketType.user)
async def create(self, ctx):
await ctx.send('started')
db[f'{ctx.channel.id}'] = {
match: {
"started": True,
"players": 1,
"host": ctx.author.id
},
player1: {
"p1id" : ctx.author.id,
"money" : 1500,
"color" : arg
}
}
await ctx.send(db[f'{ctx.channel.id}'])
await ctx.send('ended')
async def setup(bot):
await bot.add_cog(create(bot))
```here we go again this thing only outputs started 💀
.
but it's replit
have fun dealing with replit bs
i mean i guess they could use sqlite
i'm not sure if that conforms to your definition of "real db"
my bot is a small one so replit db should be good enough
why wouldn't it? sqlite is a perfectly fine db
look where its gotten you so far
i mean
i have another bot using this too
its working perfectly
maybe its because im trying to make the value a dictionary?
it works if its a string
alright back to square 1
screw dictionary
^
Okay I did this:
class GameButton(Button):
def __init__(self, ctx, style, label, game):
super().__init__(style=style, label=label)
async def callback(self, interaction, button, ctx):
if interaction.user == ctx.author:
self.clear_items()
await interaction.response.edit_message(content=f'Game selected: {GameButton.label}', view = self)
self.value = GameButton.label
self.stop()
However it tells me that it cannot access clear_items() and stop() for GameButton. I don't know if what I did is correct because I have no idea what i'm doing i'm trying to figure out by messing with it lol
why do you have ctx now
what is Button.clear_items() supposed to do?
clear_items and stop are methods of View
Ahhhh so this is why it isn't functionning !
I'm confused between making a button by subclassing a view and making a button by subclassing a button I apologise, lemme play with it again
not sure what youd do instead though sorry
discord.py when no default error handling in views
Can someone help me with submitting data to a database using SQLite and discordpy
SqlCode = (f"""INSERT INTO Database1 ("UUID", "Username", "Amount Donated")
#VALUES ("{UUIDp}", "{username}", "{donation}" ;""")
#)
# Setup a connection with our database file
connection = sqlite3.connect("Database.db")
# Create a cursor for the database to execute statements
cursor = connection.cursor()
# Execute a statement
cursor.execute(SqlCode)
# Save + close the database, never skip this
# or nothing will be saved!
connection.commit()
connection.close()
I found an example online
But im a little confused on the formatting when executing the code
OwO bot coding language= python?
if you see the sqlcode variable theres a lot of speech marks and im a little confused on where the speech marks are meant to go
this is worst way of using insert queries
!sql-fstrings
SQL & f-strings
Don't use f-strings (f"") or other forms of "string interpolation" (%, +, .format) to inject data into a SQL query. It is an endless source of bugs and syntax errors. Additionally, in user-facing applications, it presents a major security risk via SQL injection.
Your database library should support "query parameters". A query parameter is a placeholder that you put in the SQL query. When the query is executed, you provide data to the database library, and the library inserts the data into the query for you, safely.
For example, the sqlite3 package supports using ? as a placeholder:
query = "SELECT * FROM stocks WHERE symbol = ?;"
params = ("RHAT",)
db.execute(query, params)
Note: Different database libraries support different placeholder styles, e.g. %s and $1. Consult your library's documentation for details.
See Also
• Extended Example with SQLite (search for "Instead, use the DB-API's parameter substitution")
• PEP-249 - A specification of how database libraries in Python should work
» mutable-default-args
» defaultdict
Means ?
just ask in their support server, most probably not
!else
for-else
In Python it's possible to attach an else clause to a for loop. The code under the else block will be run when the iterable is exhausted (there are no more items to iterate over). Code within the else block will not run if the loop is broken out using break.
Here's an example of its usage:
numbers = [1, 3, 5, 7, 9, 11]
for number in numbers:
if number % 2 == 0:
print(f"Found an even number: {number}")
break
print(f"{number} is odd.")
else:
print("All numbers are odd. How odd.")
Try running this example but with an even number in the list, see how the output changes as you do so.
Python so confusing language
I think this easy but so hard
you use ? instead of the argument values
and then pass in a tuple in the execute statement with the query which will replace the values
My SQL code looks more like this though
INSERT INTO "Database1" ("UUID", "Username", "Amount Donated")
VALUES ("exampleuuid", "exampleusername", "500k" )
So the top half would be my query
Oh sorry this discord support channel
Still confused on how this matches up to my code
Where would the place holder go
what db are you using
SQlite
values = ("arg1 value", "arg 2 value")
cursor.execute(
"""insert into table_name
( argument1, argument2 )
values ( ?, ? )""", values
)
I think I get it a little
values (UUID, Username, Amount Donated)
cursor.execute(
"""insert into Database1
(UUID, Username, Amount Donated)
values ( ?, ?, ?)""", values
)
Is that how it would work in my instance
Yeah I realised that
also "Amount donated" won't be a valid column name when you will create the table
might use amount_donated
Previously I just did "Amount Donated" to specify it
I should probably just change it to amount tbh
Unnecessarily making it more complicated by adding a space
I connect to the database using the same method though right?
well no, you shouldn't be using sqlite3 for a discord bot
i mean the module
!pip aiosqlite use this instead
Oh
everything remains same you'll just have to await some stuff
open the link it has examples
do I have to install it via pip or can I just import aiosqlite
pip install it
eh ><
i know right
I'm trying to climb the learning curve of object oriented programming, feels like climbing himalaya ngl
users.pop(users.index(bot.user))
i am using cogs, what do i change instead of bot?
you can override the on_error method of view class to raise errors
!d discord.ui.View.on_error
await on_error(interaction, error, item, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A callback that is called when an item’s callback or [`interaction_check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View.interaction_check "discord.ui.View.interaction_check") fails with an error.
The default implementation logs to the library logger.
raise the error or do anything you want to
??
lemme understand how to subclass a button and use callbacks correctly first lol
if its a command you can just do ctx.bot
i'm so lost in this, I'll do error handling and type hinting when I finish basic skeleton of the program
its a slash command
good luck with that!!
tyyy sarth you so sweet and helpfull :D
yw :)
@commands.slash_command(name="create")
AttributeError: module 'nextcord.ext.commands' has no attribute 'slash_command'
Ok so let me break it down:
A button has a label, a style, a custom id, and a value. I can pass ctx to it for extra context manipulation. Is that correct?
class GameButton(Button):
def __init__(self, label, ctx):
super().__init__(label=label, style=game_button_style)
self.custom_id = label
self.ctx = ctx
async def callback(self, interaction, button):
if interaction.user == self.ctx.author:
await interaction.response.edit_message(content=f'Game selected: {GameButton.label}', view = self)
self.value = button.label
Although this callback function is working when I copy pasted some working code in my current online version of the bot and it's working fine. but idk how to do this with the button subclass it's driving me crazy lol
well this is a Button subclass
this code works right?
Actually... it doesn't
Lemme show you my old code that works
async def select_game(ctx, bot):
class GameView(View):
def __init__(self):
super().__init__(timeout=None)
self.value = None
@discord.ui.button(label='Genshin', style=discord.ButtonStyle.blurple)
async def genshin_callback(self, interaction, button):
if interaction.user == ctx.author:
self.clear_items()
await interaction.response.edit_message(content='Game selected: Genshin', view = self)
self.value = 'Genshin'
self.stop()
@discord.ui.button(label='Roblox', style=discord.ButtonStyle.blurple)
async def roblox_callback(self, interaction, button):
if interaction.user == ctx.author:
self.clear_items()
await interaction.response.edit_message(content='Game selected: Roblox', view = self)
self.value = 'Roblox'
self.stop()
view = GameView()
msg = await ctx.send('What **game** is it?', view = vie
and the callback doesn't take an button argument when you're subclassing
This thing works but I have no idea what it is I just copy pasted it. Now that I'm recoding my bot to make it clean code I'm diving into these complex OOP
how do i make my bot mention another user when i preform a comand
Oh I see, so I'm instanciating the wrong class you mean? :o
yes, the class should be discord.ui.Button, not discord.Button and the callback should be like this ```py
async def callback(self, inter): ...
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\bot.py", line 766, in _load_from_module_spec
spec.loader.exec_module(lib) # type: ignore
File "<frozen importlib._bootstrap_external>", line 850, in exec_module
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "c:\Users\PC\Desktop\Noas Bot\cogs\giveaway.py", line 31, in <module>
@commands.slash_command(name="create")
AttributeError: module 'nextcord.ext.commands' has no attribute 'slash_command'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "c:\Users\PC\Desktop\Noas Bot\main.py", line 64, in <module>
bot.load_extension(f"cogs.{fn[:-3]}")
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\bot.py", line 888, in load_extension
self._load_from_module_spec(spec, name, extras=extras)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\bot.py", line 769, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
nextcord.ext.commands.errors.ExtensionFailed: Extension 'cogs.giveaway' raised an error: AttributeError: module 'nextcord.ext.commands' has no attribute 'slash_command'```
!d discord.ui.Button.callback
await callback(interaction)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The callback associated with this UI item.
This can be overridden by subclasses.
@slate swan aswell as installing via pip do i also need to import aiosqlite
don't copy paste code, it's better this way
ive copy pasted parts of my own code and still made stupid errors while doing it lol
how do i make my bot mention another user when i preform a comand
help
.send("<@id of another user>")
tysmmm
commands.slash_command doesn't exist, decorators don't originate out of thin air @slate swan
hello, how can I make a discord py Slash Command to clear messages such as /purge 50 I'm using discord.Interactions
from discord.ui import View, Button
It's this button that's taken as a class in Class GameButton(Button), Button and ui.Button are the same thing ig, maybe you're talking about button with lowercase b which is a method? :o
ohhh wait you're right !
Button and ui.Button are related but different:p
your issue was the callback ig
maybe I was taking the wrong Button class :o
!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...
interaction.channel.purge
thank you
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
!paste
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.
is the limit how many messages it will delete? or how many it will stop at? How can i make it remove x number of messages
you can't delete messages older than 4weeks
yeah you're right, although I just checked and it took the correct button class. I changed it anyways to GameButton(discord.ui.Button) for more code clarity
there was some limit like that
yeah great now test that code
yeah, easily
won't suggest using any limit higher than that tho
it can ratelimit your application
if used too many times together
Thing is that I want that button to trigger the removal of all buttons attached to its message and edit the message and return a value when clicked. Can all this be in the button callback?
well self is already your button no
how do I go about doing that though?
await i.channel.purge(bulk=True,check=False,limit=100)
```` like this?
I keep getting an error telling me the table does not exist despite me manually making the table on SQlite
yeah that should work
but how many would It delete?
did you connect to the right database
yep
100
ohh so the limit is what it deletes?
is it fine that the database file is in a seperate file to the discord py file
you just need to use the correct path, it can be anywhere
yessir
then what's that callback function for? just returning a value I assume? that value gets captured by the view and with the view I can edit the message and remove buttons? am I getting it correctly?
I used
async with aiosqlite.connect("Database.db") as db:
its for doing something when that hutton is clicked
*button
this will create a database file named Database.db in the same directory as the bot and use it
what's the range of things I can do inside that callback I'm confused, could you give me an example of what i can and cannot do please sarth? 
Oh... How do I get it to use an already created database
you have an interaction object there, so you can basically do anything that you can do with an interaction
Oh alright I'll check docs ty sarth :D
provide the path of your database file instead of Database.db
no worries, its mostly responding the interactions or editing stuff
Like C:\User\ etc
Do I add \Database.db at the end aswell
no
Oh
just the path pointing to that db
Right now the path points to the folder the file is in
So I assumed I should add \database.db
it should be rhe database file's name
?
async with aiosqlite.connect("C:\Users\Fiery\OneDrive\Desktop\AtomProjects\HyperionFund Discord Bot\Databases\Database.db") as db:
how do i make it so that every 10 minutes the bot auto preforms one of its commands
probably just use some sort of loop and await asyncio.sleep()
dunno if there's a better way or not
Oh I think I found the issue
!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").
wow didn't know this existed
anyone know anything about this?
Escape the backslashes (\\) or use a raw string
How can I use cogs with slash commands like this?
ILL TRY raw string
can u give some sort of expample
!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").
Check pins
yo nice
from discord.ext import tasks
@tasks.loop(minutes=10)
async def loop() -> None:
print("I print every 10 min")
# use on_ready in commands.Cog.listener or bot.event to start the task
class GameButton(discord.ui.Button):
def __init__(self, label, ctx):
super().__init__(label=label, style=game_button_style)
self.custom_id = label
self.ctx = ctx
async def callback(self, interaction):
if interaction.user == self.ctx.author:
await interaction.response.edit_message(content=f'Game selected: {self.label}', view=None)
return self.label
class GameView(discord.ui.View):
def __init__(self, ctx, children):
super().__init__(timeout=30)
self.ctx = ctx
for x in self.children:
self.add_item(x)
async def select_game(ctx):
genshin_button = GameButton('Genshin', ctx)
roblox_button = GameButton('Roblox', ctx)
view = GameView(ctx, [genshin_button, roblox_button])
select_game_message = await ctx.send('What **game** is it?', view = view)
this still doesn't work and I don't know why, although I feel i'm getting closer :D
no use tasks.loop, the way i said is bad and I forgot tasks.loop is a thing
@discord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)```
A decorator that attaches a button to a component.
The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View"), the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") you receive and the [`discord.ui.Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button "discord.ui.Button") being pressed.
Note
Buttons with a URL cannot be created with this function. Consider creating a [`Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button "discord.ui.Button") manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.
use this
I'm using this already, although it makes code very long and redundant. I have been recommended to subclass the discord.ui.Button class so my code is clearer and less repetitive and shorter ^^
...
That makes it even more messy if you ask me
But you do you
wait a minute I think I understand what you mean 
https://github.com/Rapptz/discord.py/tree/master/examples/views this is what dpy recommends
I'm not understanding anything of OOP it's so hard lol
I am currently trying to fetch data from an api however I need my code to not run if it returns they use an invalid username. If an invalid username is used to api will return one of two things, either {"error":"Player does not exist"} or {"error":"Invalid username or UUID!"}
async with aiohttp.ClientSession() as session:
async with session.get(f'https://api.slothpixel.me/api/players/{username}') as resp:
player = await resp.json()
print(player)
if player == "{"error":"Invalid username or UUID!"}" or player == "{"error":"Player does not exist"}":
await interaction.response.send_message("Incorrect username entered please try again")
Im confused because what it returns contains speech marks therefore it messes up when i try to declare it
.json() returns a dict. Why are u checking a string
what is .Cog?
a dict?
the callback itself cant return any value, but the button has a .view property which will allow you to assign the value of the view like you once did before
Dictionary.
oh
Just check for the dict itself :p
No clue how lol
@cerulean folio for example: ```py
class MyButton(discord.ui.View):
def init(self, name):
super().init(label=name)
async def callback(self, interaction):
# do your response, and then:
self.view.value = self.label```
i would also still suggest adding an interaction_check() to your GameView to make sure its the same author, removing the need for ctx in your button
Uh if player == {...}
I need to check for a specific value rather than if its a dict or not
AHH
A message contains a view, the view is the class that contains the buttons to be pressed am I wrong?
I don't get how you make a view be a button, i'm confused i apologise
the button itself has a reference to the view its added to
Uhm
^