#discord-bots

1 messages · Page 322 of 1

obtuse rose
#

Is Zapier or IFTTT better for Twitter to Discord webhooks?

slate swan
#

whats the recommended size for discord embed images

merry cliff
#

don't do stuff in on_ready, you can set a status when you make an instance of commads.Bot():py bot = commands.Bot(intents=intents, command_prefix='!', case_insensitive=True, activity=discord.Game('Minecraft')) would show the bot as playing minecraft

slate parrot
merry cliff
merry cliff
slate swan
#

can u put img bytes as embed img?

final iron
unkempt canyonBOT
#

set_image(*, url)```
Sets the image for the embed content.

This function returns the class instance to allow for fluent-style chaining.
final iron
#

Docs are your friend

#

Always take a look at them

slate swan
#

thats why i asked here

final iron
#

The docs answer your question pretty clearly

slate swan
#

which im not using

final iron
#

Yeah?

#

Which library are you using

slate swan
#

doesnt even matter anymore

#

i figured it out

final iron
#

Good for you

#

If you’re using a fork of discord.py the same code from the docs apply

#

Also people are going to assume you’re using discord.py whenever you ask for help unless you specify otherwise

slate swan
#

"here are the docs" isnt exactly answering my question

final iron
#

If you cared to look at the paramters/return type it would

#

This is pretty clear

#

How do I use a local image file for an embed image

slate swan
final iron
#

Okay, but unless you’re using hikari it’s the exact same thing lmao

#

You asked for help and didn’t specify, which is on you

#

Now you’re getting all pressed and this is mad funny

slate swan
#

yeah im so pressed

#

and its hilarious

final iron
#

yh mad funny

slate swan
#

keep yapping about the docs for a library i said i wasnt using

#

and then call me pressed

final iron
#

“do i have to repeat myself”

#

real mad abt smth

#

aint my problem lil man

slate swan
#

u act like a child

final iron
#

See you are pressed

#

It’s aight tho

#

its calm

final iron
#

I checked out their websites and they cover a lot of broad topics

potent fox
#

!mute988196894897471508 1D Absolutely unacceptable and not how we talk to others here.

final iron
#

Like automation and such

potent fox
#

!mute 988196894897471508 1D Absolutely unacceptable and not how we talk to others here.

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied timeout to @slate swan until <t:1700176989:f> (1 day).

obtuse rose
# final iron What’s the purpose of these for the webhooks?

In my case basically just having a Discord channel that will have every new tweet a specific Twitter account posts. I used to use IFTTT in the past but after some research it seems because of the Twitter API pricing changes, nor IFTTT nor Zapier offer the Twitter option for free users. It seems I'll have to use RSS for this

final iron
#

Yeah the new changes caused a lot of issues for new/not paid users

#

What’s RSS if you don’t mind?

fierce crag
final iron
#

Yeah thats my bad

#

I crossed the line tbh

obtuse rose
final iron
#

Ah

smoky cedar
#

When I try to delete a role, I get RuntimeError: Timeout context manager should be used inside a task, any idea how to fix this? using discord py latest

smoky cedar
#
async def asyncTearDown(self):
    super().tearDown()
    for role in self.bot.get_guild(TEST_GUILD_ONE_ID).roles:
        if APP_NAME not in role.name:
            await role.delete()
    for role in self.bot.get_guild(TEST_GUILD_TWO_ID).roles:
        if APP_NAME not in role.name:
            await role.delete()
smoky cedar
#

Happens in the first loop

smoky cedar
#

It just rolls back and closes database session

#

no code related to the client

final iron
#

Can you send the whole traceback

patent lark
smoky cedar
#
Error
Traceback (most recent call last):
  File "/usr/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
    return future.result()
  File "/mnt/c/Users/Andrew/workspace/projects/musicbot/tests/integration/test_follow_it.py", line 57, in asyncTearDown
    await role.delete()
  File "/home/andrewpm/.virtualenvs/musicbot/lib/python3.8/site-packages/discord/role.py", line 534, in delete
    await self._state.http.delete_role(self.guild.id, self.id, reason=reason)
  File "/home/andrewpm/.virtualenvs/musicbot/lib/python3.8/site-packages/discord/http.py", line 625, in request
    async with self.__session.request(method, url, **kwargs) as response:
  File "/home/andrewpm/.virtualenvs/musicbot/lib/python3.8/site-packages/aiohttp/client.py", line 1167, in __aenter__
    self._resp = await self._coro
  File "/home/andrewpm/.virtualenvs/musicbot/lib/python3.8/site-packages/aiohttp/client.py", line 493, in _request
    with timer:
  File "/home/andrewpm/.virtualenvs/musicbot/lib/python3.8/site-packages/aiohttp/helpers.py", line 705, in __enter__
    raise RuntimeError(
RuntimeError: Timeout context manager should be used inside a task

void mauve
#

I'm trying to make the thread so no one else can invite here besides the moderator, but upon creating the thread it still possible to invite for non-moderator users, how do i fix it?

        thread = await interaction.channel.create_thread(
            name='123',
            message=None,
            auto_archive_duration=4320,
            type=None,
            reason=None,
        )

        thread.invitable = False
slate swan
#

Error

discord.errors.HTTPException: 401 Unauthorized (error code: 0): 401: Unauthorized

The above exception was the direct cause of the following exception:

  File "C:\Users\Owner\Downloads\selfbot\selfbot.py", line 22, in <module>
    client.run(TOKEN, bot=True)
discord.errors.LoginFailure: Improper token has been passed.```

hey guy im making self bot and got error but i put in my right token and doesnt work can someone help me? sorry bad english
unkempt canyonBOT
#

5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.

final iron
#

Self bots are explicity against Discord TOS

slate swan
#

im sorry

#

did u want me message delete?

smoky cedar
final iron
void mauve
smoky cedar
final iron
unkempt canyonBOT
#

