#discord-bots

1 messages · Page 967 of 1

unkempt canyonBOT
#
subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, capture_output=False, shell=False, cwd=None, timeout=None, check=False, encoding=None, errors=None, ...)```
Run the command described by *args*. Wait for command to complete, then return a [`CompletedProcess`](https://docs.python.org/3/library/subprocess.html#subprocess.CompletedProcess "subprocess.CompletedProcess") instance.

The arguments shown above are merely the most common ones, described below in [Frequently Used Arguments](https://docs.python.org/3/library/subprocess.html#frequently-used-arguments) (hence the use of keyword-only notation in the abbreviated signature). The full function signature is largely the same as that of the [`Popen`](https://docs.python.org/3/library/subprocess.html#subprocess.Popen "subprocess.Popen") constructor - most of the arguments to this function are passed through to that interface. (*timeout*, *input*, *check*, and *capture\_output* are not.)
pliant gulch
#

You'd make this run all of your files manually

echo wasp
pliant gulch
echo wasp
#

because i have never played with that before

#

do you happen to have an example

green bluff
#

yep

pliant gulch
green bluff
#

!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 floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

green bluff
echo wasp
green bluff
#

oh so could i do nick = str(member)

#

would that work

#

and then nick=nick

pliant gulch
echo wasp
unkempt canyonBOT
#
class subprocess.Popen(args, bufsize=- 1, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, ...)```
Execute a child program in a new process. On POSIX, the class uses [`os.execvpe()`](https://docs.python.org/3/library/os.html#os.execvpe "os.execvpe")-like behavior to execute the child program. On Windows, the class uses the Windows `CreateProcess()` function. The arguments to [`Popen`](https://docs.python.org/3/library/subprocess.html#subprocess.Popen "subprocess.Popen") are as follows.

*args* should be a sequence of program arguments or else a single string or [path-like object](https://docs.python.org/3/glossary.html#term-path-like-object). By default, the program to execute is the first item in *args* if *args* is a sequence. If *args* is a string, the interpretation is platform-dependent and described below. See the *shell* and *executable* arguments for additional differences from the default behavior. Unless otherwise stated, it is recommended to pass *args* as a sequence.
blissful sparrow
#

Can someone help me with my reload command cog thingy pls

pliant gulch
#

I barely use this library ¯_(ツ)_/¯

blissful sparrow
green bluff
#

only thing i hate about discord, you cant edit owner's nicks TY THO

blissful sparrow
blissful sparrow
#

so where exactly am I implementing it im confused?

supple thorn
#

We want your ping extension code

blissful sparrow
supple thorn
#

Why are you giving us the owner code

blissful sparrow
#

Wait what

#

I need help with reload

supple thorn
#

Yeah well he looks like he's not getting it from what you're saying

#

Better to ducking point out where and what to change in the code

#

That's what i learned mostly from people

echo wasp
#

have you used this before? the docs doesn't make much sense

supple thorn
#

Oh wait

#

He doesn't need help for the ping extension

#

Sadge i'm wrong

green bluff
#

ohp nvm i tried it on a friend it says this

#

is this because all ids match idk>

supple thorn
green bluff
#

o

blissful sparrow
#

Got it working thanks!

green bluff
#

i used fetch

#

instead of get

#

sure

pliant gulch
#

You should be passing the ID of the user, not the name + discrim

pliant gulch
#

The error seems to say you passed a string instead of an Int

echo wasp
#

do you know what a procfile is?

green bluff
#

NVM my command that inserts the id to the database used to be name i forgot to change it to ID

#

now it works

#

no errors

#

yes

#

oh any idea why is get faster?

hushed galleon
#

this is usually something you dont need to write since all guilds are cached when the guilds intent is enabled; afaik from 0_0's context they likely have it enabled but they're running their code in a task loop, so to handle uncached guilds you'd have a @before_loop to wait until the bot is ready

green bluff
#

so what would get return if it had failed

supple thorn
#

Replited?

echo wasp
#

Well it is what heroku uses for processes

supple thorn
#

I wasn't actually gonna say anything because i thought it was something about replit

#

But looked weird to me so

pliant gulch
#

Either way there is no harm done, it would only make an API call when not cached

green bluff
pliant gulch
#

This would just be an additional sanity check

hushed galleon
#

i would say to only write it when it is necessary, e.g. when you're sharding your bot and you have functionality that may require accessing guilds that are outside the shard making the request (note: i have not done sharding before so this is only theoretical, maybe im wrong)

blissful sparrow
#

So from my understanding icon_url=ctx.author.avatar_url puts the person who does the command's avatar in the footer however it says Member not defined when I try to execute this. Do I need to store the member's id and then call something to get their avatar?

#

Heres my code so far

 @commands.command()
    async def ping(self, ctx):
        before = time.monotonic()
        ping = (time.monotonic() - before) * 1000
        embed = discord.Embed(color=0xff0000)
        embed.add_field(name="Bot Latency" ,value=f"API latency: **{int(ping)}ms**", inline=False)
        embed.set_footer(text="Requested by: {}".format(ctx.author.display_name, icon_url=ctx.author.avatar_url))
        await ctx.send(embed=embed)
#

and it spits this error
AttributeError: 'Member' object has no attribute 'avatar_url'

hushed galleon
unkempt canyonBOT
#

property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.avatar "discord.User.avatar")
boreal ravine
#

it got changed in 2.0

blissful sparrow
#

No wonder its been doing my head in this entire time

#

thanks

#

so would it be icon_url=ctx.author.avatar?

boreal ravine
#

avatar.url yea

pliant gulch
blissful sparrow
#

Ah thanks

pliant gulch
#

And if they have access to the guild anyways, I'm gonna assume logically it's already cached internally

#

Since when your bot connects to the gateway you receive X GUILD_CREATE messages which have the channel data

#

And with the way discord.py handles it, you won't receive on_ready until all Futures have finished, and the futures would be corresponding to the guild for caching

hushed galleon
#

yeah those are true by themselves, but im just talking about fetch_guild

blissful sparrow
pliant gulch
#

Meaning fetching it would kind of be not required

#

If that doesn't work out, which I highly doubt; this endpoint exists GET /guilds/{guild.id}/channels

#

Meaning, if you only fetch the guild for channels, that would be useless, instead use the above ^

#

Getting rid of the whole case where channels would somehow be omitted

hushed galleon
pliant gulch
#

Not 100% but you'd have a race condition

#

It wouldn't make sense not to wait until it's ready anyways

hushed galleon
#

yeah, but i replied to your earlier comment mentioning that it would be no harm done making an API call when not cached, so i assumed you meant the case where they didnt wait until ready

hoary cargo
pliant gulch
#

As they documented on the offical docs, it can be None

#

I cannot, un-suprisingly, read the source code of the API

#

So I can't say 100% sure what cases where channels is None

#

It's better to have a second call to fallback on that does no harm in this case

#

It's not costing you anything either way, and the ratelimits aren't that small

hushed galleon
#

wait what can be none

pliant gulch
#

channels

hushed galleon
#

for the fetch_guild endpoint?

pliant gulch
#

Fetching the guild from the REST Api returns a Guild object, the documentation for the Guild object shows channels?

#

Meaning channels can be omitted in cases

echo wasp
blissful sparrow
#

avatar.url leaves no errors but it doesnt work also

pliant gulch
#

The only thing that would be "negative" is the bandwith usage

#

Even then it's neglible as this is your fallback

devout iris
#

How can i add cooldown?

hushed galleon
pliant gulch
#

If that ever happens you can just use GET /guilds/{guild.id}/channels

hushed galleon
#

i still think the cost is code readability/redundancy, cause getching the guild would imply the case where you only have partial data

pliant gulch
#

It would be redudant if we knew in what cases channels would be empty, or None. But we dont' so this is just a fallback call in case it DOES happen. And it doesn't affect too much on the readability part either? Not to me at least; hell if want to make it even more readable just make it in a ternary condition

devout iris
#

How can i show cooldown to user? As How much time left.

hushed galleon
devout iris
#

In {}

hushed galleon
#

is this for handling a CommandOnCooldown exception?

devout iris
#

Yes

hushed galleon
#

!d discord.ext.commands.CommandOnCooldown.retry_after

unkempt canyonBOT
devout iris
#

Ty

hushed galleon
#

note that the other attribute .type is specific to dpy 2.0, in dpy 1.7 its stored within the .cooldown attribute

#

in case you were planning to use that too

echo wasp
hoary cargo
hushed galleon
blissful sparrow
#

even then it throws it

sterile imp
#
@client.command()
async def say(ctx, *, text):
    if ctx.author.id not in [123, 456, 789]:
      return
    message = ctx.message
    await message.delete()
    await ctx.send(f"{text}")```

how do u make it so u specify a channel, like -say [#discord-bots](/guild/267624335836053506/channel/343944376055103488/) hi
pliant gulch
sterile imp
#

i need help

slate swan
#

@blissful sparrow what error

blissful sparrow
#

No error

#

just doesnt show up

slate swan
#

are you on vsc again

hushed galleon
blissful sparrow
slate swan
hushed galleon
echo wasp
hushed galleon
echo wasp
#

main beta_bot and bot

hushed galleon
#

as in you also have a third bot coded in the main file?

sullen pewter
#

How to work with DB Browser for SQLite3?

#

Are there tutorials?

slate swan
#

how does that have to do with discord bots?

sullen pewter
pliant gulch
sullen pewter
echo wasp
hushed galleon
pliant gulch
#

Well it kind of does

#

The thing is though, your awaiting it

#

As I mentioned in my message

boreal ravine
sullen pewter
boreal ravine
boreal ravine
slate swan
#

its useful but not needed

hushed galleon
pliant gulch
#

All of them

hushed galleon
#

ah oops i used a blocking while true in my testing

sullen pewter
#

And everything will work?

boreal ravine
#

yes

pliant gulch
slate swan
#

ticket bot has nothing really to do with a database, and even if you use one
you dont really need a database browser

boreal ravine
#

exactly

sullen pewter
#

Ic

slate swan
#

especially in the case of sqlite3

sullen pewter
#

Thanks

devout iris
#

in message purge error

hushed galleon
# pliant gulch Internally start has a few while Trues as well

hm, i tested both gather and create_task and the two bots still connected serially, although maybe this is just cause i tested with a single token instead of two py async with bot_1, bot_2: await asyncio.gather(bot_1.start(token), bot_2.start(token)) # vs. asyncio.create_task(bot_1.start(token)) await bot_2.start(token) INFO in discord.gateway: Shard ID None has connected to Gateway: ... connected ready INFO in discord.gateway: Shard ID None session has been invalidated. INFO in discord.client: Got a request to IDENTIFY the websocket. disconnected ... INFO in discord.gateway: Shard ID None has connected to Gateway: ... connected ready

heavy folio
hushed galleon
# devout iris in message purge error

in that middle part of the error it shows you tried to format the description using {ctx.author.mention} which wasn't provided by your format() call

pliant gulch
hushed galleon
#

i uh, cheaped out by using the same function for both bots

pliant gulch
#

Cause this has me really thinking

hushed galleon
hushed galleon
devout iris
#
@sil.error
async def sil_error(ctx, error):
    if isinstance(error, commands.CommandOnCooldown):
        embed = discord.Embed(
            title=":clock1: Sakinleş",
            description = "{ctx.author.mention}, bu komutu **{zmn}** saniye sonra tekrar kullanabilirsin".format(error.retry_after)
    )
        await ctx.send(embed=embed, delete_after = error.retry_after)
pliant gulch
# hushed galleon wtf ``` 1 connected 1 ready 2 disconnected 2 connected 2 ready```
from __future__ import annotations

import asyncio
import os

import discord


class First(discord.Client):

    async def on_connect(self) -> None:
        print(f"{self!r}")


class Second(discord.Client):

    async def on_connect(self) -> None:
        print(f"{self!r}")


async def main() -> None:
    TOKEN = os.environ["DISCORD_TOKEN"]

    first, second = First(), Second()
    await asyncio.gather(first.start(TOKEN), second.start(TOKEN))


asyncio.run(main())
╭─ andy@arch  ~/Development/test  
╰─$  poetry run python test.py
<__main__.Second object at 0x7fd7b0bbb3d0>
<__main__.First object at 0x7fd7af6f8940>
```It doesn't block
#

This is really confusing me, shouldn't it be blocking the second call? It's being await'd

pliant gulch
# pliant gulch This is really confusing me, shouldn't it be blocking the second call? It's bein...
from __future__ import annotations

import asyncio
import os

import discord


class First(discord.Client):

    async def on_connect(self) -> None:
        print(f"{self!r}")


class Second(discord.Client):

    async def on_connect(self) -> None:
        print(f"{self!r}")


async def main() -> None:
    TOKEN = os.environ["DISCORD_TOKEN"]

    first, second = First(), Second()
    await first.start(TOKEN)
    await second.start(TOKEN)


asyncio.run(main())
``` this blocks the second call from ever happening
hushed galleon
devout iris
pliant gulch
hushed galleon
#

gather schedules all coros as tasks before awaiting right, and .start() definitely cant block the event loop, otherwise it wouldnt be running, so the two starts are able to share the event loop

#

while in the latter example the second start is held up by the first start being awaited

pliant gulch
hushed galleon
#

well there's three different tasks running with gather right

#

two tasks are handling their bots while the main task is just awaiting on those two tasks, so main has no effect on them

hushed galleon
slate swan
boreal ravine
#

why the hell would you want that

orchid fossil
#

for what reason

#

is that useful

pliant gulch
#

Backwards compatability

slate swan
#

i.e usage of pipes

pliant gulch
#

I want to typehint with stuff from 3.10+ without making people using 3.10> to suffer

boreal ravine
#

pipes?

slate swan
#

is called a pipe

boreal ravine
#

doesn't look like one

pliant gulch
#

!e ```py
from future import annotations
import inspect

def foo(bar: str) -> None: ...

print(type(inspect.signature(foo).parameters.get("bar").annotation))

unkempt canyonBOT
#

@pliant gulch :white_check_mark: Your eval job has completed with return code 0.

<class 'str'>
pliant gulch
#

!e ```py
import inspect

def foo(bar: str) -> None: ...

print(type(inspect.signature(foo).parameters.get("bar").annotation))

unkempt canyonBOT
#

@pliant gulch :white_check_mark: Your eval job has completed with return code 0.

<class 'type'>
slate swan
boreal ravine
#

no

#

a bracket with no legs

slate swan
#

bro

pliant gulch
sullen pewter
#

How to fix this error I cant use command !sync

slate swan
#

your bot was not invited with application commands scope in that server

sullen pewter
#

Oh ty

#

Um what

pliant gulch
#

application.commands is a scope

#

Your looking at permissions right now

sullen pewter
#

Ik I alr did it

#

But I can't invite my bot for some reason

pliant gulch
#

https://discord.com/api/oauth2/authorize?client_id={YOUR_ID}&scope=applications.commands

boreal ravine
#

your bot's ID

sullen pewter
#

Ok

sullen pewter
#

Snowflake?

#

Fixed

slate swan
#

snowflake basically means ids

sullen pewter
#
@app_commands.guilds(957886366589542450)
async def my_embed(ctx):
    embed = discord.Embed(title="Quote 3: ", description=f"An experimental discord.py file that you can use to improve on your coding knowledge, Ill try my best to give you what you are asking for. (`Create a ticket for more info on this quote`)", colour = discord.Colour.blue())
    button = Button(label="Click to create a ticket!", style=discord.ButtonStyle.secondary)
    async def button_callback(interaction):
        conn = db.connect("dpyhelp.db")
        cur = conn.cursor()
        cur.execute(f"SELECT Open FROM Ticket WHERE User_ID = {interaction.user.id}")
        req = cur.fetchone()
        if req == None:
            guild = ctx.guild
            category = discord.utils.get(ctx.guild.categories, name="Tickets")
            channel = await guild.create_text_channel(f"Ticket-{interaction.user}", category=category)
            await channel.set_permissions(interaction.user, read_messages=True, send_messages=True, read_message_history=True)
            await channel.edit(permissions_synced=True)
            sqlite = (f"INSERT INTO Ticket(Open, User_ID, Channel_ID) VALUES(?,?,?)")
            vals = ("Y", interaction.user.id, channel.id)
            cur.execute(sqlite, vals)
            conn.commit()
            
            await interaction.response.send_message("Ticket created! Look at the ticket category to check for your ticket.", ephemeral=True)
            embed = discord.Embed(title=f"Press the close button to close this ticket!", colour = discord.Colour.blue())
            button2 = Button(label="Close the ticket!", style=discord.ButtonStyle.secondary)
            
            async def button2_callback(interaction):
                await interaction.channel.delete()
                cur.execute(f"DELETE FROM Ticket WHERE Channel_ID = {channel.id}")
                conn.commit()
                conn.close()
#
    await ctx.message.delete()
    view = View()
    view.add_item(button)
    await ctx.send(embed=embed, view = view)```
How can I add slash commands?
#

I tried but didn't work

sullen pewter
#

Yes

#

I think its because of the database

slate swan
#

may i know what does not work?

#

like does the slash command not get created? or you get some errors

#

another sidenote, use async bridge for sqlite

#

!pip aiosqlite

unkempt canyonBOT
blissful sparrow
#

anyone got an snippet of a command to change the status of the bot?

slate swan
#

!d discord.Client.change_presence

unkempt canyonBOT
#

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

Changes the client’s presence.

Example

```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
```   Changed in version 2.0: Removed the `afk` keyword-only parameter...
slate swan
#

the Example below

#

if you want a permanent presence, best way to do it is inside the Bot/Client class itself

#
bot = commands.Bot(..., status=discord.Status.idle, activity = discord.Game("..."))```
frozen patio
#

d!discord.Client process_commands

#

Hmm

slate swan
#

client does not have a process_commands , its a method of Bot

#

!d discord.ext.commands.Bot.process_commands

unkempt canyonBOT
#

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

This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.

By default, this coroutine is called inside the [`on_message()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message "discord.on_message") event. If you choose to override the [`on_message()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message "discord.on_message") event, then you should invoke this coroutine as well.

This is built using other low level tools, and is equivalent to a call to [`get_context()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") followed by a call to [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").

