#discord-bots

1 messages · Page 966 of 1

slate swan
#
@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)
    
#

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)

junior verge
#

I'm on replit for 1 time and already get this haha

neon spear
#

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})
crimson tendon
#

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 ?

polar plinth
#

ay

junior verge
polar plinth
#

with some cmds

junior verge
#

Yeah, when does it error?

polar plinth
junior verge
#

Start what?

polar plinth
#
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.
junior verge
#

Oh okay

#

Can you send your main code

polar plinth
#

the code in the cog?

junior verge
#

Main

#

Are you even loading your cogs?

polar plinth
slate swan
#

Can i see the code?

polar plinth
junior verge
#

your help cog

polar plinth
#

yes

junior verge
#

Yeah

polar plinth
#

bru

slate swan
polar plinth
#

its not even online

#

and when i start it its says error

slate swan
#

horse1 then idk lmao

polar plinth
#
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

junior verge
polar plinth
#

u mean this @slate swan

junior verge
#

No need for that last line

slate swan
junior verge
#

@polar plinth is help.py is /commands?

maiden fable
polar plinth
#

ok

junior verge
#

Yeah theres no need for that line

#

You are already loading it

junior verge
slate swan
polar plinth
#

folder cogs

slate swan
# polar plinth

Put client.load_extension("cog.help") outside the For loop

formal basin
#

!d discord.Guild.get_role

unkempt canyonBOT
#

get_role(role_id, /)```
Returns a role with the given ID.

Changed in version 2.0: `role_id` parameter is now positional-only.
cloud dawn
slate swan
#
for heheheheh:
    ...
client.load_extension("cog.help")```
slate swan
formal basin
#

I need to get the role from my json file

slate swan
formal basin
#

Oops

slate swan
maiden fable
slate swan
#

How would I ping a user with there ID?

slate swan
cloud dawn
slate swan
#

@slate swan what's bumper bot for? 👀

maiden fable
#

if u r making a disboard bumper bot, it won't work

slate swan
#

hunter still living in the old days

maiden fable
#

The last time I used disboard or any other bot except mods one, was like an year ago or smth

hushed galleon
#
  1. you're missing the user argument when you call your kick function
  2. the bot doesnt have a .kick() method, probably what you want is ctx.guild.kick(<user>) or the Member.kick() method
cloud dawn
maiden fable
#

PoV: sad is a class

#

!paste thanks

unkempt canyonBOT
#

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.

hushed galleon
#

no i dont mean literally type out Member.kick()

cloud dawn
maiden fable
#

does it?

cloud dawn
#

Yesn't

slate swan
#

it depends on your clients zoom

maiden fable
slate swan
#

ctrl + and ctrl -

slate swan
#

ctrl 0 iirc to reset

slate swan
maiden fable
slate swan
#

its all in your settings!

slate swan
cloud dawn
#

i got it at 100

maiden fable
#

Chromium

slate swan
slate swan
slate swan
maiden fable
slate swan
slate swan
maiden fable
#

O weird

slate swan
cloud dawn
maiden fable
slate swan
slate swan
hushed galleon
slate swan
#

am I the only one who uses 40 zoom level 😔

slate swan
maiden fable
hushed galleon
#

passing your user inside that method sure

maiden fable
#

Rip I change it to 80 and uhhh

slate swan
slate swan
#

;))

maiden fable
hushed galleon
#

oh you moved it inside the view

slate swan
#

wha-

slate swan
slate swan
hushed galleon
#

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

maiden fable
slate swan
#

you just dont know how to use your laptop hunter

dull terrace
slate swan
hushed galleon
#

a button that kicks anyone who clicks it...?

slate swan
#

russian roulette!

#

that would be funny

dull terrace
slate swan
dull terrace
#

ram is so cheap tho, imagine that being your desktops bottleneck

slate swan
#

fn doesnt take much, it really depends on graphics and much more

slate swan
#

i would buy them but i want a rgb logitech 4kit of ram

#

of 64 ofc!

dull terrace
#

i think i only have like 16gb installed and i've never used 100% of it

slate swan
#

same

final iron
slate swan
dull terrace
#

the popo is here

#

🏃‍♂️

slate swan
#

you just dont check right mr Canadian

final iron
#

32GB of 3200mhz cl16 is $110 usd

slate swan
final iron
#

I do though

#

