#discord-bots
1 messages · Page 318 of 1
well yeah
!d discord.Interaction.channel
The channel the interaction was sent from.
Note that due to a Discord limitation, if sent from a DM channel recipient is None.
!intents
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.
Is it possible to do context menu commands in a separate file then call them in main?
I want to try and clean up my code as to not have it all in one file
you can use cogs
command_list = [(command.name, command.help) for command in client.commands]
displaying only one command although I have multiple?
Try with client.walk_commands()
Yes
Is there any way to delete the message without having to await?
dm_message = client.get_partial_messageable(channel_id).get_partial_message(message_id)
await dm_message.delete()```
All api requests must be awaited but if you need to do async function in non-async context you can use asyncio.create_task() or run_coroutine_threadsafe()
No I mean do I need to do it this way to remove the DM or is there other ways to do it?
Well we are using get_partial_messageable and get_partial_message
Then await delete to actually delete the DM
Is this the way you would do it?
create_task yeah
Also why do we need a channel id to remove a DM? Why is it not enough with just the message id?
I assume it's either message ids are not globally unique or global lookup is way too expensive
can i pay someone to make me a discord bot
!rule paid
Woudln't it be easier to just save the URL for the DM in database to use for deletion?
Because now we must save both channel id and message id
I think url already contains channel id and message id
So you ain't saving space, quite the opposite

Yeah
But you have to fetch the message anyway
Nothing
We should still use this method to fetch and remove it?
dm_message = client.get_partial_messageable(channel_id).get_partial_message(message_id)
await dm_message.delete()```
It doesn't fetch any message
Thats what partial does, it does not require make http request to get anu resource, it builds a partial class of actual class
!d discord.Message
class discord.Message```
Represents a message from Discord.
x == y Checks if two messages are equal.
x != y Checks if two messages are not equal.
hash(x) Returns the message’s hash.
!d discord.PartialMessage
class discord.PartialMessage(*, channel, id)```
Represents a partial message to aid with working messages when only a message and channel ID are present.
There are two ways to construct this class. The first one is through the constructor itself, and the second is via the following...
!d
One can be constructed by requesting to discord api only, and other one you can construct it
!d
why can’t i pay someone to make me a bot here
Its against discord TOS but people are doing it anyway like me 
How much for one
Because this Discord server is not meant for selling your services
for ... in walk_commands(*, guild=None, type=<AppCommandType.chat_input: 1>)```
An iterator that recursively walks through all application commands and child commands from the tree.
property tree```
The command tree responsible for handling the application commands in this bot.
New in version 2.0.
at least that's what i found, never tried it directly
https://discord.com/channels/267624335836053506/1168529616034594838
any disc bot experts pls
I Have this ticket system, but the close button like after 10 mins expires
`node index.js
node:internal/errors:464
ErrorCaptureStackTrace(err);
^
Error [ERR_UNSUPPORTED_ESM_URL_SCHEME]: Only file and data URLs are supported by the default ESM loader. On Windows, absolute paths must be valid file:// URLs. Received protocol 'c:'
at new NodeError (node:internal/errors:371:5)
at defaultResolve (node:internal/modules/esm/resolve:1016:11)
at ESMLoader.resolve (node:internal/modules/esm/loader:422:30)
at ESMLoader.getModuleJob (node:internal/modules/esm/loader:222:40)
at ESMLoader.import (node:internal/modules/esm/loader:276:22)
at importModuleDynamically (node:internal/modules/esm/translators:111:35)
at importModuleDynamicallyCallback (node:internal/process/esm_loader:35:14)
at file:///C:register-commands.js:13:19
at ModuleJob.run (node:internal/modules/esm/module_job:185:25)
at async Promise.all (index 0) {
code: 'ERR_UNSUPPORTED_ESM_URL_SCHEME`
how to fix this error plz help
@shrewd fjord
This is a Python server
ok
but yk how to fix it?
I suggest you find an external server for it
Yo can someone help me whit on_member_joind it dosent send or react to the event what can the problem be?
Code:
@client.event
async def on_memmber_joind(member):
await print("1")
#role = client.get_guild(676446095739453450).get_roles(1146014701575221268)
channel = client.get_guild(676446095739453450).get_channel(1146014701575221268)
embed=discord.Embed(title=f"Welcome to Rash", description=f"Welcome {member.mention} Make sure to read [#719174215961542697](/guild/267624335836053506/channel/719174215961542697/) and [#719174187188748299](/guild/267624335836053506/channel/719174187188748299/)", url=f"{member.avatar_url}", color=0x000000)
embed.set_author(name=f"{member.name}", icon_url=f"{member.avatar.url}")
embed.set_footer(text="Joined at")
embed.timestamp = datetime.datetime.utcnow()
await channel.send(embed=embed)
#await member.add_roles(role)
await print("2")```
Look at the event name function again
And double check you have the intent enabled afterwards
Oh... 🤣
you dont await the print ...
Why you awaiting print without any reason, do you know what await means?
Just brain error 🤣
Hi, I need to make a quick script that send a notification on discord when a build has completed. I have achived sending messages to our builds channel with the attached code. Now I need to do this inside a function that can be called from another script?
bot = commands.Bot(command_prefix='\\', intents=discord.Intents.all())
@bot.event
async def on_ready():
print("Bot is ready!")
channel = bot.get_channel(BUILDS_CHANNEL_ID)
await channel.send("Hello World!")
bot.run(token=TOKEN)
def Notify(notification):
...?
What is this notify function supposed to do?
Send a notification/ I found another solution using webhooks that works better :)
so i have this wiithin my modal class
async def on_submit(self, interaction: discord.Interaction):
embed = interaction.message.embeds[0]
if self.ftext:
embed.set_footer(text=self.ftext.value, icon_url=self.fticon.value)
if self.time.value.lower() == "yes":
embed.timestamp = datetime.now()
else:
embed.timestamp = None
await interaction.message.edit(embed=embed)
await interaction.response.send_message()```
when i removed the last line of code the embed edited but the modal said interaction failed is there a way to edit the embed without having to send a message
!d discord.InteractionResponse.edit_message
await edit_message(*, content=..., embed=..., embeds=..., attachments=..., view=..., allowed_mentions=..., delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by editing the original message of a component or modal interaction.
thank u
does anyone know how to include graphics in discord bots
Could you elaborate? Do you mean buttons/drop down menus?
What do you mean by graphics
How can I check when a member's given a timeout and who gave them the timeout?
!d discord.on_auditlog_entry
No documentation found for the requested symbol.
!d discord.on_audit_log_entry_create
discord.on_audit_log_entry_create(entry)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild) gets a new audit log entry. You must have [`view_audit_log`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.view_audit_log) to receive this.
This requires [`Intents.moderation`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.moderation) to be enabled.
New in version 2.2.
Warning
Audit log entries received through the gateway are subject to data retrieval from cache rather than REST. This means that some data might not be present when you expect it to be. For example, the [`AuditLogEntry.target`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AuditLogEntry.target) attribute will usually be a [`discord.Object`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Object) and the [`AuditLogEntry.user`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AuditLogEntry.user) attribute will depend on user and member cache.
To get the user ID of entry, [`AuditLogEntry.user_id`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AuditLogEntry.user_id) can be used instead.
Thanks
There's nothing for timeouts there
There's something called "automod_timeout_member" but that's not what I'm looking for
Oh that’s my bad
!d discord.on_member_update
discord.on_member_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) updates their profile.
This is called when one or more of the following things change...
Yeah that's what I was bouta say
You can use that to see when a member is timed out
Then you’ll have to query the audit log to see who did it
Can I also see who timed them out?
Oh rip
Why's this so complicated
Discord being discord
How do I get started making a Discord bot?
- Take a look at https://github.com/Rapptz/discord.py/blob/master/examples/basic_bot.py Mess around.
- When you start making your bot, use the commands ext: https://discordpy.readthedocs.io/en/latest/ext/commands/commands.html
or if you wanna use slash commands: https://gist.github.com/AbstractUmbra/a9c188797ae194e592efe05fa129c57f - The library documentation is available at https://discordpy.readthedocs.org/en/latest/
And DON'T follow ANY Youtube tutorials
I have yet to see 1 that doesn't have issues
Still only prints 'help' command
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
Name it bot in the first place 
It's not named either of those I just replaced it with client for the snippet
!d discord.app_commands.CommandTree.command
@command(*, name=..., description=..., nsfw=False, guild=..., guilds=..., auto_locale_strings=True, extras=...)```
A decorator that creates an application command from a regular function directly under this tree.
Huh
command_list = [(command.name, command.help) for command in client.tree.walk_commands()]
pretty sure I tried that and it returned an empty list
It will be client.tree to get all app commands
... did you sync your command
tree already is client.tree so I could just do tree.walk_commands() no?
How many commands do you have anyway and do they show up in the discord? Also use command.qualified_name
Yes
they do show up in discord and there's 3 rn
and yes I sync them before
ok I'm embarrassed. I can't get this command to work and I don't understand why, been a long time since I used discord.py
import discord, asyncio
from discord import app_commands
from discord.ext import commands
bot = commands.Bot(command_prefix="/", intents=discord.Intents.all())
@bot.tree.command(name="hello", description="My first application Command")
async def hello(interaction: discord.Interaction):
await interaction.response.send_message("Hello!")
@bot.command(name="ping")
async def ping(ctx):
await ctx.send("pong")
@bot.event
async def on_ready():
for guild in bot.guilds:
await bot.tree.sync(guild=discord.Object(id=guild.id))
bot.run("*")
/ping works fine but when i do /hello I get discord.ext.commands.errors.CommandNotFound: Command "hello" is not found
yeah /help returns an empty list
Well your hello is a actual slash command, so you have to sync it
that's whats happening in on_ready() right?
Try printing command list
that's what's returning an empty list
Uh weird, i will get to you kater
Its not good to sync command in on_ready but for noe just use await bot.tree.sync() get rid of the loop
!d discord.app_commands.CommandTree.walk_commands
for ... in walk_commands(*, guild=None, type=<AppCommandType.chat_input: 1>)```
An iterator that recursively walks through all application commands and child commands from the tree.
@latent jay walk_commands(guild=ctx.guild)
you can't use ctx in an interaction?
then use interaction.guild 
Nice
Because you are syncing your commands in specific guild
so to sync globally?
just do not pass guild=... In your command deco and just call sync() where you sync ur cmds
but that's what I was doing before where it'd only return an empty list?
using it in on_ready is my problem somehow, I put the sync command in a normal command and after triggering that it showed up
I said command decorator,
@tree.command(..., guild=...)
Ggs
where do I put it other than on_ready though so I dont have to do a command everytime it boots up
ohh yeah that makes sense I'm so slow
!d discord.Client.setup_hook
await setup_hook()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A coroutine to be called to setup the bot, by default this is blank.
To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.
This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready) event.
Warning
Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_for) and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_until_ready)...
If you override it as an event it'll run automatically when the bot goes online:
@commands.Cog.listener()
async def on_ready(self):
print("bot is online")
import discord
bot = discord.Client(intents=discord.Intents())
@bot.event
async def on_ready():
user = await bot.fetch_user("curome")
print(user.avatar_url)
await bot.close()
bot.run("token")
So.. it is one of solutions.
Actually what i need is skript that will print my avatar url to stdout.
Is there any faster + lighter ways.. like single request with curl?
Me when people call discord.Client "bot" and use a string on fetch_user 🫠
Probably should've suppress those embeds
Ty
I got it like that
You should be able to adjust the sizes
Doesn't matter show_pfp only to test if it is valid
The returned size can be changed by appending a querystring of ?
size=desired_sizeto the URL. Image size can be any power of two between 16 and 4096.
Uh that