This also checks if the message’s author is a bot and doesn’t call [`get_context()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") or [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke") if so.

Changed in version 2.0: `message` parameter is now positional-only.
frozen patio
#

@slate swan this is the line I have, and it is breaking my code:

await client.process_commands(message)

#

I am trying to fix it

slate swan
#

may i see your client variable defination

#

.

frozen patio
slate swan
#

Why not use bot as var?

frozen patio
#

It's a matter of preference at that point

#

No

#

I come because I have an error that has never popped up for me until today

slate swan
#

Whats the error?

frozen patio
# slate swan Whats the error?
Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\Student\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 415, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\Student\Desktop\Lofi-Chill Rewrite\main.py", line 153, in on_message
    await client.process_commands(message)
  File "C:\Users\Student\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\bot.py", line 1091, in process_commands
#
ctx = await self.get_context(message)
  File "C:\Users\Student\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\bot.py", line 1001, in get_context
    prefix = await self.get_prefix(message)
  File "C:\Users\Student\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\bot.py", line 946, in get_prefix
    ret = await nextcord.utils.maybe_coroutine(prefix, self, message)
  File "C:\Users\Student\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\utils.py", line 512, in maybe_coroutine
    value = f(*args, **kwargs)
  File "c:\Users\Student\Desktop\Lofi-Chill Rewrite\main.py", line 26, in get_prefix
    prefixes = json.load(f)
  File "C:\Users\Student\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 293, in load
    return loads(fp.read(),
  File "C:\Users\Student\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "C:\Users\Student\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\Student\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
blissful sparrow
#

how do I make arguments optional?

spring flax
unkempt canyonBOT
#

typing.Optional```
Optional type.

`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...
torn sail
#

Or default value

spring flax
#

Either this or async def foo(ctx, member = None)

torn sail
#

nember lol

spring flax
#

!json

unkempt canyonBOT
#

When using JSON, you might run into the following error:

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

This error could have appeared because you just created the JSON file and there is nothing in it at the moment.

Whilst having empty data is no problem, the file itself may never be completely empty.

You most likely wanted to structure your JSON as a dictionary. To do this, edit your empty JSON file so that it instead contains {}.

Different data types are also supported. If you wish to read more on these, please refer to this article.

orchid fossil
#

!json

unkempt canyonBOT
#

When using JSON, you might run into the following error:

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

This error could have appeared because you just created the JSON file and there is nothing in it at the moment.

Whilst having empty data is no problem, the file itself may never be completely empty.

You most likely wanted to structure your JSON as a dictionary. To do this, edit your empty JSON file so that it instead contains {}.

Different data types are also supported. If you wish to read more on these, please refer to this article.

orchid fossil
#

!json class{

frozen patio
slate swan
#

just change .event to .listen()

frozen patio
#

But

slate swan
#

ah alright

frozen patio
#

I have a new error

#
Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\Student\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 415, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\Student\Desktop\Lofi-Chill Rewrite\main.py", line 153, in on_message
    await client.process_commands(message)
  File "C:\Users\Student\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\bot.py", line 1091, in process_commands
    ctx = await self.get_context(message)
  File "C:\Users\Student\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\bot.py", line 1001, in get_context
    prefix = await self.get_prefix(message)
  File "C:\Users\Student\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\bot.py", line 946, in get_prefix
    ret = await nextcord.utils.maybe_coroutine(prefix, self, message)
  File "C:\Users\Student\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\utils.py", line 512, in maybe_coroutine
    value = f(*args, **kwargs)
  File "c:\Users\Student\Desktop\Lofi-Chill Rewrite\main.py", line 28, in get_prefix
    return prefixes[str(message.guild.id)]
KeyError: '962476725839745045'
#

🤔

#

@slate swan

#

This is the error

#

But idk what it means ig the line works without it

#

What I meant was the line usually works

slate swan
#

the server is not in the json

#

are you using on_guild_join to add the servers to json?

frozen patio
#

I need to reinvite it

#

Oh Ok

sullen pewter
#

await guild.create_text_channel()

#

Is this how to create a channel?

#

I want to make a ticket bot and I want tickets to be with numbers

#

For instance: ticket - 1 or ticket - 991

severe rampart
#

can you define more behavior around that?

sullen pewter
#

Do I need database for that

severe rampart
sullen pewter
#

I want to create without database

#

Ok

slate swan
#

discord.ext.commands.errors.MemberNotFound: Member
keep getting this error even i am passing right argument

slate swan
# spring flax Show code
async def check(ctx, member : discord.Member):
    if member.id == 945984774760194149:
        await ctx.send(member.name)
    else:
        await ctx.send("false")```
spring flax
slate swan
spring flax
#

Give the full error traceback

slate swan
# spring flax Give the full error traceback
Traceback (most recent call last):
  File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
    await self.prepare(ctx)
  File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 789, in prepare
    await self._parse_arguments(ctx)
  File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 697, in _parse_arguments   
    transformed = await self.transform(ctx, param)
  File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 552, in transform
    return await self.do_conversion(ctx, converter, argument, param)
  File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 505, in do_conversion      
    return await self._actual_conversion(ctx, converter, argument, param)
  File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 451, in _actual_conversion 
    ret = await instance.convert(ctx, argument)
  File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\converter.py", line 187, in convert
    raise MemberNotFound(argument)
discord.ext.commands.errors.MemberNotFound: Member "945984774760194149" not found.```
slate swan
slate swan
spring flax
#

Is that your id? @slate swan

slate swan
#

nope

fading harness
#

if you are not sure print discord.__version__

slate swan
fading harness
fading harness
#

double check to see if the id actually exist

#

and is a guild member of the guild where you invoked the command

#

maybe you also need the member intent

slate swan
#

nah

#

it can be a id

#

bad

#

it wouldnt really matter as dpy parses the mention

slate swan
fading harness
spring flax
#

It depends on the command purpose

slate swan
#

the problem?

fading harness
#

and that member is in the guild you invoked the command

slate swan
fading harness
#

note: you also need to enable the intent in both the dev portal and code

slate swan
#

its not a valid id

nimble plume
nimble plume
#

!check @nimble plume

slate swan
fading harness
slate swan
#

he said its himself

slate swan
fading harness
#

have you enabled the guild member intent? is hat member in the guild you invoked the command? you need to enable the intent in both the dev portal and code.

fading harness
slate swan
#

!intents

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

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

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

For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.

spring flax
#

it has to be done in code too

slate swan
slate swan
#

and are you invoking the command in a dm or a guild?

spring flax
#

surely it can't be...

slate swan
#

is it something with guilds intent or is it just me

slate swan
slate swan
slate swan
#

something is off for sure

#

how are you invoking the command?

#

!check 944853480584146944

#

have you tried mentioning yourself?

slate swan
nimble plume
#

Listen

slate swan
#

ok?

slate swan
nimble plume
#

Firstly

slate swan
nimble plume
#
@client.command()
async def check(ctx, *, member : discord.Member):
    if member.id == 945984774760194149:
        await ctx.send(member.name)
    else:
        await ctx.send("false")
unkempt canyonBOT
#

discord.on_guild_join(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild") is either created by the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") or when the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") joins a guild.

This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
slate swan
#

ye

spring flax
#

how did it become a kwarg?

nimble plume
#

He just did !check @nimble plume in his server

spring flax
slate swan
slate swan
spring flax
#

you're not the only one with the first name Dyno

slate swan
#

this screams bad invocation

spring flax
nimble plume
#

Bruhhh

spring flax
#

!check 884024529914069003
@slate swan

slate swan
#

!check 944853480584146944
this is bot id and currently in my guild

spring flax
#

check it and see

slate swan
nimble plume
#

Show

slate swan
#

discord.ext.commands.errors.MemberNotFound: Member "884024529914069003" not found.

nimble plume
#

Listen

#

Id is not a member

spring flax
slate swan
#

this whole convo is making me laughpithink

nimble plume
#

Bro

spring flax
#

it's a correct ID, it's returning None from the converter

slate swan
slate swan
boreal ravine
nimble plume
#

Intents!!

spring flax
#

he said he did that already

nimble plume
#

Impossible

slate swan
spring flax
#

!psate can you send your full code? @slate swan

#

!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 floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

slate swan
#

full code

from discord.ext import commands


intents = discord.Intents()

intents.members = True
intents.presences = True
intents.messages = True


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

@client.event
async def on_ready():
    print("bot is running!")

    
@client.command()
async def check(ctx, member : discord.Member):
    if member == 884024529914069003:
        await ctx.send(member.name)
    else:
        await ctx.send("false")```
fading harness
slate swan
#

you're comparing an object to an int

spring flax
#

if member.id ==

fading harness
spring flax
#

also do this

slate swan
#

useless else btw

fading harness
#

wdym

boreal ravine
slate swan
unkempt canyonBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

nimble plume
fading harness
slate swan
#

😳

spring flax
#

import sys
import traceback
@client.command()
async def check(ctx, member : discord.Member):
    if member.id == 884024529914069003:
        await ctx.send(member.name)
    else:
        await ctx.send("false")
@check.error
async def check_error(ctx, error):
  if isinstance(error, commands.MemberNotFound):
    await ctx.send("member not found")
  else:
    print('Ignoring exception in command {}:'.format(ctx.command), file=sys.stderr)
    traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr)

