#discord-bots
1 messages · Page 180 of 1
@shut elk so in your subclass add an attribute user_id and check if the interaction author's ID is the same
class MyView(discord.ui.View):
def __init__(self, user_id: int):
super().__init__(...)
self.user_id = user_id
async def interaction_check(self, interaction: discord.Interaction) -> bool:
if interaction.user.id == self.user.id:
return True
await interaction.response.send_message("This button is not for you", ephemeral=True)
return False
oh 🤦♂️
im dumb sorry thanks 😭
import discord
from discord.ext import commands
from snipes3 import scrape_snipes
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='?', intents=intents, help_command=None)
@bot.command()
async def snipes(ctx, *args):
# Delete command message
# Validate args
if len(args) < 1:
msg = await ctx.send("Invalid arguments. Please use the following format: `snipes <ID>`")
await asyncio.sleep(5)
await msg.delete()
return
msg1 = await ctx.send("Scraping stock...")
# Scrape stock
sku = args[0]
embed = scrape_snipes(SKU=sku)
if embed != None:
await msg1.edit(content="", embed=embed)
else:
msg = await msg1.edit(content="An error occured. Please try again later.")
# Sleep for 5 seconds and delete message
await asyncio.sleep(5)
await msg.delete()
bot.run``` so i have two files snipes3.py and this in my snipes3.py file i have a input where you put the product id you need to scrape but if i use the command my bot is not passing it to my function why ?
hold up, if there is gonna be a parameter added user_id, then that means it would require a parameter when doing the view thing... That means I can only do interaction id for the user before that, not the first one that clicked right
or am i missing something
It is the ID of the user that is supposed to press that button
it gives an error because I do view = myView() for example
it says error for the user_id not being provided
so like am i supposed to do myView(id) but that only does the previous one that creates the button
You can do logic you need by yourself
I don't quite understand who's supposed to press that button
Ok, so the person who presses the button, the user_id parameter should be that
but right now, it gives an error of positional arguments not being given since there is an extra parameter, so how is that going to be the user_id of the person who presses the button, if you have to provide the parameter when creating the button
I have a command that creates the button and uses the view, using view = myView(), and in the button function, if I click a button it should create another one
Because it's the ID of user who is supposed to press the button, the user who actually presses the button is in interaction_check()
yeah, but I want to check if the person who presses the button is the first person that presses the button and if you are not, then return the call
there is no one that is supposed to press the button, anyone can
A wait I misunderstood your question
ok
!d discord.ui.View.stop just this
stop()```
Stops listening to interaction events from this view.
This operation cannot be undone.
?
async def some_button_callback(self, ...):
self.stop()
... # do callback```
mk
i did it, but it still allows others
hold up
wrong testing channel
You said "anyone can press the button"
yeah, it works thank u so much
i tested the wrong channel
Hello,I'm trying to import a Button class from my bot to another file function (it's not cog file),I need to load it somehow before I import it?
huh no?
why do people ask this question so much
I've see the same one for like 4 times in this channel
tho it doesn't make sense
how to make more than one response as ephemeral
the same message have to be ephemeral for more than one member
which library
ephemeral messages are invisible for everyone except for the interaction author
you cannot control it
check pins in this channel, 3rd message
but this message is visible for 2 members now
if you'll send in channel it won't be ephemeral
only responses can be ephemeral
so how the picture's bot does it ?
it should be visible only to you
if someone else is seeing it they did the same thing as you did
no it's a vote message , which is visible to a team
which one? the 1st 2nd or 3rd message
the third
what do you think the message means by "Only you can see this" below the buttons
irdk
noone other than you can see that
the other uses probably used the same cmd as you...
okay , can i ask another question
ofcourse
is it possible to 'response' many times to the same interaction ?
you can use follups
*followups
cool
!d discord.Interaction.followup
Returns the follow up webhook for follow up interactions.
i know thank you
how to delete the first followup used by the interaction ?
delete_original_response ?
i guess, im not too familiar with discord.py interaction system
:/
is there a way to use command buy_q ? I tried this and didnt work
from .buy import buy_q is init.py file
hello i need help please
i cant import app_commands
@bot.command() async def on_guild_channel_create(channel): # Code.. if not u != guild.owner and not u.id in wl_list: await print("PM-Beta: (Анти краш)Создание каналов") await channel.delete()
Bot ignores
somebody?
From where?
-
Show the file structure and what file you execute to start the program.
-
What file do you want to import?
-
Where are you importing from?
I think he showed all that
yes
So you are executing buy to run the program?
to run
So you didn't show nr1
?
Hey @slate swan!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
the command is good when i put into bot.py file bot when i import it doesnt show

Hence these questions, unfortunately I'm not a wizard and don't want to guess your file structure.
Right-
is it possible to supply more information to a discord button callback? i am trying to make a list of embeds and a button that will edit the embed to the next embed in the list
subclass view and override the init to provide extra arguments and attributes
ah, thanks
How can I make that this checkmark doesn't appear and you can use the same option twice?
Is it possible to take the distance of selected cities using aiohttp from the site?
iirc this is some weird limitation with select menus on desktop, they just dont let you select the same option twice, but on mobile you can
Hello guys is it normal that I have created a slash command and it prompt the user to enter a suit of number like 012345 but when i print my variable that I ask the user to fill. It do not show the 0
mhm
!e
int shit = 0125
print(shit)```
@potent spear :x: Your 3.11 eval job has completed with return code 1.
001 | File "<string>", line 1
002 | int shit = 0125
003 | ^
004 | SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers
you see?
@client.tree.command(name="math", description="math")
async def math(itr: discord.Interaction, pid: int):
print(pid)
pidss = str(0) + pid
print(pidss)
math_url = f".."
response = req.get(math_url)
product = response.json()
await itr.response.send_message(math_url)
well, the answer to your question is yes...
that's how python works...
why would you need that zero though
so how can i do to add A 0 the number the person is using
make it a string I guess
its for a request that I do, I didn't put the url
wym?
string shit = "0125"
an int with a leading 0 is not an octal number...
@potent spear I finally did that pid = format(pid, '08d') was easier tbh
that's one way
hey Im trying to chain together menu selections in a View()
this is the code
but I keep getting this error and not sure why
File "D:\repos\Scrimbot\env\lib\site-packages\discord\ui\view.py", line 425, in _scheduled_task
await item.callback(interaction)
File "D:\repos\Scrimbot\cogs\scrim.py", line 27, in cap_callback
await picks(self)
File "D:\repos\Scrimbot\cogs\scrim.py", line 62, in picks
message = await ctx.send("Select Picks", view=self.view)
File "D:\repos\Scrimbot\env\lib\site-packages\discord\ext\commands\context.py", line 842, in send
return await super().send(
File "D:\repos\Scrimbot\env\lib\site-packages\discord\abc.py", line 1522, in send
with handle_message_parameters(
File "D:\repos\Scrimbot\env\lib\site-packages\discord\http.py", line 187, in handle_message_parameters
payload['components'] = view.to_components()
File "D:\repos\Scrimbot\env\lib\site-packages\discord\ui\view.py", line 219, in to_components
children = [item.to_component_dict() for item in group]
File "D:\repos\Scrimbot\env\lib\site-packages\discord\ui\view.py", line 219, in <listcomp>
children = [item.to_component_dict() for item in group]
File "D:\repos\Scrimbot\env\lib\site-packages\discord\ui\select.py", line 214, in to_component_dict
return self._underlying.to_dict()
File "D:\repos\Scrimbot\env\lib\site-packages\discord\components.py", line 291, in to_dict
payload['options'] = [op.to_dict() for op in self.options]
TypeError: 'coroutine' object is not iterable```
k, thanks!
hi! someone can help me to fix this error?
you will need to check the code and ensure that the 'Button' object is being used correctly, and not being called as a function or method.
with the code i could be able to assist u better
@discord.ui.button with a lower-case b to create a new button object. Also your params should be self, interaction, button in that order I think.
replace the = with :
https://paste.pythondiscord.com/dimiguqeze
someone
Please help me with the error
main.py", line 14, in <module> from discord_slash import SlashCommand, SlashContext ModuleNotFoundError: No module named 'discord_slash'