await create_thread(*, name, message=None, auto_archive_duration=..., type=None, reason=None, invitable=True, slowmode_delay=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates a thread in this text channel.

To create a public thread, you must have [`create_public_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_public_threads). For a private thread, [`create_private_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_private_threads) is needed instead.

New in version 2.0.
final iron
#

invitable kwarg

smoky cedar
#

^

void mauve
# final iron `invitable` kwarg

so yeah, that is somehow does not work

Traceback (most recent call last):
  File "F:\PYPROJECTS\discord\TicketBot\autoreg-venv\Lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
    await item.callback(interaction)
  File "F:\PYPROJECTS\discord\TicketBot\package\bot\modules\view\ticket_channel.py", line 36, in send_ticket
    thread = await interaction.channel.create_thread(
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: TextChannel.create_thread() got an unexpected keyword argument 'invitable'
vapid parcel
#

is on_member_boost a thing?

patent lark
smoky cedar
vapid parcel
#

Okay, i need docs on how to catch a boost ig?

#

so you can send an embed to a certain channel of someone boosting n stuff like that

final iron
smoky cedar
#

Let me know if you want to see fanbot.py

patent lark
final iron
patent lark
vapid parcel
#

Discord should send that event tho :)

patent lark
#

well they dont.

vapid parcel
#

would make it easier GoofySkull

void mauve
smoky cedar
#

Thread needs to be private.

#

Also, look at thread.edit()

#

It looks like with pycord, it needs to be called after creation.

void mauve
#

Oh i see

#

Thanks a lot mate

smoky cedar
#

So you need to pass private_thread into the type when using create_thread

#

then call edit with invitable

final iron
smoky cedar
final iron
#

Another reason added onto the list of why to not use py-cord

final iron
#

Error doesn't really align with anything in your code

smoky cedar
#

weird right, shouldn't I expect it to just work by calling await role.delete()?

final iron
#

It should, I'm not really sure why that line is the one that's erroring as it doesn't involve a context manager

#

Are you using an old version of discord.py per-chance?

smoky cedar
#

in my requirements.py, I just have discord.py with no version specified, that should pull latest right?

final iron
#

It should

#

Just check real quick with pip show discord.py

#

Does it work if you're not mocking it?

smoky cedar
#

yeah it is up to date. The only thing I'm mocking is the interaction which shouldn't really come into play here right since the bot isn't being mocked? honestly so confused lol but gonna continue investigating

#

Hmm, maybe because it's trying to delete this role? <Role id=1004184458431315989 name='@everyone'> , the everyone role

#

nope

void mauve
#

It might be a stupid question. but will editing the perms just update the mentioned rights in the code or overwrite all of the rights and leave those ones?

        perms = discord.Permissions()

        for role_id in mod_roles_id:
            role = guild.get_role(int(role_id))
            perms.update(manage_threads=True, send_messages_in_threads=True)

            await role.edit(permissions=perms)
abstract inlet
#

!rule 5

unkempt canyonBOT
#

5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.

drifting arrow
#

!rule 1

unkempt canyonBOT
drifting arrow
#

!rule 2

unkempt canyonBOT
drifting arrow
#

!rules

unkempt canyonBOT
#

The rules and guidelines that apply to this community can be found on our rules page. We expect all members of the community to have read and understood these.

final iron
#

Why are you telling him this? He's not self-botting

final iron
unkempt canyonBOT
#

@final iron :white_check_mark: Your 3.12 eval job has completed with return code 0.

{'Example_1': False, 'Example_2': False}
torn sail
hushed galleon
#

it will overwrite the previous perms if you don't explicitly enable them or transfer them from the role's current permissions (Role.permissions)

#

seems a bit odd to have a function just for changing your mod role perms though

smoky cedar
# final iron Does it work if you're not mocking it?

I had to use asyncio.run_coroutine_threadsafe and pass in bot.loop, it was an issue relating to using a separate thread.

I could've used bot.start() instead of bot.run() to avoid using a separate thread, but since setUpClass doesn't work asynchronously, I would've had to start and stop the bot for every single test which would've been really inefficient / prone to rate limiting with repeated logins

void mauve
smoky cedar
vapid parcel
#

How to do this..?

#

also this means that your interaction can now last longer than 3 seconds correct? Thats what ive been told, so thats why im wanting to do it.

golden portal
#

!d discord.InteractionResponse.defer

unkempt canyonBOT
#

await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Defers the interaction response.

This is typically used when the interaction is acknowledged and a secondary action will be done later.

This is only supported with the following interaction types...
vapid parcel
#

Thank you

vapid parcel
golden portal
#

yes. use ctx.typing

vapid parcel
#

Yeah but gives an error saying it already responded to this command

#

thats why im wondering lol

golden portal
#

just do the typing first before responding?

#

what's the code

vapid parcel
#

well im just testing it, this command really doesnt need a defer, but just for testing

#
An error occurred: Hybrid command raised an error: Command 'coinflip' raised an exception: InteractionResponded: This interaction has already been responded to before```
golden portal
#

!d discord.ext.commands.Context.typing

fierce light
#

Just a note

unkempt canyonBOT
#

async with typing(*, ephemeral=False)```
Returns an asynchronous context manager that allows you to send a typing indicator to the destination for an indefinite period of time, or 10 seconds if the context manager is called using `await`.

In an interaction based context, this is equivalent to a [`defer()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.defer) call and does not do any typing calls.

Example Usage:

```py
async with channel.typing():
    # simulate something heavy
    await asyncio.sleep(20)

await channel.send('Done!')
```...
fierce light
#

Defer uses ur interaction

#

So ur next interaction should be a followup

vapid parcel
fierce light
#

defer is a response to an interaction so yeah

golden portal
#

eh tbf, ctx.send should do followup.send internally when you do that

fierce light
#

I mean

#

Its an interaction no?

final iron
#

defer is an interaction response, yes

fierce light
#

Dunno how u can get a context from that without a conversion

#

or something like _toctx or sum

golden portal
#

he's talking about in hybrid

#

therefore he has context

fierce light
#

Oh

#

Yeah mb i didnt see that

vapid parcel
#

Okay so this gives the bot extra time to like process the command correct?

#

instead of the standard 3 seconds?

final iron
#

Yes

vapid parcel
#

okay ty

final iron
#

15 minutes

shrewd fjord
#

Me when i dont get a strong comeback:

#

I dont know why he just didn't tell what lib bro using dead

slate swan
#

ERROR: Failed building wheel for multidict
Building wheel for yarl (pyproject.toml) ... error
error: subprocess-exited-with-error

slate swan
#

Which Python version are you on

#

and what are you trying to do

fiery girder
#

how do i make something like this in my bot i want multiple sections for one command

#

i dont want same commands but i want them like this

golden portal
#

that's just a group subcommand

#
class MyGroup(commands.GroupCog, group_name='afk', group_description='description'):
  subgroup = app_commands.Group(name='mod', description='balls')
  @subgroup.command()
  async def ignore(interaction: Interaction):
    ...
  @subgroup.command()
  async def ignored(interaction: Interaction):
    ...

probably looks like this from the screenshot
note that it can't go further than a single group nested command
see here too for another example

turbid condor
fiery girder
fiery girder
golden portal
# fiery girder does it work with hybrid or just app

GroupCog is specifically for slash, since discord slash isn't as powerful since it can't have callbacks for the initial group command, for hybrid you just do it normally as you would like a regular group command

fiery girder
#

i am making uno game so having just random command called like playcard or something is just wierd

#

thats why i was thinking about that

golden portal
fiery girder
#

if you removed the mod ofc i dont need that many options

#

i only need 2

golden portal
fiery girder
golden portal
fiery girder
#

oh ok thanks

fiery girder
#

will it run when i run the !afk ignored

golden portal
#

by default it will run first before ignored is ran for prefix command, for slash it never will

#

eh wait, im wrong

fiery girder
#

oh so i can identify b/w the slash and the prefix with this

golden portal
#

by default it will only ran if the subcommand isn't found, say !afk blah since blah isnt a subcommand, it will invoke afk with argument blah instead

fiery girder
#

oh

golden portal
fiery girder
#

so like in afk if i run !afk it will run only the async def afk and if i run !afk ignored it will run that ignored one and if i run !afk blah it will take blah as an arg

golden portal
#

yes

#

pretty much sums up commands group parsing

fiery girder
#

oh ok thanks

#

thanks

golden portal
#

wleocme

fiery girder
# golden portal wleocme

i have one more question if i like get a user from bot.fetchuser then can i send a message to a channel and make it empheremal for that user specific

golden portal
fiery girder
#

so only in like ctx.reply?

#

or interaction.reply?

fiery girder
golden portal
#

interaction.reply doesn't exist
But yea anything related to interaction response, including ctx.send in hybrid you can do ephemeral

fiery girder
#

ok thansk

fiery girder
glad cradle
#

the actual fuck why i pinged the wrong person

#

noticed this just now

fiery girder
final iron
#

That’s the whole point of functions

glad cradle
fiery girder
#

np

slate swan
#

node index.js (node:240) ExperimentalWarning: stream/web is an experimental feature. This feature could change at any time (Use node --trace-warnings ...` to show where the warning was created)
Unhandled promise rejection: Error [TokenInvalid]: An invalid token was provided.
at Client.login (C:\Users\abhay\OneDrive\Desktop\ \grbog\node_modules\discord.js\src\client\Client.js:214:52)
at Object.<anonymous> (C:\Users\abhay\OneDrive\Desktop\ \grbog\index.js:88:8)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:17:47 {
code: 'TokenInvalid'
}

(venv) C:\Users\abhay\OneDrive\Desktop\ \grbog>`

#

why bot shoiwng/invalid/token/for/no/reason

#

💀

#

i chnaged bot/token/10/times/everythig/is/perfect/still/error

fiery girder
#

its js

#

this is python server i dont think many ppl know js here

vague junco
#

How to do something like this?

fiery girder
fiery girder
#

u mean an app bookmark?

vague junco
#

Yeap

fiery girder
#

i think its interaction

#

i dont really know it sorry try asking someone else

#

its something to do with interaction thats for sure i think

shrewd fjord
final iron
# vague junco

Context Menus are a way to run an application command without typing anything. They are accessed in the "Apps" section when right clicking a user or message.

When you right click a message, they are called message commands. In discord.py 2.0 you can implement them as such:

@tree.context_menu(name='Translate with Google', guild=discord.Object(id=MY_GUILD_ID))
async def translate(interaction: discord.Interaction, message: discord.Message):  # An annotation of discord.Message makes this a message command
    ...

Likewise when you right click a user or member, they are called user commands. You can change the annotation from discord.Message to discord.Member accordingly:

@tree.context_menu(name='Ban User', guild=discord.Object(id=MY_GUILD_ID))
async def ban_user(interaction: discord.Interaction, member: discord.Member):  # An annotation of discord.Member makes this a user command
    ...

You can also annotate this with discord.User, but because context menus are only applicable in guilds, they'll probably always be members.

Documentation: https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.context_menu
Note: Context menus cannot be used inside of cogs (in the way you'd normally expect) - see the issue here: https://github.com/Rapptz/discord.py/issues/7823#issuecomment-1086830458

onyx elk
#

does anyone know how to get those forms ?

final iron
#

Which forms

onyx elk
final iron
#

Are you talking about modals

onyx elk
onyx elk
final iron
#

Yes

onyx elk
#

thanks mate

onyx elk
final iron
#

no

flat solstice
#

Am I able to retrieve basic information about a guild/server my bot is not in based on its ID? I'm only looking to resolve the guild name from its ID when the bot isn't in that server/guild

glad cradle
fiery girder
final iron
#

If there's an error you should mention it

onyx elk
#

well i just dont know how to make an embed on app commands

#

could u help (no error just the .Embed thing

final iron
#

That should 100% be erroring

#

What is client

onyx elk
final iron
#

What's MyClient

onyx elk
# final iron What's `MyClient`

class MyClient(discord.Client):
def init(self, *, intents: discord.Intents):
super().init(intents=intents)
self.tree = app_commands.CommandTree(self)
async def setup_hook(self):
await self.tree.sync()

intents = discord.Intents.default()
client = MyClient(intents=intents)

final iron
#

So you're doing discord.Client.Embed which doesn't exist

final iron
#

!d discord.Embed

unkempt canyonBOT
#

class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.

len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.

bool(b) Returns whether the embed has any data set.

New in version 2.0.

x == y Checks if two embeds are equal.

New in version 2.0...
onyx elk
final iron
#

It's just discord.Embed

onyx elk
#

ok

onyx elk
#

idk it int working is it this still?

final iron
#

Is there an error?

onyx elk
final iron
#

what

onyx elk
#

i mispel title in the title lol

void mauve
#

How do I hide HTML's code that is popping out and just send the file to the channel?

async def archive(interaction, archive_channel, user_id):
    """
    :param interaction: discord.Interaction
    :param archive_channel: Object of the Transcript channel
    :param user_id: (User ID of the Client)
    :return:
    """

    channel = interaction.channel

    transcript = await chat_exporter.export(channel)

    if transcript is None:
        return

    base_path = os.path.abspath(f"../package/bot/ui/media/user_{user_id}")

    if not os.path.exists(base_path):
        os.mkdir(base_path)

    image_paths = []

    messages = await channel.history(limit=None).flatten()  # Convert to a list

    for message in messages:

        for attachment in message.attachments:
            image_data = await attachment.read()
            image_path = os.path.join(base_path, attachment.filename)

            with open(image_path, "wb") as file:
                file.write(image_data)

            image_paths.append((attachment.url, image_path))

    image_paths.reverse()

    soup = BeautifulSoup(transcript, 'html.parser')

    attachments = soup.find_all('div', {"class": "chatlog__attachment"})

    for i, attachment in enumerate(attachments):

        anchor_tags = attachment.find_all('a')

        if anchor_tags:
            anchor_tags[0]['href'] = image_paths[i][0]

        img_tags = attachment.find_all('img', {"class": "chatlog__attachment-thumbnail"})

        if img_tags:
            img_tags[0]['src'] = image_paths[i][0]

    modified_transcript = str(soup)

    embed = create_embed(
        title=f'Transcript for #{channel.name}\n',
        description=f'Client: <@{user_id}>'
    )
    embed_message = await archive_channel.send(embed=embed)

    # FILE BEING SENT HERE
    transcript_file = discord.File(
        io.BytesIO(modified_transcript.encode()),
        filename=f"transcript-{channel.name}.html",
    )
    file_message = await archive_channel.send(file=transcript_file)

    link = await chat_exporter.link(file_message)
    new_embed = create_embed(
        title=f'Transcript for #{channel.name}\n',
        description=f'Client: <@{user_id}>\n[Open in browser]({link})'
    )
    await embed_message.edit(embed=new_embed)
final iron
#

Also flatten() is out-dated

void mauve
#

right there

#

i need to just send the file without preview

final iron
#

I don't believe that's possible

#

That's formatted by Discord

void mauve
#

oh, ok, thanks

final iron
#

See if that does anything

void mauve
#

ok lemme try

#

well it doesn't do anything

#

anyway thanks for help

acoustic kernel
#

Question, can you add specific description for a parameter for a slash command?

#

Like after where it says role it tells you the instructions for the input to that parameter?

final iron
unkempt canyonBOT
#

@discord.app_commands.describe(**parameters)```
Describes the given parameters by their name using the key of the keyword argument as the name.

Example:

```py
@app_commands.command(description='Bans a member')
@app_commands.describe(member='the member to ban')
async def ban(interaction: discord.Interaction, member: discord.Member):
    await interaction.response.send_message(f'Banned {member}')
```  Alternatively, you can describe parameters using Google, Sphinx, or Numpy style docstrings...
acoustic kernel
#

Aight thanks

pure garden
#

@unkempt canyon whats the event to get when a member boost your server

sick birch
#

it's just an on message

#

check the type of the message, though

final iron
unkempt canyonBOT
#

discord.on_member_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) updates their profile.

