#discord-bots
1 messages · Page 1108 of 1
how can everything be a var
can someone come to my bot testing server and tell me which permissions does my bot need? xd tried few different options but it didn't work
on line 21, you used a # which commented out an important part
I think what you meant is colour=0xb7ff02)
and in the end (in code, in case you'd ask), member.display_avatar.url could just be written as x
cuz you dunno what it is
class Buttons(discord.ui.View):
def __init__(self, *, timeout=180):
super().__init__(timeout=timeout)
@discord.ui.button(label="Blurple Button",style=discord.ButtonStyle.blurple,emoji="🎁") # or .primary
async def blurple_button(self,button:discord.ui.Button,interaction:discord.Interaction):
button.disabled=True
await interaction.response.edit_message(view=self)
@client.command()
async def button(ctx):
view=Buttons()
await ctx.send("This message has buttons!",view=view)
And i got this error
Ignoring exception in view <Buttons timeout=180 children=2> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label='Blurple Button' emoji=<PartialEmoji animated=False name='🎁' id=None> row=None>:
Traceback (most recent call last):
File "C:\Users\lequi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ui\view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "C:\Users\lequi\Desktop\Hint Bot\hinttest.py", line 35, in blurple_button
button.disabled=True
AttributeError: 'Interaction' object has no attribute 'disabled'
Any body any idea?
?
no, not discord.Color
🤔
you use discord.Color or discord.Colour when you want to access a colour that Danny has hardcoded for you already
you want the specific colour 0xb7ff02
so you only pass that to colour=
correct?
color=discord.colour=0xb7ff02)
no...
color=0xb7ff02)
I also noticed you made client a commands.Bot, then reassigned it to be a discord.Client
and changed presence on_ready
so I suggest just removing line 5
just remove line 5 ?
and I got a tag from the dpy server:
Don't change_presence (or make API calls) in on_ready within your Bot or Client.
Discord has a high chance to completely disconnect you during the READY or GUILD_CREATE events (1006 close code) and there is nothing you can do to prevent it.
Instead set the activity and status kwargs in the constructor of these Classes.
bot = commands.Bot(command_prefix="!", activity=..., status=...)
As noted in the docs, on_ready is also triggered multiple times, not just once.
Basically: don't 👏 do 👏 shit 👏 in 👏 on_ready.
yes
u send me ?
yes
where i typing?
bot = commands.Bot(command_prefix="!", activity=..., status=...)
oh, you don't need a bot
you can do this within your client
you have
client = discord.Client()
```, so you could change that to
client = discord.Client(activity=discord.Game(name="++introduction"))
how can i see button press counts?
and delete line 11 with the change_presence stuff
and your code is already much better on startup
does anyone know how? ik its using callback func but how exactly
@commands.command()
@commands.cooldown(1, 10, commands.BucketType.user)
async def suggest(self, ctx, *, suggestion):
"""Suggest some commands that should be included in bot."""
await ctx.send(f"{self.bot.yes} {ctx.author.mention}, your suggestion has been recorded!")
upvotes = 0
downvotes = 0
channel = self.bot.get_channel(798259756803817545)
view = View()
b1 = ButtonCreation(
style=discord.ButtonStyle.grey,
emoji=self.bot.yes
)
b2 = ButtonCreation(
style=discord.ButtonStyle.grey,
emoji=self.bot.no
)
view.add_item(b1).add_item(b2)
async def b1_callback(interaction: discord.Interaction):
nonlocal upvotes
upvotes += 1
await interaction.response.edit_message(embed=em)
b1.callback = b1_callback
async def b2_callback(interaction: discord.Interaction):
nonlocal downvotes
downvotes += 1
await interaction.response.edit_message(embed=em)
b2.callback = b2_callback
em = discord.Embed(color=self.bot.color)
em.add_field(name="Suggestion", value=f"> {suggestion}", inline=False)
em.add_field(name="Upvotes", value=f"{upvotes} Votes", inline=True)
em.add_field(name="Downvotes", value=f"{downvotes} Votes", inline=True)
em.set_author(name=ctx.author, icon_url=ctx.author.avatar.url)
em.set_thumbnail(url=ctx.author.avatar.url)
em.set_footer(text=f"Guild: {ctx.guild} ({ctx.guild.id})")
await channel.send(embed=em, view=view)
``` this is my code, but it does not update it, shows 0 (both upvotes and downvotes)
just store something like b1.count, set it to 0
Your error is on line 29, not 9
add 1 to it in the callback
better subclass the View
im doing that, setting upvotes and downvotes = 0 then +1 it in async func
Andu know how fix 29 line ?
this
Yes, add the missing : at the end of your if statements
interesting indentation
so callback in the view class?
edit; wait view does not have a callback
correct?
You know basic python, right?
if condition:
…
class UpDownVoteView(discord.ui.View):
def __init__(self):
super().__init__(timeout=60)
self.up = 0
self.down = 0
self.users = []
async def interaction_check(self, inter: discord.Interaction):
if inter.user in self.users:
return await inter.response.send_message("NO", ephemeral=True)
@discord.ui.button(label="upvote")
async def upv(self, button: discord.ui.Button, inter: discord.Interaction):
self.up += 1
await inter.response.send_message("Upovted", ephemeral=True)
@discord.ui.button(label="downvote")
async def downv(self, button: discord.ui.Button, inter: discord.Interaction):
self.down += 1
await inter.response.send_message("Downvoted", ephemeral=True)
noob
better append the users to a list so that they dont get to up/downvote again
yeah
im begginer, sorry .
thanks, ill try
just i want help to correct my first script
what about pep8
nah you're trippin
also, what did I do, that was just an example
Just a heads up, discord.py isn’t a beginner thing despite it being what draws people to python. It’s a more intermediate thing, much easier once you’ve taken the time to learn the basics of the language
I just used the tabs.....which discord provides
Yea 100% but just i want fix my code ..
let's teach discord pep8 real quick
no comments
interaction.response.send_message(content="123", ephemeral=True)
Dear tell me what is the problem?
await interaction.response.send_message
😅 oh
!indents
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
lmaoooo, ily after that meh
ew
can someone help me make a slash command dpy 2.0 , i need certain stuff on it
if i'm making a web panel for my discord bot in flask, how easy is it to exchange information between the bot and the site?
Hey Ashley its been a while , can u rq help me
yeah?
so , i need /send category1: category2: then it says your category has been sent to the owner and the bot dms u the category1 category2
dont use flask, it's blocking, use quartz instead, and it isn't that hard to pass information between a UI panel and a bot, I remember doing that once, you just need certain stuffs for that
flask isn't blocking I thought?
it is, quartz is asynchronous
okay cool
and in the dm the bot will legit say , the information is category1 category 2
easy enough for sum ppl
So can someone help me with that
do you know how to create a basic slash command at least?
nope
i forgot
in dpy v2?
ye
there are existing examples in gh
@app_commands.rename(text_to_send='text')
@app_commands.describe(text_to_send='Text to send in the current channel')
async def send(interaction: discord.Interaction, text_to_send: str):
"""Sends the text into the current channel."""
await interaction.response.send_message(text_to_send)
``` ok i have this
anyways so can someone help me
make the code
@slate swan
someone lol
well, you need to define the bot and intents correctly too ofc
ye but i dont need that
i need /send category1: category2: then it says your category has been sent to the owner and the bot dms u the category1 category2
ofc you do, otherwise your command simply will not run
can u help me make the command if its simple please
well, I've seen you here before, so you must know how to do it in v1.7.3, right?
well, have you read the migration guide first of all?
for example, you need message_content intents, since they are required, as well as in the discord dev portal, you'll need to enable app commands
I have it
well, then where's your issue?
...
/send category1: category2: then it says your category has been sent to the owner and the bot dms u the category1 category2
i need help making this?
well, you should know that that command will take 2 args
with typehint discord.CategoryChannel
ok if u guys dont know its alr
we won't write it for you, that's all we're saying
no one asked for that
how would i get the total upvotes and downvotes in a Cog class?
@slash.slash()
async def send(ctx, user: discord.Member, *, message=None):
message = message or "txt",
await user.send(message)``` done i made a slash command @potent spear now i need help making the rest
pretty sure slash commands take in interaction, not ctx
i think u should update to 2.0
well, no idea what that @slash.slash() lib is, but it surely isn't v2
i have
ye , now u can help me 🙂
what lib is that?
1.7.x does not have slash
is it discord-components?
discord-slash-commands
i think
but i made it as a template , now i need help converting this into 2.0
ye , can u help me make that?
i havent made any slash cmds with dpy
Code : https://paste.pythondiscord.com/usivaruqoc Error when i type a command : thanks for helping !
class Buttons(discord.ui.View):
def __init__(self, *, timeout=180):
super().__init__(timeout=timeout)
@discord.ui.button(label="Blurple Button",style=discord.ButtonStyle.blurple,emoji="🎁") # or .primary
async def blurple_button(self,button:discord.ui.Button,interaction:discord.Interaction):
button.disabled=True
await interaction.response.edit_message(view=self)
@client.command()
async def button(ctx):
view=Buttons()
await ctx.send("This message has buttons!",view=view)
And i got this error
Ignoring exception in view <Buttons timeout=180 children=2> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label='Blurple Button' emoji=<PartialEmoji animated=False name='🎁' id=None> row=None>:
Traceback (most recent call last):
File "C:\Users\lequi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ui\view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "C:\Users\lequi\Desktop\Hint Bot\hinttest.py", line 35, in blurple_button
button.disabled=True
AttributeError: 'Interaction' object has no attribute 'disabled'
Anybody any idea?
element is probably outside the function
Can someone help me
I said up
link of message ?
this ?
i need /send category1: category2: then it says your category has been sent to the owner and the bot dms u the category1 category2 this
and whats the proble
You have to put both of them in the same arg.
You're separating with a comma for some reason
hi! Can I ask for help here or should I create a thread so I don't flood?
You have your args in the wrong order
interaction comes first not button
Thanks man
Should be
(self, inter, button)
tyler now it gives a atributeerror
Code : https://paste.pythondiscord.com/usivaruqoc Error when i type a command : thanks for helping !
Hi need help making it lol
I bet it’s that get_avatar thing
yse
That doesn’t normally exist for cogs. Did you make one yourself?
i made it myself 
And honestly just save yourself time.
Consider literally just
member1.display_avatar.url
memberAvatar1 = member1.display_avatar.url
my what
yes iknow
So what’s the problem then?
but also i keep getting that this is not importing
Did you install the package?
We don't help with music bots here.
oh
I honestly forgot about that.
It violates Youtubes ToS.
element is only in the scope of your check function. You can’t use it outside.
What you can do is
assign the self.bot.wait_for to a variable and that variable will be that message you expect it to be.
And you can use that instead
again attribute error 
Show your errors
Yeah I literally said you don’t have that
.
i did
The error literally says you used display_avatar so you obviously didn’t
yes sorry wait im channging code
Wtf no
Code : https://paste.pythondiscord.com/usivaruqoc Error when i type a command : thanks for helping !
I said assign it to a variable and that will be the message object you want
So, I want to get interactions/slash commands working with discord.py, but I have yet to found comprehensive documentation.
Can anyone point me in the right direction?
?
You need to indent everything after line 13.
The error tells you.
You have the function and the if on the same intendation.
how i correct?
By...adding a tab to everything that belongs into the function.
The error message is pointing you to the space that is missing something.
What does an if end with?
hello, could someone help me out. I've been trying this for ages. I'm trying to make a whitelisted command that my bot can have so only users with the certian ids can use the command. I'm wanting to save the users infomation and id into a config.json file but I can't get it to work, here's my code:
Async editing files will lead to tears.
Might I suggest sqlite.
Or any lite db of your choice.
@discord.ui.button(label="Button",style=discord.ButtonStyle.gray)
async def gray1_button(self,interaction:discord.Interaction,button:discord.ui.Button):
await interaction.response.edit_message(content=f"This is an edited button response 2! {member.name}")
@client.command()
async def button(ctx, member: discord.Member):
await ctx.send("This message has buttons!",view=Buttons())
I got this but how i get the member argument in the button function?
[2022-06-19 00:15:47] [ERROR ] discord.ext.commands.bot: Ignoring exception in command button
Traceback (most recent call last):
File "C:\Users\lequi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\bot.py", line 1330, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\lequi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 987, in invoke
await self.prepare(ctx)
File "C:\Users\lequi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 904, in prepare
await self._parse_arguments(ctx)
File "C:\Users\lequi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 811, in _parse_arguments
transformed = await self.transform(ctx, param, attachments)
File "C:\Users\lequi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 663, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: member is a required argument that is missing.
Error
?
when u invoke the command you need to pass in the argument. !button @user instead of !button however because u don't use member you should just remove it from the function
A :
Sorry that was the wrong error
You're missing a : at the end of your ifs.
ansform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: member is a required argument that is missing.
Ignoring exception in view <Buttons timeout=180 children=2> for item <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='Button' emoji=None row=None>:
Traceback (most recent call last):
File "C:\Users\lequi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ui\view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "C:\Users\lequi\Desktop\Hint Bot\hinttest.py", line 31, in gray1_button
await interaction.response.edit_message(content=f"This is an edited button response 2! {member.name}")
NameError: name 'member' is not defined
Thats the one i want the for example display the user name of the member in the button function
after a button is clicked
class Buttons(discord.ui.View):
def __init__(self, *, timeout=180):
super().__init__(timeout=timeout)
@discord.ui.button(label="Button",style=discord.ButtonStyle.gray)
async def gray_button(self,interaction:discord.Interaction,button:discord.ui.Button):
await interaction.response.edit_message(content=f"This is an edited button response!")
@discord.ui.button(label="Button",style=discord.ButtonStyle.gray)
async def gray1_button(self,interaction:discord.Interaction,button:discord.ui.Button):
await interaction.response.edit_message(content=f"This is an edited button response 2! {member.name}")
@client.command()
async def button(ctx, member: discord.Member):
await ctx.send("This message has buttons!",view=Buttons())
@neat lynx
you should add a member argument into Buttons __init__ and assign it self.member = member and then you can access it in ur functions with self.member
Where should i add that
I tried but it outputs a error if i write it in init
class Buttons(discord.ui.View):
def __init__(self, member):
self.member = member
Traceback (most recent call last):
File "C:\Users\lequi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 200, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\lequi\Desktop\Hint Bot\hinttest.py", line 35, in button
await ctx.send("This message has buttons!",view=Buttons())
TypeError: __init__() missing 1 required positional argument: 'member'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\lequi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\bot.py", line 1330, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\lequi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 995, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\lequi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 209, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: __init__() missing 1 required positional argument: 'member'
well in view=Buttons() you need to pass in member
view=Buttons(member)
Ignoring exception in view <Buttons timeout=180 children=2> for item <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='Button' emoji=None row=None>:
Traceback (most recent call last):
File "C:\Users\lequi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ui\view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "C:\Users\lequi\Desktop\Hint Bot\hinttest.py", line 31, in gray1_button
await interaction.response.edit_message(content=f"This is an edited button response 2! {self.member.name}")
AttributeError: 'Buttons' object has no attribute 'member'
show code
class Buttons(discord.ui.View):
def __init__(self,member, *, timeout=180):
super().__init__(timeout=timeout)
@discord.ui.button(label="Button",style=discord.ButtonStyle.gray)
async def gray_button(self,interaction:discord.Interaction,button:discord.ui.Button):
await interaction.response.edit_message(content=f"This is an edited button response!")
@discord.ui.button(label="Button",style=discord.ButtonStyle.gray)
async def gray1_button(self,interaction:discord.Interaction,button:discord.ui.Button):
await interaction.response.edit_message(content=f"This is an edited button response 2! {self.member.name}")
@client.command()
async def button(ctx, member: discord.Member):
await ctx.send("This message has buttons!",view=Buttons(member))
you didnt add self.member = member in __init__
What inside the init function
dude in the function
Never had anything with __init_
You define self.member to the member argument
you should read object oriented programming docs
Hi, I'm trying to create a function that allows the user to create a custom role with a custom colour
@client.command()
async def role_perso(message,name,color):
guild = message.guild
await message.send(f"{color}")
await guild.create_role(name=name, color=discord.Color(int(color)))
await message.add_reaction(working_emote)
color is an hex color, but I don't know why, its class is str and I can't convert it to int
"Expected int parameter, received str instead."
"ValueError: invalid literal for int() with base 10: '0x45ba80'"
Ok
when I don't convert it to int I just get "expected int received str"
I'm on mobile rn
I don't understand why I can"t convert my hex number to int yet this is an int
But try checking what they convert to color
discord.Color wants an int as a parameter
Yes but does color in create role only accept a discord.Color object?
hello, im using a database to make a whitelisted command but how can i check to see if a user already exists within the database using the users id as a input?
Dude I've been telling you
Apparently you can just pass in the hex
You don't need discord.Color
the problem is that they want the hex as an int
should I try to convert the hex to a base 16 int?
int(my_hex,16)
I just don't see how that's necessary
my hex is a str and they refuse str
do you know how to query the database?
Is it
your question is quite broad. Which part are you havbing trouble with
SELECT id FROM users WHERE id = {userid} @full lily like that rigt im trying to compare the given user id say its 131313131313 and i want to check to see if that exists in my databae if it does i want my bot to state that it exsits if not i want it to add that user if that made sense
MY BOT is work thank but i have embed problem bot dont typing my embed. i think i have bad embed text?
I cant see shit
@client.command()
async def role_perso(message,name,color):
guild = message.guild
await message.send(f"{color}")
await guild.create_role(name=name, color=color)
await message.add_reaction(working_emote)
This is my actual code and it doesnt work
"AttributeError: 'str' object has no attribute 'value' "
okay so get the results, and check if the list that it returns is empty or not
if it's empty, you know the person isn't in your database and you should add them
I wonder if there's a sql command to all of that in one go. "Check if this row exists, and if not, add it"
maybe so do i try to select the users id from my database and if it equals nothing then to add them right?
Something close to create table if not exits ?
There probably is
My embed message, not work
client = discord.Client(activity=discord.Game(name="++introduction"))
@client.event
async def on_ready():
print('HackingTraining is ready.')
@client.event
async def on_message(message):
if message.content.startswith('++introduction'):
embed = discord.Embed(
title='Commands',
description='**__IMPAT13NTS - HACKING TRAINING__**\n**!შესავალი** :pushpin:\n**!ლინკები** :link:\n**!math instruction** :scroll:\n**!math** :pushpin:\n**!gamefield instruction** :scroll:',
color=0xb7ff02)
embed.set_image(url="https://media.discordapp.net/attachments/974804087893815326/982721780110209084/IMPAT13NTS__5_-removebg-preview.png")
embed.set_thumbnail(url=message.author.display_avatar.url)
embed.timestamp = datetime.datetime.now()
await message.channel.send(embed=embed)```
Anything in the console?
Really weird
Then ig try converting it
that's what I did 😹 can't convert it
ValueError: invalid literal for int() with base 10: '0x45ba80'
But type returns int right
yes
this is embed code
<class 'str'>
I added a print(type(color))

stuck in 1.7
Done?
embed.set_thumbnail(url=message.author.avatar_url)
If you’re not on dpy v2, yes
Did you import it?
Also you should probably be using the commands extension
@client.event
async def on_ready():
print('HackingTraining is ready.')
@client.event
async def on_message(message):
if message.content.startswith('++introduction'):
embed = discord.Embed(
title='Commands',
description='**__IMPAT13NTS - HACKING TRAINING__**\n**!შესავალი** :pushpin:\n**!ლინკები** :link:\n**!math instruction** :scroll:\n**!math** :pushpin:\n**!gamefield instruction** :scroll:',
color=0xb7ff02)
embed.set_image(url="https://media.discordapp.net/attachments/974804087893815326/982721780110209084/IMPAT13NTS__5_-removebg-preview.png")
embed.set_thumbnail(url=message.author.avatar_url)
embed.timestamp = datetime.datetime.now()
await message.channel.send(embed=embed)```
this is my embed code bot not work
You should read the error
.
Yeah, read it
yea but i dont understand. .
Literally just import the library
if i remove date?
What's ur favorite ide
How do most bots go about permission systems? I was wanting to allow the user to set permissions that roles are allowed to do, but I have no idea how this would feasibly work from a database....
How would I check that the user has a role with that permission without iterating through all their roles every time? Maybe I've set about this the complete wrong way. thanks
Don't remove anything just import datetime
how?
🗿
Import datetime
example?
import datetime at the top of your file.
IMPORT DATETIME
🥲
you are meant to know the basics of python before starting to use dpy :P
what is this called? like embed.add what
Why would you even store this?
This is a footer
I prefer tnaks tbh
I would like to allow permissions to be set to roles. I'd have to store that somewhere
You want to copy a member’s exact permissions & make a role out of it?
do I? my current idea was to assign vaules to a role id in my database, but I hadn't thought through how I would end up checking that efficiently
Yeah, you’re implementing this the wrong way
There’s a decorator called “has_permissions”
No, I know that. But that's for default discord permissions, not custom vaules
If statements
Again, yes. I'm aware how discord permissions work. That's not what I'm trying to do
Just check if any of the members roles is in the database with custom perms
Yes, I thought that. But that doesn't sound efficient for every command
some users could have 100s of roles
Yeah, and one of those roles should have a specific permission?
If it has a perm then it would be really specific and probably the top role
Not necessarily. I'm planning on having things like view user warnings which any low level mod would probably have
but again, my embed not work : /
It's not like I'm an admin and only my mod role gives me the ability to ban
change
datetime.datetime to datetime
import datetime
Not
From datetime import datetime
you somehow managed to do what we told you incorrectly
wtf
import datetime
that's how importing things work 🤔
in your code
IVE SAID EXACTLY THOSE WORDS LIKE 66000 TIMES
you can EITHER change to import datetime or do what I did
Do one of those 2, not both
^
what?
Resuming where we left off
Ig but it wouldn't override view warnings
I'm going to have multiple checks, if had admin then I won't need to check my permissions dB. doesn't solve the issue though
Anyways, storing “custom role names” as unique identifier isn’t a good idea, you should reference to a config table