A 16GB kit of 3200mhz cl16 is $55

dull terrace
#

i just wish i could afford a new graphics card

#

this 1080 is slowly becoming outdated

slate swan
final iron
#

It's $56 on Amazon.

#

I would literally pay you to find me a 32GB 3600mhz kit for $32

slate swan
#

you really cant search well, i would check on the kit but im on mobile

final iron
#

Search what well?

slate swan
final iron
#

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

slate swan
#

ez

final iron
#

Only new.

#

I'll pay you $50 to find a 32GB 3600mhz kit for $32.

slate swan
maiden fable
cloud dawn
#
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

hushed galleon
#

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

unkempt canyonBOT
paper sluice
#

did u sync the tree

cloud dawn
paper sluice
#

ok do this, sync globally, then just wait

hushed galleon
cloud dawn
#

But that shouldn't matter.

hushed galleon
#

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

cloud dawn
#

Hmm get_commands() is empty

#

When removing guild=discord.Object(id=config.debug.guild) it is in the list. Super weird.

hushed galleon
#

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

unkempt canyonBOT
hushed galleon
#

have you double checked that config.debug.guild is still the correct id you were expecting?

cloud dawn
#

Yeah i even putted it in raw py_guido

fast atlas
#

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?

hushed galleon
#

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

fast atlas
hushed galleon
#

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)

knotty agate
#

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

maiden fable
#

Yea

#

!d discord.VoiceChannel.connect

unkempt canyonBOT
#

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").
cloud dawn
#

🤦

#

That works.

knotty agate
hushed galleon
cloud dawn
#

I gotta sync it twice now tough. Once for the specific one and one for global

pliant gulch
#

Do you guys think a reactive based caching interface to be overkill?

#

Shall I just do a normal one

cloud dawn
#

Normal one

heady sluice
#

meh

#

new account cuz lemon_intensifies

pliant gulch
cloud dawn
pliant gulch
#

I guess I'll scrap that idea

blissful sparrow
left crater
#

no

maiden fable
#

@hushed galleon congrats on the helper role!

hushed galleon
#

eyy

sick birch
#

Congrats! You definitely deserve it :)

slate swan
#

@hushed galleon congrats bro you deserve it!

#

❤️

slate swan
slate swan
hoary cargo
#

why you guys poop

slate swan
#

🤨

hoary cargo
#

🗿

crimson compass
#

how do i send custom emoji

#
```this doesn't work
heady sluice
heady sluice
slate swan
slate swan
#

but yes, u have to use <>

crimson compass
#

in the code its the right id

#

i used also <>

slate swan
#

the hell

slate swan
crimson compass
#

what is a

hoary cargo
#

animated

crimson compass
#

it aint animated

hoary cargo
slate swan
#

i think thats obvious he has to replace with his id and emoji name.. but youre correct

hoary cargo
#

as you see above idk if he understands it ciudat

crimson compass
#

it has

hoary cargo
#

has what

crimson compass
#

access in the emoji

#

and i replaced with the correct ones

hoary cargo
#

well, then your formatting is wrong

crimson compass
#

is it because i use it in embed

hoary cargo
#

depends in which part you try to use them

#

emotes won't work in the footer

crimson compass
#

shall i send you the code

hoary cargo
#

send the embed where you try to put it

crimson compass
#
        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

hoary cargo
#

🗿 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

blissful sparrow
#

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?

hasty bison
#

how can i like make it so that whenever a user joins a specific channel an other channel will automatically be created

torn sail
#

await bot.load_extension(…)

blissful sparrow
#

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```
slate swan
hoary cargo
blissful sparrow
boreal ravine
blissful sparrow
#
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

boreal ravine
#

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())

abstract kindle
#

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?

rustic onyx
#

guys if using self bots isnt permitted then why dont they patch it?

boreal ravine
rustic onyx
abstract kindle
#

more like

if user has role:
  role()
blissful sparrow
sick birch
rustic onyx
#

they could patch it, self-tokens are different from bot-tokens I think

sick birch
#

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

abstract kindle
#
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

sick birch
#

Use set intersection

slate swan
slate swan
#

how do you even get the user token?

#

and how does it look if its different than a bot one?

boreal ravine
#

inspect element

slate swan
#

ah

#

right

boreal ravine
# boreal ravine No

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

slate swan
#

does dpy have something to go against selfbotting?

slate swan
cloud dawn
#