This is called when one or more of the following things change...
final iron
#

Then check

#

!d discord.Member.premium_since

unkempt canyonBOT
#

An aware datetime object that specifies the date and time in UTC when the member used their “Nitro boost” on the guild, if available. This could be None.

final iron
#

Discord doesn't dispatch any event when the server gets boosted

sick birch
#

having the boost message is the only way iirc

#

or maybe you get a guild update. haven't checked

final iron
#

It says when a Guild updates but doesn't specify

#

I can't really test it as well lol

latent jay
#

With slash commands can you set an option as accepting a file?

final iron
#

Yes

#

Typehint as discord.Attachment

latent jay
#

what's the deco for an optional argument?

final iron
#

!d typing.Optional

unkempt canyonBOT
#

typing.Optional```
`Optional[X]` is equivalent to `X | None` (or `Union[X, None]`).

Note that this is not the same concept as an optional argument, which is one that has a default. An optional argument with a default does not require the `Optional` qualifier on its type annotation just because it is optional. For example:

```py
def foo(arg: int = 0) -> None:
    ...
```  On the other hand, if an explicit value of `None` is allowed, the use of `Optional` is appropriate, whether the argument is optional or not. For example:

```py
def foo(arg: Optional[int] = None) -> None:
    ...
```...
final iron
#

Or default to a value

latent jay
#

I mean like for slash commands isn't there an arg for like /help <optional: menu>

final iron
latent jay
#

So it wouldn't need a command_choices

final iron
#

What is command_choices

#

What library are you using

latent jay
#

I meant @app_commands.choices()

final iron
#

Do you know what choices() does?

latent jay
#

Yeah but when you add them they're required right

final iron
#

I don't believe so

latent jay
#

Can I do this in slash commands? file: discord.Attachment

final iron
latent jay
final iron
#

wdym

latent jay
#

Like how can I make the bot send a file

#

in response to the slash command

final iron
#

file kwarg

#

!d discord.InteractionResponse.send_message

unkempt canyonBOT
#

await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, silent=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Responds to this interaction by sending a message.
latent jay
#

oh, I should've specified, I'm using Interaction.edit_original_response()

#

Says it's attachments?

final iron
#

!d discord.Interaction.edit_original_response

unkempt canyonBOT
#

await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the original interaction response message.

This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit) in case you do not want to fetch the message and save an HTTP request.

This method is also the only way to edit the original message if the message sent was ephemeral.
final iron
latent jay
#

And then I'd just do attachments=discord.File('path/to/file) right?

final iron
#

Yeah

#

Well attachments is a list

#

So you’d need to put that discord.File object into a list

acoustic kernel
#

Question, how do I get the bot to not send the "no response" message

golden portal
#

!d discord.InteractionResponse.send_message

unkempt canyonBOT
#

await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, silent=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Responds to this interaction by sending a message.
golden portal
#

Use that instead

latent jay
#

How could I use wait_for to check for an attachment?

shrewd fjord
#

!d discord.Message.attachments

unkempt canyonBOT
shrewd fjord
#

You can use len(message.attachments)

#

!ping

unkempt canyonBOT
#

You are not allowed to use that command here. Please use the #bot-commands channel instead.

shrewd fjord
#

Oh my wifi was ded my bad

unkempt canyonBOT
#
Missing required argument

pep_number

fiery girder
#

!paste

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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

fiery girder
#

this error keeps coming up when i start my uno

#

idk why

#

this code of this command

brazen raft
slate swan
#

!e import random; print(1 if random.randint(1,2) == 1 else 2)

unkempt canyonBOT
#

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

1
tawny hemlock
#

does discord.ext.loop runs loops even if the previous loop is still running

golden portal
#

nope, the previous needs to finish

agile cedar
#

Does anyone have experience adding role management based on a reaction to a message?

final iron
#

Don’t ask to ask. Just ask your question and you’ll get a faster response

agile cedar
#

My code:

unkempt canyonBOT
#

discord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_message_edit), if the message is not found in the internal message cache, then this event will not be called. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_add) instead.

Note

To get the [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message) being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Reaction.message).

This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.reactions) to be enabled.

Note

This doesn’t require [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members) within a guild context, but due to Discord not providing updated user information in a direct message it’s required for direct messages to receive this event. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_add) if you need this and do not otherwise want to enable the members intent.
slate swan
#

!d textwrap.wrap

unkempt canyonBOT
#
textwrap.wrap(text, width=70, *, initial_indent='', subsequent_indent='', expand_tabs=True, replace_whitespace=True, fix_sentence_endings=False, break_long_words=True, ...)```
Wraps the single paragraph in *text* (a string) so every line is at most *width* characters long. Returns a list of output lines, without final newlines.