Um, default still will work, i mean, default is ok to use as pfp on other platforms?
Called when the client is done preparing the data received from Discord. Usually after login is successful and the
Client.guildsand co. are filled up.
WARNING: This function is not guaranteed to be the first event called. Likewise, this function is not guaranteed to only be called once. This library implements reconnection logic and thus will end up calling this event whenever a RESUME request fails.
await setup_hook()
A coroutine to be called to setup the bot, by default this is blank.
...
This is only called once, inlogin(), and will be called before any events are dispatched, making it a better solution than doing such setup in theon_ready()event.
Simple ticket discord
Probably. Can you switch that to the glob.glob
well you should try it first, im pretty much eating right now because that was sent before i was eating
?
ticket bot discord for example give me 😐
Can't find source for that glob.glob for cogs
you need to use either hybrid command in hello or change the prefix to ! or something the tree command mainly works on / app commands so you need to select it from the meny
and also put the tree command in setup_hook
!d glob.glob
glob.glob(pathname, *, root_dir=None, dir_fd=None, recursive=False, include_hidden=False)```
Return a possibly empty list of path names that match *pathname*, which must be a string containing a path specification. *pathname* can be either absolute (like `/usr/src/Python-1.5/Makefile`) or relative (like `../../Tools/*/*.gif`), and can contain shell-style wildcards. Broken symlinks are included in the results (as in the shell). Whether or not the results are sorted depends on the file system. If a file that satisfies conditions is removed or added during the call of this function, whether a path name for that file will be included is unspecified.
!d pathlib.Path.glob also
Path.glob(pattern, *, case_sensitive=None)```
Glob the given relative *pattern* in the directory represented by this path, yielding all matching files (of any kind):
```py
>>> sorted(Path('.').glob('*.py'))
[PosixPath('pathlib.py'), PosixPath('setup.py'), PosixPath('test_pathlib.py')]
>>> sorted(Path('.').glob('*/*.py'))
[PosixPath('docs/conf.py')]
``` Patterns are the same as for [`fnmatch`](https://docs.python.org/3/library/fnmatch.html#module-fnmatch), with the addition of “`**`” which means “this directory and all subdirectories, recursively”. In other words, it enables recursive globbing...
Amm how do i use it in my code?
Like any other code that uses it
hey can someone help me with setting up custom prefix for all indivisual servers
You need to learn to mix things on your own sometimes
!e
from glob import glob
print(*glob("../*"), sep="\n")
@naive briar :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | ../home
002 | ../dev
003 | ../lang
004 | ../usr
005 | ../snekbox
006 | ../lib64
007 | ../lib
008 | ../etc
catlover you know about how to setup custopm prefix?
for every server
i am using a .db file btw
!d discord.ext.commands.Bot the command_prefix argument can be set to a coroutine(I believe). You just want to process the things with the coroutine and return a string that will be the prefix
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) and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#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) to provide the functionality to manage commands.
Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#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.
i cant get that function to work that gets back the string
What's the problem?
idk my self lol it dont give any error
code
i also trying () but it gave error cause i didnt put in the message id and this way it worked somehow idk how to fix this thing
c:\Users\ASUS\OneDrive\Desktop\Tindbot\main.py:17: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
bot.load_extension('jishaku')```Can someone tell what's wrong?
it was not awaited
use await bot.load_extension
await bot.load_extension("jishaku")
got it?
await outside function?
just like this
await before function
File "c:\Users\ASUS\OneDrive\Desktop\Tindbot\main.py", line 20
await bot.load_extension('jishaku')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: 'await' outside function
[Done] exited with code=1 in 0.391 seconds```
I don't think bot.load_extension is supposed to be inside a async def function
just put it in on_ready
put wot?
the bot.load_extension
My old bots never required that
do
async def on_ready():
print(f"Logged In As {bot.user}")
await bot.load_extension()
That works
it worked?
But why won't it work without the function
yea
I never did it earlier yet it used to work
prob a new discord bot feature i dont really know i started like a few months ago
Ahh
I am coding after an year so I don't know much
can anyone pls give me an example of a slah command
sure
@bot.hybrid_command(name="ping", description="Get the bot's ping.")
@commands.has_permissions(administrator=True)
async def ping(ctx):
await ctx.send(f"Pong! {round(bot.latency * 1000)}ms")
tysm
get_prefix should be an async function since you override it in the bot class
so i should use async def get_prefix?
yes
ok lemme try it
tbf the proper way is to give a callable to command_prefix of Bot rather than directly override get_prefix
but it's whatev
i tried it but coudnt get it done
something like this should be fine ```py
class Bot(commands.Bot):
def init(self):
super().init(self.get_bot_prefix, ...)
def get_bot_prefix(self, bot, message):
...
the argument for the callback takes in bot and a message object
!e ```py
a = ('a', )
print(a[1])
@golden portal :x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 2, in <module>
003 | print(a[1])
004 | ~^^^
005 | IndexError: tuple index out of range
that's pretty much the error, you did fetchone and then proceeded to try to get the second element
first its not a tuple
but fetchone gives a whole list
the whole row
it should give all of that
so guild id should be 0
!d sqlite3.Cursor.fetchone
fetchone()```
If [`row_factory`](https://docs.python.org/3/library/sqlite3.html#sqlite3.Cursor.row_factory) is `None`, return the next row query result set as a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple). Else, pass it to the row factory and return its result. Return `None` if no more data is available.
@golden portal and its also SELECT all
db.execute("SELECT * FROM guild WHERE guild_id = ?", (message.guild.id,))
it was working like 5 mins ago
just when i put it the main_db.commit() it stopped working
see
seriously, just please print your prefix so you can debug it
sure?
if you want to think about anything any problem just go to the freaking bathroom and take a Sh*t you will find the solution
eh i usually take a shower if im stuck at programming, it does help with thinking
understandable, anyways that's kinda off topic
tbh yea but i got the prefix problem fixed i think but i cant get the setup freaking working
@golden portal aperantly the on_message is not working
just send the code here with the problem desc someone will help\
i set it that on_message it just prints the message and its not printing anything
ah fk
i am stupid as fk
i didnt do @bot.listen
!rule 9
iwant ask
I have a question. If I have to keep a discord bot alive 24/7 for simple tasks and not that much traffic on a raspberry pi 4. Do I need a ice tower cooling or a case with cooling fan would be okay
my rpi case fan worked fine (~36°C) even during compilation of packages, but it was pretty noisy for my room so i had gotten a 22dBA tower cooler to run off the 3V pin
How's the cooling with the tower cooler?
idling at 31° rn, without any fan it would be at 50° and at the occasional compiling of numpy would throttle it at 80°
(though i found out recently that the 64-bit OS allowed pip to install their precompiled wheels, so that stopped being an annoyance)
hey guys, can someone tell me whats the difference between @discord.ui.Button and @discord.ui.button
Button is a class itself while button is decorator that helps to make quick button
and when should i use button and when Button?
use @button im sure you will know when to use Button subclass
im currently using button, but I want to make button that will jump to specific message
class CustomButton(discord.ui.Button):
def __init__(self, ...):
# do startup stuff
async def callback(self, ...):
# do stuff
is the same as ```py
@discord.ui.button(...)
async def somename(...):
# do stuff
for example with just @button you cant really have dynamic button name and another properties
just set url=...
now i have thiss
well thats not really how it works
i know, its working on another button
do you want to to make post in #1035199133436354600 ?
you have to do self.add_item(Button(..., url="someurl"))
no need
im confused now
can I send you the whole code?
sure
!paste
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
here it is
yeah so
in __init__ method
you need to add this self.add_item(Button(label="something", style=..., url="your url to jump to"))
import it from discord.ui
Button: discord.Button to __init__
what have you done so far
well jumptosuggestionurl isnt really a url
its this
you need actual url to message like [#discord-bots message](/guild/267624335836053506/channel/343944376055103488/)
thats not the best solution
pass it to the __init__
def __init__(self, url) like so
then pass url to url in button
like this?
yeah but now
when creating the view you need to pass that url
in your case: await suggestlog.send(embed=approval, view = ApprovalSystem()) this line
yeaa
you are creating view, just add await suggestlog.send(embed=approval, view = ApprovalSystem("some cool url"))
and can it be that suggmsg.jump_url?
i would say it should be
well i suggest you do that for each param instead of doing ApprovalSystem.something = something
and rewrite all buttons to Buttons?
class X:
something = None
def method(self):
print(self.something)
``` instead do this ```py
class X:
def __init__(self, something):
self.something = something
def method(self):
print(self.something)
nope
why not, maybe its stupid question, im just asking
imagine 2 users run the command at the same time
and can i leave it just
def __init__(self, url, title, suggestion):
ohhh
no you need to actually assign them to self
def __init__(self, url, title, suggestion): self.title = title self.suggestion = suggestion
like this?
!e ```py
class X:
something = None
def method(self):
print(self.something)
x = X()
X.something = 123
y = X()
X.something = 456
x.method()
y.method()
ah cause i edited it for instance
@slate swan :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 456
002 | 456
see its being overriten
yeah like that
yeaaa
i have it now
!e ```py
class X:
def init(self, something):
self.something = something
def method(self):
print(self.something)
x = X(123)
y = X(456)
x.method()
y.method()
@slate swan :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 123
002 | 456
with this approach you can even have 100 commands at once and it will still have correct values
try out
and can i delete this?
yea
class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.
New in version 2.0.
ohh i understand now
and why im adding just this as Button and leaving the rest of buttons like button?
!D discord.ui.button
@discord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)```
A decorator that attaches a button to a component.
The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View), the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction) you receive and the [`discord.ui.Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button) being pressed.
Note
Buttons with a URL cannot be created with this function. Consider creating a [`Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button) manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.
read note from this ^
ohh so the rest of it is just button because we dont need to pass url?
nope the rest usses button because it has a callback
callback is basically what to do when clicked
but since url buttons dont have callbacks they cant be created using button
ohhhh, so that interaction.responce.restofthecode...
understandd
but now it just moves it to another row, i want to have buttons "Accept", "Deny", "Jump to suggestion" and "Delete" in this exact order
I’m not exactly sure, but iirc by default it depends on the order they’re defined
I don't know if this should be here but
File "/home/runner/NOA/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/NOA/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/core.py", line 1029, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/home/runner/NOA/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/core.py", line 244, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'set' object has no attribute 'append'```
Anyone knows how to fix this? It was fine before I deleted a file and even after I replaced it it somehow still doesnt work
I can show the code if needed
hello does anyone can help me with a project that is using discord.py?
you can't append items to a set but you can add
yes people can help if you post code + errors/problems you're having
i dont know python
the program was perfectly running fine though, before i deleted a text file that the program uses
is there any way to like, make it work again without modifying code?
it's recommended you know python to a reasonable level (enough to understand OOP, async-IO) before using discord.py
im fucking dumb bro my friend is showing me an book that is learning you python on his web
well i would have thought just add back to text file but you can post the code for someone to look
Has anyone been able to do unit testing on a slash command? If so, how can I trigger a command if I can't manually call the method?
!d discord.app_commands.CommandTree.fetch_command
Will fetch the command
await fetch_command(command_id, /, *, guild=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Fetches an application command from the application.
Here's the code to the program
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
You’ll have to do a bit of testing for calling it
Now the issue is, not sure how you’re going to pass the interaction arg
You'll need to mock it
Unlike context, iirc theres no way to manually create an Interaction class
Like the package?
The interactions object
If they wrote their code in a testable way (as they should) it should be pretty easy to mock and test
Oh, I thought you were talking about the mock package which is used to mock classes lol
well yeah, you'd use the mock package to mock interactions
Taking a look, thanks
I can mock the interaction object, just need to figure out triggerring the command
@smoky cedar this is how we unit test @unkempt canyon with mocked interaction if you're wondering: https://github.com/python-discord/bot/blob/main/tests/helpers.py#L510-L526
on line 216 you're calling append on a set
append is for lists right?
if so, how do i make the text file that the code uses into a list?
using add just breaks it more
I wouldn’t really be using a text file for that purpose
i think it's fine, gets the job done
Obviously it doesn’t get the job done if you’re having issues now lol
use list built-in to convert, but yes use sqlite or something instead
How exactly can I do that?
do which
@unkempt canyon
question about pycharm
i used
`import discord
import os
token = os.environ.get("TOKEN1")
intents = discord.Intents.all()
client = discord.Client(intents=intents)
client.run(token)in replit and pycharm. replit works but pycharm sends the following error:
discord.client: logging in using static token
...
raise ClientConnectorCertificateError(req.connection_key, exc) from exc
aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1002)')]
`
is this on macos? if so: #discord-bots message
yes
like this?
sure, double click it
omg thank you
it finally work
i got really tired of working in replit lol
also i spent about 2 hours yesterday trying to make it work in pycharm
The fuck is happening here
There
https://www.pythondiscord.com/pages/guides/python-guides/fix-ssl-certificate/
thats also on website
A guide on fixing verification of an SSL certificate.
My bot have the activity Streaming can someone help me with big image and buttons?
huh
wdym by the buttons
ok
looks like custom rich presence
is that on a person or a bot?
In this video we use Pypresence, a wrapper for the Discord RPC, to get a custom Rich Presence 'Playing a Game' status with buttons in Python! Pypresence allows you to add text, images, and buttons to your status! If you have any questions or comments feel free to comment below or join our Discord (discord.gg/M6eFU3HrUn)! If you found this video ...
try this I guess
Bot can't have those not possible as far as i know in python but i heard it's possible in js not sure tho
How do you set a nickname for the bot?
!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).
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history) to do this. If nobody else has reacted to the message using this emoji, [`add_reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.add_reactions) 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) instead of `InvalidArgument`.
!d discord.Member.edit - the nick argument
await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., timed_out_until=..., bypass_verification=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the member’s data.
Depending on the parameter passed, this requires different permissions listed below...
property me```
Similar to [`Client.user`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.user) except an instance of [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member). This is essentially used to get the member version of yourself.
Is this correct?
me = discord.Guild.me
me.edit(nick="Hallowen Bot")```
No, you need a guild instance
When the OOP
F
discord().Guild().me().edit()
Bro really instantiated discord 😭
any coustom bot developer plz dm
nice work
how can i make commands specific to a guild like i want a command that i can use to get the main database file but only i can use it on my server
slash commands or text commands?
hybrid
!d discord.app_commands.guilds
@discord.app_commands.guilds(*guild_ids)```
Associates the given guilds with the command.
When the command instance is added to a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree), the guilds that are specified by this decorator become the default guilds that it’s added to rather than being a global command.
Note
Due to an implementation quirk and Python limitation, if this is used in conjunction with the [`CommandTree.command()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.command) or [`CommandTree.context_menu()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.context_menu) decorator then this must go below that decorator.
Example...
it would register your slash only to that guild
for text you would have to make your own check
yes
Well you can add a check. Like check the guild id of the server the command is coming from and compare it to a list of 'verified' guilds.
wait i found on on overflow
Ah alright!
@tree.command(name = "sync", description="Syncs the bot commands", guild=discord.Object(id=TEST_GUILD_ID))
can i use this with hybrid?
that is only for slash
in discord py is there any way to trigger an interaction using message?
your hybrid deco have the kwarg
Hmm... What are you trying to do exactly?
explain the thing but i thin you can use the on_message
im trying to trigger an event by a message but it has to be ephemeral
like what
Ephemeral event response to a message?
yea but in ephemeral with an embed and buttons
Ahh i see. Hmm...
i dont get it but you can use on_message can check if the message is what you want
then you can perform the task
it doesnt have ephemeral property
wdym
No sorry ping when replying i am not fimiliar with any way to do that. I dont believe you can send views in an emphramal message.
that is possible
briefly explain your situation
it is really hard to explain
but i think its not possible
ty for listening anyways
anyone wanna be my test subject?
yeah, it's me who creates module(s) object(s), not python
Bots cannot see ephemeral messages, unless they’re the one who triggered the interaction, or sent the message
Yes that. User will sent a normal message but the bot has to reply with an ephemeral message
Is that possible?
no
No. Ephemerals can only be sent in response to interactions
Not even if the user message triggers an interactable command somehow?
Which is what I originally wanted to know
only interactions, which are e.g. buttons, slash commands, etc.
I see
Thanks for that kinda already guessed that it's not possible but still wanted to ask
why do you think that adding another bot will speed up things? they're still using the same gpu
this question seems more suited for #async-and-concurrency, but generally asyncio.create_task() is for running asynchronous functions in the background and loop.run_in_executor() (or asyncio.to_thread()) is for running sync functions; if you have to mix blocking and non-blocking code together, i would suggest only threading the parts of the code that are blocking: ```py
async def update_user_data_to_collection(...):
data = await some_network_io()
processed = await asyncio.to_thread(process_gpu_stuff(data))
await upload_to_db(processed)
task = asyncio.create_task(update_user_data_to_collection(...))
Sidenote, the task should be stored to avoid garbage collection
https://docs.python.org/3/library/asyncio-task.html#asyncio.create_task```
assuming your async function doesn't have code that blocks the event loop, sure
Either way you can start multiple same task using gather
Ok i just don't know the context and pulled out this 💀💀 dont scold me if its not related
why when I add the view to this message this error happen
button = discord.ui.Button(
style=discord.ButtonStyle.link,
label='🚀',
url=link,
)
view = discord.ui.View(timeout=None)
view.add_item(item=button)
await member.send(content=message, view=view)
can someone help me with a bot? i learned from a tutorial from youtube so idk if i did it correctly it only works in private messages but not on the server i added it to
if anyone has experience something similar to a bot that gives out roles for reaching points, i need quick assistance #1169316527309340752 message
why None helps here?
How to get active developer badge?
Yes i have a working bot
How to make slash commands for my bot*
discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
Thanks
..
can I get something like this for adding normal commands please
Use google
Such a helpful response
Someone tell me how to make the bot tag a user that run a specific command?
I forgot how
Like {?.user}
You're looking for the .mention property
Hey guyss, Im making suggestion command on my Discord bot and i need help with buttons, i have channel for mods where are send all suggestions and on that message is View with four buttons and i want that if you press one, it will send message and disable all of them. Can someone please help me? I have something made, but its not working.
Sure
Send your code
You have to respond to the interaction by editing the message. Embeds don't have an edit_message method
but when i do that I cant responce that message anymore, right?
You can either respond to the interaction ephemerally first and then call Interaction.edit_original_response to edit the message with your new view, or respond by editing the message first and sending a non-ephemeral message later on
ohh so when i want to make that ephemeral i should to the first thing
Yeah
You can still do it that way if you don't want to make it ephemerally though. The order doesn't really matter if you don't care about it being ephemeral
Heyo
You know how to put this and how to continue it working after restarting the bot ?
They're called persistent views. You can find an example here: https://github.com/Rapptz/discord.py/blob/master/examples/views/persistent.py
can someone that knows about discord bots please help me with some simple feature im struggling with #1169421483026686062 message
Technically how many slash commands you can make?
1 command can have 25 sub commands which is equals to 1 slash command by discord so we can have 100 max.. then 100*25 = 2500 but what about subcommand's subcommand 💀💀
Sub commands cannot have sub commands
They can? 
it like
/parent sub1 sub2 [options]
Pretty sure that’s not possible
I haven’t seen any implementations, and I don’t really see how nesting the classes would work
I don’t really understand the point of the issue you sent either. It’s about a different topic
Well it is possible, give me a bit time let me show
Oh I’m tripping
It is possible
There’s a parent kwarg in app_commands.Group that allows you to set the parent group
Mb
hello im making my first discord bot
i have a question, what do "async" and "@client.event" mean?
The async statement basically mark the following statement as asynchronous, for example:
# async function definition
async def func():
...
# iterate through async iterable/iterator
async for item in async_iterable:
...
And the @client.event is a decorator that marks the following function as an event of the bot
!d discord.Client.event
@event```
A decorator that registers an event to listen to.
You can find more info about the events on the [documentation below](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events).
The events must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine), if not, [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError) is raised.
Example
```py
@client.event
async def on_ready():
print('Ready!')
```...
I want to know how can i add prefix to my bot
like for now it reads the messages which starts with .hi or messages like .roll
so there is no prefix for the bot rn
What library are you using?
See the prefix commands page
yeah i saw but it didnt seem to work
What about it didnt seem to work?
@client.command() async def test(ctx): await ctx.send("hello!")
This part
And what's wrong with it?
the bot dosent respond to .test
yesterday my discord bot was working. but after i update my python to version10, its giving error:AttributeError: TypeError: Client.init() missing 1 required keyword-only argument: 'intents'
How did you define your bot?
!intents
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.
yeah i use @client.command
Why are you defining client but registering the command on bot?
I just said i used client 😭
You shouldn't have multiple bot instances, by the way
You sent @bot.command() 🤷
!paste can you send the full 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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
yeah sure give me few mins
thanks! it probably changed and i didnt update the version until yesterday, probably thats why it didnt work.
like where can i add the command thing in that
See Why does on_message make my commands stop working?
Overriding the default provided
on_messageforbids any extra commands from running. To fix this, add abot.process_commands(message)line at the end of youron_message
okai thank you so much
so i can basically replace @client.event with @client.listen('on_message')?
second one
thx
metamask
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
!e ```py
print(code)
@slate swan :x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | print(code)
004 | ^^^^
005 | NameError: name 'code' is not defined. Did you forget to import 'code'?
you cant use a varriable that is not defined
code
!eval [python_version] <code, ...>
Can also use: e
Run Python code and get the results.
This command supports multiple lines of code, including formatted code blocks. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.
The starting working directory /home, is a writeable temporary file system. Files created, excluding names with leading underscores, will be uploaded in the response.
If multiple codeblocks are in a message, all of them will be joined and evaluated, ignoring the text outside them.
Currently only 3.12 version is supported.
We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!
@slate swan :x: Your 3.12 eval job has completed with return code 1.
001 | File "/home/main.py", line 11
002 | get_defCoins(uid):
003 | ^
004 | SyntaxError: invalid syntax
@slate swan :x: Your 3.12 eval job has completed with return code 1.
001 | File "/home/main.py", line 3
002 | try:
003 | IndentationError: unexpected indent
code
I have this error :
2023-11-02 11:46:27 ERROR discord.client Ignoring exception in on_member_join
Traceback (most recent call last):
File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "c:\Users\canai\Desktop\discord_bots\Gym_advice\main_GA.py", line 31, in f3
await channel.send(embed=embed)
^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'send'
For this code part :
@client.listen('on_member_join')
async def f3(member):
channel = client.get_channel(THEID)
embed=discord.Embed(title="Welcome!",description=f"{member.mention}just arrived!" , color=discord.Colour.green())
await channel.send(embed=embed)
this means the id is wrong
Okay thanks for the help !
and if the id is correct try
channel = client.get_guild(member.guild.id).get_channel(THEID)
why fetch guild when you already have it under member.guild
oh yea @slate swan
i am dumb
how can imake that after a command execute after a time period it replies a message like in 5 min
i just want a response like a few minutes after maybe even an hour after
use await asyncio.sleep(5) to wait for 5s
i dont want to wait
i want to make a poll command but after like 1 hour it will give the poll results back to the user
still the easiest solution is to wait
@command()
async def ...(...):
...
await asyncio.sleep(3600) # 1h
# send results
will this like put other commands to wait aswell like it will not work with othercommands or it just this command?
ok
so if its waiting for 1 hour in the poll command can someone else use the poll command?
yea
ok thats great
but keep in mind that if the bot restarts while the 1h waiting is still pending it wont be still waiting after reload
oh ok
hence this is not the best solution but the easiest one for sure
Create a database that tracks the polls, and their times. Create a task to check every 30 seconds. If the poll is under 30 seconds don’t store it in the DB and just sleep the function
so i just save the time in database and i just get the current time and subtract it with the previus one to see if there has been an hour?
i would say that easier would be if you insert to the database date that you want it to end and then check if this date already passed or not
It would probably be easier if you were to store the time it finishes, but there are factors where you’ll want store the time it started, and the duration
It’s your choice wether you want to store the datetime object or the unix time. I prefer unix time as it’s easier to compare, but storing the object itself would be more readable
@final iron Do you use this logic for temp bans/mutes as well?
could be
That's not even python 😭
programming joke anyway
Im having a cog question
Here's main.py
https://paste.pythondiscord.com/CLUA
Help.py
https://paste.pythondiscord.com/HATA
Here's the few reasons i think the bot have problem:
1.Online status
First pic is this bot in the console
It didnt have the blue and purple text's that checked it online and the synced how many commands
Left one is other normal bot looks like
2.when i enter / in server, the command list didnt refresh, new commands i added not showing, old command i deleted still there
Anyone please tell me is this normal
what will you in 2038 tho 🤓
command tree resync?
Wdym?
so i’m fairly sure that when you modify as well as add any new slash commands you need to resync them so that discord is updated with your new command
also from what it looks like between the two pictures. that you could be running two different versions of the code. one that has logging(the colored text you were talking about) setup and one that doesn’t.
I didn't change anything so i think it might should show up
Yah
It's still using old commands
It didn't refresh
How suppose i do?
Thanks
ok so im making a python script where you can use these commands !play Artist - Song name and queue but when i use these commands it doesnt do anything and it doesnt show anything on python cmd
it dont work
i mean it doesnt work for like mnore then 1 min or so
i tried for 3 min and waited but it never worked
No, I use discord built in features
Literally 0 reason to use bots for that
Not for bans?
Why would you ban someone temporarily anyway? 
Its great to way to get rid of annoying creeps for some time or another reason could be just remove their messages, tbh a faster way to remove messages
I wouldn't want some obvious trolls to be back in my server, if I have one anyway
Then ig just for removing messages ;-;
anyone have self bot ?
!rule 5
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
Why does my bot not reply to messages? also how can i access the debug logger?? I've tried various things but I can't seem to figure out what im doing wrong
here's my paste:
you don't have the message content enabled in your code
I enabled the message intent but it stil does not reply
!paste
discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
Are you specifiying your intents in your bot constructor?
@final iron Hey brother i gotta question. So i have created a configuration command in my bot, this function configures things like Automod and Embed colors. Heres my issue: I want to be able to re run a configuration question if an invalid response is detected. For example, if the configuration funtion asks the user "How long would you like Spam mutes to be?" And the user responds with "Pig", this is an invalid response and at this point, i want to ask that question again. Do i need to use a while loop? Or is there something that will handle this better for me?
What are you using to configure your bot? Do you have a list of questions you send and wait for a message response from the user?
Yes
And this is all being written to a database
Is there any reason why you don't have subcommands for specific configurations instead?
this is the initial setup. There will be subcommands for specific configurations in the future
^
If i were to use subcommands, wouldnt this be less user-convenient?
It would make the process longer at hand
would be a hell of a lot easier to make tho lmao
my lord that small nickname got me some reading problems
I mean, say I want to configure the embed color, but to do that I have to answer some other 4 questions that I don't want to change
again, we'll probably implement the subcommands afterwards. We just need an initial streamlined setup
If you want to do it the way you currently are, a while loop is probably your best bet. Though I'd strongly recommend joining that up into a group with subcommands for those features
Thank you for your advise.
one more thing: bot.wait_for("interaction") is a thing, right?
discord.on_interaction(interaction)```
Called when an interaction happened.
This currently happens due to slash command invocations or components being used.
Warning
This is a low level function that is not generally meant to be used. If you are working with components, consider using the callbacks associated with the [`View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View) instead as it provides a nicer user experience.
New in version 2.0.
anyone know how I can make it to where instead of me having to use cd all the time it is just always there
I'm using a Select Menu and don't want other people interacting with it
wym
when other users click on it, it runs the rest of the code. So I'm tryna stop that from happening but still allow the user that ran the command to interact
😂
Lookup how to set your default directory in command prompt
You should be checking that in the callback of the SelectMenu
on_interaction should be rarely, if ever used
Callbacks were implemented specifically for this purpose
Hey
anyone help mejust little guide me and help me very small thing
dm me if you can help me 🙏
Wtf?
lmfao
hahahjahahaj
bro i think he dead serious hes not even sarcastic
You exactly know reverse what lol, <@&831776746206265384> please handle
Ok python server really getting raided
Where r the mods bruv
whats going on here?
Please handle, ;-;
bots raiding or smth
From here..
@craggy meadow and @slate swan stop this nonsense.
hey
what do you need help with
will you save the data?
what have you tried
!rule 5
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
Lmaoooo
lets not
that is agains discords Terms of Use and your account will be reported
!pban 1168338903145664575 self bot spamming
:incoming_envelope: :ok_hand: applied ban to @distant forum permanently.
stop with this nonsense
who?
your use of language

