@client.event
async def on_message(message):
if message.guild is None and not message.author.bot and message.content == "fdp":
await message.delete()
print(f"Message was deleted !")
try:
await message.author.send(f"Insult :
{message}")
print(f"Private Message was sent !")
except Exception:
#get the channel here and send the error etc
await client.process_commands(message)
#discord-bots
1 messages · Page 966 of 1
Try now 🙂
what library are u using?
Thats dpy 1.7v
What version🙂
There is examples in the github
Yep thats how it works/(add buttons)
I'm on replit for 1 time and already get this haha
Hi, i asked this yesterday but didn't get a clear answer.
the bot worked for like a year, but for some reason it stopped working properly. I do have a channel where i only put 20 images (png). When i use this function he only reads like 11 images or less. Does someone has any idea how to fix this?
@bot.command()
async def updb(ctx):
collection.drop() # Drops database collection
channel = bot.get_channel(962354717307068426) # Gets channel that's need to be readed
async for message in channel.history(limit=20): # Reads history of channel limitation is 20
url = message.attachments[0].url # Checks per message for url (png)
urlArray.append(url) # Adds url to array
print(url)
await bot.et_channel(id=818813967198978078).send("There are " + str(len(urlArray)) + " images posted in #visitcard_database!")
for url in urlArray:
collection.insert_one({"url": url})
after.voice.channel.name from an on_member_update event
got this error :
AttributeError: 'VoiceState' object has no attribute 'name'
Why ? because on member.voice.channel.name exists (I think), and if not, how can I get the voice channel name and ID ?
What are you trying to do?
Yeah, when does it error?
when i wanna start it
Start what?
the bot
Traceback (most recent call last):
File "/home/runner/Trent/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", lin
Traceback (most recent call last):
File "/home/runner/Trent/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", lin
Traceback (most recent call last):
File "/home/runner/Trent/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", lin
Traceback (most recent call last):
File "/home/runner/Trent/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", lin
Traceback (most recent call last):
File "/home/runner/Trent/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 606, in _load_from_module_spec
spec.loader.exec_module(lib)
File "<frozen importlib._bootstrap_external>", line 839, in exec_module
Traceback (most recent call last):
File "/home/runner/Trent/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", lin
Traceback (most recent call last):
File "main.py", line 24, in <module>
client.load_extension(f"cogs.help")
File "/home/runner/Trent/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 672, in load_extension
raise errors.ExtensionAlreadyLoaded(name)
discord.ext.commands.errors.ExtensionAlreadyLoaded: Extension 'cogs.help' is already loaded.
the code in the cog?
dude what u mean
Can i see the code?
uhh i think
yes
help.py is already loaded 
Yeah
ya tell how to fix
bru
then idk lmao
Traceback (most recent call last):
File "/home/runner/Trent/venv/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 113, in on_message_delete
del snipe_message_author[message.channel.id]
KeyError: 959153212684894299
Ignoring exception in on_message_delete
Traceback (most recent call last):
File "/home/runner/Trent/venv/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 113, in on_message_delete
del snipe_message_author[message.channel.id]
KeyError: 959153212684894299
Ignoring exception in on_message_delete
Traceback (most recent call last):
File "/home/runner/Trent/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", lin
Traceback (most recent call last):
File "/home/runner/Trent/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", lin
Traceback (most recent call last):
File "/home/runner/Trent/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", lin
Traceback (most recent call last):
File "/home/runner/Trent/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", lin
Traceback (most recent call last):
File "/home/runner/Trent/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 606, in _load_from_module_spec
spec.loader.exec_module(lib)
File "<frozen importlib._bootstrap_external>", line 839, in exec_module
Traceback (most recent call last):
File "/home/runner/Trent/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", lin
Traceback (most recent call last):
File "main.py", line 24, in <module>
client.load_extension(f"cogs.help")
File "/home/runner/Trent/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 672, in load_extension
raise errors.ExtensionAlreadyLoaded(name)
discord.ext.commands.errors.ExtensionAlreadyLoaded: Extension 'cogs.help' is already loaded.
the del snipe_message_author is not the problem
saad do be smort
show where you load your files
No need for that last line
hm ic
what
remove client.load_extension("cogs.help")
ok
Is the file help.py in the folder commands
ikr
Put client.load_extension("cog.help") outside the For loop
!d discord.Guild.get_role
get_role(role_id, /)```
Returns a role with the given ID.
Changed in version 2.0: `role_id` parameter is now positional-only.
Daxle and hunter are face palming so hard rn
for heheheheh:
...
client.load_extension("cog.help")```
hunter
I need to get the role from my json file
get_channel(role)
no comments on that
?

How would I ping a user with there ID?
<@id>
@slate swan
Nice name doe lmao
@slate swan what's bumper bot for? 👀
if u r making a disboard bumper bot, it won't work
hunter still living in the old days
The last time I used disboard or any other bot except mods one, was like an year ago or smth
- you're missing the user argument when you call your kick function
- the bot doesnt have a
.kick()method, probably what you want isctx.guild.kick(<user>)or theMember.kick()method
Pretty sure sad().stop() gives an attribute error
no
PoV: sad is a class
!paste thanks
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
no i dont mean literally type out Member.kick()
Why? It fits
does it?
it depends on your clients zoom
never knew
ctrl + and ctrl -
Bumping servers 
ctrl 0 iirc to reset
uhhh alright
yup
its all in your settings!
It works doe
i got it at 100
Chromium
😳
"your" settings
Its like a partnering bot
yes
sus
O weird

?
Ain't those like against ToS?
nothing
Nope
@slate swan what i mean is that if you get a Member object, it has a .kick() async method you can use to kick them
am I the only one who uses 40 zoom level 😔
i use default 100
Prolly, zoom level on my mobile is like 80 or smth tho (the lowest)
passing your user inside that method sure
Rip I change it to 80 and uhhh
LMAO
Rip
oh you moved it inside the view
wha-
what its fine
It looks normal 
if you're making a kick command, you have the option to have a parameter with a discord.Member typehint to directly receive the member you want to kick as part of your command
Ofc, now my desktop and fn seems bigger
you just dont know how to use your laptop hunter

Idk tbh😭i cant tell the difference
a button that kicks anyone who clicks it...?
how are you using 94% ram rn
hes got that 2gb of ram😭
fn doesnt take much, it really depends on graphics and much more
32 gb of 3600 is like 32 bucks
i would buy them but i want a rgb logitech 4kit of ram
of 64 ofc!
i think i only have like 16gb installed and i've never used 100% of it
same
No
yes it is bro
you just dont check right mr Canadian
32GB of 3200mhz cl16 is $110 usd
^
i just wish i could afford a new graphics card
this 1080 is slowly becoming outdated
where you shop ebay💀
No
It's $56 on Amazon.
I would literally pay you to find me a 32GB 3600mhz kit for $32
you really cant search well, i would check on the kit but im on mobile
Search what well?

The cheapest 16GB 3200mhz cl16 kit is $55 usd. The cheapest 32GB 3200mhz cl16 kit is $110.
I will pay you $10 to find cheaper prices
ez
FN
Ignoring exception in command tree:
Traceback (most recent call last):
File "C:\Users\eboss\Downloads\dpy\venv\lib\site-packages\discord\app_commands\tree.py", line 883, in wrapper
await self.call(interaction)
File "C:\Users\eboss\Downloads\dpy\venv\lib\site-packages\discord\app_commands\tree.py", line 1022, in call
command, options = self._get_app_command_options(data)
File "C:\Users\eboss\Downloads\dpy\venv\lib\site-packages\discord\app_commands\tree.py", line 913, in _get_app_command_options
raise CommandNotFound(name, parents)
discord.app_commands.errors.CommandNotFound: Application command 'slash' not found
``` `self.tree.add_command(Core(), guild=discord.Object(id=config.debug.guild))` ```py
from discord import Interaction, app_commands
class Core(app_commands.Group):
@app_commands.command(name="slash")
async def _slash(self, interaction: Interaction, number: int, string: str):
await interaction.response.send_message(f'{number=} {string=}', ephemeral=True)
``` why the fu lol
So confused kek
the interaction in the button's callback gives you the .guild and the .user so you can use those two to kick them
# within your View class
@discord.ui.button(label='Show guild')
async def show_guild(self, interaction, button):
print('this button was clicked by someone in the guild:', interaction.guild.name)```
you would just combine the .kick(<the user object here>) method that the guild object has and the interaction's user to kick them
!d discord.Interaction.user
The user or member that sent the interaction.
did u fuck i forgot the name
did u sync the tree
Yeah
ok do this, sync globally, then just wait
is this loaded with the extensions system, or just imported into your main file?
Import
But that shouldn't matter.
oh yeah the edge case i had last time was because i copied global commands to a guild then reloaded the extension
you have the guild predefined so that wouldnt be a problem
Hmm get_commands() is empty
When removing guild=discord.Object(id=config.debug.guild) it is in the list. Super weird.
yeah that makes sense
get_commands() can take a guild object to return the commands for a specific guild
!d discord.app_commands.CommandTree.get_commands
get_commands(*, guild=None, type=<AppCommandType.chat_input: 1>)```
Gets all application commands from the tree.
have you double checked that config.debug.guild is still the correct id you were expecting?
Yeah i even putted it in raw 
i completly forgot how to use discord.py and so i am here to ask let say i have a webhook and that thing just send something to a channel in an embed i want my bot to copy that embed and whats inside it and sent it to me in dm how?
you can listen for the on_message event, check the message's .webhook_id to see if it comes from the webhook you were expecting, then pass through the message's .embeds to your send() method with the embeds= argument
its a fair number of things to understand, but the code you need to write to do just this would be a dozen lines
yea i completly forgot it was like a year ago last time
aight i would suggest the quickstart on the docs to see how you create your bot and handle a particular event https://discordpy.readthedocs.io/en/stable/quickstart.html
afterwards you can explore the API Reference to see the different attributes and methods, e.g. get_user(id) and fetch_user(id) methods on the Client (you could use these to get the User object of yourself to DM to)
is it possible to make a bot join a vc without using using the commands extension to discord.py
every tutorial ive seen uses the commands extension and im wondering if i can do it without using the commands extension
await connect(*, timeout=60.0, reconnect=True, cls=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Connects to voice and creates a [`VoiceClient`](https://discordpy.readthedocs.io/en/master/api.html#discord.VoiceClient "discord.VoiceClient") to establish your connection to the voice server.
This requires [`voice_states`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.voice_states "discord.Intents.voice_states").
Conclusion ```py
self.tree.add_command(Core(), guild=discord.Object(id=config.debug.guild))
await self.tree.sync(guild=discord.Object(id=config.debug.guild))
🤦
That works.
thanks
ah i would have thought it was already synced since you were able to invoke the command earlier
Yeah since i just did a single command so it wasn't needed but now it's a group
I gotta sync it twice now tough. Once for the specific one and one for global
Do you guys think a reactive based caching interface to be overkill?
Shall I just do a normal one
Normal one
Any reasons
Less effort works just as fine
But imagine reactive pushing & popping 😔
I guess I'll scrap that idea
Is it worth using nextcord over discord.py?
no
@hushed galleon congrats on the helper role!
eyy
Congrats! You definitely deserve it :)
i read that as pooping
i mean not really nextcord is a bit slow but dpy is very quick to implement new endpoints and is well done
why you guys poop
🤨
🗿
cuz I have to, sorry