Optional keyword arguments correspond to the instance attributes of [`TextWrapper`](https://docs.python.org/3/library/textwrap.html#textwrap.TextWrapper), documented below.

See the [`TextWrapper.wrap()`](https://docs.python.org/3/library/textwrap.html#textwrap.TextWrapper.wrap) method for additional details on how [`wrap()`](https://docs.python.org/3/library/textwrap.html#textwrap.wrap) behaves.
sour sand
#

"Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
[end of output]

note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed building wheel for yarl
Failed to build aiohttp frozenlist multidict yarl
ERROR: Could not build wheels for aiohttp, frozenlist, multidict, yarl, which is required to install pyproject.toml-based projects"

#

and i can't understand how to get c++ tools

sour sand
final iron
#

Yes

sour sand
#

k ty, ill tell you if it works !

slate swan
#

Hey i need some help swithcing the default !help command to be an embed message instead

sour sand
fervent cove
#

Hey, I've been fighting with this command for so long, and it still sometimes throws API rate limit. Any suggestions, how to make it better/smoother/orwhatever, that will make it always work?

https://paste.pythondiscord.com/AU2Q
(I'm talking ab first file, the other two files are just imports I'm using)

slate swan
# slate swan thank ya

I think im doing somthing wrong, i can get a message to embed but how do i change the values?

#

what it says i mean

ashen notch
#

I'm looking at views in discord.py, specifically persistent buttons. I'm seeing that you have to use .add_view() to make sure that it's being watched and the example that is on the discord.py repo shows it being added during the setup_hook(). I'm trying to understand two things:

  1. Does it need to be in setup_hook or is that just the example they have?
  2. Can setup_hook be called in a cog and the view added that way or does it need to be on the base bot class?
#

Not sure if I'm explaining that well at all

slate swan
#

Are you talking to me? or someone else, i can't tell

ashen notch
#

Anyone in general, sorry

#

Just had my own question is all

slate swan
#

my brain smooth

slate swan
ashen notch
#

So it should be one of the methods that'll be treated the same as if it were in the bot proper

#

Does it need the event decorator?

slate swan
#

if someone could dumb this down for me please i think i misunderstand it

final iron
#

!d discord.ext.commands.Bot.setup_hook

unkempt canyonBOT
#

await setup_hook()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

A coroutine to be called to setup the bot, by default this is blank.

To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.

This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.login), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready) event.

Warning

Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_for) and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_until_ready)...
final iron
#

setup_hook isn’t an actual event sent by Discord like on_ready, it’ll simply just executed once on login. I’d think of it more of a method than an event

final iron
slate swan
#

the other article helped a bit for some other things

#

i just sorta need to know how that custom command works and what i can change on it

hushed galleon
# ashen notch So it should be one of the methods that'll be treated the same as if it were in ...
  1. add_view() is synchronous so in theory you could put it anywhere, though constructing a view itself appears to require a running event loop at minimum
  2. For a cog I would suggest the (a)synchronous Cog.cog_load() method which gives you a good place to fetch any state needed for constructing your view

it's not particularly obvious how you'd remove the view during cog_unload() (to prevent old callbacks firing if you reload the cog), but based on their source code, any references to the view and its callbacks should be discarded when you .stop() the view

unkempt canyonBOT
#

discord/ui/view.py lines 431 to 432

def _start_listening_from_store(self, store: ViewStore) -> None:
    self.__cancel_callback = partial(store.remove_view)```
cold oyster
#

Hey question, You know how when you invoke a command using the Dyno bot, In the footer it says executed at (my timezone) then if a different user uses it it shows thier's, How does Dyno do that (Ping when responding pls)

unkempt canyonBOT
#

The timestamp of the embed content. This is an aware datetime. If a naive datetime is passed, it is converted to an aware datetime with the local timezone.

vapid parcel
cold oyster
ruby valve
#

hey so im trying to make a command to essentially create an event rsvp with slash commands. The user will simply do /rsvpcreate and then there will be a questionnaire essentially to get the details needed for the event. The bot will initially respond with "Let's create a new event! Please provide the following information." but I cant figure out how to respond again with the first question being asking for the timezone.

Sorry about bad formatting im tired as

final iron
#

How is this questionnaire formatted? Is it a modal or something else? What do you mean respond again? Respond to what?

ruby valve
#

alright so, the user does /rsvpcreate. The bot responds with a message "Let's create a new event! Please provide the following information." and will then send another message "1. What is your timezone? (e.g., 'Australia/Brisbane')". The user will reply with a regular message with the country and city or their timezone, that data will then be stored and the bot will send another message "2. What channel will the event be in?" where the user do the same thing, replying with the channel id or channel name whichll then be stored. This is my first time playing around with slash commands and I cant figure out how to respond to regular messages from the interaction (slash command) user.

final iron
#

Or a dropdown menu

ruby valve
#

just noticed i forgot to mention that there will be 8 questions, im trying to make it as user friendly as possible so I'd rather a more interactive solution. I probably could put all of them as arguments in the slash command but I feel like that would end up messy for me and the user, even if I only do a few like the channel and timezone I'm still left with the same issue

final iron
#

Different arguments require different formats

#

The timezone could also just be a string argument or a wait_for, depending on what you want

vale wing
#

Best UX

#

But yeah for discord bot good option would be redirecting users to some timestamp generation site and pasting the number from there

#

Or telling them to type time in UTC like that's their problem to convert time

slate swan
#

what is the discord for py bots

robust fulcrum
#

What?

shadow vigil
vale wing
flat solstice
#

Could I make a command/function of my bot to log into a different bot account.
Something like this psuedo code:

async def subbot(ctx, token: str):
    output=""
    subbot = discord.ext.commands.Bot(command_prefix='?', intents=discord.Intents.default())
    @subbot.event
    async def on_ready():
        output=(f'Logged in as {subbot.user} (ID: {subbot.user.id})')
    @subbot.command()
    async def test(ctx):
        output=("test response")
        await ctx.send(output)
    subbot.run(token)
    await ctx.send(output)
slate swan
#

why would you want to run a bot .. with another bot

flat solstice
# slate swan why would you want to run a bot .. with another bot

I host Discord bots for ppl, if they go down for whatever I need to trawl through Discord DMs to try to remember who owns the bot to notify them about the outage.
So my idea was I could just get my management bot (which isn't in their servers) to log in to their instance to send them a message about the outage. I had a few other use cases for such a feature but that's the easiest to explain
White label instances would also be a good use for such a implementation

harsh latch
#

1175446262884089877

placid relic
#

hello how i can setup role for use command

#

?

#

@bot.command()
async def clear(ctx, amount=5):
if amount > 100 or amount <1:
await ctx.send(f"you put {amount} in, but allowed range is 1-100")
return
textchannel: discord.TextChannel = ctx.channel
await textchannel.purge(limit=amount+1)
await ctx.send(f"deleted {amount} message in {ctx.channel.name}")

turbid condor
#

use checks

#

!d discord.ext.commands.Bot.check

unkempt canyonBOT
#

@check```
A decorator that adds a global check to the bot.

A global check is similar to a [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check) that is applied on a per command basis except it is run before any command checks have been verified and applies to every command the bot has.

Note

This function can either be a regular function or a coroutine.