@slate swan can you do this and send a screenshot of when you invoke the command and what the bot does?

slate swan
#

why????

slate swan
#

in the error it already raised a member not found???

#

and its member not memer😭

slate swan
#

cant find the meme

fading harness
#

are people here too interested in memes or something

slate swan
#

😳

boreal ravine
slate swan
#

ok

#

@spring flax
code

async def check(ctx, member : discord.Member):
    if member.id == 884024529914069003:
        await ctx.send(member.name)
    else:
        await ctx.send("false")
@check.error
async def check_error(ctx, error):
  if isinstance(error, commands.MemberNotFound):
    await ctx.send("member not found")
  else:
    print('Ignoring exception in command {}:'.format(ctx.command), file=sys.stderr)
    traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr)

error - member not found

#

useless attempt

#

jam_cavedude yea

#

what are you even trying to do 🏃‍♂️

#

hes just catching an error and print the simplified version of it😭

#

just print the error instead of raising it

#

nah, just pass it

#

just dont handle it at all

#

just let it be raised lol

#
@bot.listen()
async def on_command_error(context, exception_):
   ...   ``` :chad:
#

let the users assume what went wrong themself

#

very pog

maiden fable
slate swan
#

when is it not

maiden fable
#

Koala, try except doesn't work in on_command_error

nimble plume
slate swan
#

he means in a command which is very inefficient

maiden fable
#

Yup

slate swan
#

never seen someone change their identity so fast

#

funny

paper sluice
nimble plume
#

Hi im new

slate swan
#

the heck

#

My windows fcked up
same code is running on linux without errors

#

this guy has like 3 identities

slate swan
#

hi

nimble plume
#

Hi bro

slate swan
#

..

#

tf is happening here

tacit storm
#

not related for this channel

anyone who is having actual off topic conversations not related to this channel or it's purpose, go to one of the off topic channels to not well, clutter up this channel far more than it already has been.

slate swan
#

@slate swan@slate swan@spring flaxthank you guys my error is solved
just by including intents.guilds = True

#

<@&831776746206265384> help?

true wharf
#

ok,sorry

slate swan
blissful lagoon
#

@true wharf dont spam gifs, and keep things appropriate

daring olive
#

hello

slate swan
slate swan
slate swan
slate swan
#

afaik

#

let me check dev portal

slate swan
#

which he didnt

#
intents = discord.Intents()

intents.members = True
intents.presences = True
intents.messages = True```
#