Are u sure the emoji id is correct? its a little bit too short.
yeah i know
but yes, u have to use <>
the hell
try his one
what is a
animated
it aint animated
won't work if the bot don't have access to the emote i.e is in the server
i think thats obvious he has to replace with his id and emoji name.. but youre correct
as you see above idk if he understands it 
it has
has what
well, then your formatting is wrong
is it because i use it in embed
shall i send you the code
send the embed where you try to put it
embedVar = discord.Embed(title='`Status:`', description='**:emoji_153: is Online **', color=0xe8c02a)
await message.channel.send(embed=embedVar)
i also put the id but idk why it isnt shown when i send it here
🗿 yeah as i said, wrong format
to be more easily for you, type the emote in the chat and add \ in front of it then copy the result and put it in the code
the result needs to be in this format <:name:id> or <a:name:id> if it's animated
Anyone able to help me resolve this please?
botnew.py:21: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited bot.load_extension(f'cogs.{filename[-3]}') RuntimeWarning: Enable tracemalloc to get the object allocation traceback
or can I safely ignore iit?
how can i like make it so that whenever a user joins a specific channel an other channel will automatically be created
Await loading the extension
await bot.load_extension(…)
When I add that
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
await bot.load_extension(f'cogs.{filename[-3]}')
it gives this error
await bot.load_extension(f'cogs.{filename[-3]}')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: 'await' outside function```
cmon man we showed u the format 😭 if u need help please listen not ignore
well, you can't do that, await is used just inside async functions what you have above the for loop ?
its to check its a py file within the folder
Thank you
House that for loop inside an asynchronous function then run that function. Bot.load_extension is a coroutine/awaitable
async def check():
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
await bot.load_extension(f'cogs.{filename[-3]}')
check()
gives this now botnew.py:55: RuntimeWarning: coroutine 'check' was never awaited check() RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Use asyncio.run to run/execute coroutines. You can also call the coroutine inside another asynchronous function
e.g. ```py
import asyncio
async def coro():
...
asyncio.run(coro())
How would I create an instance of a class I have if the bot finds that the user has the role with the same name?
if user has role:
class()
```?
guys if using self bots isnt permitted then why dont they patch it?
if role in member.roles:
my_istance = MyClass()
cause I think that if you pass a self-token you can easily run a selfbot
more like
if user has role:
role()
Now it can't find a module called cogs
Because it's difficult to tell
it's quite easy
literally I think you just copy ur token and thats that lmao
they could patch it, self-tokens are different from bot-tokens I think
Discord is really just an API, even for regular users there's an API. the client does nothing but send requests back and forth. You can see this by going into your network tab
So it's difficult to tell from the server side if it's the actual discord client connecting or some automated service
roles = ["Peasant", "Farmer", "Citizen", "Educated", "Wise", "Expert"]
for role in roles:
if role in member.roles:
my_instance = role()
Something like this is what I'm trying to do
Except I know that wouldn't work, because you can't call a string
But I have classes for all of those role names
Use set intersection
only real thing they could do is have a category of user tokens or make the user token different to a bot token maybe in length but i doubt it would be done
No
how do you even get the user token?
and how does it look if its different than a bot one?
inspect element
the API your discord client uses the same as what selfbotting uses, it's just automated
so if they patched it discord would be usable entirely
does dpy have something to go against selfbotting?
unusable you mean?
No they just removed it.
Because it goes against ToS
wdym? if the user token is alike a bot token how does it stop the token from being passed to the http client?
yeah typo
Before dpy pulled support for selfbots, there used to be a flag that gets passed to the run method and depending on the given value, it would concatenate "Bot " to the given token
Selfbots use the intended API for bots, your client can utilise those endpoints but also a few restricted ones on the client
Nothing ig
well it won't work since the HTTP client adds the "Bot " prefix to the token
it's called a kwarg by the way
also how the hell do you have a 6666 tag
too many brandons
User tokens need to prepend "Bearer" to the token in the authorization header
That's one way to tell but it can be easily fooled
Bearer is not required no, Only the "Bot" prefix is required, if its a bot that is
I thought user tokens didn't require Bearer
can someone show the headers for auth?
Bearer would be for Oauth2 access tokens right?
I remember seeing else where user's using an auth header without a prefix
It's just a plain token, no prefix
how much tokens does discord use jeez
Introducing refresh tokens!
{
"Authorization": "Bot token"
}
```?
All my homies love JWT
well you guys are talking about an Oauth2 and an auth token so i thought there was 2 or several to verify requests
but i think you guys are talking about just one
Oauth2 endpoints would require a bearer token
Regular endpoints would use Bot tokens
{"access_token": "token"}
You can make requests to regular endpoints with bearer tokens
And by regular I mean the ones outlined in the discord documentation
any difference?
between each endpoint?
Bearer + regular token?
i know the twitter api does use bearer and a user context token
Bearer + the access token
Not sure if they work with regular tokens
You think they would since access tokens are just a temporary version of regular tokens
If it's only with the access token it's kind of dumb to use bearer tokens for the regular API
Nah I think you can use both access and regular tokens on endpoints
Oauth2 is a permissions framework, so your bot can do actions for a user
Basically just temporary user tokens
ah ic so does moderation fall in that category? like banning users?
No
Nah
More like being able to make a user join a guild, create new group DMs etc
Oauth is mostly for things like "log in with discord" buttons
if you were making a web dashboard for example, you would go through the oauth flow, get the user's access token, and get all of the user's guilds, display them on the dashboard for them to pick
the thing is that they don't have nitro
Your tag changes when you run out of nitro iirc
and discord resets your tag if it previously changed with nitro
ah so its like twitters user context
it does
the reason being is, every single brandon tag is taken
luck
so there's nothing to reset to
that's a lot of brandons
indeed
but you're the superior one
congrats, you were the 6561th brandon!
9999 brandons exist 
oh
is there a way to allow both prefix commands and slash commands to co exist?
if i'm not dumb
yes
Yes
9^4
How would u go about that? Im using cogs btw
Does anyone know what this mean: RuntimeWarning: coroutine 'Client.login' was never awaited
It's an awaitable, await the method
I've a simple bot ```py
from disnake import Intents
from disnake.ext import commands
from src.util.json_util import get_json_dict
CONFIG = get_json_dict('static\config.json')
bot = commands.Bot(
command_prefix='a!',
intents=Intents.all(),
sync_commands_debug=True,
)
@bot.event
async def on_ready():
print(f'Bot is ready!')
bot.login(
token=CONFIG['BOT_TOKEN']
)
You need to await it
Rewriting rin and so far I got a decent EventEmitter class, should I support middlewares
await client.login()
can't await outside a function...
you copied js 
Yes
node.js to be exact
Yes. client.login() is lower level. You can either use a main function like Yerlikaya suggested, or use client.run()
what?
Are you using asyncio.Event?
client.run has no token param...
run(*args, **kwargs)```
A blocking call that abstracts away the event loop initialisation from you.
If you want more control over the event loop then this function should not be used. Use [`start()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.start "discord.Client.start") coroutine or [`connect()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.connect "discord.Client.connect") + [`login()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.login "discord.Client.login").
Roughly Equivalent to:
```py
try:
asyncio.run(self.start(*args, **kwargs))
except KeyboardInterrupt:
return
```...
async def main():
bot = commands.Bot(...)
# do some setup here
try:
bot.login()
finally:
# do some cleanup here
asyncio.run(main())
https://prnt.sc/7GiSOnw2dx5c it doesn't
If it doesn't then something is seriously wrong with your library
And the chances of that are low
disnake?
I'm 100% sure client.run() takes a token
bot.run(token=
No
!d disnake.Client.run
run(*args, **kwargs)```
A blocking call that abstracts away the event loop initialisation from you.
If you want more control over the event loop then this function should not be used. Use [`start()`](https://docs.disnake.dev/en/latest/api.html#disnake.Client.start "disnake.Client.start") coroutine or [`connect()`](https://docs.disnake.dev/en/latest/api.html#disnake.Client.connect "disnake.Client.connect") + [`login()`](https://docs.disnake.dev/en/latest/api.html#disnake.Client.login "disnake.Client.login").
Roughly Equivalent to...
That wouldn't make sense to use
Ah, guess I don't understand how that works
Well, Event would be for synchronisation, but I don't need any here. I just want to subscribe and emit
https://gist.github.com/an-dyy/c5de6f50fc25e7a88e54a23c0aab1976 is the current impl
can you translate that to dumb language?
it cant be awaited
It's a regular function because it's higher-level
If you want more lower level control you should use start()
that's the opposite of dumb language, lol.
I want to say yes, but also I don't want to because I don't wanna 100% commit
smh
then dont work on it if youre not gonna give it 100%😡
nah its made from scratch
Because I have a reputation of never finishing my projects
So I'm trying not to give people false hope
No
How do I position the dropdown to be above the button ?
you should add the select to your view before adding the buttons
How do I make the bot add an existing role to a person?
Oh how do you creat buttons and embed at the same time ?
you can use the Member.add_roles() method and pass in the Role object you want to add to them
but like, how would I add an exact role?
there's the Guild.get_role() method to get a specific Role by its ID
and how would I know the id... or the guild, lol
can you provide some context about what you're trying to do?
you can use message.author.id or ctx.author.id if you use ctx
@commands.Cog.listener()
async def on_member_join(self, user: disnake.Member):
user.add_roles()
That.
Oh the id of the role... my bad
can't, member_join listener
alr, was thinking you could have been creating a role, in which case it already gives you the role object
I see...
anyway since the user is a discord.Member object, the member's guild can be accessed with user.guild
if you only need your autorole feature to only work for that one guild then hardcoding the ID to use with get_role is fine
I don't even know what the id is anyways.
you can get it within your discord app by enabling developer mode in settings (as yerlikaya mentioned) and right clicking the role in either server settings or on someone's profile
neato
I'm too dumb for this, lol.
btw run() passes through kwargs to the start method which has a token parameter, meaning token= is an acceptable kwarg for run() too
everything in discord has an ID (a number) tied to them like guilds, roles, and channels, which is why there's a lot of get_ methods for those objects
java intensifies.
mostly known as snowflakes!
Discord Developer Portal
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
these docs are harder than my life..
lol, no
its long but informative
I just can't understand it though.
it might be confusing until you read dpys src
to send a message to a channel you need a Channel object, to add a custom emoji to a guild you need a Guild object, and to add a role to a member you need the Member object and the Role object
I don't understand other people's code, so it would be worse for me.
is it too complicated?
yes?
Am I doing something wrong here, the bot cant seem to find the command despite loading the cog
import discord
from discord.ext import commands
class Ping(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def ping(self, ctx):
before = time.monotonic()
message = await ctx.send("Pong!")
ping = (time.monotonic() - before) * 1000
await message.edit(content=f"The bot's latency is `{int(ping)}ms`")
def setup(bot):
bot.add_cog(Ping(bot))
@bot.command(pass_context=True)
@commands.is_owner()
async def load(ctx, extension):
bot.load_extension(f'cos.{extension}')
#Embed Reply
embed = discord.Embed(color=000000)
embed.add_field(name="Load Successful!" ,value=f"The `{extension}` module has been successfully loaded!", inline=False)
embed.set_footer(text="Requested by: {}".format(ctx.author.display_name))
await ctx.send(embed=embed)
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
bot.load_extension(f'cogs.{filename[-3]}')
it probably will as its an advance lib
how can i set a hyperlink on a image?
Using name doesnt work
https://caught-lackin-in-8k-by-cyberghost.cf/4qDyXGfJ
bot.load_extension(f'cos.{extension}')
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "ping" is not found
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "ping" is not found
How to do the cog thingy in other files? Like, make it add to the bot?
in dpy 2.0 the setup() function, add_cog() method, and load_extension() methods have to be awaited as described in the migration guide https://discordpy.readthedocs.io/en/master/migrating.html#extension-and-cog-loading-unloading-is-now-asynchronous
well 2.0 does have a ton of breaking changes, so it would be pretty hard for blogs or video tutorials to keep up
where did you tried it?
like add_cog? or overall how to make a cog?
I've cogs classes in other folders, but I dunno how to add them
you would add them with the global setup function and just use the add_cog method that the Bot class has which then you would load them with load_extension which its a method the Bot class has aswell
!d discord.ext.commands.Bot.add_cog
await add_cog(cog, /, *, override=False, guild=..., guilds=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Adds a “cog” to the bot.
A cog is a class that has its own event listeners and commands.
If the cog is a [`app_commands.Group`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.app_commands.Group "discord.app_commands.Group") then it is added to the bot’s [`CommandTree`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") as well.
Note
Exceptions raised inside a [`Cog`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Cog "discord.ext.commands.Cog")’s [`cog_load()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Cog.cog_load "discord.ext.commands.Cog.cog_load") method will be propagated to the caller...
!d discord.ext.commands.Bot.load_extension
await load_extension(name, *, package=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Loads an extension.
An extension is a python module that contains commands, cogs, or listeners.
An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.
Changed in version 2.0: This method is now a [coroutine](https://docs.python.org/3/glossary.html#term-coroutine "(in Python v3.10)").
if i wanted to split a list into 8 new lists (basically the original lists values/8 and each of those put into new lists) how would i do that?
what...
make a list for each element?
theres only 1 elemt
im not sure what you mean tbh like make 8 copies of the new list?
basiacl;ly lets say i have a liost of 1000 people. how would i take that and make 2 lists of 500
i have a new problem, if the mentioned user reacts the the message then removes it and reacts again it sends the same message every time he does that how can i fix that?

Failed to load ping, reason: No module named 'cogs.'
https://caught-lackin-in-8k-by-cyberghost.cf/tHGtGLg8
!e
print([1, 2, 3][2:])
@slate swan :white_check_mark: Your eval job has completed with return code 0.
[3]
remove the while True?
just wait for the event once so remove the loop
code?
how to get the bot's avatar?
wdym
@bot.event
async def on_ready():
print('{0.user} has succesfully initialised!'.format(bot))
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
try:
await bot.load_extension(f'cogs.{filename[-3]}')
print(f'Loaded {filename[:-3]}')
except Exception as e:
print (f'Failed to load {filename[:-3]}, reason: {str(e)}')
how are you getting these 1000 members? is it using Guild.query_members() or something else? also are you on dpy 2.0 cause they added a handy utility function for this, discord.utils.as_chunks()
for member in guildid.members
f'cogs.{filename[-3]}' youre missing a colon
i need help when i run the command its not replying and nothing goes in console
@client.command()
async def post(ctx, channel: discord.TextChannel, *, data):
if ctx.author.id in [503641535342968832, 947963897158189106, 889483922776391731]: return
token = 'MY BOT TOKEN'
url = f'https://discord.com/api/v9/channels/{channel.id}/messages'
headers = {'Authorization': f'Bot {token}'}
res = requests.post(url, headers=headers, json=json.loads(data))
if res.status_code == 200:
return await ctx.send(f"Successfully sent into {channel.mention}.")
else:
await ctx.send(f'Error: {res.text}')
return await ctx.send(f"I failed to send into {channel.mention}. {headers}")```
then you can either use list slicing as okimii suggested, or have as_chunks() handle it for you
i was smiling until i seen this
do you have 2 on_message events and requests isnt async
and why are you making the requests yourself?
Omg
thanks
if you put that in on_ready, it will not run until the bot it will be ready, and it can take a while in certain cases
do u know why its broken?
bro
anyone know why?
how do i list slice if i dont know the count of the list?
well youre trying to make a request on another session and you arent even connecting to websockets why? just use the client session dpy has?
do note that with your code, if the response was a non-200 status you'll be sending your bot token into the channel
!d len
len(s)```
Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).
**CPython implementation detail:** `len` raises [`OverflowError`](https://docs.python.org/3/library/exceptions.html#OverflowError "OverflowError") on lengths larger than [`sys.maxsize`](https://docs.python.org/3/library/sys.html#sys.maxsize "sys.maxsize"), such as [`range(2 ** 100)`](https://docs.python.org/3/library/stdtypes.html#range "range").
uhmm i have this code where it check a specific channel and i wanna ask if how can i make it check multiple channels?
if (message.channel.id == 931101728647053312):
does the body actually show your token?💀
just make a list or use or
the response text no i assume not, but they send their headers right afterwards
ah
🗿what it's logical, you know that the on_ready code is executed just after the bot is ready, basically loading the cogs in on ready is a dumb thing, and in fact ig you will load them twice
read what you said again
i need help when i run the command its not replying and nothing goes in console
idk why its kinda weird
From what I understand itll load all the cogs in that folder, why would it load them twice?
does anyone know how to fix it?
Ive not told them to load again
do you have an on_message event?
using the range function is an easy way to group a list ```py
seq = [1, 2, 3, 4, 5, 6, 7]
size = 3
for i in range(0, len(seq), size):
... # i will go through 0, 3, and 6
... print(seq[i:i + size])
[1, 2, 3]
[4, 5, 6]
[7]```
What's the syntax for handling button timeouts?
@hushed galleon question since hes not sending hb it would disconnect after that request right?
i see no problem
just access the superclass init which will be the view and pass the timeout
!d discord.ui.View
class discord.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
class MyView(View):
async def on_timeout(self):
...
can u help me how do i fix it with that
Perfect @boreal ravine, thanks
oh he ment that woops
how can i disable so the user can ping himself to the command?
Currently it ignores the if member is ctx.author
Hey @sterile imp! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discordapp.com/developers/applications/me
Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!
Hey @sterile imp! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discordapp.com/developers/applications/me
Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!
@boreal ravine ```py
@client.command()
async def post(ctx, channel: discord.TextChannel, *, data):
if ctx.author.id in [503641535342968832, 947963897158189106, 889483922776391731]: return
token = 'MY BOT TOKEN'
url = f'https://discord.com/api/v9/channels/{channel.id}/messages'
headers = {'Authorization': f'Bot {token}'}
res = requests.post(url, headers=headers, json=json.loads(data))
if res.status_code == 200:
return await ctx.send(f"Successfully sent into {channel.mention}.")
else:
await ctx.send(f'Error: {res.text}')
return await ctx.send(f"I failed to send into {channel.mention}. {headers}")```
how do i add on_message to it
thats not what he meant
return isinstance(user, discord.Member) would suffice
you're ignoring yourself in the command
im not, my ID is whitelisted
can you explain me what that does?
its blacklisted
youre returning the function lol
how do i unblacklist myself
hm i dont know much about how long the heartbeat interval is, though if the request happens to block the heartbeat it should reconnect
you remove the id???
it checks if the type of the first argument is the same as the second argument
to make new lists as a var i would do
new_list = seq[i:i+size]
new_list2 = seq[i:i+size]
etc?
Does interaction serve as a form of ctx?
thanks
i think the time is like less than a sec im not quite sure ill check ddocs
for interactions yes
ok perfect
if not ctx.author.id in [..., ...]:
return
``` this would check if the author's ID isn't in the list
defining many variables like this is usually a sign that you should use a list
it mostly has the same attrs, its just the Interaction of the command or component which commands have Context which is the prefix and name of the function
yeajh ik, im tryna split that list into different, smaller lists
Delete that
Traceback (most recent call last):
File "C:\Users\beege\Documents\GitHub\EconomyDiscordBot\venv\Desktop\Coding\lib\site-packages\discord\ui\view.py", line 413, in _scheduled_task
await item.callback(interaction)
File "C:\Users\beege\Documents\GitHub\EconomyDiscordBot\ClassLibrary.py", line 214, in claim_button
role = get_role(interaction)
File "C:\Users\beege\Documents\GitHub\EconomyDiscordBot\Cogs\EconomyCog.py", line 11, in get_role
classes = [Peasant, Farmer]
NameError: name 'Peasant' is not defined
I'm getting this error, even though Peasant is defined...
do u know how to fix it
try -post #abc {"embeds": ["title": "hi"]}
where is it defined in your code?
https://discord.com/developers/docs/topics/gateway#hello
{
"op": 10,
"d": {
"heartbeat_interval": 45000
}
}
about 45 seconds
Discord Developer Portal
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
in another file. Only thing is, that function get_role works in commands that use it
However, it's not working with this interaction here
Bot is ready!
Ignoring exception in command post:
Traceback (most recent call last):
File "C:\Users\impre\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\impre\OneDrive\Desktop\The Generator Say\bot.py", line 25, in post
res = requests.post(url, headers=headers, json=json.loads(data))
File "C:\Users\impre\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "C:\Users\impre\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\impre\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 353, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 20 (char 19)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\impre\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\impre\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\impre\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: JSONDecodeError: Expecting ',' delimiter: line 1 column 20 (char 19)```
for me i got 41.25s by checking bot.ws._keep_alive.interval
maybe its dynamic in some cases
show me how you invoked the commsnd
the one u sent
can you try doing json=data
oh yeah the square brackets should be braces {}
er i mean, there should be braces inside the square brackets
oh yeah
-post #abc {"embeds": [{"title": "hi"}]}*
uhmm i have this code and it works but it sent an error everytime it delete the message
if not message.attachments:
await asyncio.sleep(2)
await message.delete()
error
discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message
https://caught-lackin-in-8k-by-cyberghost.cf/S13R6eQb
import discord
from discord.ext import commands
import time
class Ping(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def ping(self, ctx):
before = time.monotonic()
message = await ctx.send("Pong!")
ping = (time.monotonic() - before) * 1000
await message.edit(content=f"The bot's latency is `{int(ping)}ms`")
async def setup(bot):
await bot.add_cog(Ping(bot))
Where I gone wrong now 
property latency```
Measures latency between a HEARTBEAT and a HEARTBEAT\_ACK in seconds.
This could be referred to as the Discord WebSocket protocol latency.
send command example
indentation
which is the latency between an hb and a hb_ack
no?
@sterile imp try this
Its more for me to see if the bots alive, Ill sort the accuracy out later
Im just trying to get the main cogs to work
^
yeah ur right. my b
not a problem
is there a traceback?
@blissful sparrow what lib a u using? because didn't discord.py 2.0 kinda change the way cogs are loaded in?
anyone know how to change the server name + icon using a discord bot? I'm trying to make something that just resets the server to a normal state if really needed
arent they different though? sending a message gives you API latency vs gateway latency, so they dont have to be equivalent
not in the console no
uhmm i have this code and it works but it sent an error everytime it delete the message
if not message.attachments:
await asyncio.sleep(2)
await message.delete()
error
discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message
read my message on top! Yes the latency given is the latency between an hb and a ack hb
exactly
so there's no concern about them not being "accurate", he's testing a different kind of latency
!d discord.Guild.edit you can use this method on a guild object to change it's name/icon
await edit(*, reason=..., name=..., description=..., icon=..., banner=..., splash=..., discovery_splash=..., community=..., afk_channel=..., owner=..., afk_timeout=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the guild.
You must have the [`manage_guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_guild "discord.Permissions.manage_guild") permission to edit the guild.
Changed in version 1.4: The rules\_channel and public\_updates\_channel keyword-only parameters were added.
Changed in version 2.0: The discovery\_splash and community keyword-only parameters were added.
Changed in version 2.0: The newly updated guild is returned...
well isnt that inaccurate either way?
let's try to login this one XD
latest one and they load asynchrously
i think
Hello,
I'm trying to make it where if I do %stats SEN TenZ 0505 it makes the url .../SEN%20TenZ... for [username_parse]. I've tried using urllib to fix it, it doesnt work. I have to manually enter %stats SEN%20TenZ 0505.
@client.command()
# @commands.cooldown(1, 60, commands.BucketType.user)
async def stats(ctx,username: str,tag: str):
username_parse = urllib.parse.quote(username)
if ' ' in username:
username.replace(" ", "%20")
URL = f"https://tracker.gg/valorant/profile/riot/{username_parse}%23{tag}/overview?playlist=competitive&season=all"
...
hmm. show the code u have that loads ur cogs
depends on the latency you're interested in since they arent necessarily porportional to each other, e.g.
this screenshot is too big
im eventually trying to get it like this lol
try ```py
username = username.replace(" ", "%20")
minus the DB
how would you even measure the api one? just making a time and then making another time when sending the message?
btw nice ping command lol
@bot.event
async def on_ready():
print('{0.user} has succesfully initialised!'.format(bot))
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
try:
await bot.load_extension(f'cogs.{filename[:-3]}')
print(f'Loaded {filename[:-3]}')
except Exception as e:
print (f'Failed to load {filename[:-3]}, reason: {str(e)}')
Client.latency
I did, no error but no output either.
yea i think thats what i did
i remember using the message's created_at datetime once but i would end up with negative milliseconds occasionally
mhm
your bot took 50 seconds to send a message?
yeah it aint just 50 seconds its 50 megaseconds
jeez
578 days of uptime just to see that ping message
😅
>:
Traceback (most recent call last):
File "/home/runner/tester/venv/lib/python3.8/site-packages/discord/ui/view.py", line 371, in _scheduled_task
await item.callback(interaction)
TypeError: callback1() missing 1 required positional argument: 'interaction'
can you remove the try/except in on_ready and send us a paste of the entire traceback? the code you've shown us appears to be alright
youre missing the argument
how do u autoshard a discord bot?
but what arugement
the interaction argument as said in the tb?
does your bot need shards?
its in 6.2k servers so idk
yeah it probably does
dw it has all intents verified
i dont have a line 371
how would i be able to define a channel through a command
instead of putting the channel id in the code
it was raise internally one of your callbacks doesnt have it
just have an argument of the id
so uhh do u know how to shard it
because your command signature is (username: str, tag: str) discord.py will only capture the first word as the username and the second word as your tag, i.e. username = 'SEN' and tag = 'TenZ'
to fix this you'd have to either quote your username as %stats "SEN TenZ" 0505, or remake it into a keyword-only argument with the signature (tag, *, username)
maybe that can help
could u give me an example pls
channel: discord.TextChannel
why does the sudo command only delete the message bot does not create a webhook? it worked before tho
async def callback1(self, interaction):
await ctx.invoke(self.bot.get_command('roster'), role=select.values[0])
select.callback = callback1
select2.callback = callback1
When I remove try/except none of the cogs want to load now
@bot.event
async def on_ready():
print('{0.user} has succesfully initialised!'.format(bot))
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
await bot.load_extension(f'cogs.{filename[:-3]}')
is there an error in your console this time?
yes a lot of em
``# welcome message
@client.event
async def on_member_join(member):
await channel.send(f'ty for joining, {member.mention}')``
youre still missing the interaction argument
where
i forgot how to embed py code
in the parameters?
how do u do it
none of that requires the iteraction arugement
Hey @blissful sparrow!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
pycord docs
how do u embed like this
ill try it though
callbacks take the interaction argument
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
thx
# welcome message
@client.event
async def on_member_join(member):
await channel.send(f'ty for joining, {member.mention}')
how would i define a channel from the channel
without putting the id in the code
@slate swan callback1(interaction) like this correct?
discord_slash is incompatible with dpy 2.0, so you need to uninstall that and rewrite your owner cog's slash commands to use dpy 2.0's implementation
```py
code
youre still missing 2 arguments lol
Ah I see thanks
anyone
self and interaction right?
nope
async def say(ctx, *, text):
message = ctx.message
await message.delete()
await ctx.send(f"{text}")```
how do i make it so only certain ids can use it
you're manually defining the callbacks for the selects, right? since your function isn't technically bound to the class, the self parameter wouldnt be necessary
in your problem interactions type is as so interaction: discord.ui.button so it gaved an error because youre missing the argument because you need the interaction and the button argument @slate swan

is there a link where I can see how it would be done? A google search takes me to discord_slash on pypi
ik how to make it so only ppl with certain perms can do it?
otherwise sry
its a dropdown menu does that still assoicate with buttons?
ah no
can you show code?
interaction: discord.Interaction
^
sure
@commands.command()
async def rostermenu(self, ctx):
options = []
if ctx.author.guild_permissions.administrator == True:
await ctx.message.delete()
for role in ctx.guild.roles:
if role.name in team:
options.append(discord.SelectOption(label=role.name, emoji= await find_by_name(role.name, ctx.guild.emojis)))
view=View()
other = len(options)/2
if len(options) > 25:
options2 = options[:int(other)]
options1 = options[int(other):]
select = Select(options=options2)
select2 = Select(options=options1)
view.add_item(select)
view.add_item(select2)
else:
options1 = options
select2 = Select(options=options)
view.add_item(select2)
embed=discord.Embed(title="Rosters", description="Select a team to view their roster")
await ctx.send(embed=embed, view=view)
async def callback1(interaction: discord.Interaction):
await ctx.invoke(self.bot.get_command('roster'), role=select.values[0])
select.callback = callback1
callbacks should be inside the view class
afaik the documentation doesnt have up-to-date examples on this as of now, so you have to rely on the development gist and API reference to figure out anything that's changed
gist: https://gist.github.com/Rapptz/c4324f17a80c94776832430007ad40e6#slash-commands-and-context-menu-commands
docs: https://discordpy.readthedocs.io/en/master/interactions/api.html
how can i make a welcome message work in multiple servers without putting their specific channel ids in the code (with one bot)
Alright
You'd need to figure out an algorithm to find which channel to send it in
uh
Should you send it in the first channel you have perms in, check for a system channel, etc
or use a database so each guild could set up a message and which channel
That's what they said they didn't want to do
without putting their specific channel ids in the code (with one bot)
I'm assuming that also extends to storing
How to loop through folders and subfolders?
To add them bot a cog bot.
My folders: https://prnt.sc/KW73nS6p09VF
and how would i do that
Not sure if python has a native method for recursively getting all files within a folder, if it doesn't you'll have to recurse yourself
!d os.listdir
os.listdir(path='.')```
Return a list containing the names of the entries in the directory given by *path*. The list is in arbitrary order, and does not include the special entries `'.'` and `'..'` even if they are present in the directory. If a file is removed from or added to the directory during the call of this function, whether a name for that file be included is unspecified.
*path* may be a [path-like object](https://docs.python.org/3/glossary.html#term-path-like-object). If *path* is of type `bytes` (directly or indirectly through the [`PathLike`](https://docs.python.org/3/library/os.html#os.PathLike "os.PathLike") interface), the filenames returned will also be of type `bytes`; in all other circumstances, they will be of type `str`.
This function can also support [specifying a file descriptor](https://docs.python.org/3/library/os.html#path-fd); the file descriptor must refer to a directory.
Raises an [auditing event](https://docs.python.org/3/library/sys.html#auditing) `os.listdir` with argument `path`.
sorry, im fairly new
for ... in disnake.utils.search_directory(path)```
Walk through a directory and yield all modules.
Set up a database (sqlite, postgresql), then make a table with 2 columns: guild ID as the PK and bigint or string & channelID as bigint or string
class Owner(commands.Cog):
def __init__(self, bot):
self.bot = bot
this is how Ive started the class
what...
async def setup(bot):
await bot.add_cog(Owner(bot))
and this is how Ive done the cog setup
You guys gave me functions which I didn't understand, lol.
is a database like a whole different thing
like not even in the code / ide
Kayaa, how would I subclass inside a cog
Is that recursive or?
considering Id have to do discord.ui.select, aswell
a database is just a base where you store data
Yes, it's a different thing
no way
how'd you guess that?!
wait, what is self.load_extension?
dont, you shouldnt subclass in a subclass
how do i make it so only certain people can use this
@client.command()
async def say(ctx, *, text):
message = ctx.message
await message.delete()
await ctx.send(f"{text}")```
Only logical. We wouldn't want a stackoverflow error
im bill gates
🙇♂️
hm so how should i do it then
Yes, yea, add the cog to the bot.
outside of it and make an instance of the class
?
oh
oh ok so like this
class menu(discord.ui.View):
?
class naming!
it should be UpperWord and it does not suit it properly for dropdowns
anyone?
commands.has_permissions decorator
pycord
you forgot the @
I can't understand anything, lol.
that was me :)
no wonder its so bad
git blame confirms it.
It's just nice knowing that it's actually coming in helpful for people
Like, how?
first thing i see is import typing and i dont see no place where its being used, maybe im blind
Something, dunno. A bot and some random commands.
You understand how extensions work?
and it was a joke, it has some flaws tho!
That's a first step towards understanding the whole thing
Maybe you can fix it for me!
I'm using it... probably.
wait so how would i get the welcome message to work in 2+ servers even with the channel ids in the code
wdym?
wouldnt it send the messages in the other servers too?
i left bot dev like you left python so no!
load_extensions() is for loading extensions, knowing what those are can help you understand the whole thing
guess i'll do it myself then 🗿
I read those, not much of a help, though. ||sry||
does anybody know how to make welcome messages work in multiple servers
yes!
I'm with those open here, also
thanks
No problem. Let me try my best to explain: extensions are regular .py files, except they all have a setup() function:
class MyCog(commands.Cog):
...
class MyOtherCog(commands.Cog):
...
def setup(bot: commands.Bot):
bot.add_cog(MyCog())
bot.add_cog(MyOtherCog())
Using load_extension("filename.py") runs the setup() function of that extension, which will usually load a cog
and there is nowhere saying about setup.
more like containers/classes that have listeners and commands which can be used as an extension!
https://docs.disnake.dev/en/latest/ext/commands/index.html I'm with that open..
It does mention setup, here, however, they were adding a command, but that's ireelavant
JSON is javascript object notation
There is nowhere in the cogs section talking about it... only way I would is talking with someone that knows it.
Java Script Object notation
It's a file represtantion of javascript objects:
const person = {
first_name: "John",
last_name: "Doe",
age: 42
}
thankyou
That's understandable. Documentation is infinetely more valuable when you have people who know their way around it (like everyone here :D)
And that's one of the reasons why talking to other programmers and asking for help is one of the best ways to learn
and then make a command that allows server owners/mods to set a welcome channel, and write the channel id bound to the guild id in the json file-
- like the owners/mods could do something like "!setwelcome {id}" or something? I don't understand that bit
I like working alone, but ok.
I talk to poeple when I dunno what to do.
Same
Also understandable. Anyway, do you understand extensions or do you still need a little bit of help?
Don't go down the json as a db rabbit hole
i like working in groups because im lazy 😔
Pick good technologies from the start
what
Idk how to work in groups
i've tried but :3
JSON is a data representation format, NOT A DATABASE!
Its hadd💀
I put that in caps and bold because people use it WAYYY too much
Hard*
It's incredibly important that you **DO NOT ** use json as a database
ive worked with @final iron for api wrappers which was hell because i needed to teach a child oop😔
Well, this is a fantastic learning oppurtunity then
Bro
I knew oop

json is used mostly for formatting data an not saving it
I still don't understand how I would get all the files on a subfolder.
Disnake provides a recursive function to walk through all files in a folder
sure you do, dont make me pull out screenshots😭
So use that, recursively walk through all files, load them as extensions
Do it 🗿
cant i deleted the channel that had the screenshots so youre saved
would it work with something like this? https://prnt.sc/dX5au-AcWK0A
Yes, that's why it has to be recursive
question he probably wouldve asked😭
wat...
but he is cool i like working with @final iron hes pretty cool and has a similar coding style to me and hes a cool guy sometimes
while i go through that json tutorial that someone sent, could u please quickly write up a way that i could do that? could u pls try make the code bc im more of a visual learner, and i think i'd understand the tutorial more if i see your code next to what im learning
an if statement could do the trick if you have an init dunder files
Proof or it didn't happen 😩
yes pls
from disnake.utils import search_directory
for file in search_directory('.\\src\\commands'):
if file != '__init__.py':
bot.load_extension(file)
``` would this work? I just can't do anything.
you know it happened🙄
❤️
Bor I was learning python before I met you 🗿
It should, but watch out for the paths, they can be tricky
wdym?
yeah yeah🙄
Paths are different for different operating systems, so if you were going to deploy to a docker container, that path would probably error out on you
Libraries like https://docs.python.org/3/library/pathlib.html are recommended as good practice since they are OS-agnostic
again, what... doesn't it use relative path or something?
I don't understand pathlib.
It should, but raw path strings are very finicky
Best to take the safer route and use the recomended pathlib
Which api wrapper?
should get the channel first so you can save a request
ive made many but ive only worked with him in a twitter one
Is it on github?
Yes
it is but it never got published ~~ twitters api is trash~~
^
just use getch?
I should try and learn how to make a api wrapper and how to work in groups
Working in groups isn't hard tbh
You just need to communicate
Mostly don’t know which api to choose to make one
thats weird is it really not implemented yet
Finding people who wants to work with me is though
does member id change if i change my username
No
No
nope ids never change
This is why i hate discord lmao
Okimii slow 
why?
its a good thing
better explanation 😡
tysm
https://github.com/public-apis/public-apis good list here
Because everyone gets unique ids?
Its bc i had some drama with some ppl and they saved my id so when i joined they checked if my id matches the id that they saved so :|
Thanks i’ll go through that list when i wake up
They banned me >:(
I thought up of another problem
anytime!
?
i just looked at src of wrappers you could check akeno which is in my github which its quite easy to understand but couldve been done better
smh😔
channels are completely cached by the client when guilds intent is enabled, and i would figure that there arent many bots that dont have it off so there isnt any demand for getch_channel, though that does make it a bit inconsistent
I was looking of the github of a api wrapper before
I forgot what it’s called or who made it
I just saw someone’s website on their links in their profile
just look at any api wrappers src
Cracks is finally a helper?
yeah pretty cool right
aiohttp, requests and httpx are the most used
I wonder what it takes to be a helper
I mostly never see one
Well i am only here in the discords bots channel most of the time
pardon?
What would you need bs4 for with a wrapper
to me it was easier making a sync wrapper and then making an async one
If your making a wrapper, I'd assume that means there is an exposed API
Bs4 is for scrapping
Why
you dont have to worry about blocking and other async stuff
when i made my first async wrapper it didnt event had objects
Async isn't that hard to implement
yeah not anymore ofc
The official documentation
Some, but those are kind of niche
They pretty much expect you to know basic stuff
Such as bitfields, decompression and stuff
the docs of discord are quite easy you just need to read all of it and have a vision
i just dont wrap the api because its so big
as well as how to connect to the websocket
Oh well i didnt know that u can make /commands disabled too
and ratelimits!
yeah mostly everything in docs is in js
it keeps saying "bot" is not deined
you just need to have a vision on how its done in py really
Read the topics https://discord.com/developers/docs/topics/gateway
Discord Developer Portal
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
You have gateway which I linked ^ And more
For the RESTful API you will need to read the respective documentation
how do i make a python file that runs 3 other python files when it is ran
explain? or example
so i accessed a user in my server using id
ok so if they loop will it run all 3 still?
get_member(user_id, /)```
Returns a member with the given ID.
Changed in version 2.0: `user_id` parameter is now positional-only.
how would i access guild using self.client
get_guild(id, /)```
Returns a guild with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
well do you happen to use heroku?
im using discord.py 2.0 would anything have to change?
well i have 3 different bots that i run on my local server but we are going on a trip and it will not be running during the trip so i am trying to have heroku cover for me during that time
Fortunately*
!d subprocess.run