Similar to a command [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check), this takes a single parameter of type [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context) and can only raise exceptions inherited from [`CommandError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandError).

Example...
empty lake
#

?tag op

novel apexBOT
#

This is not a Modmail thread.

empty lake
#

?tag lp

novel apexBOT
#

This is not a Modmail thread.

hushed galleon
#

@empty lake oh i forgot to mention that they copy-pasted a tag from the discord.py server, and they don't actually exist here

final iron
#

You can easily find an invite online though

slate swan
flat solstice
final iron
#

Just run it

flat solstice
final iron
#

What you’re asking won’t work

#

Unless you do some extremely hacky subprocess work to start the files of the other bot and capture and redirect the stdout you’ll need to use threading

#

Threading comes with the performance implications

flat solstice
hushed galleon
final iron
#

Using the same event loop can come with unexpected issues though

hushed galleon
#

im not aware of any issues with it

#

by simple i mean the bare minimum being: ```py
subbot_tasks = []

async def start_bot():
bot = MySubBot(...)
task = asyncio.create_task(bot.start(token))
subbot_tasks.append(task)```

shrewd vapor
#

Hello, idk how to make a ban command for ban with id or member and not only id or not only the @

final iron
#

You’ll have to verify none of the bots contain blocking code or lengthy IO tasks

hushed galleon
shrewd vapor
#

Both, I'd like to do with id or name in the same command

hushed galleon
hushed galleon
#

also works for slash commands too

final iron
#

If separate files were being run it would only affect the 1 bot, but with a shared event loop it has the potential to freeze all of them and imo if you’re functioning as a hosting platform of sorts you can’t really just reject peoples code

hushed galleon
#

yeah there's a lot of factors to consider with the scalability of your program

shrewd vapor
hushed galleon
#

oh for slash commands yeah, i forgot they don't autocomplete IDs

#

have you considered using a context menu instead?

shrewd vapor
#

Yes i use only slash command with 2.x.x

#

I have never use context menu

hushed galleon
#

context menus let you add right-click actions for messages and users

unkempt canyonBOT
#

examples/app_commands/basic.py lines 85 to 89

# This context menu command only works on members
@client.tree.context_menu(name='Show Join Date')
async def show_join_date(interaction: discord.Interaction, member: discord.Member):
    # The format_dt function formats the date time into a human readable representation in the official client
    await interaction.response.send_message(f'{member} joined at {discord.utils.format_dt(member.joined_at)}')```
hushed galleon
shrewd vapor
#

Ok thanks

flat solstice
flat solstice
hushed galleon
flat solstice
shrewd vapor
#

My command don't want to load on discord...

#

I wait since 30 minutes

#

And i have bot.tree.sync in my code

loud mirage
#

Can someone help me with this {
"commands": {
"Bot": {
"command_prefix": "!"
},
"room_data": {
"PUT PLAYERIDHERE": "PUT ROOM CODE HERE"
},
"on_ready_event": {
"print_statement": "Logged in as BOT_NAME (BOT_ID)"
},
"on_member_update_event": {
"if_condition": "before.activity != after.activity and isinstance(after.activity, discord.Game)",
"actions": [
{
"player_id": "str(after.id)",
"room_code": "find_room_code(player_id)",
"if_room_code_exists": {
"channel": "bot.get_channel(CHANNEL_ID)",
"send_message": "await channel.send(f"Player {after.display_name} joined room {room_code}")"
}
}
]
},
"find_room_code_function": {
"function_body": "return room_data.get(player_id, 'Room Code Not Found')"
},
"run_bot": {
"bot_token": "YOUR_BOT_TOKEN"
}
}
}

glad cradle
#

what the actual fuck

slate swan
#

blud be coding in JSON

shrewd vapor
#

I have write that:

@bot.tree.command(name="ban", description="Ban a member")
async def ban_user(interaction: Interaction, member: discord.Member or str, *, reason: str = None):
    await interaction.response.defer()

    print(f"Attempting to ban: {member}")

    if not interaction.user.guild_permissions.ban_members:
        await interaction.followup.send(f"You are not authorized to use this command {interaction.user.mention}")
        return

    if isinstance(member, str):
        try:
            member = await bot.fetch_user(int(member))
        except discord.NotFound:
            await interaction.followup.send("User not found")
            return

    print(f"After fetch_user, member is: {member}")

    if not isinstance(member, discord.Member):
        await interaction.followup.send("Invalid user")
        return

    if member == interaction.user:
        await interaction.followup.send("You can't ban yourself")
        return

    if member == interaction.guild.owner:
        await interaction.followup.send("You can't ban the owner")
        return

    if member == bot.user:
        await interaction.followup.send("You can't ban me")
        return

    await interaction.guild.ban(member, reason=reason)
    await interaction.followup.send(f"{member} banned from the server")```

And i get this error

```shell
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 852, in _invoke_with_namespace
    transformed_values = await self._transform_arguments(interaction, namespace)
                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 818, in _transform_arguments
    transformed_values[param.name] = await param.transform(interaction, value)
                                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/transformers.py", line 181, in transform
    return await maybe_coroutine(self._annotation.transform, interaction, value)  # type: ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/.local/lib/python3.11/site-packages/discord/utils.py", line 693, in maybe_coroutine
    return await value
           ^^^^^^^^^^^
  File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/transformers.py", line 622, in transform
    raise TransformerError(value, self.type, self)
discord.app_commands.errors.TransformerError: Failed to convert juggos.rc to Member```
#

When i put the id

shrewd vapor
#

for put the id

#

or the @member

#

id if the user is not on the server

slate swan
#

That's not how it works, use a converter

#

And especially if you're using slash commands options

#

And also instead of having a check for the user's permission, make it a decorator and handle the error in your error handler

slate swan
final iron
#

As a legitmate question

#

What are you trying to do?

final iron
#

The built-in one is objectively better

#

You’re also never checking for hierarchy

loud mirage
final iron
#

What library are you using?

loud mirage
#

Wdm

#

Wdym

final iron
#

Which discord API wrapper are you using

loud mirage
#

Idk

final iron
#

Are you following a guide?

loud mirage
#

Nope

vapid parcel
#
local_time = datetime.now()
text = "© UniBot 2023-2024 • Today at {}".format(local_time.strftime("%I:%M %p"))```
#

this is how dyno/carl/mee6 do it correct?

#

so it shows the correct time for everyone..?

#

@final iron (sorry for the ping)

Just wondering if you know if thats correct..

rugged shadow
#

!d discord.Embed

unkempt canyonBOT
#

class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.

len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.

bool(b) Returns whether the embed has any data set.

New in version 2.0.

x == y Checks if two embeds are equal.

New in version 2.0...
rugged shadow
#

use the timestamp property

vapid parcel
#

damn

rugged shadow
#

it's really easy

#

you just have to pass local_time in there

#

no, wait, it's actually UTC time i think

vapid parcel
rugged shadow
#

yep

vapid parcel
#

Now real question

#

will it show different time for others based on their time?

#

thats kinda the goal here XD

rugged shadow
#

it's expecting UTC timestamp so use datetime.utcnow instead

vapid parcel
#

cuz im CST

rugged shadow
#

yeah it should

vapid parcel
#

let me test rq

rugged shadow
#

that's on Discord's side to render the time on the client

#

you just have to supply the utc timestamp and it'll convert to the client's local time

vapid parcel
#

Okay it works :)

#

Now is there a way to make it do my test before the time?

rugged shadow
vapid parcel
#

So the timestamp is a footer

#

but i also wanna have "© UniBot 2023-2024 • timestamp" as the footer you know?

vapid parcel
#

Oh i know why, i was on the wrong embed GoofySkull

#

mb

latent jay
#

How do I edit an interaction message? I can't call edit() on a interaction.response.send_message

fading marlin
#

!d discord.Interaction.edit_original_response

unkempt canyonBOT
#

await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the original interaction response message.

This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit) in case you do not want to fetch the message and save an HTTP request.

This method is also the only way to edit the original message if the message sent was ephemeral.
latent jay
#

gotcha

vapid parcel
#

Okay so i just had the timestamp stuff working right?

#

Why is it now saying Tomorrow 😭

golden portal
#

are you using the correct datetime?

#

!d discord.utils.utcnow

unkempt canyonBOT
#

discord.utils.utcnow()```
A helper function to return an aware UTC datetime representing the current time.

This should be preferred to [`datetime.datetime.utcnow()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.utcnow) since it is an aware datetime, compared to the naive datetime in the standard library.

New in version 2.0.
golden portal
#

use that, datetime needs to be aware

slate swan
vapid parcel
#

cuz it actually does it correct unlike utcnow