definately did

#

yeah i did

#

intents.members = True
intents.presences = True
intents.messages = True
intents.guilds = True```
slate swan
#

discord.Intents.default()

#

@slate swan And its recommended to switch to dpy 2 already

slate swan
#

cause there still are many intents you miss

#

why not just use all()?

#

^^

#

cause message_content is an intent too

#

messages?

#

and its different from Intent.messages

#

huh

#

elaborate?

#

!d discord.Intents.messages

unkempt canyonBOT
slate swan
#

!d discord.Intents.message_content

unkempt canyonBOT
#

Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:

• The message was sent by the client

• The message was sent in direct messages

• The message mentions the client

This applies to the following events...

slate swan
#

oh its just an intent of the wrapper and not the gateway

#

yes sir

#

good to know

slate swan
#

but im confused on why it would use the guild intent

slate swan
#

and it doesnt hurt to have them since they dont need to any verification

slate swan
#

im still confused on how this error was raised maybe an invocation error?

#

they have a member argument, and the bot was unable to get/fetch that member ez

#
@client.command()
async def check(ctx, member : discord.Member)```
slate swan
unkempt canyonBOT
#

discord/ext/commands/converter.py lines 192 to 194

.. versionchanged:: 1.5.1
    This converter now lazily fetches members from the gateway and HTTP APIs,
    optionally caching the result if :attr:`​.MemberCacheFlags.joined`​ is enabled.```
slate swan
#

you could say that

granite parcel
#
@bot.event
async def on_voice_state_update(member, before, after):
    if before.channel is None and after.channel is not None: 
        print("difference")```