Because it goes against ToS

slate swan
boreal ravine
boreal ravine
paper bane
#

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

pliant gulch
paper bane
#

well it won't work since the HTTP client adds the "Bot " prefix to the token

boreal ravine
#

also how the hell do you have a 6666 tag

paper bane
#

too many brandons

sick birch
#

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

paper bane
#

Bearer is not required no, Only the "Bot" prefix is required, if its a bot that is

pliant gulch
#

I thought user tokens didn't require Bearer

slate swan
#

can someone show the headers for auth?

pliant gulch
#

Bearer would be for Oauth2 access tokens right?

sick birch
#

Yes

#

Those are similar enough to real ones anyway to assume they're the same

pliant gulch
#

I remember seeing else where user's using an auth header without a prefix

#

It's just a plain token, no prefix

slate swan
#

how much tokens does discord use jeez

sick birch
boreal ravine
pliant gulch
#

All my homies love JWT

slate swan
#

but i think you guys are talking about just one

pliant gulch
#

Oauth2 endpoints would require a bearer token

#

Regular endpoints would use Bot tokens

cloud dawn
sick birch
#

And by regular I mean the ones outlined in the discord documentation

slate swan
#

between each endpoint?

pliant gulch
slate swan
#

i know the twitter api does use bearer and a user context token

sick birch
#

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

pliant gulch
#

If it's only with the access token it's kind of dumb to use bearer tokens for the regular API

sick birch
#

Nah I think you can use both access and regular tokens on endpoints

pliant gulch
sick birch
#

Basically just temporary user tokens

slate swan
boreal ravine
#

No

sick birch
#

Nah

pliant gulch
sick birch
#

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

boreal ravine
#

the thing is that they don't have nitro

pliant gulch
#

Your tag changes when you run out of nitro iirc

boreal ravine
#

and discord resets your tag if it previously changed with nitro

slate swan
paper bane
#

the reason being is, every single brandon tag is taken

sick birch
paper bane
#

so there's nothing to reset to

sick birch
#

that's a lot of brandons

paper bane
#

indeed

slate swan
#

but you're the superior one

sick birch
#

congrats, you were the 6561th brandon!

cloud dawn
#

no

#

If so they changed it

boreal ravine
#

9999 brandons exist pithink

sick birch
#

not quite

#

there are 6561 brandons

boreal ravine
#

oh

blissful sparrow
#

is there a way to allow both prefix commands and slash commands to co exist?

sick birch
#

if i'm not dumb

sick birch
#

9^4

blissful sparrow
#

How would u go about that? Im using cogs btw

glass tundra
#

Does anyone know what this mean: RuntimeWarning: coroutine 'Client.login' was never awaited

boreal ravine
#

It's an awaitable, await the method

glass tundra
#

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']
)

pliant gulch
#

Rewriting rin and so far I got a decent EventEmitter class, should I support middlewares

sick birch
#

await client.login()

glass tundra
pliant gulch
#

Yes

pliant gulch
sick birch
glass tundra
#

what?