golden portal
#

Probably coincidentally the timestamp was matching UTC timezone

vapid parcel
#

mhm

#

so ill just use .now instead of .utcnow

golden portal
#

Its recommended to use discord.utils.utcnow instead

#

I'm not talking about datetime.utcnow

vapid parcel
#

whats the benefits..?

#

or the "difference"

#

Pros n cons

golden portal
#

its a datetime aware

#

Pretty much every datetime in dpy is aware iirc

vapid parcel
#

So i should just do
timestamp=discord.utils.utcnow(),

golden portal
#

yea sure

final iron
#

Try it and see

vapid parcel
#

It works

#

i tried it

#

I guess ill just that..?

#

Thank you ^^

fast charm
#

hello hello i have a ready discord bot coded on python now i want to host it i want a free option like really free i treied every thing which shows on google result maybe there is hidden gem platform

vapid parcel
#

Do have a question, this is still about timestamps but for a custom embed... based on True or False basically, whats the best way to approach the timestamp for this besides the way i do it..?

    @commands.hybrid_command(name="embed")
    @commands.guild_only()
    async def custom_embed(
            self, ctx, title, color_hex, header=None, description=None, title_url=None, timestamps=False,
            footer=None, footer_image=None, thumbnail=None, image=None, author=None, author_url=None, author_icon=None
    ):
        """Lets you make a custom embed to your liking!"""
        if not title or not color_hex:
            error_embed = discord.Embed(
                title="Command Error",
                description="Invalid arguments! Please use the format:\n!embed title hex_color [header] [description]",
                timestamp=discord.utils.utcnow(),
                color=0xFF0000
            )
            error_embed.set_footer(text="© UniBot 2023-2024", icon_url=ctx.bot.user.avatar.url)
            await ctx.send(embed=error_embed)
            return

        if not color_hex.startswith("#"):
            color_hex = "#" + color_hex

        if not re.match(r'^#(?:[0-9a-fA-F]{3}){1,2}$', color_hex):
            error_embed = discord.Embed(
                title="Command Error",
                description="Invalid hex color format. Please provide a correct hex color.",
                timestamp=discord.utils.utcnow(),
                color=0xFF0000
            )
            error_embed.set_footer(text="© UniBot 2023-2024", icon_url=ctx.bot.user.avatar.url)
            await ctx.send(embed=error_embed)
            return

        if len(color_hex) == 4:
            color_hex = "#" + "".join([char * 2 for char in color_hex[1:]])

        try:
            color = int(color_hex[1:], 16)

            embed = discord.Embed(
                title=title,
                color=discord.Color(color)
            )

            if header:
                embed.description = header

            if description:
                descriptions = description.split("\\n")
                for i, desc in enumerate(descriptions, start=1):
                    embed.add_field(name=f"", value=desc.strip(), inline=False)

            if title_url:
                embed.url = title_url

            if timestamps:
                timestamp = datetime.datetime.utcnow()
                timestamp_str = timestamp.strftime("%m/%d/%y at %I:%M:%S %p")

                if footer:
                    timestamp_str = f"{footer}{timestamp_str}"

                embed.timestamp = None
                embed.set_footer(text=timestamp_str)

            if footer_image:
                embed.set_footer(text=timestamp_str, icon_url=footer_image)

            if thumbnail:
                embed.set_thumbnail(url=thumbnail)

            if image:
                embed.set_image(url=image)

            if author:
                embed.set_author(name=author, url=author_url, icon_url=author_icon)
            await ctx.send(embed=embed)
        except ValueError:
            error_embed = discord.Embed(
                title="Command Error",
                description="Invalid hex colour format. Please provide a correct hex color.",
                timestamp=discord.utils.utcnow(),
                color=0xFF0000
            )
            error_embed.set_footer(text="© UniBot 2023-2024", icon_url=ctx.bot.user.avatar.url)
            await ctx.send(embed=error_embed)```
fast charm
#

@vapid parcel how do you embed these code

vapid parcel
#

then do py

#

best way i can explain it without it messing up lol

fast charm
#

try one more time

vapid parcel
#

here ill just show you ig

fast charm
#
you mean this```
vapid parcel
#

yes

#

idk what its called GoofySkull

fast charm
vapid parcel
#

Instead of my approach^

final iron
#

0

#

You have to pay one way or another

golden portal
final iron
fast charm
#

ohh boy pay is like stealling my parents money i am minor also

final iron
#

discord.pys converters supports bools. It converts a few different inputs, which are listed in the docs

#

I’d check those out

final iron
final iron
vapid parcel
final iron
#

Somebody has to

vapid parcel
#

Which means they can sell your data, but every website sells your data in a way lmao

fast charm
final iron
vapid parcel
final iron
#

You can scrounge up the $5 a month a proper VPS requires

#

Get a job if you can’t

vapid parcel
#

Could go mow grass tho :)

final iron
#

There are other ways to make money

#

Landscaping, gardening, cleaning etc

fast charm
#

yeah there is tea shop i can clean pots @final iron

vapid parcel
final iron
#

Walk up to a house, ask for $2 to clean the weeds from their lawn

final iron
#

Do that 5 times and you’ve paid for 2 months of hosting

vapid parcel
#

make the money

fast charm
vapid parcel
final iron
final iron
fast charm
#

thanks i will work on that time to do some risky hosting

vapid parcel
vapid parcel
#

and trusted ^

final iron
vapid parcel
#

or reliable?

fast charm
#

@vapid parcel can i make a .env file there and no need of disclossing my token

final iron
#

.env files can still be opened

vapid parcel
#

Read the ToS and Privacy for their site before using.

final iron
#

Are you looking for a cheaper or more expensive option?

vapid parcel
final iron
#

Hetzner imo

vapid parcel
#

Also rather get a VPS, so i can run more than 1 bot basically, i know you run more than 1 bot in 1 terminal, just dont know how to right now sadly

vapid parcel
#

Thank you for the help

vapid parcel
#

Or would you need a VPS

final iron
vapid parcel
fast charm
#

@vapid parcel hey bro one more thing atleast discord server bot dont send me notification of exposed token

final iron
#

You’ll still have to run the files for the website

#

You can keep your database files in the directory where your website is being run from

#

If you want your database on a server you’ll need to look into pymongo

#

You can also create a little API to interact with your database if you want

vapid parcel
#

insteal of just SQLite

vapid parcel
#

they do not... they should tho lowkey, that would be smart... but they dont,

vapid parcel
#

Well the reason why is because we have no clue if we can make the SQlite db work with a website

#

we havent done much research yet, its like way in the future.. but we are just thinking of it, just thoughts, not commits lol

final iron
#

PostgreSQL would be the same situation as SQLite

#

They both interact with local database files

vapid parcel
#

oh hm

#

Well, we have to do more research tbh

#

we are just thinking on how we will do a dashboard n everything

final iron
#

I’d look into PyMongo

vapid parcel
#

Yeah its just thoughts for now, we still researching many things

#

But yeah, we wanna switch to VPS, get away from a host, then we can do many more things

#

more freedom XD

final iron
#

VPS is a good start

pale cobalt
#

where can I ask for codes For my discord bot?

rugged shadow
#

your brain

vapid parcel
turbid condor
slate swan
#

how shall i add a slash command or application command using discord.py?

slate swan
slate swan
#

instead of client

#

you can

#

how

#

just like youdo with client

#

tell me the code so that i can put a slash command in my bot

slate swan
# slate swan yeah its right there

File "c:\Users\admin\Desktop\Coding Knowledge Drive 2\Python Programs\Discord\Helper Bot version 1\main.py", line 46, in <module>
@bot.tree.command()
^^^^^^^^
AttributeError: 'Bot' object has no attribute 'tree'

#

it gives this

#

the module name is only "discord"

#

it should be discord.py

unkempt canyonBOT
slate swan
#

import name is not the same as package name

ivory storm
#

Why this bot don't responding to message

import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.typing = False
intents.presences = False
bot = commands.Bot(command_prefix='/', intents=intents,
                   help_command=None)  # added debug option


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


@bot.event
async def on_message(message):
  print(f'Received message: {message.content}')
  await bot.process_commands(message)


@bot.command()
async def ping(ctx):
  print("Ping command invoked")
  await ctx.send(f'Pong! {round(bot.latency * 1000)}ms')


@bot.command()
async def active_commands(ctx):
  commands_list = [command.name for command in bot.commands]
  await ctx.send(f'Active commands: {commands_list}')


@bot.command()
async def hello(ctx):
  print("Hello command invoked")
  await ctx.send('Hello!')