#

this event is working for all guild the bot is in how it will be set for different guilds

slate swan
granite parcel
#

anyone know?

spring flax
#

!d discord.Member.guild

unkempt canyonBOT
slate swan
#

because if you dont change it, its discord.Intents.default()

#

i dont have that either

serene lynx
#

how to use typing union on slash command nextcord?

formal basin
#

How can I store more than 1 thing in a json file. e.g channel_id: id, id

vale wing
#

With arrays

#
{
    "channel_ids": [123, 456]
}```
spring flax
#

for subclassing bot, to make a custom function is @property better or making a function?

slate swan
#

Indentation

#

Ofc it will work it’s just indentation is most likely bad

spring flax
#

what's wrong? ```py
def init(self, **kwargs):
super().init(**kwargs)
self.start_time = datetime.datetime.utcnow()

def bot_uptime(self):
    #return datetime.datetime.utcnow() - self.start_time
    delta_uptime = datetime.utcnow() - bot.launch_time
    hours, remainder = divmod(int(delta_uptime.total_seconds()), 3600)
    minutes, seconds = divmod(remainder, 60)
    days, hours = divmod(hours, 24)
    #return days, hours, minutes, seconds
    return (f"{days}d, {hours}h, {minutes}m, {seconds}s")

@bot.command()
async def uptime(ctx):
await ctx.send(bot.bot_uptime)

The command output is  `<bound method Bot.bot_uptime of <main.Bot object at 0x00000266AA445D50>>`
supple thorn
slate swan
supple thorn
#

So wouldn't it be bot.bot_uptime()

#

I could be wrong

#

Most likely

slate swan
spring flax
supple thorn
#

Oh i was right

#

Neat

slate swan
#

user_id = interaction.author.id

spring flax
#

Ah

slate swan
#

interaction.user

#

Normally I used ctx but I switched to slash commands

#

!d discord.Interaction.user

unkempt canyonBOT
slate swan
#

Ty

formal basin
#

What does this mean

midnight gorge
#

why does this happen in replit when installing a module in the packages

slate swan
#

That doesn't even show the full error...

oblique adder
#

Can I press button and get the selected drop down value? How

formal basin
#

What does this error mean

quick gust
#

we cant even see the full error bruh

formal basin
lofty pecan
#

Howdy, after creating my bot I decided to use Cogs to make it cleaner and easier to read. Now, I have a command that only certain role can use, but I don't really know how to make it. I have a json file containing the roles id allowed to use that command, but I don't know to implement it. I know there is @commands.has_permissions(administrator=True) but how can I do the same for the roles id in that file?

midnight gorge
quick gust
#

.. u realise u couldve expanded the error tab or copy pasted the error

quick gust
#

anyways, res has no items

formal basin
lofty pecan
#

I've tried this

slate swan
unkempt canyonBOT
#

@discord.ext.commands.has_any_role(*items)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has **any** of the roles specified. This means that if they have one out of the three roles specified, then this check will return True.

Similar to [`has_role()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.has_role "discord.ext.commands.has_role"), the names or IDs passed in must be exact.

This check raises one of two special exceptions, [`MissingAnyRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") if the user is missing all roles, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").