sick birch
glass tundra
unkempt canyonBOT
#

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
```...
paper bane
#

its just not a kwarg

#

remove "token="

sick birch
# glass tundra what?
async def main():
  bot = commands.Bot(...)
  # do some setup here

  try:
    bot.login()
  finally:
    # do some cleanup here
asyncio.run(main())
glass tundra
sick birch
#

If it doesn't then something is seriously wrong with your library

#

And the chances of that are low

sick birch
#

I'm 100% sure client.run() takes a token

glass tundra
#

bot.run(token=

pliant gulch
sick birch
#

!d disnake.Client.run

unkempt canyonBOT
#

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...
pliant gulch
sick birch
glass tundra
#

...

#

I'm more lost than my code, lol

pliant gulch
pliant gulch
glass tundra
#

It works... okay.

#

I didn't await anything, though?

slate swan
#

nope

#

i think .start is tho

#

im not sure

glass tundra
#

can you translate that to dumb language?

slate swan
#

it cant be awaited

sick birch
#

If you want more lower level control you should use start()

glass tundra
pliant gulch
#

I want to say yes, but also I don't want to because I don't wanna 100% commit

slate swan
#

smh

#

then dont work on it if youre not gonna give it 100%😡

#

nah its made from scratch

pliant gulch
#

Because I have a reputation of never finishing my projects

#

So I'm trying not to give people false hope

slate swan
#

😔

#

i need hope

pliant gulch
#

No

oblique adder
#

How do I position the dropdown to be above the button ?

hushed galleon
glass tundra
#

How do I make the bot add an existing role to a person?

pure sparrow
hushed galleon
glass tundra
hushed galleon
#

there's the Guild.get_role() method to get a specific Role by its ID

glass tundra
#

and how would I know the id... or the guild, lol

hushed galleon
#

can you provide some context about what you're trying to do?

pure sparrow
glass tundra
#
    @commands.Cog.listener()
    async def on_member_join(self, user: disnake.Member):
        user.add_roles()
#

That.

pure sparrow
glass tundra
hushed galleon
#

alr, was thinking you could have been creating a role, in which case it already gives you the role object

pure sparrow
hushed galleon
#

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

glass tundra
#

I don't even know what the id is anyways.

hushed galleon
#

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

final iron
#

Oh you're a helper now

#

Cool

hushed galleon
#

neato

glass tundra
#

I'm too dumb for this, lol.

hushed galleon
#

btw run() passes through kwargs to the start method which has a token parameter, meaning token= is an acceptable kwarg for run() too

hushed galleon
glass tundra
#

java intensifies.

slate swan
glass tundra
slate swan
#

theyre pretty easy

#

its just an js

glass tundra
#

lol, no

slate swan
#

its long but informative

glass tundra
#

I just can't understand it though.

hushed galleon
#

a lot of d.py stuff works with objects

slate swan
hushed galleon
#

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

glass tundra
slate swan
glass tundra
blissful sparrow
#

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]}')

slate swan
#

how can i set a hyperlink on a image?
Using name doesnt work

blissful sparrow
#

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
You wasted 114.1 KB of space!

Caught lacking on Apr 9, 2022, 10:28 PM

glass tundra
#

How to do the cog thingy in other files? Like, make it add to the bot?

hushed galleon
blissful sparrow
#

Ah that explains it thanks

#

Im following a tutorial so it must be outdated

hushed galleon
#

well 2.0 does have a ton of breaking changes, so it would be pretty hard for blogs or video tutorials to keep up

slate swan
slate swan
glass tundra
slate swan
#

!d discord.ext.commands.Bot.add_cog

unkempt canyonBOT
#

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...
slate swan
#

!d discord.ext.commands.Bot.load_extension

unkempt canyonBOT
#

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)").
hybrid ravine
#

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?

glass tundra
#

what...

hybrid ravine
slate swan
hybrid ravine
slate swan
#

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?

blissful sparrow
unkempt canyonBOT
#

@slate swan :white_check_mark: Your eval job has completed with return code 0.

[3]
slate swan
glass tundra
#

how to get the bot's avatar?

hybrid ravine
blissful sparrow
# slate swan code?
@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)}')
hushed galleon
slate swan
sterile imp
#

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}")```
hushed galleon
hoary cargo
slate swan
slate swan
#

and why are you making the requests yourself?

blissful sparrow
hoary cargo
sterile imp
hybrid ravine
slate swan
hushed galleon
unkempt canyonBOT
#
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").
slate swan
#

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):
slate swan
hushed galleon
#

the response text no i assume not, but they send their headers right afterwards

slate swan
#

LMAO

hoary cargo
# slate swan bro

🗿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

slate swan
#

aight thanks

sterile imp
#

idk why its kinda weird

blissful sparrow
sterile imp
#

does anyone know how to fix it?

blissful sparrow
#

Ive not told them to load again

boreal ravine
hushed galleon
abstract kindle
#

What's the syntax for handling button timeouts?

slate swan
#

@hushed galleon question since hes not sending hb it would disconnect after that request right?

hoary cargo
slate swan
#

!d discord.ui.View

unkempt canyonBOT
#

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.
boreal ravine
sterile imp
abstract kindle
#

Perfect @boreal ravine, thanks

slate swan
#

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

unkempt canyonBOT
#

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!

slate swan
#

bro

#

remove the old token

sterile imp
#

@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

left crater
#

thats not what he meant

boreal ravine
boreal ravine
sterile imp
#

im not, my ID is whitelisted

slate swan
slate swan
#

youre returning the function lol

sterile imp
#

how do i unblacklist myself

hushed galleon
slate swan
boreal ravine
hybrid ravine
abstract kindle
#

