#discord-bots

1 messages · Page 383 of 1

timber dragon
#

Replacing not adding

spring ferry
#

Can you copy my code add replace pls

timber dragon
#

Nuh uh

spring ferry
#

.

timber dragon
#

Gotta learn doing it yourself

spring ferry
#

Which thing need to remove ?

timber dragon
#

Read your code and check

spring ferry
#

Help

#

@slate swan Help me

slate swan
#

Help with?

spring ferry
#

It's showing still error

#

When I did this

#

This is my code can you check out and tell me what wrong?

#

@slate swan

slate swan
spring ferry
#

It's basically not replying when I type !MIB to activate my bot

zenith yarrow
#

?tag embed

novel apexBOT
#

This is not a Modmail thread.

slate swan
#

Didnt i already tell you that timezone is submodule of datetime

#

So you need to import it

#

!d datetime.timezone

unkempt canyonBOT
#

class datetime.timezone(offset, name=None)```
The *offset* argument must be specified as a [`timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta) object representing the difference between the local time and UTC. It must be strictly between `-timedelta(hours=24)` and `timedelta(hours=24)`, otherwise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) is raised.

The *name* argument is optional. If specified it must be a string that will be used as the value returned by the [`datetime.tzname()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.tzname) method.

Added in version 3\.2\.

Changed in version 3\.7: The UTC offset is not restricted to a whole number of minutes.
spring ferry
#

Ok

#

Right ?

#

Helo?

#

@slate swan

slate swan
#

Do you even know what you are doing

spring ferry
#

Importing

slate swan
#

You copied Class declaration mindlessly

#

Its obviously a wrong syntax

spring ferry
#

So what right?

#

I'm beginner

slate swan
#

If you are a beginner start from beginner things and not a discord bot project which requires advanced python concepts

spring ferry
#

Ok but it's only 1 error my project will be finished

#

Can you copy and fix my code pls ?

slate swan
#

No that's not how helping works

spring ferry
spring ferry
slate swan
#

You dont copy paste random code to your project

spring ferry
#

Ok

slate swan
#

I just wanted to show you that datetime module Has a submodule called timezone which apparently you want to use

spring ferry
#

Help me only 1 time

slate swan
#

So to your current datetime import add that timezone submodule and change the code from datetime.timezone. to timezone.

spring ferry
#

Ok

slate swan
#

is there on discord any option to switch between discord accounts like on instagram? Do I have to log out and log in every time?

slate swan
#

I don't see it on my phone

#

i dont know if its out on mobile yet

#

you can do that on pc for sure

spring ferry
#

It's working not showing error but why the bot is not replying

slate swan
#

read the warning it gave you

#

!mcintent

unkempt canyonBOT
#
Discord Message Content Intent

The Discord gateway only dispatches events you subscribe to, which you can configure by using "intents."

The message content intent is what determines if an app will receive the actual content of newly created messages. Without this intent, discord.py won't be able to detect prefix commands, so prefix commands won't respond.

Privileged intents, such as message content, have to be explicitly enabled from the Discord Developer Portal in addition to being enabled in the code:

intents = discord.Intents.default() # create a default Intents instance
intents.message_content = True # enable message content intents

bot = commands.Bot(command_prefix="!", intents=intents) # actually pass it into the constructor

For more information on intents, see /tag intents. If prefix commands are still not working, see /tag on-message-event.

spring ferry
#

Ohk

fast osprey
#

Looking over your code, I really strongly recommend you reconsider building this "antinuke" stuff. The entire purpose is predicated on your users being too stupid to handle their server themselves, and if you're already assuming that there's no reason to assume they're somehow not stupid enough to break any of the things your bot relies on.

Also, outright banning anyone who gets the admin permission is pretty laughable

spring ferry
#

So suggest me

#

How can I make

#

This good best

#

@fast osprey

#

Does u make bot like this ?

fast osprey
#

Educate your users on good security practices and make recommendations to them rather than trying to override the decisions they themselves have made

#

No, because bots like this (at least that subset of functionality) are at best unnecessary and at worst an active security risk

#

I have, however, in my time seen things like this crash and burn miserably

spring ferry
#

But I want to make a antinuke bot for my friend server

#

Antiraid

#

Antispam but my bot is not replying not enable 😅😭

#

Now I lost my hope

#

I'm not making now bot

fast osprey
#

You should not make features that attempt to excuse people from managing their own servers and understanding how permissions work. You can absolutely make a bot that aids in this rather than trying to replace it

#

But if you make a bot under the entire pretext of "You don't have to understand security or permissions, my bot takes care of it", they will continue not understanding things and there will always be a way they can screw things up

#

For spam, you should really look into the automod tooling that's available

jade jolt
#

i fixed it by doing nothing

slate swan
#

you know message that only you can see? like to the bottom it’ll say dismiss how do I do that in slash cmd

fast osprey
#

You can pass ephemeral=True when responding

snow coral
#

Yeah. Its not deleting it when there’s a bad word in the linked image

stark ingot
#

Is the API returning the correct words?

snow coral
stark ingot
#

What part is specifically not working?
It does not delete the message when there is a bad word in the image
It does not delete the message when there is a bad word in the url?

snow coral
#

Oh I know what happened

#

Sorry

stark ingot
#

We are here to help no need to be sorry :)

snow coral
#

So its something with either finding it or deleting it

#

It looks like this right now ```py

urls = func.extract_url(message.content)
if urls:
if len(urls) == 1:
text = func.image_to_text(url[0])
if any(bad_word in text.lower() for bad_word in badwords):
await message.channel.send(f"[AUTO] {message.author.mention}, your message has been deleted for containing a blocked keyword.")
await message.delete()
else:
for i in range(len(urls) - 1):
text = func.image_to_text(url[i])
if any(bad_word in text.lower() for bad_word in badwords):
await message.channel.send(f"[AUTO] {message.author.mention}, your message has been deleted for containing a blocked keyword.")
await message.delete()```

stark ingot
#

do you have the message content intent?

snow coral
#

Yeah

stark ingot
#

I am a bit confused. When you send a URL that leads to an image with bad words it correctly identifies the bad words (You can check by printing text) However the message is not deleted?

snow coral
#

Mhm. It finds the text fine from testing

stark ingot
#

does it go into the if statement? Are there any errors in your console?

fast osprey
#

In general, doing some debugging to see what is actually running would go a long way

snow coral
#

I got it to work

#

Thanks

stark ingot
#

@sacred grotto I saw your help post but it was locked.
Your issue is that you are enabling all of the intents. Discord has a few "special" intents that require additional approval when your bot gets big enough (its for data privacy reasons) So you need to go to the discord developer portal -> your app -> Bot -> Turn the settings in the screenshot ON

fast osprey
#

It is incredibly unlikely that all intents are needed, whatever this app is doing

stark ingot
#

^ The best solution would be to only use intents that you need but what I said is the direct solution to the error

slate swan
#

how to make it so users who use my bot cannot ping everyone?

stark ingot
#

You can look into allowed_mentions argument of send/respond

#

Or you can take away the permission to mention everyone on the bot if it is only on your private server or something

slender vault
#

@last sorrel hey nick you still into python bot dev?

slate swan
#

how can a slash/hybrid command have spaces?

fast osprey
#

Those are command groups

slate swan
fast osprey
#

I think umbra's gist has em if you've read that

mild token
fast osprey
#

You also don't have to use cogs. You can just subclass app_commands.Group too

signal summit
#

Im making a discord bot that returns accuracy from a given PGN (list of moves) in the chat. I have the bot writing this data given in the chat to a temporary file that the accuracy script reads from. When I download raw pgn data from the chess website it works just fine but when I use the data from the discord bot (looks the exact same) it raises an error. Could discords formatting be causing this issue?

fast osprey
#

What's the error?

mild token
merry cliff
#

I'm getting something really weird but after I stop my bot the program does not terminate and it sens this after a bit ```
Exception in thread keep-alive-handler:shard-None:
Traceback (most recent call last):
File "C:\Program Files\Python312\Lib\threading.py", line 1073, in _bootstrap_inner
self.run()
File "C:\Users\SiqiC\OneDrive\Docos\CODE DUMP BOI\Python\discord bots\sinflex\everything_bot.venv\Lib\site-packages\discord\gateway.py", line 170, in run
f = asyncio.run_coroutine_threadsafe(coro, loop=self.ws.loop)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Program Files\Python312\Lib\asyncio\tasks.py", line 950, in run_coroutine_threadsafe
loop.call_soon_threadsafe(callback)
File "C:\Program Files\Python312\Lib\asyncio\base_events.py", line 840, in call_soon_threadsafe
self._check_closed()
File "C:\Program Files\Python312\Lib\asyncio\base_events.py", line 541, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
C:\Program Files\Python312\Lib\threading.py:1075: RuntimeWarning: coroutine 'DiscordWebSocket.send_heartbeat' was never awaited
self._invoke_excepthook(self)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

#

no idea what is hapenning ¯_(ツ)_/¯

#
import asyncio
import logging

from bot.bot import Bot


async def main() -> None:
    await bot.load_extensions("bot/cogs")
    await bot.connect_to_database()
    await bot.start(bot.settings.discord_bot_token)
    await bot.close_database_connection()
    await bot.close()


if __name__ == "__main__":
    bot = Bot()
    loop = asyncio.get_event_loop()
    try:
        loop.run_until_complete(main())
    except KeyboardInterrupt:
        logging.info("Shutting down bot...")
        loop.stop()
        loop.close()
merry cliff
graceful raven
#
import discord
from discord.ext import commands, tasks
import asyncio


class Nickname(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    @self.bot.event
    async def on_member_join(member):
        print(f'{member} has joined the server.')

If I want to listen to events in another class other than main file, how do I call bot.event? self.bot.event doesn't seem to be working for some reason

#

do I need to import my main class to call bot from there?

scarlet tiger
graceful raven
scarlet tiger
graceful raven
#

Doesn't seem to be seeing people joining

#

nvm, forgot to set the members = True intent lol

mild token
#

!d discord.ext.commands.Bot.start

unkempt canyonBOT
#

await start(token, *, reconnect=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

A shorthand coroutine for [`login()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.login) \+ [`connect()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.connect).
slate swan
#

anyone familiar with pysilon?

graceful raven
timid smelt
#

Hello guys
How can I earn making Discord bots, please?

fast osprey
#

Make a bot with features that people want to use, pick some or all of the features you want to pay gate, register them with the SKU options discord gives you

mild token
#

What is sku?

timber dragon
#

Oh til they made a lot of support articles about it

mild token
#

Tnx

#

Not yet out where I am : (

#

any event which gets fire when thread or forum post get closed/lock after the time expire?

lyric juniper
#

Hi does anyone know why i get this error

#

discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.

#

All of my intents are enabled on the discord bot page settings, i just want to make a bot where i can DM the bot and say ping, and the bot replies with pong in dm;s

#
import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.messages = True
intents.message_content = True  # This is required to read message content
intents.guilds = True
intents.dm_messages = True  # Ensure to enable this intent for DMs

bot = commands.Bot(command_prefix='!', intents=intents)

@bot.event
async def on_ready():
    print(f'We have logged in as {bot.user}')

@bot.event
async def on_message(message):
    if message.author == bot.user:
        return

    print(f"Received a message from {message.author}: {message.content}")

    if isinstance(message.channel, discord.DMChannel):
        if message.content.lower() == 'ping':
            await message.channel.send('pong')

bot.run('')```

Forgot to show code
vapid parcel
#

Okay so I am working on making my bot support multiple languages using like English.json and French.json, like how many other bots do it I would think.

But my question still comes down to, @app_commands.describe(member="Please give a member.")

Is there a way to translate that? or am I just stuck with the default language (English)? Same with descriptions on command?

        Warn a member.

        **Usage:** warn <member> [reason]

        **Examples:**
        - `warn @member Breaking rules`
        - `warn @member Spam pinging`
        - `warn @member Sending inappropriate messages`
        """```

These type of descriptions ^^

They are hard coded so that is why I was wondering, I could also do something with the jsons maybe, but just wanted to see how others maybe handle the describe and descriptions of commands with multiple languages?
fast osprey
lyric juniper
#

Oh im an idiot

#

Thanks 😭

fast osprey
#

nwnw. Default() even has intents 99% of devs don't actually want

glad marsh
#

i added ptero gitsync to my hosting server, but it sends this error

        database/bot.db
Please commit your changes or stash them before you merge.```

i added database/bot.db to the .gitignore file as i dont want it to be modified from my local version, is there somehow else i can do this or can i resolve this?
fast osprey
#

Did you commit the gitignore?

#

And are you sure that what you added to it works?

hushed galleon
#

also, did you previously commit bot.db before updating your gitignore? if so, i believe the gitignore can't retroactively remove files that are already being tracked, you would need to manually untrack them by using git rm --cached <path> and then committing

btw for git-related issues, you may get more help asking in #tools-and-devops instead

vapid parcel
hushed galleon
# vapid parcel Okay so I am working on making my bot support multiple languages using like `Eng...

for application commands, dpy's CommandTree can be given a custom Translator class to localize your command names, descriptions, parameters, and choices on sync
https://discordpy.readthedocs.io/en/stable/interactions/api.html#discord.app_commands.CommandTree.set_translator
https://discordpy.readthedocs.io/en/stable/interactions/api.html#discord.app_commands.Translator

as for other forms of content like messages, embeds, and views, you can manually invoke the translator via bot.tree.translator.translate() and Interaction.translate()

fast osprey
#

json is pretty awful as a storage format in terms of space and efficiency. It's designed to be a language agnostic interchange format

vapid parcel
fast osprey
#

It's not, and people doing a thing does not remotely imply it is the best or even a good thing to do

vapid parcel
vapid parcel
#

or are you saying the translations aren't data?

fast osprey
#

"data language" doesn't make sense

#

As I said, json is for transferring data between systems

#

it is not optimized for one system internally storing and accessing it

vapid parcel
#

What I mean by data language is, its returning data. I had no other way of describing it lol

So we are on the same terms I guess

fast osprey
#

Not really, no, as there is an important distinction for how the data is used

vapid parcel
#

But I will check out what thegamecracks gave me, which should improve what I have hopefully.

The only examples I have seen were people using .json so thats why I used .json, so thats my bad

fast osprey
#

all good, it's more nuance. This won't make or break an application, but a lot of people fall into the trap of following examples without really knowing how or why they are a good idea (or in this case, a bad idea)

vapid parcel
#

That is fair, I just thought maybe opening my bot to more languages would help others out ya know, but never thought of the best way of doing it. So I looked at examples and they all showed the same way and it kinda was weird.

But thats also why I asked here, not the same topic, but close enough and it led me to the correct spot.

#

But glad I asked here lol

fast osprey
#

Yeah there are data formats (like resource files) that are better suited for storing this particular type of data within an application. Worth looking into

mild token
#
    @app_commands.command(
        name="promote", description="promote the user"
    )
    @app_commands.choices(
        position=[
            app_commands.Choice(name="Server Entry Staff",
                                value=str(RoleIds.ENTRY_STAFF)),
            app_commands.Choice(name="Server Recruiter",
                                value=str(RoleIds.SERVER_RECRUITER)),
            app_commands.Choice(name="Server Manager",
                                value=str(RoleIds.SERVER_MANAGER)),
            app_commands.Choice(name="Server Moderator",
                                value=str(RoleIds.SERVER_MODERATOR)),
            app_commands.Choice(name="Server Gatekeeper",
                                value=str(RoleIds.GATEKEEPER)),
        ],
    )
    @app_commands.describe(user="User you want to promote", position="position you want to give to the user")
    async def check_modal(self, interaction: discord.Interaction, user: discord.Member, position: str) -> None:

i want to get position choice name data

#

just printing position gives the value of it

fast osprey
#

You shouldn't be using the display name to drive logic

#

The value is what you should be using. Whatever you need, put it in the value

untold remnant
#

Hi. I would like to ask if I can create an event in which I capture information from another source? For example, I have a web panel and at a given button send, for example, a message?

shrewd apex
#

not an event specifically but u would have to run a web server side by side to get reqests from the webpanel

#

and have ur bot process it and respond to it

untold remnant
#

In what sense side by side

shrewd apex
#

u basically mean when someone performs some action on the webpanel the bot is notified right?

untold remnant
#

When someone performs an action in the panel then the bot triggers the corresponding event

shrewd apex
#

yeah then u need a web server running along with your bot accepting web requests from your web panel

#

side by side in the sense u can spawn it in another task

#

basically u need to listen to http requests

untold remnant
#

And such basic listening? I host the bot on the same server as the panel

#

Or else... Could I have some sort of tutorial on this, or basic functions? I also have the panel set up in python on Flask

fast osprey
#

Personally I recommend you do not colocate your gateway bot and a http webserver. These things do very different jobs, and you'll probably find that they actually don't need to communicate much if at all given the web server can make api requests to discord itself without going through a gateway bot

untold remnant
#

I'm looking for options to make it work in general.

fast osprey
#

What's an example of something you'd want to do?

untold remnant
#

I have a form made in the panel and I want the bot to be connected to it and send to the appropriate channel the information in it just after clicking the submit button

#

The site and form made with python, so it's easy to plug in with confidence

fast osprey
#

You don't need a bot at all to send a message

#

the web server could just post to a webhook

untold remnant
#

And how else can the bot be integrated? More than once it will have to give roles

#

Such an intention

fast osprey
#

You can give roles without going through a bot

#

bots exist to listen for events from discord. If you are pushing things to discord, the bot doesn't have to be involved at all

#

If you really want your web server to talk to a gateway bot, these should be in separate processes and communicate over IPC for the things they need to do. But people often vastly overestimate what they need the bot for

untold remnant
#

Then what is the best way to do it? Do you have a basic script or tutorial?

fast osprey
#

Do what specifically?

#

Send a message to a webhook?

untold remnant
#

What webhook?

untold remnant
fast osprey
#

libraries like discord.py have utility python wrappers that make this easier, but notably they do not require a gateway bot running

untold remnant
#

I've a webhook

tribal bison
#

I’m trying to make a discord bot that gets rid of gen-z slang but I no longer have any chatgbt tokens. I do not want to spend any money on this project so any suggestions on creating an ai model?

fast osprey
#

You should first very carefully read the relevant discord developer policy if you have not already

tribal bison
#

I’m using it to just showcase ai

#

The AI will hopefully not learn anything either as well

fast osprey
#

Namely a) if you are sending any user data to a third party, you need explicit instruction from that user to do so and to record that and b) message content can't be used to train models, regardless of who is doing it

tribal bison
#

Since making an Ai seems to be extremely painful

#

Any help is extremely appreciated 😃

fast osprey
#

As in someone says a word, and you want to reply with another word? Or are you trying to moderate?

tribal bison
#

I’ll state what I’m trying to do.

Turns sentences with Gen-Z slang and rewrite it without the slang

#

“Ong that was hype” to “On god that was cool”

fast osprey
#

You could attempt to do this with regex, but anecdotally people will misspell or otherwise alter common words

tribal bison
fast osprey
#

Regex with capture groups would do that

tribal bison
#

I’m going to make a thread for this so I don’t flood the chat with this

ancient portal
#

hello, how do i tell Main.py to decode with utf-8?

#

unicodes are not display correctly when sent to discord

slate swan
#

yo can someone help me

#

i keep getting an error even though i did everything right

wanton current
#

You need to enable it in the code as well

slate swan
#

its in the code

wanton current
#

can you show

slate swan
#

intents = nextcord.Intents.default()
intents.members = True
intents.message_content = True

wanton current
#

and the bot =?

slate swan
#

Ignoring exception in command None:
nextcord.ext.commands.errors.CommandNotFound: Command "test" is not found

#
import nextcord
from nextcord import Interaction
from nextcord.ext import commands
import os

intents = nextcord.Intents.default()
intents.members = True
intents.message_content = True

client = commands.Bot(command_prefix="!", intents=intents)

@client.event
async def on_ready():
    print("The bot is ready for use")
    print("-------------------------")

ServerId = 'aaaaa'

@client.slash_command(guild_ids=[ServerId])
async def test(interaction: Interaction):
    await interaction.response.send_message("Wsg broda")

client.run('aaaa.aa.aa')```
wanton current
#

hmm

slate swan
#

BRO IM SO DUMB

#

fixed

vapid parcel
#

Because we all work together, but if only I can access the source, that makes production bad and makes this a bad way of doing this for our bot.

hushed galleon
vapid parcel
#

Okay, so I would just have to research other ways to get gettext on mac and code space?

hushed galleon
#

im currently experimenting with rewriting my bot to use project fluent, its been fairly tedious changing out the strings

vapid parcel
#

I just do not want to do this and make it a compatibility issue for other developers on the team, for my vps it would be fine, but other developers it might come into an issue.

#

It seems fairly easy to setup and do. I actually like how you have done the docs on it and showed it. But I never thought about the compatibility tbf.

hushed galleon
#

project fluent doesn't require external compilation so its simpler in that regard

#

though afaik it doesn't come with any official tools, nothing like xgettext and msgmerge

#

as for gettext, some of the GUI editors i linked are also cross-platform so you should be able to use poedit on windows and mac for editing and compiling MO files

ancient portal
#

Hello, How do I run every single main.py in a subfolder?

I'm trying to run all of those main.py in sub folder in 1 go without having to run them 1 by 1

finite salmon
ancient portal
#

im fairly new in this, so i dont know much

finite salmon
#

create another file and name it whatever you want and in it put

from foldername1 import main
from foldername2 import main
# and so on
#

But it's an unusual way of executing code though

#

What are you trying to do

ancient portal
#

Im making a discord auto message, i copy my friend code which are hardcoded into doing 1 message per

#

Idk how to make it so that i can send a message in multiple channel in 1 file

finite salmon
#

You'd probably have to use a loop

ancient portal
finite salmon
#

Damn

#

You're using the raw api

#

Any reason why you're not using any wrapper

ancient portal
#

im very new in this, i copied my friend code

#

i dont know much haha

fast osprey
#

And for sending messages to a channel, a webhook would probably be more appropriate anywho

finite salmon
#

I personally use pycord

fast osprey
#

I'd recommend making a webhook per channel you want to send, then you can just loop over a list of webhooks and post to them

ancient portal
#

Is there any tutorial i can look into, i have 0 clues how to do all that

#

Or maybe a template where i can learn from

fast osprey
#

The link at the bottom is the raw api if you want to call it yourself, but I do suggest you use a library

mild token
#

maximum number of choice with auto complete?

wanton current
#

25

mild token
stoic tusk
#

anyone using on.render and uptimerobot to host their discord bots?

dense valve
#

whats the best 24/7 free discord bot hosting

scarlet tiger
dense valve
#

i want totally fre

scarlet tiger
dense valve
scarlet tiger
hearty basalt
#

thats like renting a house or apartment to someone for free

dense valve
#

bruh

#

L

finite salmon
slate swan
#

are there bot commands alr made here?

#

#bot-commands

#

or is there any server that has commands

#

made for free use

cyan eagle
#

Where can I learn discord py with image examples?

fast osprey
#

There isn't a free lunch. People aren't going to spend their own money running your stuff

cyan eagle
fast osprey
#

I don't think they're dumb, they're malicious

#

If you can't identify the product being sold, you are the product being sold

cyan eagle
fast osprey
#

What images are you hoping to see? The library is just text

dense valve
#

thanks

cyan eagle
#

Wait let me show you

wanton current
#

the docs have image examples

cyan eagle
wanton current
cyan eagle
#

Specially for discord bots

cyan eagle
vapid parcel
#

Is discord having API issues?

wanton current
vapid parcel
#

This is sometimes out of date ^

wanton current
#

Yeah, it's updated when they notice it

vapid parcel
#

Yeah well

#

They need to notice it now lmao

#

Cuz their api is failing rn

wanton current
#

in what way

vapid parcel
#

Getting tons of timed out warnings in console

#

and my bots ping to discord is 200+

#

when its around 50

#

Discord is going to start having API issues starting soon, I am calling it. Happens a lot :(

wanton current
#

i don't notice anything wrong

vapid parcel
#

Then maybe its my vps.. but it just started now. So I am doubting its my vps. But time will tell ig

#

2024-08-05 17:35:16 WARNING discord.state Shard ID 0 timed out waiting for chunks for guild_id 110373943822540800.

radiant heath
#

Here's my code, my issue is that i'm not sure how to send a response to a button press interaction, i commented in the 3 places its relelvant

fast osprey
#

You're following a tutorial for another library, not discord.py

#

Also, in general I strongly recommend you don't nest class definitions inside of methods

radiant heath
#
import discord, random, json
from discord.ext import commands
from discord import app_commands
from discord.ui import Button, View, text_input
#

im not following a tutorial

fast osprey
#

Yes, but where are you starting from

#

You didn't divine the concept of a View from your mind

radiant heath
#

oh lmao

#

no i didnt

#

like a tutorial i watched ages ago

fast osprey
#

The only thing that's endorsed is the official docs and the examples in the repo

#

That tutorial was built on another library or likewise very misinformed

marble rampart
mortal ravine
#

Can anybody help me code my bot for free since im a broke boi

mortal ravine
errant trench
#

I want to add the Help Section in my Discord Bot to the Discord Application Directory, but I am getting the pip error. It happens even though slash commands are installed. What can I do about this? I want it to work in my prefix

@bot.command(name='yardım')
async def help(ctx):
    embed = discord.Embed(
        title=":globe_with_meridians: Discord Bot Yardım Menüsü",
        description="Aşağıdaki komutlarla botumuzdaki oyunları oynayabilirsiniz:",
        color=discord.Color.blue()
    )

    embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/1258806020982181969/1268934570200530944/cat-animal.png?ex=66ae3ae9&is=66ace969&hm=ef55b2e095888e0b9bfc8889ec9b4b0018f1c5b556ebb73901ec392a50e7a1ce&")  # Replace with your image URL

    embed.add_field(
        name=":hammer: Taş Kağıt Makas",
        value="**Komut**: `!tkm`\n**Açıklama**: Taş, kağıt veya makas seçerek bot ile karşı karşıya gelin. Botun seçimlerine karşı kazanmayı hedefleyin.",
        inline=False
    )

    embed.add_field(
        name=":coin: Yazı Tura",
        value="**Komut**: `!yazıtura`\n**Açıklama**: Yazı veya tura tahmini yaparak paranın hangi yüzünün geleceğini tahmin edin.",
        inline=False
    )

    embed.add_field(
        name=":1234: Sayı Tahmin",
        value="**Komut**: `!sayıtahmin`\n**Açıklama**: Botun belirlediği gizli sayıyı tahmin etmeye çalışın. Her tahmininizde bot size doğru olup olmadığını söyleyecek.",
        inline=False
    )

    embed.add_field(
        name=":x: Xox (Tic-Tac-Toe)",
        value="**Komut**: `!xox`\n**Açıklama**: 3x3 bir tahtada X ve O'ları sırayla yerleştirerek üçlü bir sıra oluşturmaya çalışın.",
        inline=False
    )

    embed.add_field(
        name=":jigsaw: Bulmaca",
        value="**Komut**: `!bulmaca`\n**Açıklama**: Size verilen ipuçlarını kullanarak bulmacayı çözmeye çalışın.",
        inline=False
    )

    embed.add_field(
        name=":kiss: Öp Evlen Öldür (Kiss-Marry-Kill)",
        value=("**Komut**: `!kme`\n"
               "**Açıklama**: Üç kişilik bir liste alacaksınız ve bu kişilerden birini öpecek, biriyle evlenecek ve birini öldüreceksiniz. "
               "Seçimlerinizi yapın.\n"
               "**Ek Komutlar**:\n"
               "- `!balance`: Mevcut gem miktarınızı gösterir.\n"
               "- `!mycharacters`: Evlendiğiniz ve öldürdüğünüz karakterleri gösterir."),
        inline=False
    )

    embed.add_field(
        name=":droplet: Su İçme Hatırlatması :droplet:",
        value="**Komut**: `!suekle #kanal-adı`\n**Açıklama**: Her gün belirli aralıklar ile belirledeğiniz kanala su içmek için hatırlatıcı yolar.",
        inline=False
    )
    embed.add_field(
        name=":question: Yardım ve Destek",
        value="Herhangi bir sorunuz olursa veya yardıma ihtiyacınız olursa, lütfen bir moderatöre başvurun. İyi oyunlar!",
        inline=False
    )

    await ctx.send(embed=embed)```
fast osprey
#

What is the "pip error"?

errant trench
#

All pip are loaded but

cobalt crane
#

are you using a virtual environment?

scarlet tiger
# errant trench

Don't use extra libraries, nextcord already has built-in application commands.

errant trench
cobalt crane
#

what Nightmare said though, try not to mix libs

errant trench
#

I installed nextcord later, I didn't have it, but it still gave me an error, I don't know how to do it.

errant trench
#

I'm new to this, what should I import or how did I code it exactly and what is my prefix? ! want it to stay what is

errant trench
#

I want to use both the discord application directory and my own ! with prefix

scarlet tiger
errant trench
#

Thanks again

vocal plover
# errant trench I want to use both the discord application directory and my own ! with prefix

for this you just create the commands twice, once as prefix commands how you're used to, and once as app commands (which function fairly similarly, consult the docs but the API is similar for it)
we don't - and won't - support hybrid commands (prefix and slash with one decorator/function) because it means we have to substantially water down the API to just the commonalities between both systems, and it adds an extra layer of unnecessary complexity and abstraction we feel harms the lib more than it helps, if those are what you were looking for

stoic tusk
#

is this a good way to be able to turn on/off any commands at any time i wish to?

#

speaking as a newbie

wanton current
#

I would probably use Command.update() instead, and set enabled=False, and then catch that in an error handler. Then you don't need to add that check in every command that you have.

stoic tusk
wanton current
#
command = bot.get_command(name)
command.update(enabled=False)
#

then if a disabled command is being invoked, commands.DisabledCommand error will be raised

stoic tusk
wanton current
stoic tusk
#

idk any better, im not that good at managing/organizing stuff

wanton current
#

no just asking

#

You could read the file when starting the bot, and then loop through the commands and disable the ones you want

stoic tusk
#

i saw a friend of mine having a place where he can do something similiar to what I did so i got interested in doing it as well

wanton current
#

nice

stoic tusk
#

I intiatially just wanted to have it like this at the start of the file:

help_CmdEnabled = True

@bot.command
async def help(ctx):
  if help_Cmdenabled == True:
  await ctx.reply(f'{but.user.name} is currently still in development mode!')
wanton current
#

that works, but if you have a lot of commands, it can get messy pretty quick

stoic tusk
#

Not only that but also the main.py file gets heavier

#

or actually, before I start any command, I can use that there, instead of the start of the file

#

like this maybe

tribal bison
#

@tired star your code worked great! however some words seem to not work?

#

like fr doesnt work but af does

#

ive tried putting .lower() but it doesnt work

#

Nvm found the issue

mild token
#

is there any event which is called when timeout is uplifted?

ancient portal
#

Hello how do i fix error code 429 : Too many request from [channelID]

I'm making a Discord auto message with a timer that sends message once every hour. The said channel has a cooldown of 1 hour.

sick birch
#

compare the before.timed_out_until with after

mild token
#

Another question I would like to ask when someone is banned on_member_remove event is called?

sick birch
#

should be

mild token
#

Oki

mild token
ancient ridge
#

xd

drowsy thunder
#

How to organise my code and bot slash commands into different files?

fast osprey
#

You can just declare things in other files and import them like normal python, bots are no different. You can also make use of the extension framework if you're using dpy

tired star
fast osprey
#

For?

drowsy thunder
fast osprey
#

I gave you two options

mild token
#

await user.timeout(timedelta(seconds=duration), reason=reason even if i putting duration 30 its still adding only 10 seconds

merry cliff
merry cliff
mild token
#
    @app_commands.command(name="timeout", description="Timeout a user")
    @app_commands.describe(
        user="The user to timeout",
        duration="Duration in seconds",
        reason="The reason for the timeout",
    )
    @app_commands.checks.dynamic_cooldown(cooldown_for_everyone_but_special_og)
    async def timeout(
        self,
        interaction: discord.Interaction,
        user: discord.Member,
        duration: app_commands.Range[int, 2, 2073000],
        reason: str,
    ):
        await interaction.response.defer(ephemeral=True)
        if not self.is_hierarchy_higher(interaction.user, user):
            await interaction.followup.send(
                f"Cannot timeout {user.mention} because they have an equal or higher role."
            )
            return
        await user.timeout(timedelta(seconds=duration), reason=reason
merry cliff
#

Are you sure it’s 10 seconds?

#

Can you try again

mild token
#

i will try again

fast osprey
#

You may not want to reimplement this as there is a native timeout and you're reducing security controls

marble rampart
#

does anyone know about a template that isnt outdated for a discord dashboard i cant find any ones that work and are in python 😦

slate swan
#

@glad cradle its pretty much a textual game centered on a eastern theme called cultivation

glad cradle
#

what are you using the files for?

slate swan
#

storing user data

glad cradle
#

😭

slate swan
#

?

glad cradle
#

why you're not using a proper database?

slate swan
#

im stubborn

glad cradle
#

if you want a file like database there's Sqlite

slate swan
#

im using pure pickle()

glad cradle
slate swan
fast osprey
#

Also you can and will randomly corrupt your file and lose everything

slate swan
#

your file? or files?

glad cradle
glad cradle
#

!pypi aiosqlite

unkempt canyonBOT
#

asyncio bridge to the standard sqlite3 module

Released on <t:1708409573:D>.

slate swan
#

would be hard to adapt my functions to use sqlite

#

aiosqlite?

#

oh

glad cradle
#

yes, you need an async wrapper

slate swan
#

alright

glad cradle
#

common file operations blocks the main event loop

slate swan
#

normal functions dont right

glad cradle
#

!blocking

unkempt canyonBOT
#
Asynchronous programming

Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.

What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:

import discord

# Bunch of bot code

async def ping(ctx):
    await ctx.send("Pong!")

What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.

async libraries

  • The standard async library - asyncio
  • Asynchronous web requests - aiohttp
  • Talking to PostgreSQL asynchronously - asyncpg
  • MongoDB interactions asynchronously - motor
  • Check out this list for even more!
slate swan
#

wait so like

#

if i use normal functions inside a async function its blocking

#

??? confus

stone quest
#

yes

#

unless you make it asynchronous with its modules

slate swan
#

shiiit

stone quest
slate swan
#

so i have to make pretty much all of my functions into async ones?

#

im so cooked

stone quest
#

i mean personally with small databases sqlite3 can barely be recognised for blocking the event loop

#

but its still a consideration, personally ive just used sqlite3 and there have been 0 problems its just as it gets bigger and bigger you will need to consider refactoring

slate swan
#

no i have some special library i made for numbers

#

its a massive class

stone quest
#

how do you mean?

slate swan
#

?

stone quest
#

numbers?

slate swan
#

yeah

stone quest
#

sorry i joined half way through the conversation

slate swan
#

storing numbrs with pretty much no worry of running out of space to represent the next one

glad cradle
slate swan
stone quest
#

ah

slate swan
#

lots of it

glad cradle
#

what's really important is that you do not do web requests, heavy cpu bound work, and other things in non async contexts

stone quest
#

check the computational time it takes for the computer to process your function then decide if you need to implement it to be async

glad cradle
stone quest
#

but doesnt the request method require to be async (internally) 0? thats the point of the aiohttp package

slate swan
glad cradle
#

asyncio provides some methods to safely run blocking functions as async, without blocking the event loop

stone quest
slate swan
#

alright

stone quest
#

"lots of math" we reference is like 5-10 seconds long of billions of numbers

slate swan
#

oh

stone quest
#

but less than a ms doesnt really impede your event loop

slate swan
#

my library will flop trying to do more than 10k numbers

stone quest
#

may need to refine it, can i ask what you are handling numbers for?

glad cradle
# slate swan last time i checked those dunder functions can be like 1 to 0.1 ms

what is really an issue are operations that makes you wait a lot of time, for example when you do a web request you must wait the server response, that response could take seconds and if not done in an async context you lose that seconds waiting for the response, same thing when you work with files locally but you instead wait for the kernel and other signals

stone quest
#

just the numbers in general, what are they representing

slate swan
slate swan
#

the class is literially called BigNumber

stone quest
#

whats the numbers for haha?

slate swan
#

to represent absurdly massive numbers?

stone quest
#

so you have a class to just make big numbers end of ??

#

so confused, the numbers have no meaning nothing, just a big number?

slate swan
#

it can represent 10^^4 with alot of extra wiggle room

stone quest
#

fair enough

slate swan
#

they mean something

#

thats what they represent

#

a mantissa and exponent

#

i dont even know if ill be able to rewrite it in C xd

#

my win machine is absurdly cursed

#

anyway i guess ill go back to the main python channel

glad cradle
# slate swan i dont think ill do web request stuff

just wanted to give you a general idea, it's not important the total execution time of a function, it's important if you are waiting a lot of time without doing anything, CPU bound operations give you no gain if you make them async, they're slow in python and what's slow are the operations itself, you could make them in another thread (just an example)

so if you wait a lot of time for something without doing anything you should make that thing async

mortal ravine
#

Can someone help me script my discord bot for free since im a brokie

DM me if you can

mild token
#

I send form when someone click on a button i want when someone submits the form the embed on which button is there should stop listening , currently even after removing and submitting the form and editing the embed ,embed timeout still get fired

fast osprey
#

Embeds don't listen to anything though?

vague junco
#
import requests
import json

TOKEN = ""
APPLICATION_ID = ""
GUILD_ID = ""


def register_command():
    response = requests.post(
        url=f"https://discord.com/api/v10/applications/{APPLICATION_ID}/guilds/{GUILD_ID}/commands",
        headers={
            "Authorization": f"Bot {TOKEN}",
            "Content-Type": "application/json",
            "User-Agent": "Mozilla/5.0",
        },
        data=json.dumps({
            "name": "hello",
            "description": "Hello, world!",
        })
    )

    if response.status_code == 201:
        print("Command registration successful.")
    else:
        print(f"Error registering command: {response.text}")


register_command()

Error registering command: {"message": "internal network error", "code": 40333}

What's wrong with this code? All parameters are precisely specified

fast osprey
#

Why are you setting a User-Agent? And what's the end goal here, what is actually serving those commands?

mild token
mild token
#

Btw i have solved the issue by passing the same instance to the form

#

And disabling on submit

#

I have a query suppose i have all the commands copied to the guild only

If someone dms the bot ,will it log the messages on on_message.

crude remnant
#

Can someone help me on a error message I'm getting on one of my commands?

fast osprey
#

If you're subscribed to the right intent, yes dm's will fire on_message

stark ingot
crude remnant
mild token
fast osprey
#

The Channel Overrides section goes into this in detail

crude remnant
# stark ingot Only if you send the error message 😉

File "/data/data/com.termux/files/home/cmds.py", line 132, in shift_leaderboard
await interaction.response.send_message(embed=embed, view=view, ephemeral=True)
File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/discord/interactions.py", line 855, in send_message
await adapter.create_interaction_response(
File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/discord/webhook/async_.py", line 221, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

stark ingot
#

does the command still look like it works?

mild token
crude remnant
stark ingot
crude remnant
#

I'll fix that, thanks

unkempt canyonBOT
#
Noooooo!!

No documentation found for the requested symbol.

stark ingot
#

That is not in discord.py you will have to go to the pycord docs (to the person who ran the command above)

left delta
stark ingot
#

how do you make your options (can you show your code)

left delta
#

but I keep getting an error that tells me bridgeOption will be removed on 2.7 update

stark ingot
#

Yes bridgeOption is deprecated. I think you can just use normal options now let me check.
Edit: You need to use BridgeOption using Option is deprecated

left delta
modest harbor
#

Can someone explain how does d.py extensions differentiate from cogs?

mild token
#

so the problem is this my server have onboarding feature enabled and for creating mute feature i need to disable send_message from everyone role so is there any hack which can fix it?

#

by hack i mean the way

#

plz dont misunderstand it

stark ingot
#

or just use discord.Option but that might change in 2.7 again
Edit: I mixed it up

slate swan
#

hey can anyone help me with this embed inline im trying to make the add_field for 2 each sections like the 2 below which im trying to do for all like 2 for each sections - my code

    embed = discord.Embed(title="Stats", color=discord.Colour.dark_theme())
    embed.add_field(name="Data", value=f"`{Data}`", inline=True)
    embed.add_field(name="Total", value=f"`{Total}`", inline=False)
    embed.add_field(name="Jale", value=f"`{Jale}`", inline=True)
    embed.add_field(name="Lum", value=f"`{Lum}`", inline=False)
    embed.add_field(name="Aa", value=f"`{Aa}`", inline=True)
    embed.add_field(name="Number", value=f"`{Number}`", inline=True)
left delta
stark ingot
#

When inline is false it buts that field on a newline

stark ingot
# modest harbor Can someone explain how does d.py extensions differentiate from cogs?

Extensions are extra utilities that are in discord.py
Think of it like default libraries for python
You can do import math in python to get extra features and you can do from discord.ext import commands to get extra features in discord.py

Cogs are a way to group your commands (and other code) and allow you to split your bot into multiple files much easier. Cogs have a few extra utility features such as being able to apply changed code in the cog without restarting the whole bot.

modest harbor
stark ingot
#

Sorry no. I do not know how discord.py implemented user apps. I only use py-cord. (I just know some of the basics of d.py as py-cord is a fork of it)

modest harbor
stark ingot
#

How so?

mild token
#

see inspite of being timeout the user can send message

slate swan
#

is it gonna be fine to make a function that will send an embed that isnt defined as an async one but is still called in a async function

mild token
#
     @app_commands.command(name="timeout", description="Timeout a user")
     @app_commands.describe(
         user="The user to timeout",
         duration="Duration in seconds",
         reason="The reason for the timeout",
     )
     @app_commands.checks.dynamic_cooldown(cooldown_for_everyone_but_special_og)
     async def timeout(
         self,
         interaction: discord.Interaction,
         user: discord.Member,
         duration: app_commands.Range[int, 2, 2073000],
        reason: str,
     ):
         await interaction.response.defer(ephemeral=True)
         if not self.is_hierarchy_higher(interaction.user, user):
            await interaction.followup.send(
                f"Cannot timeout {user.mention} because they have an equal or higher role."
             )
            return
         await user.timeout(timedelta(seconds=duration), reason=reason
                           )
         embed = self.build_embed(
            "timeout", user, interaction.user, reason, duration)
        await interaction.followup.send(
             f"{user.mention} has been timed out for {duration} seconds. Reason: {reason}"
         )
        await interaction.guild.get_channel(ChannelsIds.TIMEOUT).send(embed=embed)
#

this is my command code

#

if u test on different device u will get different timeout

stark ingot
#

It looks right to me ¯_(ツ)_/¯

mild token
mild token
slate swan
#

ah okay

slate swan
#

idk how async functions work

#

like does the function wait for it to be done

#

i kinda need it to block the rest of the function

stark ingot
#

Generally it is best to keep everything in an async function async but I am not the most knowledgeable on it either

slate swan
#

alright

mild token
slate swan
# stark ingot Try switching the 2nd field to True 3rd to false 4th to true 5th to false

Hi im still not getting what i wanted here is the pic when i put ur code in

embed = discord.Embed(title="Stats", color=discord.Colour.dark_theme())
    embed.add_field(name="Data", value=f"`{Data}`", inline=True)
    embed.add_field(name="Total", value=f"`{Total}`", inline=True)
    embed.add_field(name="Jale", value=f"`{Jale}`", inline=False)
    embed.add_field(name="Lum", value=f"`{Lum}`", inline=True)
    embed.add_field(name="Aa", value=f"`{Aa}`", inline=False)
    embed.add_field(name="Number", value=f"`{Number}`", inline=True)```
stark ingot
#

Hmmm, inline is always so strange. I have to go but you could just flip a few values here and there and see what happens

slate swan
#

Ok

slate swan
#

little confused about all of this subclass stuff

#

do you really need a python subclass?

timber dragon
slate swan
timber dragon
#

Since it's max three on one line and it depends on the display size

timber dragon
golden portal
# slate swan for buttons*

yes, subclassing inherits functionalities of the class so if you wanna override its method you would do that.

slate swan
#

oh

scarlet tiger
slate swan
#

subclasses on the other hand

#

also i already made the discord bot

#

im just fleshing it out

scarlet tiger
slate swan
#

i wish to make buttons with a simple function :>

scarlet tiger
slate swan
scarlet tiger
slate swan
#

lol

glad cradle
slate swan
scarlet tiger
# slate swan lol

In py-cord it can be done this way, in discord.py in the documentation I see that it should be the same, you can try:

import discord
from discord.ui import Button, View

async def button_callback(interaction: discord.Interaction):
    await interaction.response.send_message("You pressed the button!", ephemeral=True)

# Create the button
button = Button(label="Click me", style=discord.ButtonStyle.primary)
button.callback = button_callback

# Create a view and add the button to it
view = View()
view.add_item(button)

# Example of how to use the button in a command
@bot.command()
async def show_button(ctx):
    await ctx.send("Here's a button for you:", view=view) 
scarlet tiger
#

Note: It is not highly recommended to create buttons or other components in this way, but if your button is simple you can do it

scarlet tiger
slate swan
#

thats the code stripped down?

#

can i wrap it into a class

glad cradle
slate swan
#

confus

glad cradle
#

if you don't subclass you don't have much reason to put it into a class

#

you can just do that when you need the component, directly inside the command callback

slate swan
#

i just need the command callbacks to perhaps return a value

#
import discord
from discord.ui import Button, View


async def button_callback(interaction: discord.Interaction, text= str, passedFunction = None, input1, input2):
    await interaction.response.send_message(text, ephemeral=True)
    if passedFunction != None: return(passedFunction(input1, input2))

# Create the button
button = Button(label="Click me", style=discord.ButtonStyle.primary)
button.callback = button_callback(button, "click me", specialFunction, placeholder1, placeholder2)

# Create a view and add the button to it
view = View()
view.add_item(button)

# Example of how to use the button in a command
@bot.command()
async def show_button(ctx):
    await ctx.send("Here's a button for you:", view=view) ```
#

@glad cradle ?

#

can i do this bizzare stuff

glad cradle
#

if you want to hold state you need to put that into the view or into the button

#

why don't you read a guide about OOP? it's really powerful if you learn it

slate swan
#

im stubborn

#

i am already locked into a state of knowing OOP

#

its just that this OOP is foreign to me :>

golden portal
#

wdym? you just asked about inheritance the other hour

slate swan
#

shhh

golden portal
slate swan
#

i dont remember anything earlier fr

glad cradle
slate swan
#

i have like 5 classes already ;-;

golden portal
#

nothing wrong with classes

scarlet tiger
slate swan
# golden portal also, see https://github.com/Rapptz/discord.py/blob/master/examples/views/confir...

wait this is so simple wth

# Define a simple View that gives us a confirmation menu
class Confirm(discord.ui.View):
    def __init__(self):
        super().__init__()
        self.value = None

    # When the confirm button is pressed, set the inner value to `True` and
    # stop the View from listening to more input.
    # We also send the user an ephemeral message that we're confirming their choice.
    @discord.ui.button(label='Confirm', style=discord.ButtonStyle.green)
    async def confirm(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.send_message('Confirming', ephemeral=True)
        self.value = True
        self.stop()

    # This one is similar to the confirmation button except sets the inner value to `False`
    @discord.ui.button(label='Cancel', style=discord.ButtonStyle.grey)
    async def cancel(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.send_message('Cancelling', ephemeral=True)
        self.value = False
        self.stop()```
#

super() is cogs thingy right

golden portal
#

no that's a python OOP concept

#

in fact you can see super in other languages as well

#

any OOP learning enjoyers in chat

slate swan
#

then what is it

#

a builtin?

#

or wut

golden portal
#

in simple term, super() refers to your parent's, in this case, calling the constructor

slate swan
#

so it refers to discord.ui.View ?

golden portal
#

remove super().__init__() and your child won't inherit the parent's stuff

#

yes

slate swan
#

so

#

a
subclass() is the child of its class()

#

and reversed
class() is the parent of its subclass()

golden portal
#

yes

slate swan
#

super() returns the subclass() parent which is its class()

#

alright thank u

#

oh wait

#

confus brain lool

slate swan
#

a view can contain multiple buttons yea?

scarlet tiger
slate swan
#

idk if what this code does but does it add a button?

    @discord.ui.button(label='Confirm', style=discord.ButtonStyle.grey)
    async def doButton(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.send_message('Confirming', ephemeral=True)
        result = self.func(attr1, attr2, attr3):
        if self.returnVal:
            self.returned = result
        self.stop()
scarlet tiger
#

Not only buttons, it can also be combined, menus and buttons for example

slate swan
#

actually i guess it does

celest oar
#

anyone know how to get it into the center, im not the one coding this but the guy who is, is offline so im just fixing this, heres some of the code to do with the position

base_image = base_image.resize((2479, 1080))
    overlay_image = overlay_image.resize((500, 500))

    if overlay_image.mode != 'RGBA':
        overlay_image = overlay_image.convert('RGBA')

    position = (100, 100)

    new_image = Image.new('RGBA', base_image.size)
    new_image.paste(base_image, (0, 0))
    new_image.paste(overlay_image, position, overlay_image)
#

(i have never used python before)

scarlet tiger
slate swan
scarlet tiger
slate swan
#

oh im dumb

slate swan
#

also

#
@discord.ui.button(label='Confirm', style=discord.ButtonStyle.grey)
    async def doButton(self, interaction: discord.Interaction, button: discord.ui.Button):```
this part is the one responsible for making the "component" yeah?
fast osprey
#

That decorates a method to make it into a component (button)

scarlet tiger
slate swan
#
view_or_component = discordButton(##args)
#

cause im pretty sure it returns a view

fast osprey
#

What is discordButton?

slate swan
#

class discordButton(discord.ui.View):
    def __init__(self, func, attr1= None, attr2= None, attr3 = None, returnVal: bool = False, ):
        super().__init__()
        self.func = func
        self.attr1 = attr1
        self.attr2 = attr2
        self.attr3 = attr3
        self.returnVal = returnVal
        self.returned = None
    
    @discord.ui.button(label='Confirm', style=discord.ButtonStyle.grey)
    async def doButton(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.send_message('Confirming', ephemeral=True)
        result = self.func(attr1, attr2, attr3):
        if self.returnVal:
            self.returned = result
        self.stop()
#

ignore the comments ( i copied that code )

slate swan
fast osprey
#

Well, despite the class being named "button" that would indeed give you an object that subclasses view

#

Correct

celest oar
#

this server is great help

slate swan
fast osprey
#

You asked a question that isn't on topic for this channel shrug

slate swan
celest oar
slate swan
slate swan
fast osprey
#

This isn't a channel for all possible things one could wrap with a bot

slate swan
celest oar
#

ok

fast osprey
#

As long as the method is named uniquely in the class

slate swan
#

cause i wish for the 1st option to be done

fast osprey
#

More buttons = more method declarations

slate swan
#

hm

fast osprey
#

Each method is one button, and the body of the method is what happens when that specific button gets pushed

slate swan
#

dangit

#

im out of luck then?

fast osprey
#

Huh? What are you trying to accomplish?

#

When you say "add buttons later on", do you mean you the developer adding features or the view dynamically changing during runtime?

slate swan
#

ok so like

#

imagine this

view = makeview(## args for the first button)
view = view.addbutton(## args for the second button)
view = view.addbutton(## args for the third button)
## done until u got what u needed
fast osprey
#

Hm. What are the cases where the buttons on the view would change?

#

Or are there the same X buttons every time?

slate swan
#

zones

fast osprey
#

Or is this like "I make the view and I have an int N and I want to make N buttons at that time"

slate swan
#

uhh

#

nop

#

well it depends actually

fast osprey
#

For that, instead of using the decorators like above, you can instead make a subclass of discord.ui.Button

slate swan
#

subclasses galore 💀

celest oar
#

ok i guess i gotta ask chatgpt to help me

fast osprey
#

Similarly to how to subclass a View, you can also subclass a Button or other components like Select menus.

Adding the item to the view

To add a subclassed item to your view, simply call View.add_item on your view, passing an instance of your subclassed item.

Button Example

class CounterButton(discord.ui.Button):
  def __init__(self, label='0', **kwargs):
    super().__init__(label=label, **kwargs)
    self.counter = 0

  async def callback(self, interaction: discord.Interaction):
    self.counter += 1
    self.label = self.counter
    await interaction.response.edit_message(view=self.view)

view = discord.ui.View()
view.add_item(CounterButton(style=discord.ButtonStyle.primary))
view.add_item(CounterButton(style=discord.ButtonStyle.success))
view.add_item(CounterButton(style=discord.ButtonStyle.danger))

await ctx.send('Click counter button below', view=view)
#

(From a user tag on the dpy server)

#

The key thing is that in addition to the @ui.button decorator, you can also just make Button objects on your own with their own callback. This lets you dynamically make however many of whatever type you want

slate swan
#

ooh

slate swan
fast osprey
#

Exactly

slate swan
#

is it possible to pair this with the view subclass

fast osprey
#

Absolutely and it's recommended

slate swan
#

or do i need to

fast osprey
#

Your view subclass's init can create your buttons (using the button subclass) and add them to itself

slate swan
#

hear me out on what i want my code to do

fast osprey
#
class MyView(View):
  def __init__(self):
    super().__init__()
    self.add_item(MyButton())
slate swan
# slate swan hear me out on what i want my code to do

ok so i got an embed it shows some possible zones, this part is frontend and got nothing to do actually

then i wanna make a view, add a few buttons depending on the zones that the user can go to

if they click on one button, all the other buttons disappear

slate swan
fast osprey
#

Ah yup this seems like you'd want what I described

#

The button can also internally modify the view (remove other buttons) and then edit the message to reflect that change

slate swan
#

so basically
buttonsubclass() - to make buttons

viewsubclass() - yeetus deletus buttons, and manage them

fast osprey
#

So something like

class ZoneButton(ui.Button):
  def __init__(self, whatever):
    super().__init__()
    self.whatever = whatever

  async def callback(self, interaction):
    #can use self.whatever, do logic
    await interaction.response.edit_message(view=None) # gets rid of all buttons
slate swan
#

basically

fast osprey
#

If the button callback needs to mess with the view it's in, you can use self.view

slate swan
#

perhaps

#

wait

fast osprey
#
class ZoneView(View):
  def __init__(self, zone_list):
    super().__init__()
    for zone in zone_list:
      self.add_item(ZoneButton(zone))
slate swan
#

wait..
self.view fetches the view object?

#

oop is op

fast osprey
#

In the context of the button subclass, yes

#

self is the instance of the class you're declaring

slate swan
#

how considerate of whoever made this hell hole of classes fine ballet of classes and functions

fast osprey
#

It takes a lot of mental reprogramming to think in terms of classes and objects after just doing declarative scripting, but they're incredibly powerful

slate swan
#

the most OOP ive done before this was in the form of pygame and my own number library

fast osprey
#

Oh wow

slate swan
slate swan
#

it has barely enough for my game :>

fast osprey
#

Oh your subclass can take in whatever parameters you want, or it can just pass defaults to the parent constructor. Completely up to you. **kwargs just helps if you want the consuming code of your subclass to also be able to declare base view parameters (like timeout)

fast osprey
slate swan
#

i mean im not currently working on the game but

#

its meant to reach absurd numbers

fast osprey
#

Oh like things that would normally overflow

slate swan
#

up to like

#

10^10^10^10^999999999999

#

or something

slate swan
#

like what happens if i

#
    def __init__(self, label: str = "", **kwargs, destructAll: bool = False, ):
        super().__init__(label= label, **kwargs)
        self.destructAll = randomkwarg 
#

i guess i should search for what it is

#

oh i see

fast osprey
#

**kwargs would go at the end yeah and just be a catch all for any other flags they'd pass in

slate swan
#

yeah i thought so

fast osprey
#

The docs will tell you what the base class accepts, and it's up to you if/how you pass that into super().__init__(). You can just pass in hard coded things, or accept them in your own init

slate swan
# fast osprey The docs will tell you what the base class accepts, and it's up to you if/how yo...
class discordView(discord.ui.View):
    def __init__(self):
        super().__init__()
        self.returned = None

class mkButton(discord.ui.Button):
    def __init__(self, label: str = "", func, attr1= None, attr2= None, attr3 = None, returnVal: bool = False, destructAll: bool = False, **kwargs ):
        super().__init__(label= label, **kwargs)
        self.destructAll = destructAll
        self.func = func
        self.attr1 = attr1
        self.attr2 = attr2
        self.attr3 = attr3
        self.returnVal = returnVal

    async def callback(self, interaction: discord.Interaction):
        result = self.func(self.attr1, self.attr2, self.attr3):
        if self.returnVal:
            self.view.returned = result
        if self.destructAll:
            await interaction.response.edit_message(view=None)
            self.view.stop()
#

oh wait

#

waddya' think?

fast osprey
#

Seems solid, though the view doesn't do anything or add any components

slate swan
#

it keeps self.returned tho

fast osprey
#

Right, but it doesn't have any components. Unless something outside of this is adding components to it

slate swan
#

yea

#

but doesnt rlly matter does it?

fast osprey
#

You could do that and it would work. I recommend you put that all in the view subclass so it internally is clear how it works

slate swan
#

adding it myself is the amount of control i want

fast osprey
#

What would be inheriting what? You could actually make an intermediate level, people often do this to centrally declare like error handling across multiple views

slate swan
#

huh

#

too much for me i just gotta get this to work

fast osprey
#

Then you can put the add_item's wherever, it's just much clearer and encapsulated if you do that in the view class itself

slate swan
fast osprey
#

the view= parameter of pretty much any method that sends a message

slate swan
#

i got
msg = await ctx.send(embed=Embed)
for embeds
so can i do
await ctx.send(view= view)

#

oh

fast osprey
#

yup

slate swan
#

good to know

slate swan
#

lets say i got a functin yea

#

how do i ignore certain arguements

fast osprey
#

How do you mean?

slate swan
#

explicitly coded in params part of defining a function

#

like

#

def func(arg, ignore ignore):

fast osprey
#

Why are the params there if you don't want them? ThinkO_O

#

Do you have an example?

slate swan
#

attr1,attr2,attr3 will get shoved into func regardless if the function likes it or not

fast osprey
#

You're declaring those parameters though, do you not want the user to pass them in?

slate swan
#

i only need to use attr1 for now

#

some functions might use all three in the future

fast osprey
#

Then you would accept those in those functions

slate swan
#

nop

#

i said some functions, not all functions

fast osprey
#

Right, so accept the parameters you want in those functions

slate swan
#

any way to do them cleanly?

fast osprey
#

Or is this like futureproofing that you may want additional things on the view itself in the future?

#

You can just add them in when you need them

slate swan
#

bleh

#

ima just code it ig

fast osprey
#

If you wanted this very very flexible, you could accept a dictionary or just **kwargs

#

but that makes the api less straightforward about what you're asking for

slate swan
#

i finally got it to work without crying at me

#

wait hold on

#

it cried a little

#

it worked

#

i sent a img in dms

#

ty man

haughty hatch
#

Please which is the best library to build a social media bot for account management

fast osprey
#

What does "account management" mean?

verbal gulch
#

what's the context

timber dragon
#

Everyone asks "what" but never "how is" sad

lyric pumice
#

what kind of coding is that 😭

mild token
#

For scheduling what you guys use? I have a discord giveaway command but don't know how to schedule,can't use task as it will be fixed on bot start up

stark ingot
stark ingot
mild token
#

If its possible then it will solve my problem

stark ingot
#

you can create an instance of ext.tasks.Loop and set a callback

#

I believe the first argument coro is the callback function

mild token
fast osprey
#

Store thing in database -> on startup read from database -> spin up however many asyncio tasks you want that sleep until the time you want and then do the thing

sharp night
#

hi does someone know how to work with oauth ?

wind radish
#

@gray terrace

gray terrace
#

any one know how to fix Windows Subsystem for Linux has no installed distributions.

Use 'wsl.exe --list --online' to list available distributions
and 'wsl.exe --install <Distro>' to install.

Distributions can also be installed by visiting the Microsoft Store:
https://aka.ms/wslstore
Error code: Wsl/Service/CreateInstance/GetDefaultDistro/WSL_E_DEFAULT_DISTRO_NOT_FOUND

this error?

Install Windows Subsystem for Linux with the command, wsl --install. Use a Bash terminal on your Windows machine run by your preferred Linux distribution - Ubuntu, Debian, SUSE, Kali, Fedora, Pengwin, Alpine, and more are available.

wanton current
#

wrong channel for that

gray terrace
#

where do i go?

wind radish
fast osprey
#

Probably not in scope of this server as it's not python related at all

merry cliff
fast osprey
#

(Though #unix is a thing so that's neat)

hushed galleon
brazen wind
#

How do I check a member that's pinged through a message?

Like if I send '.punch @brazen wind' it'll respond with '@brazen wind has been punched'

untold carbon
#
@bot.tree.command(name="edit", description="Edit the message content for a specified channel.")
@app_commands.describe(channel_id="The ID of the channel to edit the message content for.")
async def edit(interaction: discord.Interaction, channel_id: str):
    await interaction.response.send_message(f"Please provide the new message content for channel {channel_id}.")

    def check(m):
        return m.author == interaction.user and m.channel == interaction.channel

    try:
        message = await bot.wait_for('message', check=check, timeout=120)
        if message.content:  # Check if the message content is not None or empty
            file_path = await get_channel_file_path(channel_id)
            with open(file_path, "w") as f:
                f.write(message.content)
            await interaction.followup.send(f"Updated message content for channel {channel_id}: {message.content}")
        else:
            await interaction.followup.send("Received empty message content. Please try again.")
    except asyncio.TimeoutError:
        await interaction.followup.send("You took too long to respond. Please try again.")

can anyone tell me why whenever i say something it still keeps responding with received empty message?

scarlet tiger
brazen wind
scarlet tiger
brazen wind
scarlet tiger
brazen wind
brazen wind
scarlet tiger
# brazen wind can you help me with how 😭

Example:

from discord.ext import commands
from discord import Member

bot = commands.Bot(...)

@bot.command(name="greet")
async def example(ctx: commands.Context, user: Member):
  await ctx.send(f"Hello! {user.mention}")
stark ingot
tribal bison
#

Hmm is there a way to have a bot remember context via a reply? I am using the discord.py right now

honest laurel
tribal bison
scarlet tiger
real oriole
#

C:\Users\Games\AppData\Local\Programs\Python\Python311\python.exe
Traceback (most recent call last):
File "d:\Documents\Downloads\discord spotify.py", line 6, in <module>
import yt_dlp as youtube_dl
ModuleNotFoundError: No module named 'yt_dlp'
PS C:\Users\Games>

hey so i did install the module named yt_dlp but it still says no module name yt_dlp

blissful citrus
#

Can someone help me with this 😭

#1270973142038347869 message

I’m so confused what I’m missing because the bot is sending the message / running just fine, it’s just not detecting any real user’s status and just its own status

patent hull
fast osprey
#

(And if you're using yt_dlp that you aren't violating dev terms of service)

uneven fiber
#

how do i check what modules i have installed?

patent hull
fast osprey
#

Just pip on its own can be ambiguous if you have multiple python installations, especially on windows

#

<your python exe> -m pip freeze will specifically give you the packages in that environment

#

(Unless you're in an active venv then it's fine)

mild token
#

how long can be a button label?

patent hull
#

80 chars

foggy laurel
mild token
#

where should i intialize my db connection? on setup hook only?

foggy laurel
#

so i can just do bot.db everywhere

#

cause u only need to do it once, i just do it when the bot is run

wanton current
mild token
mild token
wanton current
#

what db are u using?

foggy laurel
#

i do like aiomysql

mild token
#

and yes i am using pool

#
    async def connect(self):
        try:
            self.pool = await asyncpg.create_pool(dsn=self.dsn)
            log_message(log_level="INFO",
                        message="DATABASE Successfully connected")
        except Exception as e:
            log_message(log_level="WARNING",
                        message=f'Failed to connect to the database: {e}')
            self.pool = None  
slate swan
#

heyo idk how to fix this yet pls help


import discord
from discord.ext import commands
import config
from main import colors

class Information(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

   

    @commands.hybrid_command(name="userinfo", aliases=["whois"], description="Display information about a user.")
    async def userinfo(self, ctx: commands.Context, user: discord.User = None):
        if user is None:
            user = ctx.author

        
        public_flags = {
            'staff': '![staff](https://cdn.discordapp.com/emojis/1232884672057573387.webp?size=128 "staff")',
            'partner': ':partner:',
            'hypesquad': '![hypesquadbadge](https://cdn.discordapp.com/emojis/1232883153283190914.webp?size=128 "hypesquadbadge")',
            'bug_hunter_level_1': '![bughunterbadge](https://cdn.discordapp.com/emojis/1232881643841392732.webp?size=128 "bughunterbadge")',
            'house_bravery': '![hypesquadbravery](https://cdn.discordapp.com/emojis/1232884053506654239.webp?size=128 "hypesquadbravery")',
            'house_brilliance': '![discord_brillance](https://cdn.discordapp.com/emojis/1225534077206003955.webp?size=128 "discord_brillance")',
            'house_balance': '![hypesquadbalance](https://cdn.discordapp.com/emojis/1232883920316661852.webp?size=128 "hypesquadbalance")',
            'early_supporter': ':earlysupporter:',
            'team_user': ':team_user:',
            'bug_hunter_level_2': ':bughunter_level_2:',
            'verified_bot': '![bot](https://cdn.discordapp.com/emojis/1248681234633195622.webp?size=128 "bot")',
            'early_verified_bot_developer': '![activedev](https://cdn.discordapp.com/emojis/1232880809078165657.webp?size=128 "activedev")',
            'certified_moderator': '![discordcertifiedmoderator](https://cdn.discordapp.com/emojis/1232882888467419190.webp?size=128 "discordcertifiedmoderator")'
        }
        badges = [emoji for flag, emoji in public_flags.items() if getattr(user.public_flags, flag)]
        badges_str = " ".join(badges) if badges else "No badges"

        
        avatar_link = f"[Avatar]({user.avatar.url})" if user.avatar else "Avatar"
        banner_link = f"[Banner]({user.banner.url})" if user.banner else "Banner"
        profile_links = f"{avatar_link}{banner_link}" if user.banner else avatar_link

        
        created_at = user.created_at
        created_str = f"{discord.utils.format_dt(created_at, style='R')}"
        created_value = created_at.strftime("%m/%d/%Y") if (discord.utils.utcnow() - created_at).days < 365 else f"{int((discord.utils.utcnow() - created_at).days / 365)} years ago"

        
        mutual_guilds = len([guild for guild in self.bot.guilds if guild.get_member(user.id)])

        
        embed = discord.Embed(
            color=colors.default
        )
        embed.set_author(name=f"{user} ({user.id})")
        embed.set_thumbnail(url=user.avatar.url if user.avatar else None)

        embed.description = badges_str
        embed.add_field(name="Created", value=created_value, inline=True)
        embed.add_field(name="Profile", value=profile_links, inline=True)

        footer_text = f"Mutual servers: {mutual_guilds}"
        embed.set_footer(text=footer_text)

        await ctx.send(embed=embed)

async def setup(bot):
    await bot.add_cog(Information(bot))
fast osprey
#

Hard to without knowing what's happening and what isn't working

slate swan
fast osprey
#

...

#

what is happening, and what do you want to happen, and how do those things differ

slate swan
#

no error in console and to work?

fast osprey
#

What are you physically doing, on your keyboard, and what do you see on your screen

slate swan
#

your discord message?

fast osprey
#

Is your bot running? What are you doing after you run your bot, and what happens?

slate swan
fast osprey
#

When you say "doesn't work", again, what are you doing, and what happens

#

Are you typing something into discord? If so, what and where?

foggy laurel
#

a detailed description of what you do and what happens is needed or nobody will be able to help

slate swan
#

that’s a goood response for someone who doesnt speak english wym

foggy laurel
# slate swan no response

have you tried putting the interaction as a parameter in your method header? because then you can defer the interaction and do a follow up with the embed

#

it either does not reply to the context properly at the moment or takes longer than 3 seconds, which is the timeout duration for interactions if you dont defer them

slate swan
#

no

#

also wat

foggy laurel
#

any command you run, creates an interaction object, which u can get by replacing your whole ctx param with interaction: discord.Interaction (i think)
there you can do interaction.defer to get 15 minutes instead of 3 seconds to reply, and then do a followup with your embed

#

u using discord.py`?

fast osprey
#

When you say "no response", what are you doing

#

Are you typing a prefix command? If so, where? Are you executing a slash command?

slate swan
slate swan
fast osprey
#

But how are you invoking it

#

I've been asking what you are doing to test this

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied timeout to @proud mulch until <t:1723135323:f> (10 minutes) (reason: duplicates spam - sent 4 duplicate messages).

The <@&831776746206265384> have been alerted for review.

slate swan
#

whats the thing to find info on public_flags?

fast osprey
#

!d discord.User.public_flags

unkempt canyonBOT
slate swan
#

how to add this badge to my userinfo command? only hype squad badges seem to work

wanton current
#

Did u read it lol

finite salmon
#

Mb

fast osprey
#

There is no way to definitively tell if someone has nitro. You can guess based on if they use nitro features, but the api doesn't tell you

slate swan
#

is that a work around?

slate swan
slate swan
shrewd apex
#

u can check it if you perform oauth with identify scope

#

there is a premium type flag somewhere iirc

slate swan
#

im smart innit

fast osprey
#

You're going to get false negatives no matter what you do

slate swan
#

pls elaborate?

fast osprey
#

The API does not tell you when someone has nitro

#

you are guessing. You are going to be wrong

slate swan
#

if the user has a banner they would obviously have nitro innit?

#

o nitro basic oops

wanton current
fast osprey
#

False negative means you say someone doesn't have nitro when they actually do

slate swan
#

oh

opal vortex
#

bruh

#

a person can have nitro

#

BUT NO BANNER set up

#

bruh I thought there was a property for nitro in discord.py

#

smth like premium_since or smth.

#

that can be None if they do not have nitro.

#

or is that for server boosting? idek atm.

fast osprey
#

That is just server boosting yes

slate swan
#

people dont consider nitro basic nitro anyway

opal vortex
#

anything above paying 0$ to discord for nitro is still nitro lol.

reef fiber
#

Uh I need help with my bot

fast osprey
#

What's the problem?

slate swan
#

how would i go about getting a users profile theme? like there primary and accent?

slate swan
#

errr @fast osprey 🥺

outer violet
#

i think you can get their banner though (if they have one)

dry kelp
#

so it seems impossible to read an asset after it got deleted, is there any way to find it?

fair herald
#

can someone help me with my bot? dm me im on dnd

shadow vigil
#

odd, can you make your bot hidden?

#

like hidden from the server list?

#

because I added my bot to my server but I don't see it in the member list but can use commands and stuff

stark ingot
#

That seems more like a discord quirk. Like discord has not updated your bots online status or something.

If your bot only uses http interactions and not the gateway it will also not appear to be online.

Also it could be due to the bots permission not being allowed certain things in a channel. As discord only shows members with some set of permissions in the member list. I think it is the send message permission and this will update per channel depending on permissions

vapid parcel
#
[2024-08-08 14:35:02,390] [ERROR [523] Ignoring exception in on_member_join
Traceback (most recent call last):
  File "/usr/local/lib/python3.11/dist-packages/discord/client.py", line 449, in _run_event
    await coro(*args, **kwargs)
  File "/root/unibot/cogs/workers/welcome_leave_handler.py", line 76, in on_member_join
    await member.add_roles(join_role)
  File "/usr/local/lib/python3.11/dist-packages/discord/member.py", line 1083, in add_roles
    await req(guild_id, user_id, role.id, reason=reason)
  File "/usr/local/lib/python3.11/dist-packages/discord/http.py", line 754, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10007): Unknown Member```

Tf does that mean?
#

How are they Unknown when they just joined?

vapid parcel
finite salmon
#

Or they immediately left after joining maybe

vapid parcel
#

I got a question

dry kelp
#

How the heck is it going thru both if statements?

#

When they are clearly different puuuu

#

@stark ingot Your name says ping when responding

#

clear else statement

fair herald
#
C:\Users\luffy\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\cog.py:796: RuntimeWarning: coroutine 'setup' was never awaited
  setup(self)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Loaded cog: test
Logged in as default (1265842230762016798)
------
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "ping" is not found```
#

can someone help me?

hushed galleon
#

id expect that error from using discord.py 1.7.3 or pycord

hushed galleon
#

and the version?

fair herald
#

i forgot how to check the verison

#

im kinda slow

hushed galleon
#

pip show discord.py or pip list should tell you

fair herald
#

wwdf?

#
WARNING: Package(s) not found: discord.py```
hushed galleon
#

err that package you shouldnt have

fair herald
#

can u help me

#

ima send u my code in your dms or i can share my screen?

hushed galleon
#

if its for a self bot we can't help with that