seems like the channel was pretty lively earlier
Whats the code to dm a mentioned member
Soemthing like this 👇
!dm @cyan eagle hello
!d discord.Member.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) objects. **Specifying both parameters will lead to an exception**.
I am not able to copy code :/
But its send message , j want to dm
That’s how you do it…
@final iron i need a help
import os
intents =
discord. Intents.default()
intents. typing = False
intents.presences = False
client =
discord.Client(intents-intent s)
@client.event
async def on ready():
print("Logged in as (8.user).formatent))
client.run(os.getenv('TOKEN') )
@client.event
async def
on_message(message):
if message.author ==
client.user:
return
message.content.startswith("! dm'):
mentioned_members = message.mentions
nonmention message = message.content.replace('Idm ').strip()
for member in
mentioned members:
dm_channel await member.create_dm()
await
dm_channel.send(nonmention_me ssage)```
Can you tell me whats wrong here bot is not responding to command
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
It’s very clear you’ve just copied code online and pasted it in
Learn the basics first
I used raplit ai
like i said before you aint gonna make a bot in python not knowing python
i dont have any motive to code in python i just want a dm command for me to play with my freands
Spending 10 to 15 days is not worth for 1 command soo thats why j joined this server and used raplit ai
If you want to get a job done but cant/dont want to do it yourself pay someone lol
is using BeautifulSoup for searching websites illegal?
or against the ToS of discord
its about website tos
i mean i am just using the bot to get the website link nothing else in that
website link from another website?
from here yes
its an api
yeah
so you obviously can use the results
are you using beautiful soup to access api?
nope
so what are you doing with bs?
apprantly i thought beautiful soup was included there
but its not used
i never said i was using beautiful soup anyways 😭
yeah totally
welp i just asked if its legal or not i didnt say i "used" it
then why you ask about something that you dont use 😵💫 ?
good question
for general knolege
i just dont remember why did i import this i am not even using it
so i thought i might be using it before and forgot so asked just to be safe
how can i get rid of these types of errors:
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
Respond to interactions within 3 seconds
do u know why nothing will append to this empty file ive sent in dbchannel?
@bot.command()
@commands.cooldown(1, 2, commands.BucketType.guild)
async def loa(ctx, userID=None, amt_time=None):
support = ctx.guild.get_role(SUPPORT_ID)
if (support in ctx.author.roles):
if userID == None or amt_time==None:
await ctx.reply(f"Invalid usuage.\n*`usuage: {PREFIX} userID time in days`*")
return
else:
# user = guild.get_member(int(userID))
dbchannel = bot.get_channel(1155888521840693359)
logsdata_msg = await dbchannel.history(limit=1, oldest_first=True).flatten()
while len(logsdata_msg) == 0:
logsdata_msg = await dbchannel.history(limit=1, oldest_first=True).flatten()
logsdata_msg=logsdata_msg[0]
file = logsdata_msg.attachments[0]
cont = await file.read()
alldata = ast.literal_eval(cont.decode('utf-8'))
alldata.append({"userID": userID, "time": amt_time})
await loa_logs(alldata, logsdata_msg, dbchannel)
await ctx.reply(f"Successfully added <@{str(userID)}> to the database.")```
.flatten() is not a thing anymore
what do i use instead
flatten is outdated
!d discord.TextChannel.history
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator) that enables receiving the destination’s message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history) to do this.
Examples
Usage...
there is an example on docs
It’s an iterable now
Flattening into a list:
messages = [message async for message in channel.history(limit=123)]
# messages is now a list of Message...
oh okay
it still won’t add anything to the file
!paste
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
Share the current code
wait not that
@bot.command()
@commands.cooldown(1, 2, commands.BucketType.guild)
async def loa(ctx, userID=None, amt_time=None):
support = ctx.guild.get_role(SUPPORT_ID)
if (support in ctx.author.roles):
if userID == None or amt_time==None:
await ctx.reply(f"Invalid usuage.\n*`usuage: {PREFIX} userID time in days`*")
return
else:
# user = guild.get_member(int(userID))
dbchannel = bot.get_channel(1155888521840693359)
messages = [message async for message in dbchannel.history(limit=1)]
while len(messages) == 0:
messages = [message async for message in dbchannel.history(limit=1)]
messages=messages[0]
file = messages.attachments[0]
cont = await file.read()
alldata = ast.literal_eval(cont.decode('utf-8'))
alldata.append({"userID": userID, "time": amt_time})
await loa_logs(alldata, messages, dbchannel)
await ctx.reply(f"Successfully added <@{str(userID)}> to the database.")```
!paste
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
huh
import discord
from discord.ext import commands
import chess
import chess.svg
from cairosvg import svg2png
intents = discord.Intents.default()
bot = commands.Bot(command_prefix='.', intents=intents)
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name}')
@bot.command()
async def new(ctx):
chess.Board()
game = chess.Board()
await ctx.send("Chess game started!")
if game.turn:
await ctx.send("White's turn")
else:
await ctx.send("Black's turn")
await ctx.send(file=discord.File("board1.png"))
@bot.command()
async def move(ctx, move):
game = chess.Board()
if game.legal_moves:
game.push_san(move)
else:
await ctx.send("Invalid move. Please try again.")
with open("board.svg", "w") as f:
f.write(chess.svg.board(board=game))
svg2png(url="board.svg", write_to="board.png")
await ctx.send(file=discord.File("board.png"))
if game.turn:
await ctx.send("White's turn")
else:
await ctx.send("Black's turn")
if game.is_checkmate():
await ctx.send("Checkmate! Game over.")
elif game.is_check():
await ctx.send("Check!")
elif game.is_stalemate():
await ctx.send("Stalemate! Game over.")
bot.run('token')
Im coding a discord chess game, when i run the game, it went well until it get to black turn (white go first), i tried to move d7 to d6 and it gave me this error:
IllegalMoveError: no matching legal move for d7d6 (d7 -> d6) in rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1
Did i do sth wrong here or are there any bug
Have you tried reading it?
yes
So…
looks like this error comes from chess library not discord
Doesn’t matter
Read the embed…
Follow the extremely, extremely simple instructions…
Welp even first line of error tells everything in the chess one
You’re not writing to a file anywhere in the code
await loa_logs(alldata, messages, dbchannel) does
async def loa_logs(data, messages, dbchannel):
buffer = io.StringIO()
buffer.name = "loa.py"
buffer.write(str(data))
buffer.seek(0)
await messages.delete()
await dbchannel.send(file=discord.File(buffer, 'loa.py'))```
Do you know what StringIO does?
!d io.StringIO
Pretty sure you didn’t
class io.StringIO(initial_value='', newline='\n')```
A text stream using an in-memory text buffer. It inherits [`TextIOBase`](https://docs.python.org/3/library/io.html#io.TextIOBase).
The text buffer is discarded when the [`close()`](https://docs.python.org/3/library/io.html#io.IOBase.close) method is called.
The initial value of the buffer can be set by providing *initial\_value*. If newline translation is enabled, newlines will be encoded as if by [`write()`](https://docs.python.org/3/library/io.html#io.TextIOBase.write). The stream is positioned at the start of the buffer which emulates opening an existing file in a `w+` mode, making it ready for an immediate write from the beginning or for a write that would overwrite the initial value. To emulate opening a file in an `a+` mode ready for appending, use `f.seek(0, io.SEEK_END)` to reposition the stream at the end of the buffer.
This is not used to write to files lmao
what do i use instead
This is why we don’t copy and paste code off the internet
open
i havent
the file is in a discord channel
and why do u have to be so condescending
okay i may not know everything unlike you
but theres no need to be rude
Not being rude lmao
then you must have a great personaility
A file-like object opened in binary mode and read mode or a filename representing a file in the hard drive to open.
Note
If the file-like object passed is opened via open then the modes ‘rb’ should be used.
To pass binary data, consider usage of io.BytesIO.
You can get a file like object with that
Then open it in memory of course and do allat
but the code is the exact same as another databse and that works fine. ive sent an empty file name loa.py to the channel, is that why nothing is being appended to it?
Possibly? You’re not using StringIO for its intended use so it’s a given it’s not going to function possibly each time
how would i send thw file to the channel for the intended use
This’ll return a file-like object
Then you can do everything from there
i just sent the file like this
@bot.command()
async def a(ctx):
c = bot.get_channel(1155888521840693359)
buffer = io.StringIO()
await c.send(file=discord.File(buffer, 'loa.py'))```
Okay?
Like I said before, you’re not using StringIO for its intended purpose
Sometimes it’ll work, sometimes it won’t
how can i get a category from its id?
Yes with .get_channel(id)
oh ok
class OrderButton(discord.ui.View):
def __init__(self):
super().__init__()
self.value = None
@discord.ui.button(label="Claim", style=discord.ButtonStyle.green)
async def order1(self, button: discord.ui.Button, interaction: discord.Interaction):
await interaction.response.send_message("You clicked me!")
@client.hybrid_command()
async def test(ctx):
view = OrderButton()
await ctx.send(view=view)```
Why is it giving me an error:
[2023-11-03 12:53:58] [ERROR ] discord.ui.view: Ignoring exception in view <OrderButton timeout=180.0 children=1> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Claim' emoji=None row=None>
Traceback (most recent call last):
File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 427, in _scheduled_task
await item.callback(interaction)
File "c:\Users\HP\OneDrive\Desktop\MetaBotsForge\Server\Bot\main.py", line 310, in order1
await interaction.response.send_message("You clicked me!")
AttributeError: 'Button' object has no attribute 'response'```
in dpy 2.0 button and interaction got flipped around to (interaction, button)
https://discordpy.readthedocs.io/en/stable/interactions/api.html#discord.ui.button
The function being decorated should have three parameters,
selfrepresenting thediscord.ui.View, the discord.Interaction you receive and thediscord.ui.Buttonbeing pressed.
i havent even given a detailed answer tho
😭
So, button.response.send_message?
ergh, i mean sure you could write that...
Any better method
im just saying to flip button and interaction around in your parameters
Oh okay
@discord.ui.button(label="Claim", style=discord.ButtonStyle.green)
async def order1(self, button: discord.ui.Button, interaction: discord.Button):
await interaction.send_message("You clicked me!")```
Smth like this 😭 ?
Elloh
interaction should be the second parameter of your function, and button should be the third parameter
oh wtf did discord.py's repository deleted again oh nevermind github's just having a bunch of issues that broke the discord.py repo (https://www.githubstatus.com/)
How is everyone

!ot
Please read our off-topic etiquette before participating in conversations.
Ye i dunno what that means 🙂 the reason why I joined this server is I need help
Can I dm you if u are a python programmer 🙂
cannnnnnn I doo thattt? ^~^
Use #ot0-psvm’s-eternal-disapproval please
#❓|how-to-get-help
you're more likely to get help asking your full question in the server than prodding people to DM you
SOOO
@discord.ui.button(label="Claim", style=discord.ButtonStyle.green)
async def order1(self, interaction: discord.Button, button: discord.ui.Button):
await interaction.send_message("You clicked me!")```
Works?
i think you meant to write discord.Interaction instead of discord.Button
nope it dosent
huh didnt u say use discord.Button
OH WAITI
Im so dumb sry 💀
@hushed galleon
@discord.ui.button(label="Claim", style=discord.ButtonStyle.green)
async def order1(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.send_message("You clicked me!")```
Error again
interaction.response.send_message was correct the first time too
Then what's the error here
It says interaction failed 😭
most likely because you used interaction.send_message which isn't a valid method
Oh
interaction.response.send_message()?
Also error :(
Nvm nvm it worked thanks
Im soooo dumbb ahhhhh im embarrased
fyi during dpy 2.0's development it used to be (button, interaction), but when danny left and development stopped, various forks came out to finish the remaining work which is why disnake, nextcord, and pycord all still have it ordered as (button, interaction)
when danny came back and resumed development, he thought it would make more sense to have it ordered as (interaction, button), presumably to be consistent with the new slash commands which would have interaction as their first parameter, but of course people had already started posting code using (button, interaction) which has led to many more people copying their code without realizing it's not compatible with discord.py anymore
may god bless you 😇
😭
oh cool the discord.py repo is back, this is the official example would have cited earlier had i been able to find it
https://github.com/Rapptz/discord.py/blob/v2.3.2/examples/views/confirm.py#L29-L31
examples/views/confirm.py lines 29 to 31
@discord.ui.button(label='Confirm', style=discord.ButtonStyle.green)
async def confirm(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message('Confirming', ephemeral=True)```
Is it possible to send a message to a specific channel using interaction?
you can't do that as a response to the interaction itself, but you can get the TextChannel object you do want to send to and use that afterwards: py @discord.ui.button(label='Confirm', style=discord.ButtonStyle.green) async def confirm(self, interaction: discord.Interaction, button: discord.ui.Button): await interaction.response.send_message('Confirming', ephemeral=True) channel = interaction.client.get_channel(1234) # channel ID await channel.send('Someone just used the confirm button!')
!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.
Thanks
Can i go to the next iteration of a tasks.loop and keep the interval till the next-next one?
what i want is
print(0) -> dispatch_send -> wait for 1.5s -> next iteration of the task
!d discord.ext.tasks.Loop.restart you could call this after dispatching
restart(*args, **kwargs)```
A convenience method to restart the internal task.
Note
Due to the way this function works, the task is not returned like [`start()`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop.start).
`(venv_name) C:\Users\abhay\OneDrive\Desktop\mater bot>python main.py
Traceback (most recent call last):
File "C:\Users\abhay\OneDrive\Desktop\mater bot\main.py", line 25, in <module>
client = Client()
^^^^^^^^
File "C:\Users\abhay\OneDrive\Desktop\mater bot\main.py", line 12, in init
super().__init(command_prefix=commands.when_mentioned_or('.'), intents=discord.Intents().all())
^^^^^^^^^^^^^^
AttributeError: 'super' object has no attribute '_Client__init'
(venv_name) C:\Users\abhay\OneDrive\Desktop\mater bot>`
why this error im trying to fix doesnt get fixed plz help
main.py code here
`import discord
from discord.ext import commands
from colorama import Fore, Back, Style
import time
import json
import platform
from buttons.blacklist import BlacklistView
class Client(commands.Bot):
def init(self):
# You should call the constructor of the parent class using super() and ensure that it has the correct parameters.
super().__init(command_prefix=commands.when_mentioned_or('.'), intents=discord.Intents().all())
async def setup_hook(self):
for ext in self.cogslist:
await self.load_extension(ext)
async def on_ready(self):
prfx = (Back.BLACK + Fore.GREEN + time.strftime("%H:%M:%S UTC", time.gmtime()) + Back.RESET + Fore.WHITE + Style.BRIGHT)
print(prfx + " Logged in as " + Fore.YELLOW + self.user.name)
print(prfx + " Bot ID " + Fore.YELLOW + str(self.user.id))
print(prfx + " Discord Version " + Fore.YELLOW + discord.__version__)
print(prfx + " Python Version " + Fore.YELLOW + str(platform.python_version()))
client = Client()
client.run("ig my token") # bot token inside quotes
`
@hushed galleon
he is helper so
could u help?
I already gave the answer...
def __init__(self):
When you're calling your super()...
`(venv_name) C:\Users\abhay\OneDrive\Desktop\mater bot>python main.py
[2023-11-04 09:18:52] [INFO ] discord.client: logging in using static token
Traceback (most recent call last):
File "C:\Users\abhay\OneDrive\Desktop\mater bot\main.py", line 27, in <module>
client.run("token fr") # bot token inside quotes
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\abhay\OneDrive\Desktop\mater bot\venv_name\Lib\site-packages\discord\client.py", line 860, in run
asyncio.run(runner())
File "C:\Users\abhay\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "C:\Users\abhay\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\abhay\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "C:\Users\abhay\OneDrive\Desktop\mater bot\venv_name\Lib\site-packages\discord\client.py", line 849, in runner
await self.start(token, reconnect=reconnect)
File "C:\Users\abhay\OneDrive\Desktop\mater bot\venv_name\Lib\site-packages\discord\client.py", line 777, in start
await self.login(token)
File "C:\Users\abhay\OneDrive\Desktop\mater bot\venv_name\Lib\site-packages\discord\client.py", line 621, in login
await self.setup_hook()
File "C:\Users\abhay\OneDrive\Desktop\mater bot\main.py", line 15, in setup_hook
for ext in self.cogslist:
^^^^^^^^^^^^^
AttributeError: 'Client' object has no attribute 'cogslist'
(venv_name) C:\Users\abhay\OneDrive\Desktop\mater bot>`
And this is why we don't copy code we find online
You never defined cogslist
You also shouldn't be calling your commands.Bot subclass client
discord.Client exists so it's insanely confusing
how do i fix it?
this isnt any code available on github
Well you need to define cogslist lol
ok lol
There are other sources of code other than Github
Thousands
Oh nvm
It's off stackoverflow
I have a problem starting my discord.py Bot with the .exe file that pyinstaller created from my main.py.
After i start the main.exe in the "dist" folder, a python shell terminal starts li...
`(venv_name) C:\Users\abhay\OneDrive\Desktop\mater bot>python main.py
Traceback (most recent call last):
File "C:\Users\abhay\OneDrive\Desktop\mater bot\main.py", line 25, in <module>
client = Client()
^^^^^^^^
File "C:\Users\abhay\OneDrive\Desktop\mater bot\main.py", line 12, in init
super().__init(command_prefix=commands.when_mentioned_or('.'), intents=discord.Intents().all())
^^^^^^^^^^^^^^
AttributeError: 'super' object has no attribute '_Client__init'
(venv_name) C:\Users\abhay\OneDrive\Desktop\mater bot>`
Same error as before...