Does interaction serve as a form of ctx?

slate swan
slate swan
abstract kindle
#

ok perfect

boreal ravine
hushed galleon
slate swan
# abstract kindle ok perfect

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

hybrid ravine
sterile imp
#

bro now it gives error in chat

#

wait let me blur

boreal ravine
#

Delete that

abstract kindle
#
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...

sterile imp
#

do u know how to fix it

boreal ravine
boreal ravine
slate swan
abstract kindle
#

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

sterile imp
#
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)```
hushed galleon
slate swan
boreal ravine
sterile imp
#

the one u sent

boreal ravine
#

can you try doing json=data

hushed galleon
#

er i mean, there should be braces inside the square brackets

boreal ravine
#

oh yeah

boreal ravine
slate swan
#

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
blissful sparrow
#

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))

You wasted 46.36 KB of space!

Caught lacking on Apr 9, 2022, 11:08 PM

#

Where I gone wrong now Cry

slate swan
#

thats not even accurate

#

!d discord.ext.commands.Bot.latency

unkempt canyonBOT
#

property latency```
Measures latency between a HEARTBEAT and a HEARTBEAT\_ACK in seconds.

This could be referred to as the Discord WebSocket protocol latency.
sterile imp
slate swan
slate swan
boreal ravine
blissful sparrow
#

Im just trying to get the main cogs to work

slate swan
silver wolf
sterile imp
#

OMG IT WORKED

#

@boreal ravine

slate swan
silver wolf
#

@blissful sparrow what lib a u using? because didn't discord.py 2.0 kinda change the way cogs are loaded in?

slate swan
#

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

hushed galleon
blissful sparrow
slate swan
#

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
slate swan
hushed galleon
#

exactly

#

so there's no concern about them not being "accurate", he's testing a different kind of latency

boreal ravine
unkempt canyonBOT
#
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...
slate swan
lone hare
blissful sparrow
#

i think

potent otter
#

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"
...
silver wolf
hushed galleon
#

this screenshot is too big

blissful sparrow
boreal ravine
blissful sparrow
#

minus the DB

slate swan
#

btw nice ping command lol

blissful sparrow
# silver wolf hmm. show the code u have that loads ur cogs
@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)}')
slate swan
#

thats hb latency

potent otter
hushed galleon
#

i remember using the message's created_at datetime once but i would end up with negative milliseconds occasionally

slate swan
boreal ravine
#

your bot took 50 seconds to send a message?

slate swan
#

bro

#

it clearly says ms

hushed galleon
#

yeah it aint just 50 seconds its 50 megaseconds

slate swan
#

jeez

hushed galleon
#

578 days of uptime just to see that ping message

slate swan
#

😅

#
>:
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'
hushed galleon
sterile imp
#

how do u autoshard a discord bot?

slate swan
slate swan
slate swan
sterile imp
#

its in 6.2k servers so idk

slate swan
#

yeah it probably does

sterile imp
#

dw it has all intents verified

slate swan
umbral night
#

how would i be able to define a channel through a command

#

instead of putting the channel id in the code

slate swan
slate swan
sterile imp
#

so uhh do u know how to shard it

hushed galleon
umbral night
slate swan
#

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
            
blissful sparrow
#
@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]}')
hushed galleon
#

is there an error in your console this time?

blissful sparrow
#

yes a lot of em

umbral night
#

``# welcome message
@client.event
async def on_member_join(member):

await channel.send(f'ty for joining, {member.mention}')``

slate swan
#

where

umbral night
#

i forgot how to embed py code

slate swan
umbral night
#

how do u do it

slate swan
#

none of that requires the iteraction arugement

unkempt canyonBOT
#

Hey @blissful sparrow!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

slate swan
#

pycord docs

blissful sparrow
slate swan
#

ill try it though

slate swan
hushed galleon
unkempt canyonBOT
#

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.

blissful sparrow
umbral night
#

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
#

@slate swan callback1(interaction) like this correct?

hushed galleon
slate swan
#

interaction is self here no?

#

It is.

slate swan
slate swan
slate swan
sterile imp
#
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
hushed galleon
slate swan
#

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

blissful sparrow
umbral night
#

otherwise sry

slate swan
#

its a dropdown menu does that still assoicate with buttons?

slate swan
#

interaction: discord.Interaction

slate swan
#

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
slate swan
hushed galleon
umbral night
#