Check that discord_slash module is installed or in the correct location for it to find it
can i dm you?
added
in discord.py how do i make so someone can only enter a certain range of numbers or only some certain strings as options for a command
you can use the ***commands.Check() *** decorator to check the input of a command and determine whether it meets certain conditions.
check that the input is a number within a certain range, you can use the isnumeric() method and check if it is within the range.
aight hanks
hey i mistakely add my test application on discord developer badge soo how i switch to my main bot
😢
going to the Discord Developer Portal, selecting the "Applications" section, and then selecting the test application. From there, you should be able to remove it from your developer badge. Once that is done, you can then add your main bot to the developer badge.
but there's a problem i deleted the test application too
from developer portal
you will need to create a new application for your main bot and add it to your developer badge in order to use it.
i alr have my main bot but when i use application command it show
and when i go to that link it say i already claimed my badge
then you should contact discord support for further help.
as that is out of my reach at that point
np ty for your suggestion
np

can someone help with my bot something is not working
(like dm me and I'll show you on stream the problem)
?
u legit just posted that someone will respond, why can't u just talk about it here
@open vapor
cuz my problem is weird but I'll try to explain it.
I did pip install discord but when I tried to run the program it did this
send your code in chat brother it helps me
ok
import bot
if name == 'main':
bot.run_discord_bot()
import discord
def run_discord_bot():
TOKEN = 'my token is here but i will not show it '
client = discord.Client()
@client.event
async def on_ready():
print(f'{client.user}is now running!')
client.run(TOKEN)
and there's another code that is not related
@blazing condor ?
import discord
def run_discord_bot():
TOKEN = 'my token is here but i will not show it '
client = discord.Client()
@client.event
async def on_ready():
print(f'{client.user}is now running!')
client.run(TOKEN)
if __name__ == '__main__':
run_discord_bot()
You put the if statement in the wrong place, used the wrong name in it, didn't import the module before calling the function, and didn't indent the last line properly.
File "C:\Users\hackt\Desktop\desktop\Exile\main.py", line 5, in <module>
from views.contact import Confirm
ModuleNotFoundError: No module named 'views.contact'; 'views' is not a package```
Help 🙂
@blazing condor
need to create a package named 'views' in the current working directory, and then create a module named 'contact.py' within the 'views' package.
from views.contact import Confirm
in the main.py file, you should use the following import statement to import the Confirm class you mentioned above
https://paste.pythondiscord.com/hifogicoyo
This is a button view that I call using a command, but when I call the button, I want it so that only one person can press the button at a time. Although I am making the button disabled, it loads too slow and allows time for multiple people to press the button and enter the code. I am wondering how I can prevent this from happening, since I cannot really do anything with the init, and everything has to be done within this button function. I tried 3 ways: button disable, self.stop(), and using the list append checking if the interaction user id was the first in the list. However, all these methods failed to work and still, multiple people are able to press the button at the same time. Please let me know (with a ping) how I can potentially fix this problem, thanks!
need to embed an emoji in a response message (pycord), given the emoji name
how 2.
File "C:\Users\hackt\Desktop\desktop\Exile\main.py", line 5, in <module>
from views.contact import Confirm
ModuleNotFoundError: No module named 'views.contact'; 'views' is not a package```
Help 🙂
What's that supposed to be?
How to show emotions for robots:
Custom emotes are represented internally in the following format:
<:name:id>
Where the name is the name of the custom emote, and the ID is the id of the custom emote.
For example,:python3:is the name:id for :python3:
When sending standard unicode/discord emojis, you just send the unicode character. This is handled differently from language to language, but in python, you can send \N{NAME}, the codepoint, \uFFFF, or just the unicode char itself: 🇦 You can get info on this by using the ?charinfo command
You can quickly obtain the <:name:id> format by putting a backslash in front of the custom emoji when you put it in your client.
Example: \:python3: would give you the <:name:id> format.
When adding reactions, you can either send the unicode for standard emojis, or send name:id, not <:name:id> for custom emojis.
New in 1.1.0 You can use <:name:id>
Animated emojis are the same as above but have an a before the name- ie: <a:name:id>
ah, need an a
makes sense why it didn't work
danke
anyone got a good discord bot tutorial that explains everything?
voted_users = set()
vote_count = {"Astro": 0}
@bot.tree.command(name="poll", description="Poll")
@app_commands.describe(vote='Your vote')
async def vote(interaction: discord.Interaction, vote: Literal['Duwap', 'Astro']):
if vote == "Astro":
if interaction.message.author.id in voted_users:
await interaction.response.send_message("You have already voted")
return
astroID = '@eager hill'
voted_users.add(interaction.message.author.id)
vote_count["Astro"] += 1
await interaction.response.send_message(f'You voted for Astro! Total votes for Astro: {vote_count["Astro"]}')
I am recieving the error py discord.app_commands.errors.CommandInvokeError: Command 'poll' raised an exception: AttributeError: 'NoneType' object has no attribute 'author'
anyone know why and how can i fix it?
!d discord.Interaction.user
The user or member that sent the interaction.
Why
discord.py already has tasks extension
!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").
how would i stop this loop
like what if i only wanted it to schedule once
so i've this function here:
@commands.hybrid_command(brief="Mock the bot's creator.")
async def birb(self, ctx: commands.Context, stuff: str = "1 + 1 = 3"):
"""Mock the bot's creator."""
a_id = ctx.message.author.id
img = Image.open("resources/img/birb_logic.png")
draw = ImageDraw.Draw(img)
font = ImageFont.truetype("resources/fonts/whitneysemibold.ttf", 12)
draw.text((64, 28), stuff, (200, 200, 200), font=font)
img.save(f"resources/img/{a_id}.png")
await ctx.send(file=discord.File(f"resources/img/{a_id}.png"))
os.remove(f"resources/img/{a_id}.png")
```and right now the problem is at the end, with `os.remove`
windows is telling me it's used by another process whenever i try to call the command
but idk what process could be using it?
!d discord.ext.tasks.Loop.stop
stop()```
Gracefully stops the task from running.
Unlike [`cancel()`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop.cancel "discord.ext.tasks.Loop.cancel"), this allows the task to finish its current iteration before gracefully exiting.
Note
If the internal function raises an error that can be handled before finishing then it will retry until it succeeds.
If this is undesirable, either remove the error handling before stopping via [`clear_exception_types()`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop.clear_exception_types "discord.ext.tasks.Loop.clear_exception_types") or use [`cancel()`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop.cancel "discord.ext.tasks.Loop.cancel") instead.
Changed in version 2.0: Calling this method in [`before_loop()`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop.before_loop "discord.ext.tasks.Loop.before_loop") will stop the loop before the initial iteration is run...
Requires minimum effort of research
You can save the edited image as io.BytesIO buffer so you don't have to save it as file btw
could you elaborate?
Since the discord.File's fp argument can be a bytes-like object, you can use something like io.BytesIO buffer to create an instance from it.
# assuming that you've already edited the image
buffer = io.BytesIO()
image.save(buffer, format="PNG") # save/write the image data to the buffer
buffer.seek(0)
file = discord.File(fp=buffer, filename="out.png") # use the buffer to create a file instance
await ctx.send(file=file)
uh
what does buffer.seek(0) do?
and should i preferably use with, given that it's a file context?
@naive briar
Change the bytes stream position; after the image was saved, the stream position is changed to the end of the bytes that were saved or written, and you need to seek back to the start of the buffer to read the data that was saved or written.
!e
import io
buffer = io.BytesIO()
buffer.write(b"Cat")
buffer.write(b"Meow")
print(buffer.read()) # <-- returns "None"
buffer.seek(0) # seek back to the beginning
print(buffer.read())
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | b''
002 | b'CatMeow'
ok
oh wait nvm i didnt import tasks 💀
You can if you want to make sure that the buffer will be closed
But I think Python will get rid of it after it's used anyway
Hi, sorry to bother you again but even without stop, this loop didn't even loop
is there a specific reason why it didnt loop through
What are you even trying to do with it
so i have a button that sends when the view is called as per usual
and I want to make it so when 10 seconds of the button being sent out, the code will execute and the button will be disabled
after 10 seconds, for this to execute
coroutine asyncio.sleep(delay, result=None)```
Block for *delay* seconds.
If *result* is provided, it is returned to the caller when the coroutine completes.
`sleep()` always suspends the current task, allowing other tasks to run.
Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.
Example of coroutine displaying the current date every second for 5 seconds:
await asyncio.sleep(10), but it will run multiple times right
No
only once?
Like multiple button presses = multiple instances of asyncio sleep..
why does message.edit not have a file= argument and instead requires you to put stuff in a list
Probably API limitations
? If people press the button multiple times, will it not just do like that multiple times of asyncio sleep and repeat the code underneath it?
aight thx
also, i have this error where when multiple people click this button in the same time, it lets them do so and the code executes multiple times. I tried making some gateways for the function but it does not work somehow. How would I make this only run once and pressed once, by the first person that presses it?
iirc discord.py actually makes it so you can't close the file using file.close() and instead automatically closes it once the file is sent
class io.BytesIO(initial_bytes=b'')```
A binary stream using an in-memory bytes buffer. It inherits [`BufferedIOBase`](https://docs.python.org/3/library/io.html#io.BufferedIOBase "io.BufferedIOBase"). The buffer is discarded when the [`close()`](https://docs.python.org/3/library/io.html#io.IOBase.close "io.IOBase.close") method is called.
The optional argument *initial\_bytes* is a [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object) that contains initial data.
[`BytesIO`](https://docs.python.org/3/library/io.html#io.BytesIO "io.BytesIO") provides or overrides these methods in addition to those from [`BufferedIOBase`](https://docs.python.org/3/library/io.html#io.BufferedIOBase "io.BufferedIOBase") and [`IOBase`](https://docs.python.org/3/library/io.html#io.IOBase "io.IOBase"):
I'm trying to make a website with a discord login using OAuth2. Everything works but when i print out the user id of the user on my flask website it is different from my actual id. Does somebody know why
Could it be your bot's ID?
ok turns out it was some sort of rounding error. I have a flask program and i tried to send in the id with this: flask.rendertemplate("htmlfile", id={{user_id}})
turns out in my html file i hda to do this:
var userId = {{ id |tojson|safe}};
the "tojson|safe" part makes it round safely
the good ol piping
hi, who can help me with my bot code? i have a problem with discord.py
Just ask about your problem
Might anybody know if discord.py dispatches on_guild_join for the initial connection?
I know discord sends out all of your guilds in a massive GUILD_CREATE payload
Not sure if discord.py counts that as "on_guild_join"
Initial connection no, I think you might be thinking of some mixture between initial connection and establishing connection, but what discord.py does is creates a bunch of futures, chunks using that future then gives it a result, after all guilds are chunked (this can be skipped via an option) it'll dispatch
READY => on_connect
finished chunking => on_ready
Gotcha. So on_guild_join is not dispatched before on_ready?
Then for each future it'll dispatch on_guild_join per each guild that is AVAILABLE
Since guilds can be un-available as well which yields another diff event
And which is that?
Yea, it'll go ```
1). HELLO
2). IDENTIFY + HEARTBEAT
3). DISPATCH(GUILD_CREATE)
4). on_guild_join this is discord.py's own event not the APIs
holdon
Ah, on_guild_join being discord.py's own event explains all of it haha
Should be GUILD_DELETE
It get's confusing sometimes because discord.py adds it's own events
And probably the main example would be READY
READY (DISCORD API) => `on_connect` (DISCORD.PY)
chunking guilds => `on_ready` (DISCORD.PY)
Yeah, I thought on_guild_join was one of Discord's events (GUILD_CREATE) but as you explained, it doesn't seem to be
Hello, I am making a streak tracker. How can I scheduled messages?
Let's say I want the bot to send me the message at 9 pm
!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").
Well, that's loop
It will work tho
but... it won't have the same functionality as a message schedule
Wait, there's time
My bad, Thanks! @naive briar
Yes it's a 2.0 feature
Pass in a datetime object
It'll be ran at that time every day
Right
Hello!
I am trying to make a command in my bot that if 1 role is present it runs the function or if another role is present it does it, but if not, return an error
How would I do something like that?
And I want to be able to get the roles via there ids
To create buttons I used discord.ui
Is there any official library?
i should read the docs
If anyone can tell that'd be great (i dont have to read docs...)
discord.ui is part of the official lib
Ah
discord.py has the ui package inbuilt in itself
the library you used earlier was just a copy of it
Misinformation from CHATGPT
The discord.ui is not a module of the discord.py library and it is not an official package.
chatgpt isn't always necessarily right, its just an AI afterall lol
!d discord.ui.View it exists in dpy
class discord.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
yeah
I am messing with it
tho it is useful
👍
in most cases, yes
converting my py code to rust...
tho for discord.py you'll always get wrong/bad answers
Not always
Quite often
That's just outdated info, chatGPT is trained on old data, discord.ui didn't exist as a part of dpy that time probably
True
Hello!
I am trying to make a command in my bot that if 1 role is present it runs the function or if another role is present it does it, but if not, return an error
How would I do something like that?
And I want to be able to get the roles via there ids
!d discord.ext.commands.has_any_role
@discord.ext.commands.has_any_role(*items)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has **any** of the roles specified. This means that if they have one out of the three roles specified, then this check will return `True`.
Similar to [`has_role()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.has_role "discord.ext.commands.has_role"), the names or IDs passed in must be exact.
This check raises one of two special exceptions, [`MissingAnyRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") if the user is missing all roles, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingAnyRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
use this check
i can do ?
stats = Stats.value(ctx)
await ctx.send(stats.area)
What
can i call it like that
No, it's not class method
I literally just explained like yesterday
Or at least not even 5 days ago
but i dont understand the class sub what thing
OOP moment
import asyncio
class J:
def __init__(self, var1, var2):
self.var1 = var1
self.var2 = var2
print(self.var1, self.var2, sep="\n")
@classmethod
async def new(cls):
# do some async things
var1 = await asyncio.sleep(0, result="Variable 1: Cat")
var2 = await asyncio.sleep(0, result="Variable 2: Meow")
return cls(var1=var1, var2=var2)
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
ins = loop.run_until_complete(J.new())
i just want to get the value of the thing
or are there some other better ways to get this done
i just want to import the whole chunk of variable one time instead of calling it one by one
the variable is in my database
!e ```py
class Stats:
def init(self, a):
self.a = a
def do_something(self):
return self.a+1
stats = Stats(1)
print(stats.do_something()) # will work
print(Stats.a) # will raise error
@slate swan :x: Your 3.11 eval job has completed with return code 1.
001 | 2
002 | Traceback (most recent call last):
003 | File "<string>", line 9, in <module>
004 | AttributeError: type object 'Stats' has no attribute 'a'
same goes for your your Stats class, you add the bot attribute when the class is initialised
so trying to use it will raise an error
hmm
but i cant async the init either
i dont even know how to search solution for this online 💀
you dont need a class if its just for returning a value
just use a simple async function
hmm ok
stats = funcname(ctx)
await ctx.send(stats.area)
You need to await the coroutine an async function returns
back to discord 101
Learn OOP
hmm ok
Has there been a poll done on if people prefer slash commands or prefix/traditional commands?
Prefix command >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Sl*sh command
how to fix this
AttributeError: module 'discord.ext.commands' has no attribute 'Cogs'
!d discord.ext.commands.Cog
class discord.ext.commands.Cog(*args, **kwargs)```
The base class that all cogs must inherit from.
A cog is a collection of commands, listeners, and optional state to help group commands together. More information on them can be found on the [Cogs](https://discordpy.readthedocs.io/en/latest/ext/commands/cogs.html#ext-commands-cogs) page.
When inheriting from this class, the options shown in [`CogMeta`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CogMeta "discord.ext.commands.CogMeta") are equally valid here.
I dunno
I have a 3 param command
ok
Slash command seems really convenient for that
@naive briar do you have a discord bot? You seem fairly active in this channel..
I'm just doing it for fun
i have a command with 4 parameter
dont ask about the if-else loop that works for that
rpm trade buy hydro a 123
Mine is complicated param
I want to email my monthly progress, is it possible to email using discord.py? If so, are there any cons?
!d email
Source code: Lib/email/__init__.py
The email package is a library for managing email messages. It is specifically not designed to do any sending of email messages to SMTP (RFC 2821), NNTP, or other servers; those are functions of modules such as smtplib and nntplib. The email package attempts to be as RFC-compliant as possible, supporting RFC 5322 and RFC 6532, as well as such MIME-related RFCs as RFC 2045, RFC 2046, RFC 2047, RFC 2183, and RFC 2231.
The overall structure of the email package can be divided into three major components, plus a fourth component that controls the behavior of the other components.
WAIT THERE IS???
Thank you
@app_commands.command(name = "imagine", description = "Generate an anime image!")
@app_commands.choices(quality=[
app_commands.Choice(name="low", value="fast"),
app_commands.Choice(name="medium", value="medium"),
app_commands.Choice(name="high", value="slow"),
])
async def imagine(self, interaction, prompt : str, negative_prompt : str, quality: app_commands.Choice[str]):
This is mine, the reason slash commands might be better for me is because prompt and negative prompt can be like “Sail boat, flying, sky”
💀
lemme show u mine
Amazing command
Ok XD
!paste
why
👀
I clicked into it
?
ahem
Good afternoon sir, I have a question sir, can anyone help me to guide me on making the auto aap game growtopia and create bots from bot discord sir
loop = asyncio.get_event_loop()
loop.run_in_executor(None, waifudiffuser.imagine, prompt, negative_prompt, ctx, loop, msg)
waifudiffuser 💀
(Quality isn’t used because image generation is computationally expensive and I can’t afford a host XD.)
What else am I supposed to call it? XD it is what it is
waifu diff user or waifu diffuser
whats an auto aap game
Diffusion -> diffuser something that diffuses something
So it diffuses waifus
XD
Want to see some of the horrible results and progress??
sure sure
horrible results are always good when u end up like me
name 'bot' is not defined
name 'bot' is not defined
name 'bot' is not defined
name 'bot' is not defined
growtopia game sir
auto verifikasi link baypass aap
It can do hands now which is good
wait
can u show me them without hands
but dm
they are going to go rage if u flood more
whoops
No, sir, I mean if it's for verification, the link automatically sent by the Growtopia devs, sir, and there's one that creates CID, it can be bolted from the Discord script, sir. Wait, I'll try a screenshot
Most action I've seen here in years.
How to display linked youtube video thumbnails in embeds?
why not just send the link and let it embed itself?
Bc for music bot and I want to display thumbnail instead of just sending the link. The link by itself doesn't show the thumbnail. Its purely aesthetic.
I figured it out anyway.
how i can import a view from file1 to file2 ?
from extensions.Dashboard import CopyDropDownView
ImportError: cannot import name 'CopyDropDownView' from 'extensions.Dashboard'
class DashboardDropdown(discord.ui.Select):
def __init__(self, emoji_list=list):
self.emoji_list = emoji_list
options = []
super().__init__(placeholder='Select Extension To Setup...',
min_values=1, max_values=1, options=options)
async def callback(self, interaction: discord.Interaction):
if self.values[0] == 'welcome_goodbye':
await WelcomeGoodByeDashboardEmbed(interaction=interaction,guild=interaction.guild)
class CopyDropDownView(discord.ui.View):
def __init__(self, emoji_list:list):
super().__init__(timeout=None)
self.emoji_list = emoji_list
self.add_item(DashboardDropdown(emoji_list=self.emoji_list)
Hi
Whats meaning of self bot in discord.py?
running user account as a bot
hey, wheenver i restart my bot i cant interact with the buttons
How to make buttons persistent?
its against TOS
@client.event
async def on_member_join(member):
channel = client.get.channel("1064291777072337026")
await channel.send("Hallo")
why is there no message when someone joins the server
Can modals have a description?
Any1 can make a code that runs on pc/vps that acts as a discord account not as a bot
What even is client.get.channel
!d discord.Client.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
What
how should I do that
```py
import dataclasses
@dataclasses.dataclass
class Getter:
bot: "Bot"
@property
def channel(self):
return self.bot.get_channel
bot.get = Getter(bot)
its get_channel, not get.channel
and the ID should be an integer
Ah ok
Sir this is Python.
channel = client.get_channel(1064291777072337026)
so? @slate swan
not the id,
without id?
it's the name of the argument, you don't type that out there lol
i mean that's how most of dpy is working 🗿 redirecting to another class's method
just replace the dot with _
ids should be provided as 1234,not "1234"
so now that is correct
async def snipes(ctx, *args):
if "staff" not in [role.name for role in ctx.author.roles]:
return````
is it wrong that way i only want that staff can use the role
yes
!d discord.ext.commands.has_role use a check
@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
If the message is invoked in a private message context then the check will return `False`.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
Ok ty
My bot has admin perms, how can I remove the messages?
of a channel
i dont want to recreate the channel
it will change the channel id and other bad stuff will happen
you can't get the channel id again, it's unique for each channel
ik
That's why im asking "how can i remove\delete messages"
A normal message?
ye...
ctx.message.delete()
like !clear 1000
@pastel basin
How many messages will it delete?
1
To delete 200 msgs, should I use a for loop?
for _ in range(201):
ctx.message.delete()
!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...
ty
.bookmark
Click the button to be sent your very own bookmark to [this message](#discord-bots message).
@slate swan I've tested it now and there's still no message when someone joins
you need member intents
!d discord.Intents.members
Whether guild member related events are enabled.
This corresponds to the following events...
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, 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
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
something like this, but you set members to true instead of message_content
intents.members = True
?
@slate swan
how do i get the banner and guild_avatar of the user
when i use {user.guild_avatar} it replies with none and {user.banner} returns with none
but if i use {user.guild_avatar.url} it says AttributeError: 'NoneType' object has no attribute 'url'
The user just don't have guild avatar 🤷
What's so confusing about it
Then they also don't have a banner
i do have banner and i used the cmd
!d discord.User.banner
property banner```
Returns the user’s banner asset, if available.
New in version 2.0.
Note
This information is only available via [`Client.fetch_user()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.fetch_user "discord.Client.fetch_user").
I have now managed that when someone joins the server, a message comes, but the commands no longer work can anyone help
Sure, I can.
do you need the code?
yeah, but not with ctx beacuse for some reason it doesnt work for me
If you use ctx then i cant help you
lets go to dms alright @slate swan ?
@slate swan Just dont send the token alright?
Where can i learn to code bots?
man how is you gonna do that
@app_commands.describe()
async def ea(interaction:discord.Interaction):
def check(reaction, user):
return user == interaction.user
await interaction.response.send_message('**Please react to this message with the emoji you want to add**', ephemeral=False)
the_reaction = await bot.wait_for('reaction_add', check=check)
await the_reaction[0].emoji.save(the_reaction[0].emoji.name+".png")
img = discord.File(the_reaction[0].emoji.name+".png")```
What's wrong with this code?
timestamp = member.joined_at.strftime("%b %d, %Y %H:%M")["timestamp"]
fmt_time = discord.utils.format_dt(timestamp, "f")
embed.add_field(name="Join Date:", value=f"{fmt_time}", inline=True)```
What's wrong with it then
please help
Send the whole error / code then
I can't see where in the code or error that is connected
Hey @slate swan!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
can u help
The bot doesn't respond. No error logs :/
This code isn't even where the error was raised
!d discord.Guild.create_custom_emoji
await create_custom_emoji(*, name, image, roles=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a custom [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji") for the guild.
There is currently a limit of 50 static and animated emojis respectively per guild, unless the guild has the `MORE_EMOJI` feature which extends the limit to 200.
You must have [`manage_emojis`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_emojis "discord.Permissions.manage_emojis") to do this.
it is
In line 97
how can i get a bytes object from an image so ?
File "C:\Users\user\Desktop\Other\Bots_For_Sell\cleevno\bot.py", line 97, in ea
await interaction.guild.create_custom_emoji(name=the_reaction[0].emoji.name,image=str(the_reaction[0].emoji.name)+".png")
Seems like it, huh?
It's literally in the error
ah i forgot the last line
to do a slash commands inside a cogs file i use @lavish micamands.command or @bot.tree.commands?
!d discord.app_commands.command
@discord.app_commands.command(*, name=..., description=..., nsfw=False, auto_locale_strings=True, extras=...)```
Creates an application command from a regular function.
With .command()
app is stll underlined
@app_commands.command()
ahh
mb
i have 2 ()
deleted them
still an error
What's the error then
@strange knoll.commands.command()
its not an error but underlined
it is an error
app.commands isnt definied
you can't use an object without importing it.
i have to import app_commands in the cog file too?
ofcourse, if you're using it
That's just how Python works
ye sorry i had forgotten lol
if i have 50 cogs file i have to import all of them here?
for all my cogs
Use for loops
should i store discord user id as string or int in my discord bot db, or does my question not have enough context
Integer, at least that's what I do
Why did you think about storing it as string anyway
the existing codebase stores uids as strings
Can someone tell me what's wrong with this code please?
@client.command(name = 'whois')
async def whois(ctx, member: discord.Member = None):
# Check if the command was used in the correct channel
if ctx.channel.id == 745832741135712386:
if member is None:
await ctx.send("Please provide a user.")
return
# Get the URL of the modnoted user's avatar
avatar_url = member.display_avatar.url
embed = discord.Embed(title=f"", description=f"", timestamp=datetime.datetime.now(), color=discord.Color.blue())
embed.set_author(name=f"{member.name}#{member.discriminator}", icon_url=avatar_url)
embed.add_field(name="User", value=member.mention, inline=True)
# Send the embed to the channel
await channel.send(embed=embed)```
we're gonna need some errors or smth
There is no errors
channel is not defined
And setup logging to log the errors
I'm trying to make a mute command, but I keep getting this error.
Traceback (most recent call last):
File "/home/runner/juicebotw/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 46, in mute
await member.add_roles(mutedRole, reason=reason)
File "/home/runner/juicebotw/venv/lib/python3.10/site-packages/discord/member.py", line 1018, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
File "/home/runner/juicebotw/venv/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
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/juicebotw/venv/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1349, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/juicebotw/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/home/runner/juicebotw/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
Your bot just don't have to permission to edit the roles of the target member
!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.
I have the roles set for him to have it.
And I have it aswell.
Ouch you are right
Nevermind, someone turned off that permission. Thank you.
Now it gives me this.
Traceback (most recent call last):
File "/home/runner/juicebotw/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 46, in mute
await member.add_roles(mutedRole, reason=reason)
File "/home/runner/juicebotw/venv/lib/python3.10/site-packages/discord/member.py", line 1018, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
File "/home/runner/juicebotw/venv/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
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/juicebotw/venv/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1349, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/juicebotw/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/home/runner/juicebotw/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
When command is run or on bot run?
"Permission issues"
Command.
I know, but the bot and I have every permission possible
It could be due to bot not refreshing commands
.*
Application commands from dev portal invite?
Is the bot's highest role is higher than the member's highest role?
It's a prefix command, everytime I make an application command it decides it wants to kill itself.
Ewww prefix command idk shi about prefix commands haven't used them in years
We rocking slash 💪
F**k.
I just realized that.
Changed now it's stil not working.
still*
Is the mute role still higher than the bot's highest role
Also Discord has timeout command built-in btw
I know.
!hastebin
!paste
This keeps popping up again when I run. https://paste.pythondiscord.com/maqufetire
Hi 👋 I'm trying to add a embed.set_thumbnail {image_url} but I keep getting a syntax error. Help pls
please paste your code
i try help you
Thanks, & here's a snippet embed.set_thumbnail(url={string}) I replace string with the image url, but I get a syntax error 🤔
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, 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
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
how do i do it for py cord
url or locale image?
Prob url 🤔
embed.set_thumbnail(url=ctx.author.avatar.url)
or
embed.set_thumbnail(url=https://......)
or
file = discord.File(choose_image, filename="image.gif")
embed.set_image(url="attachment://image.gif")
The second one thanks
work?
How do I make a slash command?
When I add the image url, I get syntax error.
Basic or advanced slash?
paste your error
Can't atm. It sends the whole embed command to the console saying "syntax error" under image url.
Either or.
give me a screen please
Prob easier on dm. My Internet is being 💩 😢
i cant help you dude ... try it later
On dm or?
Thanks 👍
HI, how to make something like @novel apex ?
Anyone have a base drop down menu code
@bot.event
async def on_webhook_create():
How do I remove a webhook?
@bot.command()
async def menu(ctx):
embed = discord.Embed(title="Select an option", description="1. Option 1\n2. Option 2", color=0x00ff00)
await ctx.send(embed=embed)
hey i have some problem in host bot with discloud
when i upload my codes in it it show
#Traceback (most recent call last):
D File "/home/user_974333490105552897/main.py", line 2, in <module>
* from discord import SlashCommandGroup
�ImportError: cannot import name 'SlashCommandGroup' from 'discord' (/usr/local/lib/python3.11/site-packages/discord/__init__.py)```
but it work in vs codes
thanks
How can I make this work?
timestamp = member.joined_at
fmt_time = timestamp.strftime(timestamp, "f")
embed.add_field(name="Joined Server", value=f"{fmt_time}", inline=True)```
The result should show a different time and date for each person based on their time zone
Who can help me to fix my code? Paying with nitro or PayPal… DM ME
This is not what I'm looking for. I want it to be displayed as this example <t:1673976900:f>
But instead of current time, use the time when the member actually joined the server
yes it show that
No
ohh lemme see
timestamp = member.joined_at.strftime('%d %B %Y %I:%M %p'))
embed.add_field(name="Joined Server", value=f"{timestamp}", inline=True)```
if a user dm’s the bot copy the message and author into a channel in the server
here now try
Still the same
async def on_webhook_create(message):
webhooks = await message.channel.webhooks()
for webhook in webhooks:
await webhook.delete()```
ignore
I want it to be showed as this
yes
ok
lemme change
timestamp = member.joined_at.strftime('%d %B %Y %I:%M %p'))
embed.add_field(name="Joined Server", value=f"{timestamp}", inline=True)```
try now
You just posted the exact same code
I don't need to try it, it's the exact same code.
Yes
nope i change the date & time format
wait lemme show you
I don't think you understand what I'm trying to do.
what is the problem please?
from liste_bjr import reponse_description
ModuleNotFoundError: No module named 'liste_bjr'
You want like this ?
No
I told you I want it to appear using this format
<t:1673979360:f>
like
month date , year time
lemme try in my bot & show you
see join & create in embed you want like this?
!d discord.utils.format_dt
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.11)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
@young dagger that’s what ur looking for
Yeah
😮
Do you know why its not working?
timestamp = member.joined_at
fmt_time = discord.utils.format_dt(timestamp, "f")
embed.add_field(name="Joined Server", value=f"{fmt_time}", inline=True)```
pass the style kwarg as f
instead of just f
Sorry but can you show me how I do that?
do you know what a kwarg is?
I mean how to pass the style kwarg as f
Well it does not
Because the bot doesn't response
Errors? What's the value that you're getting?
No errors
Did the bot respond before you added that line?
Yes
Then you have an error handler that's eating your errors
I think I was mixing up the codes.
i'm lost...
@mental hollow @fading marlin My second question. How can I use the same method for Account Created when timestamp = member.joined_at?
!d discord.User.created_at
property created_at```
Returns the user’s creation time in UTC.
This is when the user’s Discord account was created.
Yes, but timestamp is being used by member.joined_at
Right?
You can have multiple timestamps 🤷
^
Just call the variables different things
Should I rename them like timestamp2 etc? If not, how does the code know which timestamp to use?
The code doesn't
You do
just pass the timestamp object directly into your function
much easier
and you would know what timestamp is for what
How do I do that?
replace the timestamp variable with a datetime object directly instead?
dont create the variable in the first place
My code:
async def on_webhook_create(message):
webhooks = await message.channel.webhooks()
for webhook in webhooks:
w = await webhook.delete()
print(w)```
Error
Pls help
Which one?
Can you show me an example how it would look like? So I can get a better understanding please
Bot ignores event
What does it say in your console?
And does not remove the webhook
Bot ignores event
None
I’m not gonna spoon feed so here’s an example of what I mean
what your doing:
count = 10
new_number = count + 4
what you should do instead:
new_number = 10 + 4
the count variable isn’t needed when you can directly pass 10, apply this knowledge to ur own code
that’s not a valid event?
Doesn't seem like there's an event to detect webhook creates
link?
!d discord.on_integration_create
discord.on_integration_create(integration)```
Called when an integration is created.
This requires [`Intents.integrations`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.integrations "discord.Intents.integrations") to be enabled.
New in version 2.0.
So like this?
member_joined = member.joined_at + discord.utils.format_dt("f")
account_created = member.created_at + discord.utils.format_dt("f")
embed.add_field(name="Joined Server", value=f"{member_joined}", inline=True)
embed.add_field(name="Account Created", value=f"{account_created}", inline=True)```
Well it didn't work
do you know what variables are?
@mental hollow@slate swan@sick birch discord.AuditLogAction?
Yes
(
Yes
!rule 6 this is not allowed
How can I delete a newly created webhook
great, so when using discord.utils.format_dt, replace the timestamp variable with its actual value
Sorry I don't know how to do that
timestamp = member.joined_at
fmt_time = discord.utils.format_dt(timestamp, "f")
embed.add_field(name="Joined Server", value=f"{fmt_time}", inline=True)```
that was the code you provided us with
with what I said, you should pretty easily be able to do what you wanted
if you can’t, you clearly don’t know what variables are, and in that case, you should probably try to work on a smaller project before creating a discord bot, creating a discord bot is quite difficult / not straightforward and it would help you massively if you knew basic Python
I want to learn how to pass the timestamp object directly into the function, as you told me about
^ this tells you exactly how
member_joined = discord.utils.format_dt(member.joined_at, "f")
Thanks
perfect!
Makes sense
What's the f
Hey! What can be the problem here? The server id correct, 100%, but i only get "You don't have a license."
authorized_server_id = "id"
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$statsimportant'):
if message.guild.id == authorized_server_id:
await message.channel.send("Hello!")
else:
await message.channel.send("You don't have a license.")
The ID is a string
A string will never equal an integer
!e print("12345" == 12345)
@sick birch :white_check_mark: Your 3.11 eval job has completed with return code 0.
False
Might anyone know why my bot is instantly giving exit code 0 when I try to run it?
Not without code
love u
Code 0 is success
**Error:
TypeError: on_guild_channel_update() takes 0 positional arguments but 2 were given
My code:
async def on_guild_channel_update():
print("Text")```**
?
!d discord.on_guild_channel_update
discord.on_guild_channel_update(before, after)```
Called whenever a guild channel is updated. e.g. changed name, topic, permissions.
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
It takes before and after
Well yeah, but the bot itself is not coming online
Not made any major changes to the code recently.
async def main():
for filename in os.listdir(cogs_folderpath):
if filename.endswith('.py'):
await bot.load_extension(f'cogs.{filename[:-3]}')
await bot.start(TOKEN)
asyncio.run(main())
You know what, it's probably an issue with my Python or my IDE actually.
(edit: pycharm issue, works fine when I run it in terminal)
Hey!
first_server_id = "1043898005767598153"
second_server_id = "69"
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$statsimportant'):
if str(message.guild.id) == first_server_id:
await message.channel.send("statsimportant embed first")
if str(message.guild.id) == second_server_id:
await message.channel.send("statsimportant embed second")
else:
await message.channel.send("You don't have a license.")
When i try using the $statsimportant in the first server, then i got both "statsimportant embed first" and "You don't have a license." why is this?
async def on_guild_channel_update(before, after):
await after.edit(name=before.name)
Ignore
open cmd
okay
what next
@bot.command(name='hello')
async def _hello(ctx):
await ctx.send('Hello!')
This isn't working.
pip install discord
pip3 install discord?
Oh
No .py
No
would someone be kind enough to help me please?
Puthon install
Python -m pip install discord.py
how did you install python?
!d python -m
Python Runtime Services
The modules described in this chapter provide a wide range of services related to the Python interpreter and its interaction with its environment. Here’s an overview:
trough web
You don't got python installed
Did you run file or just install
You must run the file that you installed from python website
I opened a topic in the forum
https://discord.com/channels/267624335836053506/1064978704050171965
if you dont tick the option to add python to path, python and pip wont be usable in the command line, but on windows you're given the py launcher by default which works as an alternative
i have it downloaded and i runned it
assuming the web installer included the python launcher, you would run py -m pip install discord.py
but the topic is closed... and i can't open it. I need help i'm locked on my project
i tried downloading python again in ubuntu and this time it worked ithink
if this is right thing
your error message does not match the code you showed in that post, but a full traceback would be ideal - you can always make another post and repeat your question with further information
yeah that looks like it installed correctly
okay
Please don't ping random people
python3 -m pip install -U discord.py
on cmd windows
@bot.slash_command()
async def banner(ctx, user:discord.Member):
user = await bot.fetch_user(user.id)
banner_url = user.banner.url
await ctx.respond("{}".format(banner_url))
``` how would i make this code send like this
nvm ive got it
i think he tried to ping the helper role :p
!d discord.Member.display_avatar
property display_avatar```
Returns the member’s display avatar.
For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.
New in version 2.0.
so i do /banner {user} and comes up with an embed but how to i mention that user or have it put ther name i want it to say {user} banner
@bot.slash_command()
async def banner(ctx, user:discord.Member):
user = await bot.fetch_user(user.id)
banner_url = user.banner.url
embed = discord.Embed(title="Users Banner", color=0xFF0000)
embed.set_image(url='{}'.format(banner_url))
await ctx.send(embed=embed)
``` this the code
@bot.slash_command()
async def banner(ctx, user:discord.Member):
user = await bot.fetch_user(user.id)
banner_url = user.banner.url
embed = discord.Embed(title="{user.name}'s Banner", color=0xFF0000)
embed.set_image(url='{}'.format(banner_url))
await ctx.send(embed=embed) ```
It's a format code for the "Full" or "Full date and time"
From my understanding
thanks u sir
Np
pretty much, as documented in discord's API and discord.py
https://discord.com/developers/docs/reference#message-formatting-timestamp-styles
https://discordpy.readthedocs.io/en/stable/api.html#discord.utils.format_dt
How can I make it so that you can only run a specific command if you have admin rights?
There is no way to see a users connections via bots is there?
What could cause this errors?
you can add
@commands.has_permissions(administrator=True)
right below your @client.command()
Ty
Are you trying to create a bot to play audio?
What could cause this errors? How can I setup error handling to see what's causing this error?
Its telling you the error is on LN:195 with Interaction.reponse.defer()
Is there any reason you dont use inheritance and make your own Button class given the amount of logic you have inside that button?
Then you wouldnt need to "check" if pressed because a button has a callback method.
See https://discordpy.readthedocs.io/en/stable/interactions/api.html?highlight=button#discord.ui.Button
It has a method called callback
I personally haven't used pymongo; but it appears it is failing to find either your cursor or the value you attempted to look up which is 3343587727049317749
I would check your DB code.
There is nothing related to 3343587727049317749
I would check your code; you may be failing to close a cursor position in your code or the code you are using to attempt to get/use a cursor is failing.
Hello do anyone know where can I learn python discord library?
like d.py?
Exactly discord.py
that ik , i have to await it i fixed it already
i meant the other one for c1
Do you know any videos? or this is it?
I don't recommend video's since so much has changed lately.
Thanks! can I ask more questions about this later?
what is inheritance? i dont get what u mean by question
Absolutely; I will do my best to support. I may be away~
should i send u my code
Okie thaks
oh wait, its right here
I may be referencing it wrong; but I personally call it sub-classing.. its essentially when you do
class my_view(discord.ui.View):
the "my_view" object is a copy of discord.ui.View and knows everything it knows. But the twist is I can now either overwrite its defined methods/attrs or add my own.
There is way more to it then what I just described though.
Inheritance is one of the pillar of object oriented programming, I'd recommend reading up on it online as it's quite important to know
I'm going to ask a little question with discord, I want to show these boost winners on a certain channel, how do I do it?
Can you elaborate on what you mean by "boost winner"?
ok what's the issue with it tho
and u can see with my code right? i sent it
the one with the boost pressed
I did see your code; either; A. the Interaction timed out (took longer than 3 seconds to reply/defer) or B. Your view/setup is not correct and I would print the interaction parameter and see what it is.
It should be an object; but again. I would follow Robin's instructions first. It will serve you better than solving your current situation ever could.
ok
where
hellloo
@client.event
async def on_raw_reaction_add(payload):
if payload.emoji == starboard_emoji:
print("we made it here")
I have this bit of code here, and i want it so that if it detects that soemone added a specific emoji to a message itll print that message but it isnt printing it for some reason, anyone know why?
well i think i know this already, it's just class and subclass
How can I fix my error tho?
Setup your button using a subclass and try your code that way. Then report back.
Any reason you are using the 'raw' version instead of the "on_reaction_add()" event?
that'd help it run faster?
i looked up how to check for reactions earlier on on google and that was one of the options so i just went with it, it worked for my other need for it so i didnt wanna touch it xd
No idea. I was trying to get you to take up better coding practices.
I would defer your interaction immediately
wait why would i create another subclass for that tho
K, and ok
I suggest reading the discord.py docs. Use the search bar in the top left of their docs page. Its handy.
But then I also have a problem where when multiple people press in the same time, it registers multiple
Here -> discordpy.readthedocs.io/
even if I implemented ways to stop it from happening, I tried like lots of ways but none worked
Okay so you want a button to only be clicked once? Once per user?
Maybe only a specific user? I can teach you that.
Yes to which part?
that i think i can do but multiple users, I implemented many ways that should've worked but there seems to be like poeple slipping in
and resulting in multiple buttons being created from that
cuz its supposed to be 1 click --> make 1 button
People dont "slip in" code does what it is written to do
but it becomes 2 clicks on one button ---> makes 2 buttons
first
Okay you can disable a button after it is clicked.
well, i tried many things like using a list to set the person who did first and check if the person is the first in the list, self.stop, this self.press boolean way, and more
Ok, i already did
oh yeah, its a bit messy but button.disabled
yeah i looked at the two, as well as tried to swap it to regular on_reaction_add and my original thing i used it for doesnt work with it, thats why im using on_raw
i did it later on, but there is always going to be people that are able to slip in, that's why i made the gateway of the self.pressed, along with trying to do the self.stop, list way, etc
Are you inside a bot class or outside? Are you using the proper decorator?
im using @client.event, andd im assuming im outside
I've had this problem for a bit, but ig now I limit the amt of ppl that can click it so not many people are going to press it at once, but if there ends up being too many people anyways, i just wanna know how I can prevent it if there's no solution then its fine
There is, one moment.
regardless my other thing thats also in the on_war_reaction_add is working just fine, its just the if statement comparing the payload.emoji to the starboard_emoji isnt responding with True and I dont know why
Reason being; is you are probably comparing two objects; which via raw isn't going to match afaik.
im comparing payload.emoji and "⭐"
I suspect that I am getting CursorNotFound error with the following code:
class MyClient(commands.Bot):
async def setup_hook(self):
@tasks.loop(hours=24)
async def update_elo_ratings():
# Get all the users in the collection
users = collection.find()
for user in users:
summoner_id = user['summoner_id']
summoner_name = get_summoner_name(summoner_id, RIOT_API_KEY)
tier, rank = get_tier_and_rank(summoner_name, summoner_id, RIOT_API_KEY)
elo_rating = get_elo_rating(summoner_name, summoner_id, RIOT_API_KEY)
collection.update_one({"summoner_id": summoner_id}, {"$set": {"tier": tier, "rank": rank, "elo_rating": elo_rating}})
await asyncio.sleep(10)```
i put a print(payload.emoji) and it does print ⭐
Right; payload.emoji is an object. You are comparing an object to a unicode char.
Ouh
After it updated all users, I receive the CursorNotFound error.
Atleast It may be. I only know the non raw
So payload.emoji returns a Partialemoji object. Which you may be able to use the .name attr of it to compare as validation. Could even use an id
Also here's the code from before, I don't know how making defer on the first line instead of like 3rd will help the time and solve the error, cause I think the button expires in 3 seconds but the 2 lines before that shouldnt take that long right
Lets focus on getting you to subclass the Button and have us disable it after one user.
ah, i already have it in my code
Okay, may I see it?
ye ye here
i disabled the button with button.disabled=True
Did you re-send the view?
and edit original response but it's not going to fit all users unfortunately, since some are going to slip in
yes, my issue isn't disabaling the button it already works, but it's the slim margin that people get in when there is like 3 people spamming the button, it obviously won't disable in time, and will allow some people to click it before it becomes disabled
Store a counter?
that causes multiple people to enter the code at once and is why I made the gateway that I was talking about..
I would have left it inside the button subclass imo and implemented a counter to prevent that issue.
Well, I was talking about my self.pressed=True if you saw in the code, and many other similar ways that are supposed to stop this from happening, but despite all of this, there are still people that somehow manage to get in
oh, I have the gateway thing
u can check this, it's the self.pressed=True
I tried many other implementations such as self.stop() to stop all other views from ever happening again but i dont think that did anything either, as well as the list way if u saw I talked abt it earlier but ye
the list way is similar to the self.pressed boolean way but using a list, but they all don't always work
Okay. So you've tried the other path. Got it.
yes
Verify your interaction object regardless and print it
sure
Right now, it's completely fine because I limited the views so there wont be multiple people clicking hopefully, but in the future there might be
Should i print the interaction object on the top?
isn't it just going to be an object of the discord interactions
Yes.
K
Do you always get that 404 error or is it intermittent?
I would check your collection.update_one() code.
only happens when multiple people click at once, the more people click it at once the more chance. But some times, even if people werent trying to spam it in the same time, they get it by accident, prolly like 50% of the time when there are 2+ people
Nothing wrong with it? It's updating all the users?
Right; but somehow you are passing in an "id" that doesn't exist.
ok
The issue may be your sleep().. The button isnt unique; just the interactions.
yeah
Should I add the close() method to close the cursor?
@tasks.loop(hours=24)
async def update_elo_ratings():
print("Updating all users from the database...")
# Get all the users in the collection
users = collection.find()
for user in users:
summoner_id = user['summoner_id']
summoner_name = get_summoner_name(summoner_id, RIOT_API_KEY)
tier, rank = get_tier_and_rank(summoner_name, summoner_id, RIOT_API_KEY)
elo_rating = get_elo_rating(summoner_name, summoner_id, RIOT_API_KEY)
collection.update_one({"summoner_id": summoner_id}, {"$set": {"tier": tier, "rank": rank, "elo_rat>
await asyncio.sleep(2)
users.close()```
What? That isn't a cursor.. users is whatever collection.find() returns.
So what is wrong with collection.update_one? I mean it's updating all the users from the database.
wait how would the other buttons affect the current button though? Are you saying that the buttons because I didn't make them unique, they will cause trouble with each other? Because there aren't multiple buttons at once, i dont think it will affect anything if only one of the buttons will be clicked at a time. But still, it might be which might mean that I would have to switch to the other way of making buttons, instead of a decorator, I do it the other way directly to a variable. Is there a way to do this without changing the way I make them? And for the sleep, shouldnt it only affect these msgs:
d=emojis[random.randint(0,len(emojis)-1)]
embed=discord.Embed(title=f"{d} Grind Channel 1 {d}", description=f"• Click the button below to earn 1-5 points (boosters receive 1-6)!\n• The event ends <t:1674529200:R> | <t:1674529200:f>\n• Use {com} for all commands including status check", color=color)
await interaction.channel.send(view=chan1(), embed=embed)```
which the only one that might be causing problems is the next view? So how would I fix this one if you know what I mean like what is the problem with having async sleep / how should I like structure this without changing ways of making my buttons
I probably can make the buttosn the other way but haven't done it so far, since I don't specifically know how to do that and dont want to change too many things but yeah
I am not disagreeing with you; you passed in an invalid summoner_id and it failed.
That long number I copied earlier; it is failing to find it.
async def checks():
while True:
await self.bot.wait_for('message', check=check)
await echannel.send("Confirmed")
async def checks2():
while True:
await self.bot.wait_for('message', check=check2)
await echannel.send("Declined")
asyncio.run(await checks())
asyncio.run(await checks2())```Does this mean that both functions are being ran at the same time?
You shouldn't be using asyncio.run() like that
It should be used only once and should be used to kickstart the entire application
It is not possible. All summoners are getting updated. The error occurs after it updates all the users.
async def checks():
while True:
await self.bot.wait_for('message', check=check)
await echannel.send("Confirmed")
async def checks2():
while True:
await self.bot.wait_for('message', check=check2)
await echannel.send("Declined")```How can I run both these functions simultaneously?
also is it fine if u provided an example of how I can make a button the other way and apply it to the view
If two people click the same button for the same view; it isn't unique. So that sleep will block any subsequent clicks..
Which would cause a interaction timeout..
Huh
true, but how can it even get past my gateway that I set??
and how can sleep block clicks, i thought it was just blocking the coroutine functions after it
am a bit confused sry
Btw how do you know that the error is caused because I passed in an invalid summoner_id?
No
Sorry it doesn't block the "click"..
I am not entirely sure how they are getting passed your Gateway. I would print vars and see what is going on.
ok
also should i do my gateway first or defer