UTC.
ha?
sorry, I'm not sure what you mean here? I'm not storing role names
???
the timezone
It looked mike you were with “warning”
you used UTC.now in datetimez it's going to be UTC
i dont understand how correct time .
that's the permission node
Still not really an idea of what you’re trying to achieve
remove
remove indeed
import datetime and add import UTC. ?
I'm trying to assign roles a "permission" in my bot.
not sure how it's gonna work tbh
w h a t
;d ?
🗿
yes that's what you coded it to do
now
yes now that's what you did
that's what this code does
Well, I suppose it’s member specific and has not much to do with the current roles the member has?
It's role specific, settable like this:
sorry for sending that again I just think that image explains it better than me :P
I think I see what you want
You want to give an existing role in a Guild to a member with the specified permissions?
done?
Here we go again
it's up to the admin to add the role to the user.
it's like "assigning" a "permission" to a role so a user can use that command

so any user with the role has that "permission"
And why wouldn’t you just add a role…
What do you mean?
Nope
: /
Don’t touch the import
i want correct time bro
Roles exist for this purpose, why create a db for it?
so you're saying have a role for every permission I might need?
like have the role called Warnings
I guess that's a way of doing it, less clean imo but idk.
Depends on how many “moderation” roles you might need
🤍
fair enough
async def on_member_join(member):
await client.get_channel(971319830064017458).send(f"{member.name} has joined", delete_after=30)```
not working, how to fix?
Sorry to bother you with this lol, I'll do some more thinking
You need members intents
pls be more specific. wdym
You need the members intents from the discord developers portal and you need to enable them in your code
!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.
Yup, a bit of a redundant oneliner, but sure
class Buttons(discord.ui.View):
def __init__(self, member, *, timeout=180):
super().__init__(timeout=timeout)
self.member = member
@discord.ui.button(label="0",style=discord.ButtonStyle.green)
async def gray_button(self,interaction:discord.Interaction,button:discord.ui.Button):
label = int(button.label)
label += 1
button.label = label
await interaction.response.edit_message(view = self)
@discord.ui.button(label="0",style=discord.ButtonStyle.red)
async def gray1_button(self,interaction:discord.Interaction,button:discord.ui.Button):
label = int(button.label)
label += 1
button.label = label
await interaction.response.edit_message(view = self)
#await self.member.kick(reason="Test")
@client.command()
async def button(ctx, member: discord.Member):
await ctx.send("This message has buttons!",view=Buttons(member))
Anybody know how i add a check to it that only the author can use the buttons?
@commands.command()
async def whomedia(self, ctx):
check_role = discord.utils.get(user.guild.roles, name='Media Perms')
for user in ctx.guild.users:
if check_role in user.roles:
await ctx.send(user.name)``` ```user is referenced before``` can someone tell me why this is happening?
@client.command()
async def whomedia(ctx):
check_role = discord.utils.get(ctx.guild.roles, name='Member')
for user in ctx.guild.members:
if check_role in user.roles:
that's not what I want
So what exactly do you want?
I'm trying to check if per user has media perms
Yes its the code
you're using a variable without referencing it
so it goes through each user, then check if it has media perms
i.e your variable isn't declare/doesn't exist
thanks
Then everyone in the server with the role gets listed
for example if it's a dict, just add user = dict() before
Ohhhhh
same question i need XD
still don't work
async def whomedia(user, self, ctx):
pass the variable to the function
ok ty
isnt it self, user, ctx?
so the function knows that user you're talking about
I would suggest you to send the output in one message
Because it will timeout your bot fast
Try this
doesn't work
i don't want any arguments
temporary = ""
for user in ctx.guild.members:
if check_role in user.roles:
temporary += user.name+"\n"
Yeah, include an interaction_check function
!d discord.ui.View.interaction_check
await interaction_check(interaction)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A callback that is called when an interaction happens within the view that checks whether the view should process item callbacks for the interaction.
This is useful to override if, for example, you want to ensure that the interaction author is a given user.
The default implementation of this returns `True`.
Note
If an exception occurs within the body then the check is considered a failure and [`on_error()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View.on_error "discord.ui.View.on_error") is called.
what does this do
It adds the names in a variable that you can send afterwards
so your bot doesn't send too many messages if you have many members with that permission
so it doesnt timeout
local variable 'user' referenced before assignment
@commands.command()
async def whomedia(ctx):
check_role = discord.utils.get(ctx.guild.roles, name='Media Perms')
temporary = ""
for user in ctx.guild.members:
if check_role in user.roles:
temporary += user.name+"\n"
await ctx.send(temporary)
Try this
There was no error for me
local variable 'user' referenced before assignment
How exactly i implement it i dont really understand that could you please explain if you dont bother?
you're using the variable user as it was an object. But the variable user does not exist.
here's a simple example:
def send_message():
print(message.user.id)
return
async def on_message(message):
send_message():
Did you used the code?
Override the interaction_check function, and return a boolean depending on if the author should be able to use it or not
yers
You might also wanna pass in the member object into the view
in my example, you're using message BEFORE it exists
i don't want an argument though
then put it inside the main function?
Ok so what should i use as member object
Interactions.user?
ctx.author, the person to run the command
Compare that with interaction.user, and return a boolean depending on that
@client.command()
async def button(ctx, member: discord.Member):
await ctx.send("This message has buttons!",view=Buttons(member))
Where exactly?
await ctx.send("This message has buttons!",view=Buttons(member), interaction_check=ctx.author)
No, override the function in the view
no, your whole code is already inside a function no?
oh nvm I got it
what is it please? I'm curious
async def myView(discord.ui.View):
def __init__(self, member: discord.Member, ...):
...
self.member = member
async def interaction_check(self, interaction: discord.Interaction):
# optionally add a message to people who can't use the interaction
if interaction.user != self.member:
await interaction.response.send_message("You can't use that :(")
return False
# The return is the most important part
return True
... # other view components here
@commands.command()
async def whomedia(self, ctx):
user = ctx.guild.members
check_role = discord.utils.get(user.guild.roles, name='Media Perms')
temporary = ""
for user in ctx.guild.members:
if check_role in user.roles:
temporary += user.name + "\n"
await ctx.send(temporary)```
@cerulean folio ^^
I solved my problem
But in a different way since I'm not using @command decorators :(
async def my_callback(interaction):
if interaction.user == interaction.user:
await interaction.response.edit_message(content="whatever", view = None)
data['15'] = 0
await select_game(data)
return True
@cerulean folio I sent the code
oh wait
ohhhh so your referenced it !
nice :D
it don't work
When command is run, it checks every user in the guild and returns the user names that have the rank (media perms)
Only the guy who i tag can use it
I need it to be used by author
Well you just need to pass in a member object, so the exact implementation shouldn't matter
Pass it in like you're already doing
Ok
it should be a field in __init__
So i gonna pass in ctx?
If you want to, but I'd only pass in the member object/id of the person who should be able to use the view
Okey thank you
no prob
@cerulean folio
class Buttons(discord.ui.View):
def __init__(self, author, member, *, timeout=180):
super().__init__(timeout=timeout)
self.member = member
async def interaction_check(self, interaction: discord.Interaction):
if interaction.user != self.author:
await interaction.response.send_message("You can't use that", ephemeral=True)
return False
return True
@discord.ui.button(label="0",style=discord.ButtonStyle.green)
async def gray_button(self,interaction:discord.Interaction,button:discord.ui.Button):
label = int(button.label)
label += 1
button.label = label
await interaction.response.edit_message(view = self)
@discord.ui.button(label="0",style=discord.ButtonStyle.red)
async def gray1_button(self,interaction:discord.Interaction,button:discord.ui.Button):
label = int(button.label)
label += 1
button.label = label
await interaction.response.edit_message(view = self)
#await self.member.kick(reason="Test")
@client.command()
async def button(ctx, member: discord.Member):
await ctx.send("This message has buttons!",view=Buttons(ctx.author, member))
So i passed it in like that but i get that error
Traceback (most recent call last):
File "C:\Users\lequi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ui\view.py", line 410, in _scheduled_task
allow = await self.interaction_check(interaction)
File "C:\Users\lequi\Desktop\Hint Bot\hinttest.py", line 28, in interaction_check
if interaction.user != self.author:
AttributeError: 'Buttons' object has no attribute 'author'
@commands.command()
async def whomedia(self, ctx):
users = ctx.guild.members
result = [x for x in users if discord.utils.get(x.guild.roles, name='Media Perms')
await ctx.send(result)
try this?
I already sent him a working command but it didn't work for him
Are you looking for users with a specific role or a specific permission? @scarlet aurora
sorry I edited it
Also may I put in we don't spoonfeed others in the future? thanks
what does that mean?
I think sending ready code
Yes, sending fully completed code without anything to support it
Okey
I won't do that again but I'd like to know why that rule is set please
Not really a rule, more of a courtesy
Because people need to learn
not just copy and pasting i guess
It's because spoonfeeding doesn't help anyone learn, and only serves to shut someone up (albeit temporarily)
They'll come back later with a similar question because there's no learning value in pressing CTRL+C and CTRL+V
Smart
What, copy pasting?
Right, not a hard rule, but again a courtesy I'd prefer we followed as it does everyone a favour in the long run
Well, I don't agree that it's always the case. Some people struggle for so much time, sending them the right answer sometimes helps not lose motivation to keep learning. Because some might just abandon.
Although I totally agree that most people just come for a ready to use code just to feel some achievement. Not a good way to teach indeed
I agree, very dependent on the person. It's too much effort to figure out if it's worth spoonfeeding someone or not, so in general we'd like to stay away from it
I mostly struggle too because lacks of knowledge (Might it be in Python or in English), And sometimes it helps me more to get some code that i can analyse for the next time
Im try me in python since now activly around 3 weeks and i understand much because people sent me code that i could analyse, But there are always new things that brings me into struggle (Like these buttons)
@commands.command()
async def whomedia(self, ctx): #defining the command to search users that have media perms
user = ctx.guild.members # storing all server members in 'user' variable
check_role = discord.utils.get(user.guild.roles, name='Media Perms') # here you're trying to send a list of users to be checked by a function that's supposed to check an individual user.
temporary = "" # declaring an empty string
for user in ctx.guild.members: # iterating through guild members (with a variable you defined above as all guild member which is kind of weird)
if check_role in user.roles: # checking if None is in user.roles (i think this is always True or always False)
temporary += user.name + "\n" concatenating your string
await ctx.send(temporary) #sending string
I would suggest that you do something like:
@commands.command()
async def whomedia(self, ctx): #defining function
users = ctx.guild.members # storing users in a var
result = list() # declaring result variable
for user in users: # iterating through users
if discord.utils.get(user.guild.roles, name='Media Perms'): # checking if role exists in user.guild.roles
result.append(user?name) # adding user name to list
await ctx.send('\n'.join(result)) # transforming list into string and sending it
In python there are "inline loops" that basically shortens code and makes it more readable.
Thus, this part of the code:
for user in users: # iterating through users
if discord.utils.get(user.guild.roles, name='Media Perms'): # checking if role exists in user.guild.roles
result.append(user) # adding user to list
could become:
result = [x for x in users if discord.utils.get(x.guild.roles, name='Media Perms')
indeed, i'll edit it
Is it fine now?
. Anybody an idea how i could fix it?
what are you trying to do?
Hi, how can I check if a role has the default colour?
I want to code a command that allows the bot to delete only roles with a custom colour
After u define self.member = member put self.author = author
or "List comprehension"
ur checking if the guild has that role, not the user.
I have a question here guys please.
So since I didn't learn with good sources, what I usually do is something like this:
@client.event
async def on_message(message):
prefix = message.content.split(' ')[0]
msg = ' '.join(message.content.split(' ')[1:])
if prefix == '!greet':
await message.channel.send(f'Hi <@{message.mentions[0]}> !\n
<@{message.author}> told you this:\n
`\n{msg}\n`)
client.run(token)
But now that I looked for a way to limit simultaneous command uses per user to 1, I've been told I should use bot decators.
Can someone send me a nice course/lesson/tutorial/video/guide about how should I reshape my bot?
All functions are ready and split in files, so what's remaining in my main.py is just the message parser with all the if statements to filters commands.
if discord.utils.get(user.guild.roles, name='Media Perms') in user.roles: ?
no i was talking about the list comp
Oh I don't know, I asked the dude to test it. Since I don't know the function I just explain what they generally has to do to fix it, so they can adapt with their knowledge 😊
Yeah commands u can use them like
@bot.command(name="greet")
async def greet(ctx):
await ctx.send("hello")
If u dont name the command in the Deco it will auto name with the func name
Oh also for my question:
what's the difference between client and bot
i.e between client.run(token) and bot.run(token)
oh rly? there's nothing more i should know it's that easy?? :o
Yes
ugh I been parsing all commands XD
and ur bot var be like
bot = commands.Bot(command_prefix="ur prefix")
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client"), This class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") and is automatically set upon instantiating the class.
async with x Asynchronously initialises the bot and automatically cleans up.
New in version 2.0.
alright...
thanks a lot !
I'll make the appropriate changes to all my code then
👍
Get familiar to commands then u can switch to cogs
So u don't need to put all ur code stuff in 1 file
So u can separate them
I mean...
I already did... XD
Oh cool
My previous main.py was like 1200 lines so... I ended up splitting it. It was a nightmare to reconnect everything 😭
especially importing stuff...
Haha lol
i'm still struggling with some parts
U are free to ask
thank you ! will do later
Hey, does anyone know to add permission lock to a command using hikari-lightbulb?
you mean a permission check?
Yea
Like only people with administrator permission can do the command
@lightbulb.add_checks(lightbulb.has_guild_permissions(hikari.Permissions.ADMINISTRATOR))
``` this should work
Ok! Thank you so much!
what is wrong?
when doing the command, the point doesn't type any text
well then, authrole is not in the roles of the invoker
did u run the bot?
I just dropped discord.client() to start using commands.Bot() and was wondering how to do client.fetch_user(arg) now
bot.fetch_user(id)
aw okie thank you !
an equivalent with ctx?
like does ctx.bot.fetch_user(arg) works?
No
alrightie
Yes
yes
arg should be an ID and you need to await this
yo sarth, does hikari have oop / decorator like button things, like dpy
An alternative component handler for hikari, inspired by discord.py's views.
ah nice
thank you !
So I read in dpy docs that client can be replaced by bot in nearly any circumstances... nearly XD
I just got this error:
msg = await ctx.wait_for('message', check=check)
AttributeError: 'Context' object has no attribute 'wait_for'
ohhhh
I'm stupid nevermind
Bot has everything that Client does
its a sublass of Client
yeah I apologize i put ctx instead of bot i'm just being stupid sometimes
async def buy_this(user, item_name, amount):
item_name = item_name.lower()
name_ = None
for item in mainshop:
name = item["name"].lower()
if name == item_name:
name_ = name
price = item["price"]
break
if name_ == None:
return [False, 1]
cost = price * amount
users = await get_bank_data()
bal = await update_bank(user)
if bal[0] < cost:
return [False, 2]
try:
index = 0
t = None
for thing in users[str(user.id)]["bag"]:
n = thing["item"]
if n == item_name:
old_amt = thing["amount"]
new_amt = old_amt + amount
users[str(user.id)]["bag"][index]["amount"] = new_amt
t = 1
break
index+=1
if t == None:
obj = {"item":item_name, "amount" : amount}
users[str(user.id)]["bag"].append(obj)
except:
obj = {"item":item_name, "amount" : amount}
users[str(user.id)]["bag"] = [obj]
with open("bank.json", "w") as f:
json.dump(users, f)
await update_bank(user, cost*-1, "wallet")
return [True, "Worked"]
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.Economy' raised an error: SyntaxError: invalid syntax (Economy.py, line 237)
looks like your indentation is super messed up
ok
uhhh why is the bot not responding to the cmnd. tht cog is loaded still it doesnot respond to the commands in tht cog
I have a little problem I can't identify in this bit of code:
async def other_callback(interaction):
async def show_proofs(arg):
embeds = list()
embeds.append(add_embed(arg, users))
for index, proof in enumerate(arg['proofs'].split(',')):
embeds.append(discord.Embed(color = arg['tag_color']))
embeds[index].set_image(url = proof, description=EMPTY)
return embeds
await interaction.response.edit_message(embeds=await show_proofs(arg), view=None)
return True
show_proofs.callback = other_callback
view = View()
view.add_item(show_proofs)
await message.channel.send(embed=add_embed(arg, users), view =view)
Here's the traceback:
await interaction.response.edit_message(embeds=await show_proofs(arg), view=None)
File "/interactions.py", line 791, in edit_message
await adapter.create_interaction_response(
File "/async_.py", line 219, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.1.description: This field is required
Someone came across this?
ur embed needs to have a description
How to send a cog help?
but, it used to work fine few minutes ago
it's confusing :o
you can make 25 apps per account. any way to increase it ?
Dunno make alts?
okay thx
is there a way for a bot to send a user to a specific channel, rather than just pinging them in said channel?
as with my bot it would be kinda convenient to be able to type x command to 'start game' and it takes u directly there, esp if you're in a server with alot of channels (like one of my main servers has :p)
oh
view = UpDownVoteView()
await ctx.send('yes', view=view)
await view.wait()
upv = view.up
downv = view.down```
(sorry for the late reply)
you can simply mention the channel since what you need is indirectly altering the client using a bot which isn't possible and never will be
alright, i wouldve sworn i had come across that before. alg
that isnt possible, the most you can do is, mention the channel
channel = Bot.get_channel(_id) or await fetch_channel(_id)
await ctx.send(f"Visit -> {channel.mention}")
so that it mentions a channel like so #discord-bots which users can click on and they're redirected to the channel (or join the channel if it is a voice channel)
yep
Hey, can anyone help me with editing the thumbnail of an embed
Whenever I edit the message with a new embed, the old image just gets detached from the embed
hi there, I'm using the <:name:id> format to use emojis in other servers but it just gives me this
and yeah I made sure it has the perms
how can i strip down a dict to just one of its keys when referencing it?
old image?
which image?
The initial thumbnail
I'm trying something with Message.add_files() and Message.remove_attachments()
if you are editing the thumbnail, the older one will get removed obviously
I got it working, except it's a little sluggish
Like the old image gets removed and then the new image gets edited in as an attachment and then it pops on to the embed
so you are using set_thumbnail or set_image (and yes all the attachments will be cleared up on edit if it contained previous attachments, that's how discord works)
I'm using set thumbnail
weird
i have
Knife = {name: 'Knife', category: 'dagger', cond: 'used', dmg: 3, value: 25}
in Items.py
class NewGameState:
def __init__(self):
self.Inventory_Start = ['Backpack', Items.Knife]
in my class, and
inv_string = ('__**Starter Gear**__', '\n'.join([f'- {obj}' for obj in state.Inventory_Start]))
in my inv check command
what i want to do is when i check the inv, only take the name attribute from the knife
Knife.get("name")
¯\_(ツ)_/¯
I know this is pretty basic but I made a discord bot that scrapes images from the web. I’m pretty proud of it.
Would be better if you made an Item class with a Dunder str that returns the name and subclass it for other items or such
not sure what u mean there
checkthe channels perms for external emojis perm too
thanks for the suggestion, figured it out
Do you know how to use classes?
aight, nothing better
Ok ignore me then
lmaooo
but why use classes if you don't know how to use them.....
there are alternatives....(which are messier ofc)
buy the hacker plan, and nobody would steal the code, you know many big bots are open-sourced ¯\_(ツ)_/¯
So I have member: discord.Member
How do I get the member’s id and name?
property name```
Equivalent to [`User.name`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.name "discord.User.name")
search the docs instead
should use a vps over than horrible plan
"I wanna host discord bot on replit"
so I provided the most straight-forward answer, not my fault
create a license?
atleast show him the right/good/better path
okay god
not really
depends on which vps and plans you buy and the vps's specs
max 10$ dollars i would pay for
see the pins
the thing is im not tryin to only get one name, i want to be able to have a bunch of items that are later added to inv have the same thing done to them when i use the inv command. ie, i need a way of filtering out only the name for any item under one of my 'inv' categories
10 dollars aint much though, so I take my words back
10 bucks a month max for me tbh
no
under powered machines
(copied from dpy)
-
Bots are not what the platform is designed for. Heroku is designed to provide web servers (like Django, Flask, etc). This is why they give you a domain name and open a port on their local emulator.
-
Heroku's environment is heavily containerized, making it significantly underpowered for a standard use case.
-
Heroku's environment is volatile. In order to handle the insane amount of users trying to use it for their own applications, Heroku will dispose your environment every time your application dies unless you pay.
-
Heroku has minimal system dependency control. If any of your Python requirements need C bindings (such as PyNaCl binding to libsodium, or lxml binding to libxml), they are unlikely to function properly, if at all, in a native environment. As such, you often need to resort to adding third-party buildpacks to facilitate otherwise normal CPython extension functionality. (This is the reason why voice doesn't work natively on heroku.)
-
Heroku only offers a limited amount of time on their free programme for your applications. If you exceed this limit, which you probably will, they'll shut down your application until your free credit resets.
😔 imagine having volatile storage
Possible to do like
If the user uses ,daily today he gets 1500
If he uses ,daily tomorrow again he gets 3000
In simple words increasing 500 coins per ,daily
But if the user fails to use it for the next day reset the amount
yes it is possible, use a db with a task
hello..is there a way i can make my bot read commands from a webhook? Thanks
and ik we can do something with on_message, but i want to incorporate it with discord.ext commands
Are webhooks able to read messages? I thought they could only send
Send only yea
Check if message has .webhook_id to determine is a message is webhook, then just read message.content
Oh read commands from a webhook as in read commands... From a webhook
How to make embed image none?
embed.set_image(url=None)
why is it comming like this
i'd like to buy bathwater
@commands.command()
async def shop(self,ctx):
em = discord.Embed(title=f"Shop Items",colour=0x2f3136)
for item in mainshop:
name = item["name"]
price = item["price"]
desc = item["description"]
em.add_field(
name=name,
value=f" :mw_reply: ` ${price} ` — {desc} ",inline=False)
em.set_footer(text='Page (0/1)')
await ctx.send(embed=em)
is it belle delphine's bath water
How to make the bot send the numbers likes this 25,000 rather than 25000?
print("25,000")
ez
💀 ** **
I wouldn’t ask if it was that easy
..
users[str(ctx.author.id)]["bank"]
``` for this ^
its output is 25000
not 25,000
uh
wait
k*
!e
print(f"{20000:,}")
@visual island :white_check_mark: Your eval job has completed with return code 0.
20,000
Damn
how do i use it here tho?
👀 👏
Lmao same
It works on f-string and string formatting only
yes, if it's inside f-string expression, otherwise it won't
it's fine, thank you
Traceback (most recent call last):
File "C:\Users\DEBARKA NASKAR\Desktop\Dank Frost\main.py", line 19, in <module>
class HighLowView(discord.ui.View):
File "C:\Users\DEBARKA NASKAR\Desktop\Dank Frost\main.py", line 61, in HighLowView
async def Lower(self, interaction, button):
TypeError: 'Button' object is not callable```
why am i getting this error
code?
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.
discord.ui.Button to discord.ui.button
ohh yes
only self, interaction
also what's the global for?
hello... tried this code here, but getting this error. any idea what have i done wrong?
the error quite says it all you need a colon
well in this screenshot you have the bot's token, so you better reset your token
and he needs to pass the token as a string lol
Traceback (most recent call last):
File "C:\Users\DEBARKA NASKAR\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 200, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\DEBARKA NASKAR\Desktop\Dank Frost\main.py", line 82, in highlow
users = await get_bank_data()
File "C:\Users\DEBARKA NASKAR\Desktop\Dank Frost\main.py", line 106, in get_bank_data
user = json.load(f)
File "C:\Users\DEBARKA NASKAR\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 293, in load
return loads(fp.read(),
File "C:\Users\DEBARKA NASKAR\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "C:\Users\DEBARKA NASKAR\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\DEBARKA NASKAR\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\DEBARKA NASKAR\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1330, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\DEBARKA NASKAR\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 995, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\DEBARKA NASKAR\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 209, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: JSONDecodeError: Expecting value: line 1 column 1 (char 0)
why am i getting this
ye lol in the client discord is all caps
just why
yup theres many erros lol
firstly add a colon at line 12, and secondly, indents are important in python, so fix that
what
no
not about you...
somebody asked a question and deleted it wtf 😭
ash
have you tried rust?
Traceback (most recent call last):
File "C:\Users\DEBARKA NASKAR\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 200, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\DEBARKA NASKAR\Desktop\Dank Frost\main.py", line 82, in highlow
users = await get_bank_data()
File "C:\Users\DEBARKA NASKAR\Desktop\Dank Frost\main.py", line 106, in get_bank_data
user = json.load(f)
File "C:\Users\DEBARKA NASKAR\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 293, in load
return loads(fp.read(),
File "C:\Users\DEBARKA NASKAR\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "C:\Users\DEBARKA NASKAR\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\DEBARKA NASKAR\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\DEBARKA NASKAR\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1330, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\DEBARKA NASKAR\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 995, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\DEBARKA NASKAR\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 209, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: JSONDecodeError: Expecting value: line 1 column 1 (char 0)
why am i getting this
what is f?
wut
in line 106
async def get_bank_data():
with open("bank.json", "r") as f:
user = json.load(f)
return user
dis
well iirc the error raises when it tries to load invalid json
!e
import json
json.loads('')
@slate swan :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | File "/usr/local/lib/python3.10/json/__init__.py", line 346, in loads
004 | return _default_decoder.decode(s)
005 | File "/usr/local/lib/python3.10/json/decoder.py", line 337, in decode
006 | obj, end = self.raw_decode(s, idx=_w(s, 0).end())
007 | File "/usr/local/lib/python3.10/json/decoder.py", line 355, in raw_decode
008 | raise JSONDecodeError("Expecting value", s, err.value) from None
009 | json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
yep
oh k
async def create_account(user):
users = await get_bank_data()
if str(user.id) in users:
return False
else:
users[str(user.id)] = {}
users[str(user.id)]["wallet"] = 150000
users[str(user.id)]["bank"] = 0
return True
async def get_bank_data():
with open("bank.json", "r") as f:
user = json.load(f)
return user
i have this tho
hi, how can i make that teh bot reply to the user’s message where he call 5he command?
!d discord.ext.commands.Context.reply
await reply(content=None, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A shortcut method to [`send()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.send "discord.ext.commands.Context.send") to reply to the [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") referenced by this context.
For interaction based contexts, this is the same as [`send()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.send "discord.ext.commands.Context.send").
New in version 1.6.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") or [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.10)") instead of `InvalidArgument`.
and how can i made it that the bot send an embed?
content=embed=embed doesn’t work
just embed=embed
Ok
you've tried bf?
How can i make that the bot add an emoji to his message and if the user clicks it it delets the message? I can’t find it in the docs
!d discord.Message.add_reaction
await add_reaction(emoji, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Adds a reaction to the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji").
You must have the [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission to use this. If nobody else has reacted to the message using this emoji, the [`add_reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") permission is required.
Changed in version 2.0: `emoji` parameter is now positional-only.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") instead of `InvalidArgument`.
!d discord.Message.delete
await delete(*, delay=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the message.
Your own messages could be deleted without any proper permissions. However to delete other people’s messages, you need the [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission.
Changed in version 1.1: Added the new `delay` keyword-only parameter.
Users getting 150k for free :
just for starting xD
too many people have this
sql dbs are ezier than json
SQL is closer to english than... dictionaries.
INSERT INTO users VALUES ('sz_skill', 'password123'); looks better than db["users"].append(["sz_skill", "password123"])
if you have a mechanism to give someone money then that's pretty fucked
admin abooz
i meant people could make alts and give their main money
async def mute(ctx):
if ctx.author.guild_permissions.administrator == True:
mute = ctx.guild.get_role (985475444981764106)
await ctx.add_roles(mute)
await ctx.send(f"{ctx.user.name} has been muted.")
else:
await ctx.send("you are not adminstrator, noob")
``` why isnt this working ? it doesnt give an error
???
do you have an on_message or on_command_error event?
yes
can you show
ok wait
async def on_message(message):
if message.author == bot.user:
return
if message.channel.id == 987651665492586568 and message.content.lower() != "!verify":
await message.delete()
await message.channel.send(f'{message.author.mention}please only write !verify and not something other', delete_after=3)
else:
await bot.process_commands(message)```
remove the await bot.process thing and change .event to .listen()
no all my other commands work, its not bot event problem its my code problem @slate swan
pls ping me if you answer cuz i wont see it if you dont
Hey can u help me make a slash command in dpy v2.0 with these things
ctx.add_roles?
hm?
you can't add a role to a Context
you can add a role to a Member
ctx.user is also not a thing iirc
do you mean
!mute <ping someone>
and the pinged person is muted?
so like instead of ctx i would need to add member?
you want to take a Member as an argument
oh ok ty
like this
async def mute(ctx, member):
then you can use
await member.add_roles(mute)
async def mute(ctx,member):
if member.author.guild_permissions.administrator == True:
mute = member.guild.get_role (985475444981764106)
await member.add_roles(mute)
await ctx.send(f"{ctx.user.name} has been muted.")
else:
await ctx.send("you are not adminstrator, noob", delete_after=3)``` like this right?
it's good
thanks
but you might wanna send that the member was muted
not the person who used the command
huh?
async def mute(ctx,member):
if member.author.guild_permissions.administrator == True:
mute = member.guild.get_role (985475444981764106)
await member.add_roles(mute)
await ctx.send(f"{member.name} has been muted.")
else:
await ctx.send("you are not adminstrator, noob", delete_after=3)
```like this?
you still have to use if ctx.author.guild_permissions.administrator == True:
oh okay
ctx.author is the person who used the command
okay
member is the person who you pinged
thanks
async def mute(ctx,member):
if ctx.author.guild_permissions.administrator == True:
mute = member.guild.get_role (985475444981764106)
await member.add_roles(mute)
await ctx.send(f"{member.name} has been muted.")
else:
await ctx.send("you are not adminstrator, noob", delete_after=3)
``` it still doesnt work? no error in console? like nothing happens @heady sluice
no, what is that?
no there is no error?
!intents might just answer like this
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.
yes i do
the on_command_error event catches errors for you, and if used wrong, it just makes the errors not show
oh
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
await ctx.send("**Invalid command. Try using** `help` **to figure out commands!**")
elif isinstance(error, commands.MissingRequiredArgument):
await ctx.send('**Please pass in all requirements.**')
elif isinstance(error, commands.MissingPermissions):
await ctx.send("**You dont have all the requirements or permissions for using this command :angry:**")
this is an example of a bad error handler
cuz it's missing else: raise error
oh ok
do you have smth like this
no
damn it moment
like where is the problem?
do other commands work
can you show another command
I have the same code

like what do you mean just a random command of mine?
yes
async def userinfo(ctx,member: nextcord.Member = None):
if member is None:
member = ctx.author
embedVar = nextcord.Embed(title="Information", description="Shows information of the user", color=0x00ff00)
embedVar.add_field(name=f"{member.name}", value=f"{member.discriminator}", inline=False)
embedVar.set_thumbnail(url=f"{member.avatar}")
#embedVar.add_field(name=f"{member.joined_at}"),value=f"{"%b %d,%Y, %T"}", inline=False)
embedVar.add_field(name=f"{'Discord account creation date'}", value=f'{member.created_at.strftime("%d %b %Y %H:%M")}', inline=False)
await ctx.send(embed=embedVar)
can you maybe just tell me the problem or do you dont know it either?
absolutely no idea
damn
Why not use @commands.has_permissions(administrator=True)
And have
@mute.error
. . .
```?
more complicated
idk
Don’t mind me, I use it for cooldown errors
yeah there's no other option for that
but please tell me you use a global error handler
what

oh ok
But try this
If it works
I need help someone
Making a slash command
@swift pumice
what?
“If it works”
.
idk
try it
ok
I cant figure out how to make a command like this "!image <Image.png>"
what's this?
So when i do like !image meme.png it will send the image from my ./image folder
ok
Hey can u help me make something quick ?
@swift pumice wait
Wait wait
I wanna kms
@client.command()
async def mute(ctx,member: discord.Member):
if member.guild_permissions.administrator == True:
mute = member.guild.get_role(988041989406740551)
await member.add_roles(mute)
await ctx.send(f"{member.name} has been muted.")
else:
await ctx.send("you are not adminstrator, noob", delete_after=3)
``` try this ^
change the role id btw
@swift pumice
thanks

Did nothing rather than removing author from if member.author.guild. . .
thanksss it works now :)))
np
Why wont this work?
@client.event
async def on_message(msg):
channel = msg.channel
if msg.content == ('!image ', image):
await channel.send(file=discord.File('./images/'+image))
Pretty new to Python :/
Wut?
to me the only logical thing would be if msg.content.startswith("!image") and msg.content.split(" ")[1]:
well no cuz he doesn't know what it could be
maybe he has a list of what the options are
.
I suppose the image folder has images, so he might wanna check the names of the images and check if msg.content.split(" ")[1] is one of those names
Exactly
I hate the fact you don't use commands PurpleSkull
why not use commands instead of an on_message event
Doesn't want to work, or i might just imported it wrong :/
there's also the option someone just writes !image and doesn't get a response
And after that?
await channel.send(file=discord.File('./images/'+image))
or am i just stupid
probably stupid
image is not defined, is it?
No, should be defined as "None" or what?
it should be the name of the image file...^ @cloud cairn