how can i make a welcome message work in multiple servers without putting their specific channel ids in the code (with one bot)

slate swan
#

Alright

sick birch
umbral night
#

uh

sick birch
#

Should you send it in the first channel you have perms in, check for a system channel, etc

slate swan
sick birch
#

That's what they said they didn't want to do

sick birch
#

without putting their specific channel ids in the code (with one bot)

#

I'm assuming that also extends to storing

slate swan
#

its not in there code

#

its in the database

sick birch
#

Ah, hard coding?

#

Then yes, a database is the best way to do it

glass tundra
umbral night
sick birch
unkempt canyonBOT
#

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`.
umbral night
#

sorry, im fairly new

unkempt canyonBOT
blissful sparrow
#

im still getting this though

sick birch
# umbral night sorry, im fairly new

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

blissful sparrow
#
class Owner(commands.Cog):
    
    def __init__(self, bot):
        self.bot = bot

#

this is how Ive started the class

glass tundra
#

what...

blissful sparrow
#
async def setup(bot):
    await bot.add_cog(Owner(bot))

and this is how Ive done the cog setup

glass tundra
#

You guys gave me functions which I didn't understand, lol.

umbral night
#

like not even in the code / ide

slate swan
#

Kayaa, how would I subclass inside a cog

sick birch
#

Is that recursive or?

slate swan
#

considering Id have to do discord.ui.select, aswell

slate swan
sick birch
sick birch
#

how'd you guess that?!

glass tundra
#

wait, what is self.load_extension?

slate swan
sterile imp
#

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}")```
sick birch
#

Only logical. We wouldn't want a stackoverflow error

slate swan
sick birch
slate swan
glass tundra
#

Yes, yea, add the cog to the bot.

slate swan
slate swan
#

oh

#

oh ok so like this
class menu(discord.ui.View):

slate swan
#

it should be UpperWord and it does not suit it properly for dropdowns

sterile imp
glass tundra
slate swan
#

pycord

slate swan
glass tundra
#

I can't understand anything, lol.

sick birch
#

that was me :)

slate swan
sick birch
#

yup. that was my first merged PR

glass tundra
sick birch
#

It's just nice knowing that it's actually coming in helpful for people

glass tundra
#

Like, how?

slate swan
# sick birch :sadcat:

first thing i see is import typing and i dont see no place where its being used, maybe im blind

glass tundra
#

Something, dunno. A bot and some random commands.

sick birch
slate swan
sick birch
#

That's a first step towards understanding the whole thing

sick birch
glass tundra
#

I'm using it... probably.

umbral night
#

wait so how would i get the welcome message to work in 2+ servers even with the channel ids in the code

glass tundra
umbral night
#

wouldnt it send the messages in the other servers too?

slate swan
sick birch
# glass tundra wdym?

load_extensions() is for loading extensions, knowing what those are can help you understand the whole thing

sick birch
glass tundra
#

I read those, not much of a help, though. ||sry||

umbral night
#

does anybody know how to make welcome messages work in multiple servers

slate swan
glass tundra
slate swan
#

thanks

sick birch
# glass tundra I read those, not much of a help, though. ||sry||

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

umbral night
#

im unsure how to use a database

#

and i didnt understand the other stuff as i'm new

glass tundra
slate swan
sick birch
#

It does mention setup, here, however, they were adding a command, but that's ireelavant

umbral night
#

is json java script or something?

#

whats that

sick birch
glass tundra
# sick birch

There is nowhere in the cogs section talking about it... only way I would is talking with someone that knows it.

slate swan
sick birch
#

It's a file represtantion of javascript objects:

const person = {
    first_name: "John",
    last_name: "Doe",
    age: 42
}
umbral night
#

thankyou

sick birch
#

And that's one of the reasons why talking to other programmers and asking for help is one of the best ways to learn

umbral night
#

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
glass tundra
sick birch
#

Also understandable. Anyway, do you understand extensions or do you still need a little bit of help?

sick birch
slate swan
#

i like working in groups because im lazy 😔

sick birch
#

Pick good technologies from the start

umbral night
slate swan
sick birch
slate swan
#

Its hadd💀

sick birch
#

I put that in caps and bold because people use it WAYYY too much

slate swan
#

Hard*

sick birch
#

It's incredibly important that you **DO NOT ** use json as a database

