#discord-bots
1 messages · Page 357 of 1
i tried making my bot send msg for join and leave with else msg
but its not working
the bot isnt entering
`@client.command(pass_context=True)
async def join(ctx):
if ctx.author.voice:
channel = ctx.message.author.voice.channel
await channel.connect()
await ctx.send("i have joined your party")
else:
await ctx.send("are you dumb? you need to join a voice channel first")
@client.command(pass_context=True)
async def leave(ctx):
if ctx.voice_client:
await ctx.guild.voice_client.disconnect()
await ctx.send("i am leaving the party guys")
else:
await ctx.send("hey dumbass, add me in a voice channel first")`
this when I use sys right??
it was bettr if u cud tell whr i did wrong
also showing all greens
what?
its been a long time since i’ve seen “pass context” in a deco
ignore him
dw about it, it happens
oh wait nvm, i thought he was talking to you and saying that was the solution
it literally says “pycache” as the folder name. what do you think the folder is for?
start with some error messages then. saying “it doesnt work” doesnt tell us anything
welp
thr is no error
all greens
that is the prblm
lol
thats for if a member joins a server, not for if a bot is in a vc
nyways not gonna use tht
!traceback | so if theres nothing like this below, whats the issue then?
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.
the bot isnt doing stuff
i just copied the code frm my old prjct and pasted
then what happnd idk
but the bot used to do it in my old prjct
not joining the voice channel?
you're probably missing message_content intents. also that code is outdated.
yes finally u got it
fuck. i keep forgetting to check intents
!intents | double check these and tell me what it says
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.
daang
literally 2dy mrng it worked in my old prjct
but yes i did update it wihn i started out my new prjct
mayb cuz of tht
can I see your client variable definition, and the intents you used?
umm idk what u mean
lemme just send somn in https://discord.com/channels/267624335836053506/1233166567114674346
yes thats how imports work
I still need help doin this 😂
didnt you already get your question answered?
Nah
stop saying def. say function or method if its inside a class
I did ```py
from ..main import main
and got ``` from ..main import main
ImportError: attempted relative import with no known parent package```
hmm thats weird
ask the person who gave you that answer
i couldnt tell you ngl
didnt you tell me to do that? 😅
no??
Idk who did
I think someone suggested sys but It didnt work
or I didnt do it right
i said if you’re looking at proj root (like on the side where it says the parent folder name), you would do “from proj root.main import main”
ah
well idk what else to do then
<prefix>ping
not even close
its a function arg
yes because you need to use your bot prefix
whats the prefix for your bot?
so replace “<prefix>” with “!”
yes, obviously
opens fine
why are you looking at images??
it shows up correctly when you're on the official documentation
https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html#positional
can you rephrase?
@blazing beacon
how long did it take you to realise you replace “<prefix>” with your prefix in “<prefix>ping”?
@vapid parcel look at this shit 
user
yes because you do <prefix><command>
so !help
help is the name and ! is the prefix
just make commands that do stuff
i feel like you should be learning python
!res
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
learn python first ☝️
@vapid parcel come here rn and see this
stop saying def. say function or method if its in a class. be clear. this is like the fourth time i’ve told you this
its the fourth time i’ve said it and you’ve blown me off. just take my advice - you’re the one asking for help after all
psst, #discord-bots message
as much as you want them to do more basic programs first, we should still teach or direct them to specific concepts to learn as it becomes relevant to whatever they need help with
lowkey didnt know about the pins. thanks for the advice. i’ll be more lenient and liberal (idk if thats the word) with my advice 
then you should’ve heeded my advice long ago
rephrase
you can set the name of the command to be that, but that’s not advisable at all
then you cant run any commands
on_message would be necessary for this
i cant tell if you want slash commands or not
he said prefix call tho?
i dont think they strictly meant how would it be done via the commands extension, just how can it be done at all
(dpy can definitely handle responding to a bare slash)
the nice part of separating prefixes from the command name is that it's easier to change the prefix, like having a different prefix per guild as set by admin, or having multiple prefixes work for the same command
the design decisions were made like nearly a decade ago, when discord's slash commands didnt exist and there weren't dedicated bot accounts
how do people have custom prefixes linked to a database?
whos “he” 
oh danny
mf went through a whole story arc 😭 @blazing beacon @vapid parcel
i think the typical options are either passing an async function to command_prefix=, or overriding the get_prefix() method
which one is better / easier?
i dont wanna load 200 prefixes 😭🙏🏽
💀 he got development
not really sure, i guess it depends on preference / whichever you learn first
the latter is how i do it
skidded from a tutorial ofc
if you have a github account, you can go to https://gist.github.com/ and create a public or secret gist
for example, here's one of my gists:
https://gist.github.com/thegamecracks/0f9ab7ad3982e65ff4aa429acb39cc4e
async def get_prefix(bot, message):
return something_from_db
bot = commands.Bot(command_prefix=get_prefix, ...)``` ```py
class MyBot(commands.Bot):
def __init__(self):
super().__init__(command_prefix="not needed", ...)
async def get_prefix(self, message):
return something_from_db```
oh, like to suggest stuff to the library? sure, discussions would be fine for help-related things while issues would be suited for bug reports or feature requests
no those were just examples for dynamic prefixes
if you want something custom that doesn't look like <prefix><command>, on_message would be more suitable
you can still write commands at the same time if your on_message in a listener
bot = commands.Bot(...)
@bot.command()
async def add(ctx, x: int, y: int):
await ctx.send(f"{x} plus {y} is {x + y}.")
@bot.listen()
async def on_message(message):
if message.content == "!":
await message.channel.send("Hello! I'm a cool bot!")```
kind of, some of dpy's decorators will look at the function name
in the case of command() and listen(), they have a parameter to let you specify the name separately from the function's name
@bot.command(name="add")
async def my_add_command(ctx, x: int, y: int): ...
@bot.listen("on_message")
async def greet_when_prefix_is_sent(message): ...```
all function objects have a __name__ attribute which i assume discord.py uses if you don't provide a name in the decorator call ```py
def foo(): ...
foo.name
'foo'```
just dpy
wait so how would i have a default prefix and get a prefix from the db if they have a custom one? like how would the custom prefix stuff work
thats a keyword argument, so you assign something specifically to that. you can also have positional arguments, which are listed in order
you'll always need to query the database (or a cache) to know if it exists, e.g. ```py
async def get_prefix(bot, message):
if message.guild is None:
return DEFAULT_PREFIX
async with bot.pool.acquire() as conn:
prefix = await conn.fetchval("SELECT prefix FROM guild WHERE guild_id = $1", message.guild.id)
return prefix or DEFAULT_PREFIX```
ah ok i see. what about running commands with said prefix?
say i have two servers, one is assigned “!” only for their server and the other has “?” assigned only for their server. how do i run commands using the two for both servers?
i’ll just make 10 bot instances, each with different command prefixes 
every time a message is received, presumably excluding bots, it'll call your prefix function to determine what prefixes it should accept for that message
what do you want them for
oh okay 👌. how do i pass in a guild though? or does it get the guild automatically
yes. you can (pretty much) make any table in sql
why would you want to do that when discord has already done it for you
!vps
._.
!hosting
Using free hosting options like repl.it or Heroku for continuous 24/7 bot hosting is strongly discouraged.
Instead, opt for a virtual private server (VPS) or use your own spare hardware if you'd rather not pay for hosting.
See our Discord Bot Hosting Guide on our website that compares many hosting providers, both free and paid.
You may also use #965291480992321536 to discuss different discord bot hosting options.
you'll always have a message object, so you can get the guild from that
why would you want to make your own? just call the API for chat history
does it always give bot and message args?
can someone pls help with render
render uses python 3.11.9 and its having a problem with wheel in requirements.txt
i downgraded to 0.37.1 still got same error (in wheel)
why make your own db when you can just get the data from discord
"note: This error originates from a subprocess, and is likely not a problem with pip.
error: subprocess-exited-with-error"
not about #discord-bots , try #python-discussion instead
okay
hosting requires hardware, internet service, and electricity, so reputable services like digitalocean will charge you upfront to help pay the cost of running their business
#discord-bots message for a command_prefix function yes, if you're overriding get_prefix() then you'll get (self, message) which is basically the same
“hey. heres a bunch of hardware that will be perfect for your bot. all we ask is $2 a month-“
“replit.”
“wh- wha-?”
“replit.”

.bookmark
gas
lowkey need to sleep
cancer 13 gave me so much brain hurty owie owie that its quarter to 1 in the morning
2 ways:
- check in a custom deco
- check inside the function
dont watch videos
they lead you astray
take it from me

im going to bed
fuck my life 
How can I get the supports commands badge for my discord bot? It uses slash commands but there still seems to be no badge
I think you need to invite bot with application commands option checked?
if you add commands as a prefix it doesnt work
you need to use this ```py
@bot.tree.command(name="your_command_name", description="Your command description")
async def your_command(interaction: discord.Interaction):
# Your command logic here
await interaction.response.send_message("Command executed!")
the discription is what shows up in the slash menu
like this bot i made like ask would be the command name and "Ask me anything" will be the command discription]
:incoming_envelope: :ok_hand: applied timeout to @rancid citrus until <t:1714094349:f> (10 minutes) (reason: duplicates spam - sent 4 duplicate messages).
The <@&831776746206265384> have been alerted for review.
import discord
# Replace with the actual channel name (case-sensitive)
channel_name = "your_channel_name"
intents = discord.Intents.default()
intents.message_content = True # Needed for slash commands
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_ready():
guild = bot.get_guild(guild_id) # Replace with your guild ID if needed
for channel in guild.text_channels:
if channel.name == channel_name:
target_channel = channel
break
else:
print(f"Channel '{channel_name}' not found.")
return
# Use target_channel.send(...) to send messages
bot.run('your_bot_token')
@bot.event
async def on_message(message):
if message.author == bot.user: # Ignore bot's own messages
return
# Get the channel where the message was sent
channel = message.channel
# Get the member object representing the user who sent the message
member = message.author
# Check if the user is the server owner
if member == message.guild.owner:
print(f"{member.name} is the server owner.")
# Check if the user has the "Administrator" permission
if member.guild_permissions.administrator:
print(f"{member.name} has administrator permissions.")
point 3
without the bot you can just right click the user ans see the user id
bro put all your concerns in one message up im unable to keep up😂😂😂
No u can't
U cant unless its your own message
no it will come in the channel the best you can do is make the bot delete it as soon as the message shows up
what exactly are you planning on?
Check discord.py api docs it will have everyting that can be done
no its the user id of the user who wrote the triger message
This will send "hello" in the channel with that channel id
okay
guild means server
yes
server has many categories and catetories have many channels
example: this server/guild is called python in that we are in the "topical chat" category and this is the discord-bots text channel
yes there are many kinds of channels
this is a text channel
there is voice channel and threads
can i see your bots code im finding it difficult to understand wo it
Ive done it like this on my code as well. I did two bot projects. It shows up on one of em, but it doesnt show up in the other one
from commands.plzhelp import plzhelp
class PersistentViewBot(commands.Bot):
def __int__(self):
intents = discord.Intents.all()
super().__init__(command_prefix="/", intents=intents)
async def setup_hook(self) -> None:
self.add_view(ClaimTicketButtonView(timeout=None))
self.add_view(UnclaimTicketButtonView(timeout=None))
bot = PersistentViewBot(command_prefix="/", intents=discord.Intents.all())
This is my initializer 👆
and then one of the slash commands /plzhelp
@bot.tree.command(name="plzhelp", guild=GUILD, description="View a list of commands")
async def plzhelp_command(interaction: discord.Interaction): # Help Command
await plzhelp(interaction,
allowed_role_ids=allowed_role_ids,
command_logs_channel_id=command_logs_channel_id,
bot=bot)
Oh, idk it's always shown up for me
GGWP
In this cmd
if message.content.startswith('$test'):
await message.reply('This is a test', mention_author=True)
How could I make it run a function then send the message?
define the function and run it as you would normally run a function
Ok thats what I did but got a weird error so Js making sure I did it right
then tell us what u did
so we can point out the mistake
Its regarding a whole seperate thing, nothing to do with discord but ill send it
and tbh this is not a command
what? 💀
anyways here python if message.content.startswith('$gen'): gen() await message.reply('Video Generation has started, please ensure your Direct Messages are public so our bot can send you your result.', mention_author=True) this the cmd
this the error
File "C:\Users\liama\AppData\Roaming\Python\Python310\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "C:\Users\liama\Downloads\RedGen Files\Generator\bot.py", line 57, in on_message
gen()
File "C:\Users\liama\Downloads\RedGen Files\Generator\functions.py", line 31, in gen
File "C:\Users\liama\Downloads\RedGen Files\Generator\reddit\subreddit.py", line 24, in get_subreddit_threads
if settings.config["reddit"]["creds"]["2fa"]:
TypeError: There are no type variables left in dict['reddit']
gen() is defined in functions.py and imported from there to bot.py
well the error is telling you that the structure of your the dict from which you are accessing variables might differ
from what you are using
so you should check what the structure of the dict looks like
and then change your statement accordingly
that's what the error says
yea but idk what to do now
Im not great w python
well even I don't have any expericence with reddit and their api so can't help in this case
Is it an issue with the reddit gen stuff?
yes
damn. Bc the generation works just fine with main.py but the second I put the main func in a cmd it breaks
it occurs here File "C:\Users\liama\Downloads\RedGen Files\Generator\reddit\subreddit.py", line 24, in get_subreddit_threads if settings.config["reddit"]["creds"]["2fa"]:
line 24 in subreddit.py
well you can try creating a post in #1035199133436354600 and someone who knows about the issue might help
Hm I might be able to remove that, thats for when I had my reddit 2fa on but now that I dont I can prob remove it
I think the problem might be since its discord when the script tries to print to console discord doesnt know what to do
i doubt that's the issue
alr then idk 😂
I just dont understand how when I run main.py it runs the main() function, now Im running the main function in another file and its breaking
@turbid condor Is there a specific way I need to call the function?
Like await main() ???
idfk 😭
nope
well shi
await is used for coroutines
are you avaliable to vc? If you wouldnt mind I can screenshare and maybe you could better help me here
and this function you are using isn't a coro
well sry can't i'm also occupied with my stuff
alr nw
not you
a few slight corrections
@bot.listen('on_message')
async def message_listener(msg):
if msg.content == "!":
await msg.channel.send(...)
in any case i think you should consider using commands an example is something like this
@bot.command()
async def command_name(ctx, arg1=None, arg2=None):
await ctx.send(...)
General question: I'm writing my own bot from scratch, but I'm largely confused on why the docs & examples for discord.py don't really use a class that inherits from discord.bot
Essentially I want a bot that does actions when messages are sent, deleted, or edited, and has custom command support. The docs & examples all basically never use a discord.bot-inherited class, and yet they do show a lot of examples of using a class that inherits from commands.Cog
I'm just at a general loss as to how to structure the bot
inheriting from commands.Cog is because you wanna create a Cog class, that's required because you want the functionalities of a Cog class and it can load properly with bot.add_cog
while, you dont necessarily need to inherit the commands.Bot class, because rarely would you want to override methods or modify the functionality of a Bot class.
For instance, this inherits the commands.Bot because they want to use and override the Bot.setup_hook, it's a necessary step. But you dont really have to do it if you dont need it.
examples/advanced_startup.py line 18
class CustomBot(commands.Bot):```
Oh I see, so you'd only create this child class to explicitly replace the built-in class variables & methods, but otherwise there isn't any benefit to doing so
yea, or if you want to add attributes or whatever, since the convenience of the bot instance is you have access to it in pretty much most scope in dpy
which act as a global variable
!start
Wildcard imports are import statements in the form from <module_name> import *. What imports like these do is that they import everything [1] from the module into the current module's namespace [2]. This allows you to use names defined in the imported module without prefixing the module's name.
Example:
>>> from math import *
>>> sin(pi / 2)
1.0
This is discouraged, for various reasons:
Example:
>>> from custom_sin import sin
>>> from math import *
>>> sin(pi / 2) # uses sin from math rather than your custom sin
- Potential namespace collision. Names defined from a previous import might get shadowed by a wildcard import.
- Causes ambiguity. From the example, it is unclear which
sinfunction is actually being used. From the Zen of Python [3]:Explicit is better than implicit. - Makes import order significant, which they shouldn't. Certain IDE's
sort importfunctionality may end up breaking code due to namespace collision.
How should you import?
- Import the module under the module's namespace (Only import the name of the module, and names defined in the module can be used by prefixing the module's name)
>>> import math
>>> math.sin(math.pi / 2)
- Explicitly import certain names from the module
>>> from math import sin, pi
>>> sin(pi / 2)
Conclusion: Namespaces are one honking great idea -- let's do more of those! [3]
[1] If the module defines the variable __all__, the names defined in __all__ will get imported by the wildcard import, otherwise all the names in the module get imported (except for names with a leading underscore)
[2] Namespaces and scopes
[3] Zen of Python
bro what are you trying to do
idk

Ikr it's so good I bought lifetime premium
Yeah, it's equivalent to
return None
"comically large spoon" feeder
That's me 😎
Spoon(size="comically large").feed(User(python_knowledge_level=PythonKnowledgeLevel.noob))
Comically large is so large I can't even convert it to integer
float("inf") 😔
why does that lowkey make sense
the whole point of making a message listener is for you to rename the function while still keeping the same event
in .event, the name of the function has to be the event you're watching for
but in .listen(), you can add the name of the event in the brackets and then rename the function itself
@bot.listen('on_message')
async def my_very_cool_message_listener(message):
pass```
it's an event
and yes its dpy built in
rephrase 
you lost me
i answered your question
events are only for dpy
no, they're unique to every channel
you need to check the server before the channel
there is a .fetch_channel() function, now that i think about it
theres too many
what city shuts off all the electricity at a certain time?? 
doesnt mean you need to turn off all the electricity
they're public info. your user ID is: 1231805530008457246
fair enough 
hey guys can anyone hel p me?
im tryna think of what i can use to make this work
basically i need to read a line of text from the output, grab a specific line from that output, and then store that line into a variable to be used later on in the process
Confidence Threshold:
31
0%
100%
{
"predictions": [
{
"x": 115.5,
"y": 227,
"width": 79,
"height": 88,
"confidence": 0.374,
"class": "rotten",
"points": [```
for example, this is an output. I need to find "confidence": 0.374 and store it into a variable to be used later
thing is, i have no clue how to do it in one execution
yes
the thing i sent is from roboflow
im using machine image learning and i need to figure out how to store its results
yep pretty much
lol im a highschooler and its for a class im taking
#data-science-and-ml ⬅️ you probably misclicked
oh sorry.
this is a discord bot help channel
its alright. you'll get better help over there is what im saying 
that got me confused
are those libraries?
im not working with a database rn tho, that's supposed to be placed on RPI
raspberry pi
thanks man
have a good one
not for here ❌
channel literally says discord bots, not ML or AI
maybe. can this conversation move to #data-science-and-ml? definitely. should you go there to talk about this stuff? yes.
yes
this channel has an ID of: 343944376055103488
yes the discord api works on ids only.
you have to invite the bot
otherwise imagine that random bots could be joining your server and nuking it
I mean if you're the server owner yes
or have admin permission
but you cannot make the bot join any random server. it has to be a server where you have the permissions to add a bot or you are the server owner
Traceback (most recent call last):
File "/home/ubuntu/Book-Verse/main.py", line 110, in <module>
main()
File "/home/ubuntu/Book-Verse/main.py", line 106, in main
BookVerse().run()
File "/home/ubuntu/Book-Verse/main.py", line 102, in run
super().run(TOKEN)
File "/usr/local/lib/python3.10/dist-packages/disnake/client.py", line 1126, in run
return future.result()
File "/usr/local/lib/python3.10/dist-packages/disnake/client.py", line 1105, in runner
await self.start(*args, **kwargs)
File "/home/ubuntu/Book-Verse/main.py", line 99, in start
await super().start(*args, **kwargs)
File "/usr/local/lib/python3.10/dist-packages/disnake/client.py", line 1067, in start
await self.connect(
File "/usr/local/lib/python3.10/dist-packages/disnake/shard.py", line 501, in connect
raise item.error
File "/usr/local/lib/python3.10/dist-packages/disnake/shard.py", line 164, in worker
await self.ws.poll_event()
File "/usr/local/lib/python3.10/dist-packages/disnake/gateway.py", line 709, in poll_event
raise msg.data
File "/usr/local/lib/python3.10/dist-packages/aiohttp/client_ws.py", line 244, in receive
msg = await self._reader.read()
File "/usr/local/lib/python3.10/dist-packages/aiohttp/streams.py", line 681, in read
return await super().read()
File "/usr/local/lib/python3.10/dist-packages/aiohttp/streams.py", line 640, in read
await self._waiter
File "/usr/local/lib/python3.10/dist-packages/aiohttp/http_websocket.py", line 314, in feed_data
return self._feed_data(data)
File "/usr/local/lib/python3.10/dist-packages/aiohttp/http_websocket.py", line 321, in _feed_data
for fin, opcode, payload, compressed in self.parse_frame(data):
File "/usr/local/lib/python3.10/dist-packages/aiohttp/http_websocket.py", line 486, in parse_frame
raise WebSocketError(
aiohttp.http_websocket.WebSocketError: Received fragmented control frame```
what causes this?
do you want to keep the memos separate for every server or do you wanna make it common
they will never do that
disnake user 👁️👁️
human npcs are counted as bots maybe it's true
in each server:
- each person uses their own memo channel
- each person uses the same memo channel
how did you actually understand what he was asking😭
why don't you use a database then
he's brought me down to his level of brainrot 😭
database important yes store show momes 
i should put on my resume i can speak some cancel13
moms
mems
bot need db always store channel history read message read channel history. no db test channel db, bad not good
it's not as efficient. you'll probably rate-limit yourself
RATELIMITING
If your bot makes too many requests to the discord API, then discord will temporarily (for some time) ban your IP address from accessing the API.
Every history fetch will make many requests to the API.
Then you will have to filter all those messages later which is a very tedious (hard and unnecessary) job.
Also, this will make your bot very slow until your IP gets banned.
if message.author.bot:
#This means sender is a bot```
no use db channel. bad practice ❌
use db. we no use channel db it only db no channel db or db channel
api call more expensive than cache call. they is use cache call which get info from memory. too many api call go bankrupt
(i can speak cancel13)
I can speak cancel√169
good
use sqlite3
or an online noSQL db
❌
wrong link nvm

library
!d sqlite3 | but learn this first
Source code: Lib/sqlite3/
SQLite is a C library that provides a lightweight disk-based database that doesn’t require a separate server process and allows accessing the database using a nonstandard variant of the SQL query language. Some applications can use SQLite for internal data storage. It’s also possible to prototype an application using SQLite and then port the code to a larger database such as PostgreSQL or Oracle.
The sqlite3 module was written by Gerhard Häring. It provides an SQL interface compliant with the DB-API 2.0 specification described by PEP 249, and requires SQLite 3.7.15 or newer.
This document includes four main sections:
but the elephant 😭
no elephant. sqlite
"maybe this elephant tell us secrets of store db"
can't make this shit up
!ot
Please read our off-topic etiquette before participating in conversations.
this guys tweaking @upbeat otter
I don't belong to the human race anymore so don't ping me 😭
bros fully merged with the elephant 😭🙏
what secrets has it told you

idk 😭
let him be 😭
alright 

!ot
Please read our off-topic etiquette before participating in conversations.
You should have ran and hosted it in the dream too that way wouldn't have to worry after waking up
Imagination is a wild thing you could have imagined it all
lowkey imagined texting my friends, they gave responses and then freaked out when i looked down at my hands and there was no phone to text them back with
See imagination is wild
abc refers to Abstract Base Class, it's an OOP concept that defines common attr/methods that are inherited by multiple different classes. but it's not meant to be used directly, Messageable is an abstract class. Usable classes like DMChannel, TextChannel, etc inherits Messageable class
i kinda make it in simple terms but you get the idea
import discord
from discord.ext import commands
import bot_token
import details
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="!", intents=intents)
@bot.event
async def on_ready():
print("bot is READY")
@bot.event
async def setup_hook():
cmd = await bot.tree.sync()
print(f"loaded {len(cmd)} commands")
@bot.event
async def on_message(message):
if message.author.id == details.my_id and "You received 35 Pokécoins!" in message.content:
await message.add_reaction(details.new_mon)
@bot.command()
async def hello(ctx):
await ctx.send("hello")
bot.run(bot_token.TOKEN)``` Guys my !hello doesn't work
@viscid hornet
I've seen u helping a lot of ppl can you help me too sorry for the ping
The on_message works here but not !hello
im biking rn
you need to add await bot.process_commands(message) at the end of your event, outside the if condition
or you can change @bot.event to @bot.listen()
Ahha ty mate
How do I stop this discord timeout thingy? WARNING discord.gateway Shard ID None heartbeat blocked for more than 60 seconds.
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.
What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:
import discord
# Bunch of bot code
async def ping(ctx):
await ctx.send("Pong!")
What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.
async libraries
- The standard async library -
asyncio - Asynchronous web requests -
aiohttp - Talking to PostgreSQL asynchronously -
asyncpg - MongoDB interactions asynchronously -
motor - Check out this list for even more!
my return message is awating but the code isnt, idk if I could run an await w it
wait no nevermind, nothing in the command is awaited
How can I detect when a message is sent if the id of the channel is ...
Can you share the code?
!pastebin
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.
What do you exactly want to do?
Like I said ive already figure it out. thanks
!code | just to lyk
and your issue is that when a message is sent in a DM, there is no guild, so .guild returns None
and None doesn't have any attributes, so None.id isnt a real thing
and therefore it raises errors
doesnt look like anything is wrong with it
use your own pc
just use a .env file or read it from a .txt file
i use a txt file since it doesnt add to the imports
encryption in this case doesnt really mean anything. just dont share your token directly and you have nothing to worry about
format your code like this
```py
your code here
no, putting your token in .env doesn't "encrypt" it
the reason we put secrets in .envs is because it's usually .gitignored, so it doesn't get pushed to version control, and also, when developing, you can view all your secrets in one place easily.
but the most important reason to use environment variables is to be 12FA: avoid putting configuration in code (and by extension, secrets) so you can deploy the same code in multiple environments with only configuration changes
just good practice stuff
i said “or” for a reason
do either
if not message.guild:
...```
!code | also use syntax highlighting
ohh alr then 
Can someone give me a high-level explanation on the differences between discord.Client and discord.ext.commands.bot ? I'm having trouble understanding when to use one over the other
ok so Bot is like Client v2. it allows you to use cogs, remove spaghetti code, has more features
lemme get a list for you
So most if not all the time I would be better off using bot over client
Maybe. It definitely leaves room to expand from
yes, unless you're not doing any command stuff and you really just want a quick and simple client
Who can help me i have got a problem the error is too long i cant send here come MP
Anyone know why this isn't editing the message?
import discord
from discord import ui, ButtonStyle, message
class editMessage(ui.Button):
def __init__(self):
super().__init__(
label = "Edit message!",
style = ButtonStyle.green,
)
async def callback(self, interaction: ...):
await interaction.response.edit(content = "Edited message")
This is bot.py code:
@bot.command(name="buttontest2")
async def buttontest2(ctx):
button = buttons.editMessage()
view = discord.ui.View()
view.add_item(item=button)
await ctx.send("Testing the edit function", view=view)
.edit_message
hi
Oh lol

Thanks lmao
yo?
hittin me with the "This interaction failed"
i dont take dms
!paste | put the error here
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.
on discord or in code?
and after i put the error what i do ?
discord
send it here
that's weird. it should be a valid response
!code | also syntax highlighting 🗣️
hm
literally tells you your error in the traceback
lemme test it out
where is traceback ?
the thing you just sent me 
Line 5 man
Well yes but I don't know how to correct it
"permission denied" yes but where's the error 
And why is permission denied ?
🤷
Print the path you're trying to use and print the current working directory's path
See whether the path you're trying to use is in fact under the current working directory
I mean, I also have the suspicion that your cwd is C:\Windows\System32 because of the specific circumstance of using Python from MS Store
Either check whether the guild attribute gives None or the channel type is dm
just use whatever it returns to determine if its a dm or not
code works fine.
did you forget to save?
No
I'm using replit it autosaves lol
test it again
k
not replit 
If it equals "private" or discord.ChannelType.private
Ion got a good enough pc to use vscode lol
or anything really
!d discord.ChannelType.private
A private text channel. Also called a direct message.
@wide plaza You should refer to the documentations for things like this
k

how did it not tell you there was an indentation error? 😭

:D
you can edit anything
!d discord.Message.edit
await edit(*, content=..., embed=..., embeds=..., attachments=..., suppress=False, delete_after=None, allowed_mentions=..., view=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the message.
The content must be able to be transformed into a string via `str(content)`.
Changed in version 1.3: The `suppress` keyword-only parameter was added.
Changed in version 2.0: Edits are no longer in-place, the newly edited message is returned instead.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError) instead of `InvalidArgument`.
anything there can be edited
Why would it when everything is indented correctly syntactically although not semantically
or at least a multiple args error, because self is outside a class

It's just a parameter
ohhh
That function is probably never used in their program
i see why it was saying there was no response
can I make multiple buttons in one class as well?
limit is 25
either: ```py
class MyView(ui.View):
...
@ui.button(button 1 kwargs)
...
@ui.button(button 2 kwargs)
...```
Ty!
or ```py
class MyButton1(ui.Button):
...
class MyButton2(ui.Button):
...
class MyView(ui.View):
def init(self):
self.add_item(MyButton1())
self.add_item(MyButton2())```

i've used the second example for paginators because if there's only 1 page, you cant use attributes in the decorators so you cant set the last buttons to be disabled conditionally (if that makes sense)
I see
so you cant do something like this ```py
class MyView(ui.View):
def init(self):
super().init()
self.my_var = 5
@ui.button(label = self.my_var, ...)
async def ...(...):
...
why are you teaching basic python here
😭
i didnt know it 
you cant send commands in groups because bots dont take friend requests or interact with links
😭bro
not joking asw 😭
well that's fine then but how tf do you work with OOPs then 😭
also you're not comparing it to anything. you're most likely doing py print(discord.ChannelType.private)
and wondering why it doesn't magically make the comparison you want
a bot will never join a group
but why group no command type compare?
wouldn't you do that in the function where u pass the pages to it?
ok Asher is here 😳
stop being C13 😭
for me, i pass the pages to the view 
3rd time py if message.guild: # something if in a server, None if in dm
and u can still disable it inside the init no? checking length of pages
if isinstance(message.channel.type, discord.ChannelType.private):
#Message is in dm
sup
all good wby
F, good luck. you're in uni?
yeah
ic
oh yeah. my dumbass just made them separate buttons and added them to the view with a disabled kwarg instead of accessing them through self.children 
i am pretty sure u can access it via self.button_decorated_method.disabled as well
!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.
no like in the view __init__ where i pass the data: py class MyPaginator: def __init__(self, pages, ...): self.pages = pages if len(self.pages) == 1: for i in [3, 4]: self.children[i].disabled = True
so if there's only 1 page, it disables the buttons to move forward
hmm no i was talking about accessing the button via its decorated method name instead of children
class A:
def __init__(self):
self.foo.disabled = True
@discord.ui.button()
async def foo(self, inter, button): ...
fuck off
no way its that easy
i think it is? been a while since i have used dpy noe
what the hell did you write 😭
yeah their button decorator returns a button object
thank you and fuck you for this knowledge 🙏
;-;
disabling children on purpose is wild
same 😔it's not exciting anymore as it once was
gotta stop people from going to page 4 out of 3
bro your humour is kinda ded rn 😭
it was all i could come up with 😭 🙏
just cycle them back lol % time to bring out the modulo
or just don't make pages
spam embeds
?
!d discord.Embed
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
x == y Checks if two embeds are equal.
New in version 2.0...
check bot cmds
embed = discord.Embed( description="Do not catch this Pokemon before the timer ends", colour="0x00ff00")
await message.channel.send(embed= embed)```
Remove the quotation marks around the color value
Also I believe every embed must have a title but I'm not 100% sure
Come on you just copy pasted it
What?
You just copy pasted the exact thing
"thing" is not so "exact"
Pasted what?
Heh?
Are you coding at pjone!
Ye ty
?
Yessir
Damn
..
Remember meh?
yes
I thought u would ignore me
should have
Bruh
Anyway wht are u doing currently?
nothing
Do you know c#?
yes?
C sharp
i know what c# is
i had to learn it for school
U said "yes?" So i thought
Ic how much time did it took you
took me to what
To learn c sharp
. .....
idk i knew few languages before so it was pretty easy
i wouldnt take it as granted time to learn
Still....
idk i had like 2h/week of c# lessons and it took 2months to learn all basics?
so about 16h
Ic..
Oh and also i had a question are u graduated??
no not yet
@viscid hornet if you don't need me for something important, do not fucking ping me to this server. It's really annoying when you ping me 3 times in a row for something I don't care abt.
Instead of making fun of someone for not understanding how to do something, maybe help them understand, instead of pinging me n making fun of them.
You could maybe not be a dick, and maybe HELP them and teach them something, sounds shocking.. but you should try it!! 😁
my brother in christ, what do you think i’ve been trying to do ☠️
alr nps wont happen again
Clearly not man, not to be a dick but dude, you are "helping" but when they don't understand, you make fun of them.
If you don't wanna help anymore, just move on, let someone else help.
Im sorry but its kinda annoying, we all start somewhere man.
yo is there a channel for people looking for jobs? looking for someone with experience in python (flask) and frontend development
theres #career-advice but i think this is
!rule 9
oh damn 😭
nah man. guys not listening to me to the point whee my advice dont mean anything anymore. whats the point of trying to help someone if they wont listen?
yeah ima lowkey do this more. im so done with that guy 
also, I wanna show you battle ship
we have battle ship inside of discord 😭
go outside 😭😭
this mf learned pillow for battleships
make chess next 🤑
already have
The irony of this statement coming from you is insane
actually on the topic of help, #1233479221985284186 🙏🏽
- no you wont be ratelimited because its a call to cache.
- you cant send a message with a custom id
- you get a message link through the context menu somewhere near replies. to format it, do: https://discord.com/channels/<guild_id>/<channel_id>/<message_id>
- you can check a message’s attachments through its attributes i think
Discord is the easiest way to communicate over voice, video, and text. Chat, hang out, and stay close with your friends and communities.
!d discord.Message.attachments
A list of attachments given to a message. If Intents.message_content is not enabled this will always be an empty list unless the bot is mentioned or the message is a direct message.
there you go
you can then check the file extension to see if its an image file
send a message with the same attachment or edit the message with a new attachment?
just get the attachment, store it as a variable and send a new message with said attachments
i will test it
you need the ID to make the url so you already have it
anyone know how i can make a command that sends multiple images and text ? i now use "file: file = discord.File". But i can only make it send 1 image that way
yeah but i dont know how it works, i now have this code for it:
bot.group()
async def viper_haven(ctx):
file: File = discord.File(r'C:\Users\Luuk\Pictures\botniet.png', filename="bot.png")
embed = discord.Embed()
embed.set_image(url="attachment://bot.png")
await ctx.send(embed=embed, file=file)```
It's a matter of doing more discord.File instantiations and passing them all as a list to the files parameter
!d discord.ext.commands.Context.send
oh wait i forgot the bot is offline
there's a files kwarg that takes a list of File objects
so py await ctx.send(files = [File1, File2, File3])
so i have to make for every image a different discord.file and than at the bottom `await ctx.send(files = [File1, File2, File3])
yes
ahhh okay, thank you
and the await ctx.send(embed=embed, file=file) should still be in the code
Bruh
!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.
i now have this:
async def cypher_ascend_a(ctx):
file: File = discord.File(r'C:\Users\Luuk\Downloads\cypher ascend-a one-way.png', filename="cypher ascend-a one-way.png")
embed = discord.Embed()
file: File = discord.File(r'C:\Users\Luuk\Downloads\cypher A site ascend.png', filename="cypher A site ascend.png")
embed = discord.Embed()
embed.set_image(url="attachment://cypher ascend-a one-way.png")
embed.set_image(url="attachment://cypher A site ascend.png")
await ctx.send('Aline yourself under this line in the generator and aim at the spike in the sky to get this heaven one-way')
await ctx.send(files = [File1, File2, File3])
await ctx.send(embed=embed, file=file)```
it doenst take the images on the await ctx.send(files = ['cypher ascend-a one-way.png','cypher A site ascend.png' ]) line
you have to convert them to file objects
!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) 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) is also needed to retrieve message history.
Changed in version 2.0: The `reason` keyword-only parameter was added.
Examples
Deleting bot’s messages...
you do realise you could’ve just sent it as an actual link i can click on, right?
why do you have a bunch of “source_” variables at the top? you know you can just use whatever you’re assigning to them to skip the unnecessary extra step
an embed shouldnt matter
cleaner code >> working code
how do i convert them to file objects
lemme check for you 👌
discord.File(“your file path”)
!d discord.File
class discord.File(fp, filename=None, *, spoiler=..., description=None)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send) for sending file objects.
Note
File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send)s.
what is suppost to be on spoiler and description
i think description is for if you hover the mouse over the picture and spoiler is just this
(mods its a cat photo)
you can leave them blank, it doesnt change anything
what are you doing? 
async def cypher_ascend_a(ctx):
class discord.File(r'C:\Users\Luuk\Pictures\Cypher setup\ascend\A site\cypher A site ascend.png', filename="cypher ascend-a one-way.png", *, spoiler=..., description=None)
file: File = discord.File(r'C:\Users\Luuk\Pictures\Cypher setup\ascend\A site\cypher A site ascend.png', filename="cypher ascend-a one-way.png")
embed = discord.Embed()
file: File = discord.File(r'C:\Users\Luuk\Pictures\Cypher setup\ascend\A site\cypher ascend-a one-way.png', filename="cypher A site ascend.png")
embed = discord.Embed()
embed.set_image(url="attachment://cypher ascend-a one-way.png")
embed.set_image(url="attachment://cypher A site ascend.png")
files
await ctx.send('Aline yourself under this line in the generator and aim at the spike in the sky to get this heaven one-way')
await ctx.send(files=['cypher ascend-a one-way.png', 'cypher A site ascend.png'])
await ctx.send(embed=embed, file=file)```
i have this now but it says class discord.File(r'C:\Users\Luuk\Pictures\Cypher setup\ascend\A site\cypher A site ascend.png', filename="cypher ascend-a one-way.png", *, spoiler=..., description=None) ^ SyntaxError: invalid syntax
dont copy and paste lmao
just put the filename in. the lib will handle the rest
and go from your parent folder using “/“ as a separator


so this discord.File('C:/Users/Luuk/Pictures/Cypher setup/ascend/A site/cypher A site ascend.png')

from your parent folder
(the “./“ is optional)
“./ascend/A site/cyper A site ascend.png”
??

So if i put ./ascend/A site/cypher A site ascend.png” it would be good
depending on your parent folder, yes
Just get neuralink and use a real human 
you need to learn how to do do machine learning stuff for this. it's outside the scope of this channel
easiest way is to just hook it up to chatgpt API
it is currently impossible to make machines think like humans
the best we can do is natural language models that pretend to talk like humans
you are most definitely not going to make the first human intelligence AI model
scientists with large data centers still have not cracked the problem
your best option is to either make your own language model and host it yourself, or use chatgpt's
most people just use chatgpt api
in c13 we trust
not sure what you're saying
you can tell that to chatgpt too, it will pretend for you
only for the right purposes
imagine dispatching gets replaced by AI and they hit you with that “ if you have a medical emergency, press 1. any queries about the NHS, press 2. etc”
import discord
fp = "asset/image/image.png"
discord.File(fp)
with open(fp, "rb") as file:
pngbytes = file.read()
discord.File(pngbytes)
hello. i'm trying to create a File object from bytes, but this gives me an error. anyone know a fix?
File ~\.venv\Lib\site-packages\discord\file.py:97, in File.__init__(self, fp, filename, spoiler, description)
95 self._owner = False
96 else:
---> 97 self.fp = open(fp, 'rb')
98 self._original_pos = 0
99 self._owner = True
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte
discord.File can only take a file-like object or a filepath, so in that example the simpler approach would be: py file = discord.File("asset/image/image.png") if you only have just the raw bytes, you can use an in-memory file object: ```py
import io
f = io.BytesIO(raw_bytes)
file = discord.File(f)```
yea, turns out i completely missed the second line of notes lmao
thanks
I don't think ephemeral msg can be edited
You sure?
Not sure
I think i had seen it in some bot
But u can edit it via message.edit
Using pagination in button response
Since message is a Message object
I cannot do that it's not discord.Message as far I've tested
Or maybe I'm wrong
!d discord.InteractionResponse.send_message
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, silent=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
!d discord.Interaction.edit_original_response
await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the original interaction response message.
This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit) in case you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if the message sent was ephemeral.
after using send_message(), the above method will be able to edit it
I see
and if you do need a message object, Interaction.original_response() is required to retrieve it since send_message() returns nothing
oh derp, forgot that wasnt allowed for ephemeral messages
@turbid condor
If u are trying to edit the message with which button are attached then u can use edit_message instead of send_message
wtf is with it showing (edited) 4 times
!d discord.InteractionResponse.edit_message
await edit_message(*, content=..., embed=..., embeds=..., attachments=..., view=..., allowed_mentions=..., delete_after=None, suppress_embeds=...)```
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.
Ignore it
||not official client don't mind me|| @hushed galleon
But this can be only used for cases where working is similar to pagination
This didn't work
What error it gave?
I'm passing original 1st button's interaction into Pagination instance
oh ya for a paginator, you'd have a fresh interaction with each button click, edit_message should be valid with that
I don't remember let me check again
Nah i use same for every button 🤣
Except stop button
All 4 buttons has same response
Well then that might be your issue
Yea my code is bit too complicated ig
Since an interaction can only be responded to once
Instead of await self.interaction... use await interaction.response.edit_message()
That should work
I should try out this too
Recheck the message above i forgot to add response
interaction.response.edit_message()
Okay
I told u to recheck the message
Oh yea this works too
My bad
Any idea why when I hosted my bot (for personal use) and I try to use any of the slash commands a This interaction failed error raises (in discord)? I have to say that, the commands are loaded correctly and the prefix commands work perfectly, the issue is only with the slash commands after the hosting.
Send the system logs
you probably not responding within 3 secs
defer the interaction
the error??
All we know from that message is that your command errors, could you provide more context and exceptions?
I was starting with @bot.tree.command etc., the bot started but doing "/ciao" doesn't work
did you sync?
why do people not even post their errors and expect help 💀
@bot.tree.command(name='ciao', description='Says hello to a mentioned user.')
async def ciao(ctx: commands.Context, user: discord.Member):
await ctx.send(f"Ciao {user.display_name}!")
3 people have asked u if it raised an error
well this command won't even work you are using a prefix command as an app_command that's not how it works
Oh
Discord.py allows for several ways to create/define application commands within it’s codebases. In this page we’ll go through several of these.
main.py```py
import env,discord
from discord.ext import commands
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='c!', intents=intents)
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name}')
@bot.command()
async def ping(ctx):
await ctx.send('Pong!')
bot.run(env.DISCORD_API_TOKEN)```
how to arrange commands like ping into separate files inside a folder called 'commands' to avoid clutter in main.py
im trying
import env,discord,os
from discord.ext import commands
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='c!', intents=intents)
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name}')
async def load_extensions():
for filename in os.listdir('./coms'):
if filename.endswith('.py') and filename != '__init__.py':
extension = f'commands.{filename[:-3]}'
await bot.load_extension(extension)
bot.run(env.DISCORD_API_TOKEN)```
and inside the folder called coms i created ping.py and wrote this:
from discord.ext import commands
class Ping(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def ping(self, ctx):
await ctx.send('Pong!')
def setup(bot):
bot.add_cog(Ping(bot))
didn't work
2024-04-27 13:49:32 INFO discord.client logging in using static token
2024-04-27 13:49:34 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: f1f239b070f2caaf9a2dbdd5016ed560).
Logged in as Catmium
2024-04-27 13:49:41 ERROR discord.ext.commands.bot Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "ping" is not found```
did you load the extension
ohh you never called your load extensions function
how to?
im guessing you know how functions work
where do i write load_extensions()
you need to call() it
make a new event and call it setup_hook then put it in there
on_ready can be called multiple times so you dont wanna be reloading your extensions twice or thrice
will this work?
it will, but 2 things:
- read what i said earlier
- it’ll raise errors because its an async function
async functions are awaited
so “await my_func()”
/home/cosmo/Documents/Catmium/main.py:16: RuntimeWarning: coroutine 'load_extensions' was never awaited
load_extensions()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
my bot is still running
yep. point 2
with no extensions loaded so none of your commands work
☝️
(read what im saying lmao)
yes you're texting before i'm done sending images lol
ohh my bad then
@bot.event
async def setup_hook():
load_extensions()
this?
@viscid hornet
bro what happened did you die
RIP bro 2024-2024
i miss my wife
yes
but remember the second thing
i was gone for 2 minutes 😭🙏🏽
/home/cosmo/Documents/Catmium/main.py:19: RuntimeWarning: coroutine 'load_extensions' was never awaited
load_extensions()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
2024-04-27 14:07:50 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: f78bae503fe6f8d8cf89d8ca5c3035e8).
Logged in as Catmium```
i tried await load_extensions but it just crashed
says it was never awaited
that shouldnt be related to your error though
try it again
I'm running into a problem with a quiz bot I'm making when it lasts more than 15 minutes. The entire game chains off the first interaction of calling the command to start it, but I've found out that the token of this interaction gets expired since all the commands begin to 401. I think a way around this would be setting a channel webhook instead, but I want it to be handled automatically by the bot. Is there a way to create channel webhooks via discord.py?
no idea
import env,discord,os
from discord.ext import commands
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='c!', intents=intents)
async def load_extensions():
for filename in os.listdir('./commands'):
if filename.endswith('.py') and filename != '__init__.py':
extension = f'commands.{filename[:-3]}'
await bot.load_extension(extension)
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name}')
@bot.event
async def setup_hook():
await load_extensions()
bot.run(env.DISCORD_API_TOKEN)
from discord.ext import commands
class Ping(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def ping(self, ctx):
await ctx.send('Pong!')
def setup(bot):
bot.add_cog(Ping(bot))
this is the ping.py inside commands folder
ah
the setup func should be async
mywah?
and the adding cog should be awaited
no probs
hey um are you a guy or a girl?
what is your name?
just call me axo lmao
ok axo ! your pokemon adventure is about to unfold! a world of dreams and adventures await!
but if you have to know, its amelia
na it's okay
ooh yay
!ot kinda off topic now
Please read our off-topic etiquette before participating in conversations.
uw
If my embed length crosses the limit of 6000 characters, when will the error raise, when I change for example the description and it crosses that limit or when I attempt to send the embed?

when you send it
I think
need to check the source code
or just try it
I looked at the src and yeah, most likely it will error when I attempt sending it
the checks are preformed in interaction_message_response_params method
which is called when sending the message via response.send_message
this one is weird though
self refers to a ChannelSelect
when you send it
“can i enable this?” “no.” “why?” “no.”
😭 🙏

type ignore my beloved 
frfr (idk what that is)
its used to ignore type warnings from your typechecker
@viscid hornet Apparently everything works
so that type warning/error was useless :kekw:
guys, gitignore isn't ignoring the pycache inside commands folde
try just __pycache__/ 
didn't work
weird
how about commands/__pycache__/
I don't really know, you would need to ask in #python-discussion ig 
didn't work
k
as leo rightfully said, typehints do fuck all at runtime 
just do __pycache__ and it'll ignore every pycache folder in your repo
moved to #python-discussion
doesnt work
ok skill issue
thats cursed
allow me to post images then i'll move

Im not a mod 😭
skill issue
I mean why does bro have to do that to gitignore 😭
that is not your problem
wait ray whats that wet cat emoji
i saw one posted here the other day
holdup
ok sorry 💀
YEAH THAT

ew background
nitro flex
i’ll fix it later
gift me next time
💀
not happening 
looks like a fake png now 😭
it doesn't show the "Untracked" sign, as it does "M", so I'm assuming you have already pushed it to github once. Now you cannot gitignore it. The solution would be to delete that folder (and add __pycache__ in gitignore)
thank you for the info! I didn't know this
how to add choices to a slash command?
you can either use a literal typehint, typehint to an enum or add choices in a deco
Want users to select something from a hard coded list?
Use "choices", three different ways to do it. Need channels, roles, members, etc? See ?tag slash types.
View Documentation (has examples)
Option 0: True & False
Need True and False as choices? Simply type the argument with bool and discord will handle it.```py
@...command(...)
async def testephemeral(
interaction: Interaction,
ephemeral: bool
):
print(ephemeral, type(ephemeral))
will print either True or False
**Option 1: typing.Literal**
This is the easiest.```py
from typing import Literal
@...command(...)
async def choosecolour(
interaction: Interaction,
colour: Literal["Red", "Green", "Blue"]
):
print(colour) # will print either "Red", "Green" or "Blue"
Option 2: @app_commands.choices```py
from discord import app_commands
@...command(...)
name is shown to the user and value is returned to you.
value can be of type str, int or float.
@app_commands.choices(
colour=[ # param name
app_commands.Choice(name="Red", value="red"),
app_commands.Choice(name="Green", value="green"),
app_commands.Choice(name="Blue", value="blue")
]
)
async def choosecolour(
interaction: Interaction,
colour: Choice[str] # [str] denotes the value type, not required.
):
print(colour) # will print the chosen Choice obj
colour.name for the name and colour.value for the value you set
**Option 3: enum**```py
from enum import Enum
class Colours(Enum):
# format: name - value
Red = "red"
Green = "green"
Blue = "blue"
@...command(...)
async def choosecolour(
interaction: Interaction,
colour: Colours
):
print(colour) # will print our enum. in this case, the Colour class above
# colour.name for the name and colour.value for the value you set
Options 0, 1 and 3 also work for hybrid commands.
Choice obj cannot be set as default.
this is taken from the dpy server
i've tried the second one and it worked! but then i checked the terminal and there was this;
interaction.response.send_message("test")
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```
code:
```@tree.command(
name="welcome",
description="Enable welcoming for new user"
)
@app_commands.choices(
active=[
app_commands.Choice(name="on", value="on"),
app_commands.Choice(name="off", value="off")
]
)
async def welcome(interaction: discord.Interaction, active: app_commands.Choice[str]):
interaction.response.send_message("test")```
error says it all
await it await interaction.response....
hi guys, is there any good guide on learning to make discord bots in python? i can already program in python
https://fallendeity.github.io/discord.py-masterclass/
https://github.com/Rapptz/discord.py/tree/master/examples
A hands-on guide to Discord.py
ty
Hello could someone help please I am trying to build a discord bot with interactive buttons but I keep getting errors even after installing pip discord-components.
File "/home/container/main.py", line 3, in <module>
from discord_components import DiscordComponents, Button, ButtonStyle, InteractionType
ModuleNotFoundError: No module named 'discord_components'
customer@apollopanel~ Server marked as offline...
[Pterodactyl Daemon]: ---------- Detected server process in a crashed state! ----------
[Pterodactyl Daemon]: Exit code: 1
[Pterodactyl Daemon]: Out of memory: false
[Pterodactyl Daemon]: Aborting automatic restart, last crash occurred less than 60 seconds ago.```
discord_components is an old and outdated library
https://github.com/Rapptz/discord.py/tree/master/examples/views check this to see how to make buttons
Ah okay, Thank you
Could anyone help with this issue
import discord
intents = discord.Intents.all()
intents.typing = False
intents.presences = False
client = discord.Client(intents=intents)
token = ''
@client.event
async def on_ready():
print(f'Logged in as {client.user.name} ({client.user.id})')
@client.event
async def on_message(message):
print (f'Message from {message.author}: {message.content}')
client.run(token)
I want it as a message logger but when I open it it closes immediately
why do you want to log messages of others?
need to await it
the discord.Client 😭
whats the console say?
!traceback
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.
Using discord as backend and my python as frontend
It works fine but the python program thinks it's done so it closes
No right way round I want to use python as chatapp
And put encryption
so you want to use python to send messages using the bot?
shouldnt do
It does
this sounds a little extra if ima be honest
Idk why
!traceback
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.
also you should be running this inside of a code editor since if you run it by double clicking it, it’ll close down automatically if theres any errors