Changed in version 1.1: Raise [`MissingAnyRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
lofty pecan
#
 if id_user in dic.keys() or ctx.message.author.server_permissions.administrator:```
 but I have this error `Command raised an exception: AttributeError: 'Member' object has no attribute 'server_permissions'`
quick gust
#

its probably guild_permissions

slate swan
#
@commands.has_any_role(role_id1, role_id2, ...)```
quick gust
#

server is generally not used, its guild

slate swan
# midnight gorge ?

That's not the full error, it literally explains nothing.
The screenshot is hiding half part of the error

lofty pecan
#

and I can make a self.id = load(open(rolesid), 'r')!

slate swan
#

..

lofty pecan
#

omg !

#

lets go

lofty pecan
lofty pecan
slate swan
slate swan
lofty pecan
# slate swan yeah?

Yeah because i'm using classes, so a self.idroles seems to be a great option to use the command you suggested

#

thansk ashley !

formal basin
maiden fable
lofty pecan
maiden fable
#

Decorator

#

@commands.has...

lofty pecan
#

ho really ?

#

well then I'll just access it inside the function

slate swan
#

🐢 why do you want it to be a class variable and not a normal global one

slate swan
# slate swan ..
@bot.command()
async def test(ctx: commands.Context):
      roles = [role.id for id in ctx.author.roles]
      if 12245594949 not in roles: return
@bot.command()
@commands.has_any_role()
async def test(ctx: commands.Context): ...```
now tell me which one seems better huh?
slate swan
#

idk what were he doing i just saw that he is using ctx.message.author so i say to use ctx.author

#

ctx.author is just a shortcut for ctx.message.author

slate swan
#

an uwu class

#

aw

#

with an uwu attribute

#

uwu.uwu moment

#

lmao

boreal ravine
#

it had attributes 🥴

slate swan
#

i have a uwu wave

slate swan
lofty pecan
slate swan
#

uwu will take over "test"

boreal ravine
slate swan
slate swan
slate swan
maiden fable
#

!ot thanks (:

unkempt canyonBOT
slate swan
#

🏃

#

xD yeah

#

I switched from discord.ext to slash commands and before I use to use ctx.author.id

#

But there’s none for interaction

#

discord

slate swan
slate swan
slate swan
#

lmao

slate swan
slate swan
slate swan
#

First of all, what library are you using?

boreal ravine
slate swan
slate swan
#

!d discord.Interaction.user

unkempt canyonBOT
slate swan
#

You can access the id from this

oblique adder
#

Nextcord “”

I want to make a confirm button for a selection menu how do I get he selected value from the selection menu by clicking on the button ?

paper sluice
#

select.values[0]

oblique adder
paper sluice
paper sluice
#

so what value are you trying to get?

oblique adder
#

The value from the dropdown

paper sluice
#

thats the select menu

oblique adder
#

Yes

paper sluice
#

select.values gives u a list of all the opitons selected

#

[0] will give u the first one

#

which i assume is what you want

lofty pecan
#

Good noon, I'm currently using cogs for my bot. I have one with admin command, such as changeprefix. Therefore I have a file called prefixes.json to store the prefix data for each server the bot is on. But how can I then grab this value to use it as the bot command without changing the config.json file?

oblique adder
#

Ik that but I want to make a confirm button therefore I need to get the value from the dropdown from clicking on that button

paper sluice
oblique adder
#

So that is the only way to do it ? Thank you

lofty pecan
slate swan
#
@bot.slash_command(description="Top")
async def hvtrend(ctx):
    await ctx.defer()
    page = requests.get('')
    tree = html.fromstring(page.content)
    user = ctx.user
    for i in range(1, 5):
        link = f'' + tree.xpath(f"/html/body/div/div/div/div/main/div/div/div/div[3]/div/div[{i}]/a/@href")[0]
        await user.send('\n'+link)

i am trying to take top 5 links from a website, the links are coming in 1 by 1 and i want them to come in 1 message like
link1
link2

lofty pecan
#

why don't you put ctx.send inside the loop?

#

wait you did

#

ho sorry I missunderstood your question

#

you could str format with list

slate swan
#

!d intents

unkempt canyonBOT
#
slate swan
#

link1

#

link2

lofty pecan
#

basically f'first link {0} \n second link {1}'.format(list)

#

something like that

slate swan
#

!d discordpy.intents

unkempt canyonBOT
lofty pecan
#

so you append the link to a list and then use that formating inside the ctx.send()

slate swan
lofty pecan
#

I'm currently using cogs for my bot. I have one with admin command, such as changeprefix. Therefore I have a file called prefixes.json to store the prefix data for each server the bot is on. But how can I then grab this value to use it as the bot command without changing the config.json file?

config = fetch('config')

print("Logging in!")

bot = commands.Bot(command_prefix=config["prefix"])


for file in os.listdir("./cogs"):
    if file.endswith(".py"):
        name = file[:-3]
        bot.load_extension(f"cogs.{name}")

try:
    bot.run(config["token"])
except Exception as e:
    print(f'Process canceled: {e}')```
That's the main file that launches everything
formal basin
#

What does this error mean

placid skiff
#

The error is speaking

lament mesa
formal basin
#

No

placid skiff
#

Then replit made some shit as it normally does

lofty pecan
formal basin
lofty pecan
#

I'm writing a method to add prefixes to the bot, but despite correctly adding the prefix it doesn't recognize it when I do the command

async def get_prefix(bot, message):
    default_prefix = config["prefix"]
    custom_prefix = prefixes[f"{(message.guild.id)}"]
    return default_prefix + custom_prefix

bot = commands.Bot(command_prefix=get_prefix)``` well I made this and whats following is the prefix adding method 
```python
@commands.command()
    @commands.has_permissions(administrator=True)
    async def addprefix(self, ctx, prefix):
        """ Change bot's prefix """
        prefixes = fetch('prefixes')
        (prefixes[str(ctx.guild.id)]).append(prefix)

        with open('prefixes.json', 'w') as f: #writes the new prefix into the .json
            json.dump(prefixes, f, indent=4)

        await ctx.send(f'Prefix added: {prefix}') #confirms the prefix it's been changed to
lofty pecan
#

just send the codes where the error is

#

it should tell you the line where the error occurs

formal basin
#

There

lofty pecan
# formal basin

you're making a function, a function and then use that function inside that function and apply random.choice

#

how is that supposed to work

formal basin
#

Yes

lofty pecan
#

!d random.choice

unkempt canyonBOT
#

random.choice(seq)```
Return a random element from the non-empty sequence *seq*. If *seq* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError "IndexError").
lofty pecan
#

it returns a random element from a list

#

therefore it gets the len of that said list

#

your function is a command and you're applying a list operator on it

lofty pecan
#

so yes

lofty pecan
sullen pewter
#

How can I make a close button in the ticket channel?

junior verge
#

What's your indentation

lofty pecan
#

that's a lot of async def

sullen pewter
sullen pewter
sullen pewter
junior verge
unkempt canyonBOT
#

Leading whitespace (spaces and tabs) at the beginning of a logical line is used to compute the indentation level of the line, which in turn is used to determine the grouping of statements.

Tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to and including the replacement is a multiple of eight (this is intended to be the same rule as used by Unix). The total number of spaces preceding the first non-blank character then determines the line’s indentation. Indentation cannot be split over multiple physical lines using backslashes; the whitespace up to the first backslash determines the indentation.

junior verge
#

Oh

sullen pewter
#

?

junior verge
#

Not sure why you are doing multiple async def

sullen pewter
#

So it creates a ticket channel

junior verge
#

(embed=em) theres also no em

sullen pewter
#

wdym

junior verge
#

Read your code

spring flax
#

because you're compparing a int to a string.

lofty pecan
#

You're in VS code apparently when you see a little wavy line under your code that means there is a problem

slate swan
#

oh ok ty

spring flax
#

why are you putting the channel id as a string?

sullen pewter
lofty pecan
#

passing your mouth on top of it can tell you what's wrong

slate swan
#

idk haven't coded in python in a while xd

spring flax
#

!e ```py
x = 5
y = "5"
print(x==y)

unkempt canyonBOT
#

@spring flax :white_check_mark: Your eval job has completed with return code 0.

False
lofty pecan
sullen pewter
lofty pecan
#

it's not defined anywhere

#

embed is a funciton paramater

sullen pewter
#

oh

lofty pecan
#

you're assigning its value with em

#

but it's nowhere in your code

junior verge
#

You did # before your line

sullen pewter
#

O I forgot to delete it

sullen pewter
junior verge
#

And fix your indentation please

sullen pewter
#

So I don't need this line right?

lofty pecan
#

it's up to you

sullen pewter
#

I think its correct

#

should be

junior verge
junior verge
sullen pewter
formal basin
sullen pewter
formal basin
junior verge
#
category = client.get_channel(id_here)

for channel in category.voice_channels:
    await channel.delete()
sullen pewter
#

change voice to text

supple thorn
#

Probably

formal basin
modest harbor
#

im trying to make a on_message event that sends out server name, but it doesnt seem to work

supple thorn
#

It'd be really hard for you to make what you want using discord.py when you don't even know how to define a variable's value

winged bone
junior verge
formal basin
#

All I need is a join command

supple thorn
junior verge
#

Your define is useless if you aren't using it

supple thorn
#

This has everything to do about basic python

#

I mean literal basic python

modest harbor
supple thorn
#

message.channel.send()

formal basin
#

All I need is a join vc command

#

Can anyone help

#

Not for music

supple thorn
#

Yeah i'm not helping anymore

#

I literally wrote your code and fixed your errors before

supple thorn
#

And you haven't learned even basic python

junior verge
formal basin
junior verge
#

And your error is what Cane said basic python

supple thorn
#

You're skipping the basics to do something advance that will bite you in the ass

lofty pecan
#

Before using cogs I made a bot without any, I then switched to cogs after properly constructing my commands

supple thorn
junior verge
#

The line:

cogs = []
``` Can you tell me why you got that @formal basin
supple thorn
modest harbor
slate swan
sullen pewter
#
async def ticketcreate(ctx):
    button1 = Button(label = "Ticket", style = discord.ButtonStyle.green)
    button2 = Button(label = "Close", style = discord.ButtonStyle.red)
    async def button_callback(interaction):
      category = discord.utils.get(ctx.guild.categories, name="Tickets")
      ticket_channel = await interaction.guild.create_text_channel(name="ticket", category=category)
      await ticket_channel.set_permissions(interaction.user, read_messages=True, send_messages=True, read_message_history=True)
      await ticket_channel.edit(permissions_synced=True)
      
      async def button2_callback(interaction):
        await interaction.guild.delete_text_channel(ticket_channel)

      button1.callback = button_callback
      button2.callback = button2_callback
      view = View()
      view.add_item(button1)
      view.add_item(button2)
      await ctx.send(embed = discord.Embed(title = "Ticket", description = "Create a ticket"), view = view)
      embed = discord.Embed(title="New ticket from {}#{}".format(ctx.author.name, ctx.author.discriminator), description= "Please wait, we will be with you shortly!", color=0x00a8ff)```
why isnt this working?
supple thorn
#

CokeCane

slate swan
supple thorn
supple thorn
slate swan
formal basin
#

All I need is a bot that joins the vc your in

supple thorn
paper sluice
spring flax
#

how do I make this into a datetime.datetime object? time_online = datetime.datetime.utcnow() - self.start_time
Where self.start_time is a datetime.datetime.utcnow()

formal basin
#

That’s what my command

modest harbor
lofty pecan
#
async def get_prefix(bot, message):
    default_prefix = config["prefix"]
    guild = message.guild
    if guild:
        return prefixes[f"{guild.id}"]
    else:
        return default_prefix```
I want to make a custom prefix, **the prefix changes in the json file but the bot doesn't recognize it**, any idea why?
supple thorn
#

@modest harbor also

lofty pecan
#

nothing happens basically

slate swan
supple thorn
#

Won't work cause it's message.content.startswith

modest harbor
spring flax
supple thorn
sullen pewter
sullen pewter
modest harbor
slate swan
sullen pewter
#

should I make ticket_channel global variable

paper sluice
#
    async def button_callback(interaction):
      category = discord.utils.get(ctx.guild.categories, name="Tickets")
      ticket_channel = await interaction.guild.create_text_channel(name="ticket", category=category)
      await ticket_channel.set_permissions(interaction.user, read_messages=True, send_messages=True, read_message_history=True)
      await ticket_channel.edit(permissions_synced=True)
      
    async def button2_callback(interaction):
      await interaction.guild.delete_text_channel(ticket_channel)
#

fuck, discord sux

slate swan
supple thorn
slate swan
#

!botvar

unkempt canyonBOT
#

Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:

bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"

@bot.command()
async def get(ctx: commands.Context):
    """A command to get the current value of `test`."""
    # Send what the test attribute is currently set to
    await ctx.send(ctx.bot.test)

@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
    """A command to set a new value of `test`."""
    # Here we change the attribute to what was specified in new_text
    bot.test = new_text

This all applies to cogs as well! You can set attributes to self as you wish.

Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!

slate swan
maiden fable
slate swan
lofty pecan
#
config = fetch('config')
prefixes = fetch('prefixes')

print("Logging in!")

async def get_prefix(bot, message):
    default_prefix = config["prefix"]
    guild = message.guild
    if guild:
        return prefixes[f'{guild.id}']
    else:
        return default_prefix

bot = commands.Bot(command_prefix=get_prefix)```
slate swan
lofty pecan
maiden fable
#

Oh, hmmm

#

Well, there u go. Another issue

slate swan
spring flax
lofty pecan
slate swan
spring flax
#

oh nevermind what I said

#

I put a trailing comma by mistake

lofty pecan
slate swan
#

more it inside get_prefix function

spring flax
#

so it actually returns the wrong time

class Bot(commands.Bot):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.start_time = datetime.datetime.utcnow()

    @property
    def _uptime(self):
        bot_uptime = disnake.utils.format_dt(self.start_time, "R")
        return bot_uptime
slate swan
lofty pecan
#

yes

#
def fetch(filename: str):
    """ Fetch file """
    try:
        with open(f'{filename}.json', encoding='utf8') as data:
            return json.load(data)
    except FileNotFoundError:
        raise FileNotFoundError("JSON file wasn't found")```
#

it's a function I use everywhere lol

#

So I don't have to type it all the time

slate swan
#

call the fetch function inside get_prefix

lofty pecan
#

hooo

#

oke oke

spring flax
slate swan
#

it should

spring flax
#

it returned 4 hours ago in the timestamp when it was a few seconds

lofty pecan
#

it works amazingly !

slate swan
#

because its saving utcnow maybe

lofty pecan
#

thanks a lot I should have realized the issue lol

slate swan
#

pleasure

spring flax
#

ah so i guess i should subtract them because that works

#

do you know how to make a timedelta into a datetime.datetime?

slate swan
#

you want to add/subtract it somewhere?

spring flax
#

yeah

slate swan
#

you can add datetimes and timedeltas

spring flax
#

yeah but if i do time_online = datetime.datetime.utcnow() - self.start_time this returns a timedelta

sullen pewter
#
async def ticket1(ctx): 
  button1 = Button(label = "Ticket", style = discord.ButtonStyle.green)
  button2 = Button(label = "Close", style = discord.ButtonStyle.red)
  async def button_callback(interaction):
    category = discord.utils.get(ctx.guild.categories, name="Tickets")
    ticket_channel = await interaction.guild.create_text_channel(name="ticket", category=category)
    await ticket_channel.set_permissions(interaction.user, read_messages=True, send_messages=True, read_message_history=True)
    await ticket_channel.edit(permissions_synced=True)
      
    async def button2_callback(interaction):
      await interaction.guild.delete_text_channel(ticket_channel)

    button1.callback = button_callback
    button2.callback = button2_callback
    view = View()
    view.add_item(button1)
    view.add_item(button2)
    await ctx.send(embed = discord.Embed(title = "Ticket", description = "Create a ticket"), view = view)
    await ctx.send(embed = discord.Embed(title="New ticket from {}#{}".format(ctx.author.name, ctx.author.discriminator), description= "Please wait, we will be with you shortly!", color=0x00a8ff))```
#

Why isn't this working?

slate swan
#

bad indentation

sullen pewter
#

I fixed it

slate swan
#
@client.command()
async def ticket1(ctx): 
  button1 = Button(label = "Ticket", style = discord.ButtonStyle.green)
  button2 = Button(label = "Close", style = discord.ButtonStyle.red)
  async def button_callback(interaction):
     ...
     async def button_callback2(interaction):
        ...
     await ctx.send()
     await ctx.send()``` this is smthing you have
#

the 2nd callback is inside the 1st one

#

and other parts too

slate swan
sullen pewter
slate swan
#

since that literally means difference in time

spring flax
#

oof then do you have alternatives?

sullen pewter
#
async def ticket1(ctx): 
  button1 = Button(label = "Ticket", style = discord.ButtonStyle.green)
  button2 = Button(label = "Close", style = discord.ButtonStyle.red)
      async def button_callback(interaction):
      category = discord.utils.get(ctx.guild.categories, name="Tickets")
      ticket_channel = await interaction.guild.create_text_channel(name="ticket", category=category)
      await ticket_channel.set_permissions(interaction.user, read_messages=True, send_messages=True, read_message_history=True)
      await ticket_channel.edit(permissions_synced=True)
      
    async def button2_callback(interaction):
      await interaction.guild.delete_text_channel(ticket_channel)

    button1.callback = button_callback
    button2.callback = button2_callback
    view = View()
    view.add_item(button1)
    view.add_item(button2)
    await ctx.send(embed = discord.Embed(title = "Ticket", description = "Create a ticket"), view = view)
    embed = discord.Embed(title="New ticket from {}#{}".format(ctx.author.name, ctx.author.discriminator), description= "Please wait, we will be with you shortly!", color=0x00a8ff)```
slate swan
#

what are you trying to do?

sullen pewter
#

a bot that creates a channel and send a message with 1 button

spring flax
sullen pewter
#

But to create a channel it need to press the button

slate swan
#

lemme test smthing wait

junior verge
#

How do you even get the markdown timestamp in discord.py

shrewd kraken
#

is it possible to do error handling for a specific cog?

junior verge
#

Pretty sure yes

slate swan
#

!e py from datetime import datetime as d print("<:t:{}:R>".format(int(d.utcnow().timestamp())) print("<:t:{}:R>".format(int(d.now().timestamp())))

unkempt canyonBOT
#

@slate swan :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 2
002 |     print("<:t:{}:R>".format(int(d.utcnow().timestamp()))
003 |          ^
004 | SyntaxError: '(' was never closed
slate swan
#

eh

sullen pewter
#
async def ticket1(ctx): 
  button1 = Button(label = "Ticket", style = discord.ButtonStyle.green)
  button2 = Button(label = "Close", style = discord.ButtonStyle.red)
  async def button_callback(interaction):
    category = discord.utils.get(ctx.guild.categories, name="Tickets")
    ticket_channel = await interaction.guild.create_text_channel(name="ticket", category=category)
    await ticket_channel.set_permissions(interaction.user, read_messages=True, send_messages=True, read_message_history=True)
    await ticket_channel.edit(permissions_synced=True)
      
  async def button2_callback(interaction):
    await interaction.guild.delete_text_channel(ticket_channel)

  button1.callback = button_callback
  button2.callback = button2_callback
  view = View()
  view.add_item(button1)
  view.add_item(button2)
  await ctx.send(embed = discord.Embed(title = "Ticket", description = "Create a ticket"), view = view)
  embed = discord.Embed(title="New ticket from {}#{}".format(ctx.author.name, ctx.author.discriminator), description= "Please wait, we will be with you shortly!", color=0x00a8ff)```
#

will this work now?

paper sluice
#

you should run and check

sullen pewter
#

ok

#

Its wrong

#

It should create a button in the channel that it created

paper sluice
#
  view.add_item(button1)
  view.add_item(button2)

u already added both buttons to the view

#

what do you expect??

sullen pewter
#

what should I do then

slate swan
#

which one's more accurate?

spring flax
#

the same i guess

paper sluice
#

dont add both buttons to the view, add the second one in a diff view and send that in the new channel

slate swan
#

the first one is a utcnow and the second one is a now

sullen pewter
spring flax
#

but it gets adjusted to user's tz

paper sluice
blissful sparrow
#

Define what ban is

paper sluice
#

well, did u define ban?

blissful sparrow
#

ban =

paper sluice
#

...

gilded gust
#

Hey, I'm getting a "There is no current event loop in 'Thread-3 (start)'." error. I know that I have to create a new asyncio event loop but I'm not sure how that will work in my current use case

def main():
  threading.Thread(target=func1.start).start()
  threading.Thread(target=func2.start).start()

@tasks.loop(seconds=3)
async def func1():
  # do stuff

@tasks.loop(seconds=8)
async def func2():
  # do stuff
``` This is the format of my code for now
raise RuntimeError('There is no current event loop in thread %r.'

RuntimeError: There is no current event loop in thread 'Thread-3 (start)'.

paper sluice
#

python doesn't have afunction called ban

novel apexBOT
#

This is not a Modmail thread.

blissful sparrow
#

Use the documentation to find out how to ban someone I'm not that fluent lol

blissful sparrow
#

Then define it in a variable

visual island
gilded gust
#

I already asked the question in a help channel, no one aswered

gilded gust
#

and this is the code for a discord bot

visual island
lofty pecan
#

Well, thanks to anyone that helped me with the issue I got, I finally finished making my bots and that wouldn't have been without your help so thanks a lot!

gilded gust
upbeat gust
#

bruh

#

Pls just look at docs

#

Guild.ban

oblique adder
#

How do I move the dropdown to be above buttons ?

slate swan
#

^^

oblique adder
#

How do I do that ?

heavy folio
#

!d discord.ui.Button

unkempt canyonBOT
#

class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.

New in version 2.0.
heavy folio
#

!d discord.ui.View

unkempt canyonBOT
#

class discord.ui.View(*, timeout=180.0)```
Represents a UI view.

This object must be inherited to create a UI within Discord.

New in version 2.0.
heavy folio
#

put them before the buttons then

#

oh

#

hang on

slate swan
#

Does anyone know how i could make a logging channel system?
For example:
I have finished with a ticket, i rename it to foxx-done, then the bot will edit an existing message with the stats of all the tickets i have completed, so it would be foxx: 1 then if i did it again it would be foxx: 2 and so on.
I’m think of using a json file to log the users but i’m not sure how to do this, any ideas?

visual island
slate swan
#

anyone know how to implent this as verification on a discord server?

maiden fable
#

!d disnake.ui.TextInput

unkempt canyonBOT
#

class disnake.ui.TextInput(*, label, custom_id, style=<TextInputStyle.short: 1>, placeholder=None, value=None, required=True, min_length=None, max_length=None)```
Represents a UI text input.

This can only be used in a [`Modal`](https://docs.disnake.dev/en/latest/api.html#disnake.ui.Modal "disnake.ui.Modal").

New in version 2.4.
slate swan
visual island
upbeat gust
#

why are you passing the __repr__ of an instance

#

Where it says syntax error

#

<ButtonStyle.secondary: 2>

slate swan
#

you can just style=2

upbeat gust
#

you just pass ButtonStyle.secondary

upbeat gust
#

.red

#

...

#

import it

slate swan
#

!d discord.ButtonStyle

unkempt canyonBOT
#

class discord.ButtonStyle```
Represents the style of the button component.

New in version 2.0.