slate swan
umbral night
#

i dont even know how to use a database

#

nor json

sick birch
slate swan
#

json is used mostly for formatting data an not saving it

glass tundra
sick birch
slate swan
sick birch
#

So use that, recursively walk through all files, load them as extensions

final iron
slate swan
glass tundra
sick birch
slate swan
#

question he probably wouldve asked😭

glass tundra
#

wat...

slate swan
#

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

umbral night
#

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

slate swan
final iron
umbral night
#

yes pls

glass tundra
#
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.
slate swan
slate swan
#

anyways!!!!

final iron
sick birch
slate swan
sick birch
# glass tundra wdym?

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

glass tundra
#

I don't understand pathlib.

sick birch
#

Best to take the safer route and use the recomended pathlib

slate swan
#

should get the channel first so you can save a request

slate swan
supple thorn
final iron
slate swan
final iron
#

^

slate swan
#

just use getch?

supple thorn
#

I should try and learn how to make a api wrapper and how to work in groups

final iron
#

You just need to communicate

supple thorn
#

Mostly don’t know which api to choose to make one

slate swan
#

thats weird is it really not implemented yet

supple thorn
green bluff
#

does member id change if i change my username

supple thorn
slate swan
slate swan
supple thorn
#

Okimii slow ducky_drawing

slate swan
green bluff
slate swan
umbral night
#

tysm

supple thorn
slate swan
# slate swan why?

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 :|

supple thorn
slate swan
#

They banned me >:(

supple thorn
slate swan
slate swan
supple thorn
#

How do i make a api wrapper

#

I’ve never made one

slate swan
#

smh😔

hushed galleon
#

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

supple thorn
#

I forgot what it’s called or who made it

#

I just saw someone’s website on their links in their profile

slate swan
#

just look at any api wrappers src

supple thorn
#

Cracks is finally a helper?

slate swan
#

aiohttp, requests and httpx are the most used

supple thorn
#

I wonder what it takes to be a helper

supple thorn
#

I mostly never see one

#

Well i am only here in the discords bots channel most of the time

slate swan
#

pardon?

pliant gulch
#

What would you need bs4 for with a wrapper

slate swan
#

to me it was easier making a sync wrapper and then making an async one

pliant gulch
#

If your making a wrapper, I'd assume that means there is an exposed API

#

Bs4 is for scrapping

slate swan
#

when i made my first async wrapper it didnt event had objects

pliant gulch
#

Async isn't that hard to implement

slate swan
#

yeah not anymore ofc

pliant gulch
#

But you can rarely have both sync and async together

#

Async tends to be infectious

slate swan
#

yeah

#

but it depends

#

New feature?

pliant gulch
#

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

slate swan
#

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

pliant gulch
slate swan
#

Oh well i didnt know that u can make /commands disabled too

slate swan
pliant gulch
#

Ratelimits are easy enough

#

That is if you understand how they work

slate swan
#

yeah

#

its all easy when you get the hang of it really

pliant gulch
#

I've recently learned that there are hidden ratelimits

#

So that's gonna be a pain

blissful sparrow
#

Am I doing something wrong here

slate swan
#

yeah mostly everything in docs is in js

blissful sparrow
#

it keeps saying "bot" is not deined

slate swan
#

you just need to have a vision on how its done in py really

pliant gulch
#

You have gateway which I linked ^ And more

#

For the RESTful API you will need to read the respective documentation

echo wasp
#

how do i make a python file that runs 3 other python files when it is ran

#

explain? or example

green bluff
#

so i accessed a user in my server using id

echo wasp
green bluff
#

buti cant edit their nick

#

is there anyway i can?

echo wasp
#

ok so if they loop will it run all 3 still?

green bluff
#

how would i get member object

#

using id

unkempt canyonBOT
#

get_member(user_id, /)```
Returns a member with the given ID.

Changed in version 2.0: `user_id` parameter is now positional-only.
green bluff
#

how would i access guild using self.client

unkempt canyonBOT
#

get_guild(id, /)```
Returns a guild with the given ID.

Changed in version 2.0: `id` parameter is now positional-only.
green bluff
#

thanks

#

so like this?

echo wasp
#

well do you happen to use heroku?

green bluff
#

im using discord.py 2.0 would anything have to change?

echo wasp
#

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

sick birch
#

Fortunately*

pliant gulch
#

!d subprocess.run