bot.run(
    'TOKEN')
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.

ivory storm
#

Thank you its work

slate swan
# slate swan import name is not the same as package name
import discord
from discord.ext import commands
import asyncio

command_prefix = "."

intents = discord.Intents.all()

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

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name}')

@bot.tree.command()
async def hello(interaction: discord.Interaction):
    """Says hello!"""
    await interaction.response.send_message(f'Hi, {interaction.user.mention}')    
    
    
bot.run('')

in this when i put other commands they are working but this tree command isnt working also this tree command is only slash command right?

ivory storm
#

How to show bot here

slate swan
slate swan
#

i want my slash command to be there

slate swan
#

then send output of pip list

#

!paste

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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

slate swan
#

put this in your code print(discord.__version__)

#

right after you import discord

slate swan
#

this is output

#

okay how about __author__

slate swan
#

odd

slate swan
#

you can try ig

slate swan
slate swan
#

!help\

#

Hi what are you doing here

slate swan
#

in hybrid command ".hello" is working but not "/hello"

#

. is my default prefix

#

when i type /hello nothing pops up

#

can you do from discord import app_commands

#

and see if this import works

#

yes its working

#

no error on that

#

show full code with @bot.tree.command()

slate swan
# slate swan show full code with @bot.tree.command()
import discord
from discord import app_commands
from discord.ext import commands
import asyncio

print(discord.__version__)
print(discord.__author__)

# Set your command prefix
command_prefix = "."

intents = discord.Intents.all()

# Create an instance of the bot
bot = commands.Bot(command_prefix=command_prefix, intents=intents)

# Event handler when the bot is ready
@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name}')

# Command to get ping
@bot.command(name='ping')
async def get_ping(ctx):
    latency = bot.latency * 1000  # Convert to milliseconds
    await ctx.send(f'Pong! {latency:.2f}ms')

@bot.command(name='raid')
async def raid(ctx):
    await ctx.send("Timer set! I will ping you after 30 mins!")
    await asyncio.sleep(1800)
    message1 = ctx.author.mention
    await ctx.send(f"Raid cooldown is over! {message1}")

@bot.command(name='hourly')
async def hourly(ctx):
    await ctx.send("Timer set! I will ping you after 1 Hour!")
    await asyncio.sleep(3600)
    message1 = ctx.author.mention
    await ctx.send(f"Hourly cooldown is over! {message1}")

@bot.command(name='timer')
async def timer(ctx, time):
    await ctx.send(f"Timer of {time} seconds have been set!")
    await asyncio.sleep(int(time))
    message2 = ctx.author.mention
    await ctx.send(f"Time up! {time} Seconds have been passed. {message2}")    

@bot.hybrid_command
async def hello(ctx):
    await ctx.send("hello!")
    
@bot.tree.command()
async def hello(interaction: discord.Interaction):
    """Says hello!"""
    await interaction.response.send_message(f'Hi, {interaction.user.mention}')
    
# Run the bot with your token
bot.run('')
#

and what error you get

slate swan
#

did you invite bot with application.commands scope?

#

the bot is up and the other commands are working

slate swan
slate swan
#

ok wait i get what ur saying

slate swan
#

and do what it says

slate swan
#

i ticked bot and application.commands in scope and administrator and using that url i invited the bot again

#

👍

#

but still not working :(((((((((((((((((((((

#

you need to sync the commands

#

i put / and my bot doesnt even appear there and when i put /hello still it doesnt appear

#

add this code ```py
@bot.event
async def setup_hook():
await bot.tree.sync(discord.Object(YOUR_GUILD_ID))

#

YOUR_GUILD_ID?

#

yeah YOUR_GUILD_ID

#

that you are testing the bot in

#

yeah

#

why my msg is red

#

oh nvm

slate swan
# slate swan that you are testing the bot in

File "c:\Users\admin\Desktop\Coding Knowledge Drive 2\Python Programs\Discord\Helper Bot version 1\main.py", line 25, in setup_hook
await bot.tree.sync(discord.Object(12121212121212121212))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: CommandTree.sync() takes 1 positional argument but 2 were given

#

that 121212121212 is my guild id but my guild id is different

#

!d discord.app_commands.CommandTree.sync

unkempt canyonBOT
#

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

Syncs the application commands to Discord.

This also runs the translator to get the translated strings necessary for feeding back into Discord.

This must be called for the application commands to show up.
slate swan
#

sorry you have to add guild=discord.Object(...)

slate swan
#

obviously you put id instead of dots

#

oh my guuild id

#

i put that but same

#

same what

#

it still does not appear?

#

no

#

i guess you have to wait a bit

#

it may take a while

slate swan
#

no pls thats very complicated

#

i cant understnad it

#

now i remember why i dont use discord.py
so much effort just to have slash command

slate swan
slate swan
#

If you don't, you need to learn Python and the various required topics/themes to know

slate swan
#

thats why i came to ask questions

slate swan
#

and look at that code ...

slate swan
#

i doubt you know what OOP, decorators and async await syntax is

#

if you are new

merry cliff
#

yeah please just start with the basics

cloud dawn
naive briar
#

I started to learn Python just to make myself a bot 🫠

#

It's probably 3 years ago, almost right after I created my account

slate swan
turbid vortex
#

who will write a bot that will check all the files on the server that the participants throw off through the virustotal and into the channel for admins to throw off information whether the file is infected

main torrent
#

How to make costom status

turbid vortex
slate swan
#

!rule pay

unkempt canyonBOT
#

9. Do not offer or ask for paid work of any kind.

slate swan
#

uuu blud be breaking code of conduct

#

ban him!@

turbid vortex
vale wing
#

Skill issue

merry cliff
#

lol

#

It’s definitely possible but there is a rate limit

slate swan
#

anyone abl to help me with my discord bot?

slate swan
#

i have trouble running my discord bot, anyone ableto help?

slate swan
lofty pecan
#

does anyone know a good tutorial about raspberry pi discord bot hosting?

vapid lance
#

Hello, I need help with my bot. Anyone wants to help me?

vale wing
#

Even if it's quantum computing

lofty pecan
vapid lance
vale wing
lofty pecan
vale wing
#

Install ubuntu

lofty pecan
#

So far I'm using pycharm to code and run my bot lol

#

plus I know nothing about Linux

vale wing
ivory storm
vale wing
lofty pecan
vale wing
#

Also a bunch of bad indents but I am assuming that's pasting problem

ivory storm
ivory storm
#
import discord
from discord import app_commands
from discord.ext import commands
import json
import os

# Get configuration.json
with open("configuration.json", "r") as config: 
    data = json.load(config)
    token = data["token"]
    prefix = data["prefix"]
    owner_id = data["owner_id"]


class Greetings(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self._last_member = None

# The bot
intents = discord.Intents.default()
client = discord.Client(intents=intents)
tree = app_commands.CommandTree(client)
intents.message_content = True

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

# Load cogs
if __name__ == '__main__':
    for filename in os.listdir("Cogs"):
        if filename.endswith(".py"):
            bot.load_extension(f"Cogs.{filename[:-3]}")

@bot.event
async def on_ready():
    print(f"We have logged in as {bot.user}")
    print(discord.__version__)
    await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name =f"{bot.command_prefix}help"))

#@bot.command()
#async def hello(ctx):
#       await ctx.send("Hello, I'm a Discord bot!")

@bot.command()
async def embed(ctx):
    embed=discord.Embed(title="Sample Embed", url="https://realdrewdata.medium.com/", description="This is an embed that will show how to build an embed and the different components", color=0xFF5733)
    await ctx.send(embed=embed)

@tree.command(name = "test", description = "My first application Command", guild=discord.Object(id=1168187306822336533)) #Add the guild ids in which the slash command will appear. If it should be in all, remove the argument, but note that it will take some time (up to an hour) to register the command if it's for all guilds.
async def first_command(interaction):
    await interaction.response.send_message("Hello!")

bot.run(token)
vale wing
#

So we typically ask to learn more before blindly trying stuff

lofty pecan
#

Hey again, I've created a class for a dropdown menu as follow:

class OCModifier(discord.ui.View):
    def __init__(self, bot, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.bot = bot
        self.modified_field = ""
        self.colour = None

    @discord.ui.select(
        placeholder="Select a field to modify for your OC.",
        options=[
            discord.SelectOption(label="OC Name", value="oc_name"),
            discord.SelectOption(label="OC Age", value="oc_age"),
            discord.SelectOption(label="OC Nationality", value="oc_nationality"),
            discord.SelectOption(label="OC Gender", value="oc_gender"),
            discord.SelectOption(label="OC Sexuality", value="oc_sexuality"),
            discord.SelectOption(label="OC Universe", value="oc_universe"),
            discord.SelectOption(label="OC Story", value="oc_story"),
            discord.SelectOption(label="OC Picture", value="oc_picture"),
            discord.SelectOption(label="OC Colour", value="oc_colour")
        ]
    )
    async def select_field(self, interaction: discord.Interaction, select_item: discord.ui.Select):
        self.modified_field = select_item.values[0]
        self.children[0].disabled = True
        await interaction.message.edit(view=self)
        await interaction.response.defer()
        self.stop()```
#

But I realised it'd be more practical to have the options to depend on parameters given by the user to have a general class. So I tried doing the following:

class DropdownMenu(discord.ui.View):
    def __init__(self, bot, labels, values, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.bot = bot
        self.modified_field = ""
        self.colour = None
        self.labels = labels
        self.values = values

    @discord.ui.select(
        placeholder="Select the name of the OC you want to modify")
    async def select_field(self, interaction: discord.Interaction, select_item: discord.ui.Select):
        self.modified_field = select_item.values[0]
        self.children[0].disabled = True
        self.options = [discord.SelectOption(label=label, value=value) for label, value in zip(self.labels, self.values)]
        await interaction.message.edit(view=self)
        await interaction.response.defer()
        self.stop()```

But now it says `unresolved reference` in the decorator
#

Is there a way to do what I want ?

signal turret
#

oh hi

#

adad

  • gay
lofty pecan
faint rapids
#

I just installed discord-py-slash-command in Python 3.11, but I am still encountering the ModuleNotFoundError. How can I fix this issue?

Traceback (most recent call last):
  File "d:\.vscode\discord-bot\bot.py", line 3, in <module>
    from discord_slash import SlashCommand
ModuleNotFoundError: No module named 'discord_slash
slate swan
#

Why use a one or more years old outdated library

shrewd apex
slate swan
lofty pecan
slate swan
#

Does anyone know how to make a command on discord.py (no slash commands)

slate swan
#

@minor solstice I'm kinda of a beginner dev so what do I put here?

#

Can anyone help me?

hushed galleon
# lofty pecan Well that's the thing, I don't have one yet, I don't know what to choose, I don'...

personally i flashed Raspberry Pi OS 64-bit Lite onto mine which overall worked out pretty well, but that's cause i already knew how to remote SSH into it and do most of the setup from the command-line (the Lite edition doesn't provide a desktop)

regardless of the OS i would recommend using a 64-bit build, especially if you're installing compiled packages that don't have 32-bit ARM wheels (numpy, Pillow, etc. i think a lot of compiled packages don't have armv7l)

shrewd apex
#

++ pick the rpi oses unless u have bit of experience setting up headless pc's coz u would have to configure ssh and vnc clients manually raspian has those pre installed

#

there is a official image flasher as well rpi imager which helps you with the configuration

slate swan
#

Bro

#

Why isn't no one helping me...

shrewd apex
slate swan
#

@shrewd apex bro I meant no slash commands

shrewd apex
#

...

#

how did u figure out i sent slash command code?

slate swan
#

I told my friend and he said it was slash command

shrewd apex
#

damn well sorry to say but it isnt slash command code 🤡

#

it uses context

#

not interaction

slate swan
#

@shrewd apex bruh

#

I'm kinda new to coding so this is gonna be kinda hard

shrewd apex
#

show code

#

u forgot a "

#

to end the string

slate swan
#

Oh that's funny becuz I put a string at the end

#

Lemme check the problem

#

@shrewd apex 💀

shrewd apex
#

i think its probably for better that u learn python before attempting a discord bot also do use a pc for coding, programming in mobile is tedious to say the least

upbeat mason
#

i know you guys have some kind of custom one

#

nvm i found it

#

ping me if you respond

glad cradle
upbeat mason
#

oh damn ty

glad cradle
#

!d nextcord.slash_command

unkempt canyonBOT
#
class nextcord.slash_command(name=None, description=None, *, name_localizations=None, description_localizations=None, guild_ids=..., dm_permission=None, ...)```
Creates a Slash application command from the decorated function. Used inside [`ClientCog`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.ClientCog)’s or something that subclasses it.
upbeat mason
#

thanks

glad cradle
#

you're welcome

upbeat mason
slate swan
#

It's nextcord.slash_command, not nextcord.ext.commands.slash_command

upbeat mason
#

eh

#

i got it to work

#

thanks to you too

paper crescent
#

how can i create a thread in forum channel?

slate swan
unkempt canyonBOT
#
await create_thread(*, name, auto_archive_duration=..., slowmode_delay=None, content=None, tts=False, embed=..., embeds=..., file=..., files=..., stickers=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates a thread in this forum.

This thread is a public thread with the initial message given. Currently in order to start a thread in this forum, the user needs [`send_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.send_messages).

You must send at least one of `content`, `embed`, `embeds`, `file`, `files`, or `view` to create a thread in a forum, since forum channels must have a starter message.
slate swan
#

Simple as that

paper crescent
#

what can I do with this

#

@slate swan

final iron
paper crescent
#

just pasted that

upbeat mason
#

is it possible to bypass the 28 day timeout limit?

final iron
#

Copy and pasting it will not work

upbeat mason
#

okay ty

vapid parcel
#

goofy

upbeat mason
#

there's another way though

vapid parcel
#

thats discords API rules 😭

#

Yeah which I think breaks API rules :/

upbeat mason
#

No

vapid parcel
#

Dyno only goes up to 14 days..? So 28 isnt that bad lmao

#

So maybe ask DYNO to upgrade :)

upbeat mason
#

They probs have a reason

vapid parcel
#

I have a reason too tho 😭

#

what is bro on 😭

upbeat mason
#

you aren't thinking outside the box 🌠

#

wanna know how

vapid parcel
#

Nope

upbeat mason
#

ok

vapid parcel
#

28 days is good enough :/

upbeat mason
#

I'll just use Carl to mute people for 999 years

vapid parcel
#

okay 👍

south raven
#

Yo

upbeat mason
#
Ignoring exception in command <nextcord.application_command.SlashApplicationCommand object at 0x00000000049F1410>:
Traceback (most recent call last):
  File "C:\Users\phil\AppData\Local\Programs\Python\Python311\Lib\site-packages\nextcord\application_command.py", line 918, in invoke_callback_with_hooks
    await self(interaction, *args, **kwargs)
  File "c:\Users\phil\Desktop\projects\python\horizon_management\commands\giveaway.py", line 80, in giveaway
    self.bot.loop.create_task(self.update_giveaway(ctx, message.id, end_time_timestamp))
                                                        ^^^^^^^^^^
AttributeError: 'PartialInteractionMessage' object has no attribute 'id'

The above exception was the direct cause of the following exception:

nextcord.errors.ApplicationInvokeError: Command raised an exception: AttributeError: 'PartialInteractionMessage' object has no attribute 'id'

i hate python

fading pollen
clear lark
fading pollen
#

I did right?

#

Oh I'm sorry

fading pollen
clear lark
#

What errors are you getting?

fading pollen
clear lark
#

Go ask YT for that

fading pollen
clear lark
fading pollen
final iron
#

Why are you running it if you don't know what it does?

fading pollen
#

i just dont know how to run this specific one

final iron
#

Before running anything like this you should go over each piece of code to see what it does

fading pollen
clear lark
#

also, wherever you got the code, its mysql is just there in raw text

fading pollen
#

that the only part im confused

fading pollen
final iron
#

Okay. Did you go over each part of code?

fading pollen
#

i did

final iron
#

Okay, so we can figure out how it's running

#

At which line is the bot starting from?

fading pollen
#

2209

final iron
#

Okay, and when it's running the bot where is it referencing the token from?

fading pollen
#

Bot_Token = os.getenv('TOKEN')

final iron
#

Okay, and what does os.getenv() do?

fading pollen
final iron
#

So, if we look at the beginning of the code what else involves environment variables?

fading pollen
#

load_dotenv?

final iron
#

Great

#

So what does load_dotenv do?

fading pollen
#

loads .env files?

final iron
#

Correct

#

So, if we're loading a .env file and then getting an environment variable named TOKEN...

fading pollen
#

but technically couldnt i do Bot_Token = os.getenv('TOKEN') to bot_token = 'token' ?

final iron
#

If you wanted to