#discord-bots

1 messages ยท Page 370 of 1

shy eagle
#

what message

wanton current
#

are you defining the function below your client?

shy eagle
#

yeah

wanton current
#

move it so it's defined above

#

the code is read top to bottom

shy eagle
#

one sec

primal sail
#

hello everyone i lf store data for each of my user for start i make something like this
global donnees

ID = ctx.author.id
if ID not in donnees:
donnees[ID] = {
'Inventaire': ["breche commune"],
'personnages': [],
'equipements':[],
'argent': 0,
'prime': 0,
'elo': 0,
'pv': 0,
'fragementCommun': 0,
'fragementInhabituel': 0,
'fragementRare': 0,
'fragementMystique': 0,
'fragementDivin': 0
}

but i loose the data at each restart of my bot i think i need to use database but how can i made for use it and can i recycle my code with my dictionary or i need to remove it and make the same with database ? thanks

shy eagle
#
NameError: name 'get_prefix' is not defined```
#

sending the error one more time

#

what do i do

#

some sort of import?

primal sail
#

where did you define your prefix ?

#

you need to make something like that at the start of your code intents = discord.Intents.default()
client = discord.Client(intents=intents)
client = commands.Bot(command_prefix='!', intents = discord.Intents.all())

#

but go watch tutorial for make discord bot i think for get the basic

shy eagle
#

im trying to make a code to change prefix when you're in another discord server

primal sail
#

oh i see

shy eagle
#

^

#

client = commands.Bot(command_prefix = get_prefix, help_command=None, intents = discord.Intents.all())

#

and says get_prefix is not defined

wanton current
#

can you send your entire code

shy eagle
#

althought i believe it should have been correct

wanton current
#

!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.

shy eagle
#

of the whole bot?

wanton current
wanton current
shy eagle
#

here @wanton current

wanton current
#

you need to put your function above the client definition:

def get_prefix(client, message):
  with open('prefixes.json', 'r') as f:
    prefixes = json.load(f)


  return prefixes[str(message.guild.id)]

client = commands.Bot(command_prefix = get_prefix, help_command=None, intents = discord.Intents.all())
primal sail
#

or i can use it with db

wanton current
wanton current
primal sail
#

i cant just save my dictionary ๐Ÿ˜ญ ?

upbeat otter
primal sail
#

because i make all my current code with dictionary

#

and i am really lazy to remake all

primal sail
upbeat otter
primal sail
#

i want to store inventory and other information of every user

#

this is my dictionary : ID = ctx.author.id if ID not in donnees: donnees[ID] = { 'Inventaire': ["breche commune"], 'personnages': [], 'equipements':[], 'argent': 0, 'prime': 0, 'elo': 0, 'pv': 0, 'fragementCommun': 0, 'fragementInhabituel': 0, 'fragementRare': 0, 'fragementMystique': 0, 'fragementDivin': 0 }

#

how can i save it in a json so ?

twilit grotto
#

make a json file, and save the dictionary to it ;)

primal sail
#

yes but how ๐Ÿ˜ญ

#

i never use json before

twilit grotto
unkempt canyonBOT
#

json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)```
Serialize *obj* to a JSON formatted [`str`](https://docs.python.org/3/library/stdtypes.html#str) using this [conversion table](https://docs.python.org/3/library/json.html#py-to-json-table). The arguments have the same meaning as in [`dump()`](https://docs.python.org/3/library/json.html#json.dump).

Note

Keys in key/value pairs of JSON are always of the type [`str`](https://docs.python.org/3/library/stdtypes.html#str). When a dictionary is converted into JSON, all the keys of the dictionary are coerced to strings. As a result of this, if a dictionary is converted into JSON and then back into a dictionary, the dictionary may not equal the original one. That is, `loads(dumps(x)) != x` if x has non-string keys.
twilit grotto
#

and write to file

primal sail
twilit grotto
wanton current
#

json isn't a db

quick gust
#

json work but json bad db

primal sail
wanton current
quick gust
#

it's not supposed to store data

primal sail
#

but if that work where is the problems ?

wanton current
quick gust
primal sail
#

i see

#

i gonna use db

#

someone has good tutorial for learn how to use db ?

#

like sql lite

wanton current
#

that's for sql

primal sail
#

how can i save a list in sql lite ?

#

i make something like that await cursor.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER, argent INTEGER, prime INTEGER, elo INTEGER, pv INTEGER, fragmentCommun INTEGER, fragmentInhabituel INTEGER, fragmentRare INTEGER, fragmentMystique INTEGER, fragmentDivin INTEGER, personnages TEXT, equipements TEXT)") but i want store more than 1 personnage text value personnage = character in french

#

and i check and i cant save list

#

so how can i make ?

wanton current
#

sqlite doesn't support arrays, but you could use something like json and store it as TEXT in your database

white narwhal
primal sail
#

which db can support arrays ?

white narwhal
#

Help me pls

primal sail
#

my bot is host in replit so

white narwhal
primal sail
white narwhal
wanton current
wanton current
primal sail
#

for first say hello, say your problem, stop spam pinging everyone, and show your code

white narwhal
primal sail
#

show your code please

#

run what ?

twilit grotto
#

or malicious

primal sail
#

just ask if you try running a script or something else xd

twilit grotto
#

we need to see your code to help u

primal sail
#

@slate swan

#

.py

#

this is always not the code but yeah

#

i dont want help that and you dont show the code so i cant xd

twilit grotto
#

what you are trying to run is malicious.

zealous finch
#

what is pyaes

twilit grotto
#

no one can assist you further :)

zealous finch
#

?

slate swan
#

If you don't know then no one can assist you @slate swan

zealous finch
#

can someone guide me trough creating a python bot

#

and what is pyaes

twilit grotto
#

went ahead and reported him as well

primal sail
#

yes

twilit grotto
#

enjoy making a new account

primal sail
#

how old are you

#

you cant have more than 14

twilit grotto
#

doesnt matter

#

its malicious

#

!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.

primal sail
#

you really correct me bro im french and have better english than you

twilit grotto
#

you are truly so immature its embarrassing. take your malicious, broken, open source bullshit and hop out of here

#

damn thats crazy, almost like i couldnt tell

primal sail
#

not an excuse

#

are 12 dont let you do illegal shit

zealous finch
#

send you something @primal sail

twilit grotto
#

19

#

you were attempting to, by running malicious code targeted towards stealing other peoples information and accounts

primal sail
#

17

twilit grotto
#

imagine being immature ๐Ÿซต

#

indeed i am, i'm from america

#

?

primal sail
#

someone already use replit db ?

primal sail
shy eagle
#

yo can i have a minute to solve something real quick

twilit grotto
#

today lol

#

about an hour or two ago

shy eagle
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Member' object has no attribute 'avatar_url'

#

so this is the error alright?

twilit grotto
#

bought me and my girlfriend breakfast

shy eagle
#

!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.

wanton current
shy eagle
#

heres the code

twilit grotto
#

a local restaurant which im not naming

primal sail
twilit grotto
#

im in the keys so

#

everything is expensive

shy eagle
wanton current
#

nw

primal sail
#

50 MiB is enough for store data (like maybe 50 per user) for like 1k member ?

#

in a db

wanton current
#

depends on what you're storing

#

50MiB is quite large for text only

primal sail
#

string and int

wanton current
#

Shouldn't take up that much

primal sail
#

but not so much int

#

ok thx

twilit grotto
#

do sum bout it

primal sail
#

i can pay 7$ per month for 2go so if i have problem i gonna try that (if my server projet earn me money xd)

wanton current
twilit grotto
#

you do realize at certain points in america, the time is different? theres multiple timezones, just like everywhere else in the world.

primal sail
#

its 5pm in france

primal sail
#

(i think)

wanton current
#

Yeah but paying $7 for 2GB is a scam

twilit grotto
wanton current
primal sail
wanton current
#

Whatever floats your boat

primal sail
sturdy egret
#

Anyone got any clue how to send a button to a webhook, every time I try I get a value error

primal sail
sturdy egret
#

But it says it needs to have a associated state

spice warren
#

You send a View like that, not a Button

#

Ah you're trying to use a stateless webhook. If you made the Webhook via url and that Webhook has the token, you can use Webhook.fetch to gain the necessary state:

#

I forgot to brain

#

!d g discord.Webhook.fetch

unkempt canyonBOT
#

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

Fetches the current webhook.

This could be used to get a full webhook from a partial webhook.

New in version 2.0.

Note

When fetching with an unauthenticated webhook, i.e. [`is_authenticated()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook.is_authenticated) returns `False`, then the returned webhook does not contain any user information.
sturdy egret
spice warren
#

The webhook you're calling .send on is not a "full" webhook, it's Partial as the docs above touch on

You can call Webhook.fetch() to update it in place with a Full webhook... which can send Views

sturdy egret
#

okay so

#

i fetch webhook t

#

then just do webhook.send(view=button)

spice warren
#

What is button

sturdy egret
#
import discord
from discord import ui



class ButtonSendCode(ui.View):
    def __init__(self):
        super().__init__(timeout=None)

    @discord.ui.button(label="Send Code", style=discord.ButtonStyle.green, custom_id="persistent:button_one")
    async def button_one(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.send_message("hi")
#

that is button

spice warren
#

Okay cool button is a View

#

Not a Button, lol

shy eagle
#

yo got another issue ๐Ÿ˜†

#

!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.

shy eagle
sturdy egret
shy eagle
spice warren
#

Nothing, you send an instance of this ButtonSendCode view with the view= kwarg

wanton current
spice warren
sturdy egret
#

ah

#

i tried that already

#

noi didnt

sturdy egret
#

the line i used was await webhook.send(view= ButtonSendCode)

wanton current
#

Did you fetch it before (the webhook)?

sturdy egret
#

yea im using webhook= Wbhook.from_url

spice warren
#

You need to fetch that webhook

spice warren
#
webhook = Webhook.from_url(...)
webhook = await webhook.fetch()
await webhook.send(...)
sturdy egret
#

ahhhh

#

so

#
                    await.webhook.fetch()
                    await webhook.send(view= ButtonSendCode)
#

also what do i need to import

#

for the fetch

#

await.webhook.fetch()
^
SyntaxError: invalid syntax

#

cause i just get left with that

spice warren
#

Read it again

#

You can solve this one yourself I bet

sturdy egret
#

...

#

i dont

#

wanna talkabout it

spice warren
#

Where did you get await.webhook from?

hushed galleon
unkempt canyonBOT
#

discord/webhook/async_.py line 1390

state=self._state,```
spice warren
spice warren
# sturdy egret ^

Read it again, I have not done await.webhook anywhere in that codeblock

sturdy egret
#

oh yea

#

still same issue

#

ValueError: Webhook views require an associated state with the webhook

spice warren
#

I just edited the codeblock, sorry, read it again for the new change

sturdy egret
#

ValueError: Webhook views require an associated state with the webhook

#
                    webhook2 = await webhook.fetch()
                    await webhook2.send(view= ButtonSendCode)
sturdy egret
hushed galleon
spice warren
#

They are not providing client though

#

Hence the recommendation to fetch

hushed galleon
#

thats why i mentioned fetch() passing through _state, if the partial webhook is missing it then fetch() won't return it either

sturdy egret
#

so

#

what should i do from ```
webhook2 = await webhook.fetch()
await webhook2.send(view= ButtonSendCode)

#

what do i need to do

spice warren
#

Oh now I see what you meant, yeah, you're right

hushed galleon
spice warren
#

yep

#

a "full" webhook has the underlying webhook user info attached

sturdy egret
#

soooo what do i do?

spice warren
#
webhook = Webhook.from_url("...", client=<your bot>)
await webhook.send(...)
sturdy egret
#

al;ready have a line like that

spice warren
#

client, not session

sturdy egret
#

how do i obtain tat

spice warren
#

it is your bot or client object

sturdy egret
#

?

#

sorru i dont follow

spice warren
#

y'know where you do like

#

bot.run() or client.run()? It's that client/bot

sturdy egret
#

wait so bot.run(token)

#

or no?

#

bot.run(config.TOKEN, log_handler=None)

spice warren
#

That bot object is what you use, yes

#

Don7t edit that line at all, that's just the bot i meant

sturdy egret
#

so i just say client = bot

upbeat otter
cosmic spoke
#

Yo

#

Anyone interested in making a anime bot

wanton current
#

already have one rooDab

wanton current
#

YES, but what numbers are incorrect?

civic reef
#

guys, can anyone help me in my doubt of task.loop in python-help channel?
It's almost half an hour and after 1 hr of inactivity it closes so asking it here
Thanks in advanc!!

blissful crane
#

pass in the embed to the ModuleButton's init

copper flume
#

callback embed?

blissful crane
#

yea ig

scarlet tiger
#

you can use an attribute as a reference

copper flume
#

wdym how

#

the embed is not generator until the button is clicked

blissful crane
#

I am confused on what you want exactly

scarlet tiger
#

do you want to get the embed this function correct?

async def callback(self, interaction: Interaction) -> Any:
        self.embed = discord.Embed(...)
        return await interaction.edit_original_response(
            embed=self.embed, view=self.view
        )```
copper flume
scarlet tiger
# copper flume yeah this embed
class ModuleButton(discord.ui.Button):
    def __init__(...):
        super().__init__(...)
        self.embed = None # HERE

    async def callback(self, interaction: Interaction) -> Any:
        self.embed = discord.Embed(...)
        return await interaction.edit_original_response(
            embed=self.embed, view=self.view
        )


class HelpPanel(discord.ui.View):
    def __init__(self, ...):
        super().__init__(...)
    
    @discord.ui.button(...)
    async def ...(self, interaction: discord.Interaction, _):
        view = discord.ui.View(timeout=120)
        for cog in self.bot.help_cogs['main']: # List of cogs
            # Here
            buttton = ModuleButton(...)
            view.add_item(button)

        view.children[0].disabled = True
        return await interaction.response.send_message(
            embed=button.embed,
            view=view,
            ephemeral=True
        )
copper flume
#

basically, When the user clicks the button of HelpPanel, it will send an ephemeral embed with a View

copper flume
#

cause I want the first button to be already clicked

scarlet tiger
copper flume
scarlet tiger
copper flume
#

this on clicking the Main button

scarlet tiger
copper flume
#

here, main button is the button in HelpPanel

copper flume
scarlet tiger
copper flume
#

or is it the best to make the embed manually in HelpPanel's button

scarlet tiger
#

I have a question why do you have another view?

view = discord.ui.View(timeout=120)

#

use current view

copper flume
#

I want.

copper flume
#

My goal is to have the first child's embed on clicking main button

#

Leave, I'll not provide the embed there

#

it will be None.

scarlet tiger
#

It's so simple you just have to add a reference. If you just want to send the embed message just use the attribute.

copper flume
#

And how?

copper flume
#

for author and interaction.client

scarlet tiger
shy eagle
#

hey there, got an issue would anyone care to help?

#

!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.

shy eagle
#

heres the code and here's the error discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Guild' object has no attribute 'member'

copper flume
shy eagle
#

kk

shy eagle
#

yes

#

why?

scarlet tiger
#

is member_count

shy eagle
shy eagle
scarlet tiger
#

๐Ÿ˜…

copper flume
scarlet tiger
#

Why did you delete your messages? I can't help you that way.

left dew
#

has anyone had any issues when inviting a discord bot to a server? when i try and click to save unsaved changes to generate a URL it wont save it

ancient stump
formal basin
#

how to make a slash command only appear for the owner of the bot

boreal loom
rain hedge
fast osprey
slate swan
ancient stump
formal basin
slate swan
formal basin
ancient stump
hushed galleon
ancient stump
slate swan
#

For example postgres but if you dont want to set it up and stuff you Can use sqlite for example which just requires a file like database.db

#

you can ask in #databases if you have related questions

boreal loom
slate swan
#

show full traceback

#

!traceback

unkempt canyonBOT
#
Traceback

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

slate swan
#

from where did you get bot.select

slim bloom
#

How do I get my bot to send a message on a voice channel?

ancient stump
formal basin
#

for example like string1= Hello there string2= hi there

slim bloom
hushed galleon
ancient stump
slim bloom
hushed galleon
#

if you want one argument to take the entire string without needing quotes, you can make it a keyword-only argument with a leading star: py @bot.command() async def cmd(ctx, arg1: str, *, arg2: str): ... !cmd "Hello there" hi there would then be equivalent to the first example

ancient stump
hushed galleon
#

it works like a regular text channel, right?

#

!d discord.VoiceChannel.send

unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) objects. **Specifying both parameters will lead to an exception**.
ancient stump
ancient stump
# slim bloom <a:Fer:1185537564925501480>

voice_channel_id = 1245797706589278280 ###PUT HERE THE VOICECHANNEL ID

voice_channel = ctx.guild.get_channel(voice_channel_id)

await voice_channel.send("Test")

i just tried it, it works!
i would try this template if you are not familiar with Python.

slim bloom
#

alrr

worn valve
#

This doesnโ€™t work and idk why :(

    message = ' '.join(map(str, args))
    channel = bot.get_channel(modmail_channel)

    if channel:
        embed = nextcord.Embed(
            title="**Mod Mail**",
            description=message,
            color=nextcord.Color.purple()
        )
        bot.loop.create_task(channel.send(embed=embed))

@bot.event
async def on_message(message):
    if message.guild is None:
        member = target_guild.get_member(message.author.id)
        if member:
            log(f"DM from **<@{message.author.id}>**: \n\n{message.content}") ```
#

It worked like 2 hours ago but now it doesnโ€™t work and I didnโ€™t change anything

worn valve
#

No

#

Just doesnโ€™t work

#

I have a log thing which has the def as the EXACT same but different name and channel

#

I tried to print after

@bot.event
async def on_message(message):

And it didnโ€™t work

ancient stump
#

hm

worn valve
#

I also tried to log it as the exact same thing but โ€œLogโ€ instead of โ€œMod Mailโ€ and it didnโ€™t work

#

And log works normally

ancient stump
#

add a error handling/prints

worn valve
#

So smth to do with this part of the code:

async def on_message(message):
    if message.guild is None:
        member = target_guild.get_member(message.author.id)
        if member:
            modmail(f"DM from **<@{message.author.id}>**: \n\n{message.content}") ```
#

Wait ima try smth

summer carbon
#

@vocal magnet can I have permission to screen share?

worn valve
#

Also the โ€˜logโ€™ is where I was testing it, it usually would be modmail

worn valve
#

Found the issue, I had 2 on_message events

slim bloom
#

How do I cool down the server? prefix command

twilit grotto
upbeat otter
#

!d discord.ext.commands.cooldown

unkempt canyonBOT
#

@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command)

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.BucketType).

If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandOnCooldown) is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error) and the local error handler.

A command can only have a single cooldown.
upbeat otter
glad marsh
#

Why does this only work with bot.event and not with bot.listen()

@bot.listen()
async def on_message_2(message):
    if message.author.bot:
        return
    if message.channel.id == 1245101494689333340:
        try:
            await asyncio.sleep(1)
            await message.add_reaction('โญ')
            await asyncio.sleep(1)
            await message.add_reaction('โš ๏ธ')
        except Exception as e:
            print(f'Error adding reaction: {e}')```

does on_message_2 have something to do with it
finite salmon
glad marsh
#

on_message events

finite salmon
glad marsh
#

very stupid of me ๐Ÿ’€

#

thanks for your help

finite salmon
#

I agree

#

My pleasure

shy eagle
#

hey there

#

got an issue anyone willing to help?

slate swan
#

Just ask, it's wasting everyone's time asking to ask

shy eagle
#

!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.

shy eagle
#

so here's the code and here's the error

#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Embed.__init__() got an unexpected keyword argument 'Timestamp'

slate swan
#

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

timestamp, not Timestamp

shy eagle
#

oh kk

#

thank you !

upbeat otter
fast osprey
#

Don't beat up on them, it's just politeness. It's fine to assume in help dedicated spaces that folks are there to help

ancient stump
fast osprey
#

I strongly suggest you don't make channels for tickets. There's a ton of limitations and this is what discord made threads for basically

ancient stump
fast osprey
#

Otherwise looks pretty smooth

shy eagle
#

!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.

shy eagle
#
sqlite3.OperationalError: incomplete input```
#

Code and Error.

ancient stump
# fast osprey Otherwise looks pretty smooth

thank you, it took me almost a day. i didnt know exactly how to create the transcript system. i put the channel history in embed. but embeds have restrictions when it comes to words. i will use this to convert blocks.

fast osprey
#

The nice thing about threads is you really don't need a transcript. You just archive it

#

Incredibly smooth ux, just add people to the thread if you want it private then archive it when it's done

ancient stump
hushed galleon
#

huh, i checked my test bot's ratelimits and it showed 2000/1d for channel creates (shared bucket between guilds), and 1000/0.01s for deletes - thought the create limit would be much lower, but i guess you have max guild channel caps too

fast osprey
#

iirc that's one that they actually tend to vary between bots. The bot level rate limit tends to come into play less than the per guild max usually with these systems though

hushed galleon
#

oh wait i think i misunderstood the bucket key, the ratelimits are still localized by top-level resources

#

looks like thread creates is 50/300s for me

#

and thats what, 1000 active threads max per guild vs 250 text channels?

formal basin
#

!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.

formal basin
ancient stump
#

oh you pasted

#

missing package (means that the requested resource set could not be found) ig contact the host support

fast osprey
#

Unknown webhook happens when you try to followup before responding

naive briar
ancient stump
boreal loom
#

ok

fast osprey
#

took me almost a day

ancient stump
midnight oracle
#

How do I do a Button with a link?

midnight oracle
slate swan
#

basically you set url

midnight oracle
slate swan
formal basin
#

!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.

formal basin
formal basin
#

but it doesnt work on on my host

#

or my other host

slate swan
#

what doesnt work mean?

#

you get an error?

formal basin
slate swan
formal basin
# slate swan can you do `.send_modal` when you already sent a message to .response?

like this

      await interaction.response.send_modal(VerificationModal())
      class VerificationModal(discord.ui.Modal):
            def __init__(self):
                super().__init__(title="Enter Verification Code")
                self.add_item(discord.ui.TextInput(label="Verification Code"))

            async def on_submit(self, interaction: discord.Interaction):
                user_code = self.children[0].value
                if int(user_code) == bot.user_codes[interaction.user.id]:
                    await interaction.response.send_message("Email verified successfully!  | Your email will be used to send you updates and statuses etc of zagzag. To remove it use /email-remove", ephemeral=True)
                    await bot.redis.set(key, email)
                    # Implement logic to mark the email as verified
                else:
                    await interaction.response.send_message("Invalid verification code. Please try again.", ephemeral=True)
      
     ```
ancient stump
#

does anyone know how i can connect my discord bot to a website? like most famous bots where you can change the settings and setups on the website. i know you need HTML but what else? and do you have any good DOCS to start with?

wanton current
#

There aren't really any "docs" for making a Discord bot web dashboard, but you'd have to be familiar with web development, as well with databases probably, and also finding a way to communicate things between your bot and your web dashboard. As well as things like OAuth2, and the list goes on.

#

It's definitely not an easy task.

slate swan
#

no

#

I mean Can you still respond with a modal if you already sent text

formal basin
fierce plaza
#

Is there a built in function for grabbing a users name?

#

i would like to have it printed in the logs when someone does a command

formal basin
# fierce plaza Is there a built in function for grabbing a users name?
@bot.event
async def on_app_command_completion(interaction: discord.Interaction, command: discord.app_commands.Command):
      guild = bot.get_guild(your-guild-id)
      channel = guild.get_channel(the-channel-id-you-want-the-logs-in)
      await channel.send(f'{command.name} command used by {interaction.user}({interaction.user.id}) in ``{interaction.guild.name}``')
      print(f'{command.name} command used by {interaction.user}({interaction.user.id}) in ``{interaction.guild.name}``')
    ```  

Got a template for you
#

oh you want it printed

#

wait one sec

fierce plaza
#

just in the terminal

#

so if i can get it to a variable its good

formal basin
#

@bot.event
async def on_app_command_completion(interaction: discord.Interaction, command: discord.app_commands.Command):
           print(f'{command.name} command used by {interaction.user}({interaction.user.id}) in ``{interaction.guild.name}``')
#

like that

fierce plaza
#

and i just put on_app_command_completion() at the end of my commands?

fierce plaza
#

oh wait its an event

formal basin
#

its an event

fierce plaza
#

yeah

#

i wonder if i can just plug that in and itll work?

formal basin
#

?

fierce plaza
#

yeah

formal basin
#

yeah it will

#

just put it anywhere

#

i use it myself

lost root
#

Guys, can anyone tell me how to transfer money via a slash command for an economic discord bot, I am writing a bot in python but disnake.py

fierce plaza
# formal basin yeah it will

so what about this... im running the bot using a .service file. Something i just learned about the other day. So i cant directly see the logs

#

what do i have to do to have a terminal that monitors the logs and can recieve print commands?

lost root
#

ye ye

#

have database have

fierce plaza
#

i assume it would just be some fancy SQL then, no?

lost root
#

SQlite3

fierce plaza
#

but what i dont have is one that actively monitors the bot

#

it just runs in the background

lost root
#

I need to figure out how to make a command using a slash

#

to transfer currency on the server, I need a code

formal basin
lost root
#

guuys?

#

someone tell me how to do this?

formal basin
#

only redis

lost root
#

hmm

#

its problem

ancient stump
lost root
#

I need to figure out how to make a command using a slash
to transfer currency on the server, I need a code

slate swan
lost root
#

I donโ€™t know how to write in code the transfer of money to the user in an economic bot using a slash command

slate swan
#

Then learn how to, nobody is going to write code for you here

lost root
#

I'm asking if someone can explain to me how to write it correctly?

#

I tried to rewrite it many times, look at the forums and didnโ€™t find anything.

slate swan
#

You just said you dont know how to code

formal basin
slate swan
ancient stump
#

you wont find anyone here who will make you codes, unless there is a private payment for helping outside the server (i dont know if that violates rule nr 9) you have to learn to code yourself like everyone else here. we can help you correct your mistakes but we cant make them for you! @lost root

lost root
#

I know how to program, I just donโ€™t know how to write a transfer of money to a user using a slash command

slate swan
#

What do cogs have to do here ๐Ÿ’€

lost root
formal basin
slate swan
slate swan
#

You Can Ask on dpy discord

ancient stump
formal basin
slate swan
slate swan
#

But sure

ancient stump
#

i advised you sum hrs bevor, to contact your host, often it is due to missing packages

ancient stump
fierce plaza
#

is it safe to hardcode API keys into my discord bot?

#

idk if someone is able to yoink them or not

formal basin
ancient stump
formal basin
#

the smtplib is blocking

sick birch
remote furnace
#

Is anyone good at making a discord bot? Dm me

flat pier
cosmic spoke
#

Anyone wanna make a anime bot

vapid parcel
#

Why is the title not showing up in the modal?

#

did I do something stupid or is it just broken lmao

#

I fixed it

merry cliff
#

Ok

fierce plaza
#

im trying to make a new / command called graph. I have @bot.tree.command(name="graph", description="Create a graph!") above my async def graph, but discord doesnt see it as a command. I even do /graph and my terminal says /graph doesnt exist

#

anyone know any ways to fix it?

fierce plaza
#

thanks!

torn solar
#

!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.

torn solar
#

thats error

#

!paste

#

wait nevermind im stupid i dont have role createdff

hollow kraken
#

I need to have a function occur and finish before another function occurs, is there any wait like function for this?

golden portal
#

isnt that a normal function at that point ๐Ÿค”

upbeat otter
#

lmao yeah didn't read it properly

solid pecan
#

do you guys have any tutorials/websites i should visit to get started with discord bot development?

red sparrow
#

doesnt work

shrewd apex
unkempt canyonBOT
#
Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, 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

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

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

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

red sparrow
shrewd apex
#

for the client

red sparrow
#

or whatever its called

shrewd apex
#

discord.Client(intents=...)

shrewd apex
#

did u even read the contents of the embed

red sparrow
shrewd apex
#

then i would recommend learning some python before attempting discord bots, discord bots arent exactly a beginner friendly project

red sparrow
ancient stump
#

!d discord.Intents

unkempt canyonBOT
#

class discord.Intents(value=0, **kwargs)```
Wraps up a Discord gateway intent flag.

Similar to [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions), the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.

To construct an object you can pass keyword arguments denoting the flags to enable or disable.

This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the `intents` keyword argument of [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client).

New in version 1.5.
wispy falcon
#
bot = commands.bot(command_prefix=".",ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  intents=discord.Intents.all())

The output just says
AttributeError: module 'discord.ext.commands' has no attribute 'bot'

#

it used to work but now it doesnt

wispy falcon
#

nvm it works. i just uninstalled discord.py and installed it back

#

what library is easier or better?

patent hull
#

py-cord was created when Danny, the mantainer of discord.py, announced that discord.py's development stopped

#

but it also, Danny, resumed the development of discord.py

#

Now, both libraries are great, but none of them are easy.

#

And I also guess that discord.py would be a better choice ๐Ÿคท

#

that is a subjective opinion.

scarlet tiger
wanton current
#

Use whatever you like

scarlet tiger
#

Yes, it is subjective, for me it is easier pycord but for others it is discord.py.

wispy falcon
#

alright

shy eagle
#
ModuleNotFoundError: No module named 'discord_slash'```
#

was trying to add slash commands and got this error

hushed galleon
#

discord-py-slash-command is a couple years outdated and had published a massive rewrite before it stopped receiving updates, hence why that module can't be imported

shy eagle
#

so i can't add slash commands?

hushed galleon
#

i suggest using discord.py's built-in slash commands instead, or a fork like disnake

#

if you really want to stick with the same maintainer of discord-py-slash-command, interactions.py is their new package

hushed galleon
wanton current
#

*there's a guide in the works

hushed galleon
hushed galleon
lament depotBOT
shy eagle
#

ok, the thing is im on replit ..

#

because its much more easier for me

#

i dont wanna download too many files

hushed galleon
#

you already had discord.py installed in order to use discord-py-slash-command

#

if its v2.0 or above, that means you have native slash command support already

shy eagle
#

oh

#

but then why do i have this error

wanton current
hushed galleon
#

don't use it if you have d.py 2.0+, disnake, etc.

shy eagle
#

ok well i do have d.py 2.0

#

so then what should i use?

hushed galleon
shy eagle
#

kk

scarlet tiger
# shy eagle kk

oh use pycord which has the slash commands already built in and no additional installations.

wanton current
scarlet tiger
#

I didn't know, when I used it I had to use external packages and it was difficult.

shy eagle
#

thing is gonna have to write the whole code from scratch ๐Ÿ˜…

#

just to add slash commands

#

but i believe its worth it

hushed galleon
scarlet tiger
hushed galleon
#

some devs find the new commandtree stuff complicated, but imo i like how the implementation is separated into its own subpackage

upbeat otter
#

yeah it's a lot more clean and easier to manage

hushed galleon
#

unrelated question, i'm trying to figure out which active threads in a channel have a specific user in them to limit the number of threads a user can request, is there any detailed documentation on how thread members are cached by discord.py? or i guess how thread events work in general? i'm messing with it right now and it seems extremely finicky, just to name a few quirks:

  • on startup, thread.members is empty until new members join the thread
  • when creating a thread, the owner isn't included in thread.members
  • when joining a thread, thread.members is wiped and doesn't get re-populated, only updating for new members joining
  • when leaving a private thread, the thread isn't evicted from cache unless the bot has manage threads perm
    official api docs don't seem to cover this, and i'd rather not spam .fetch_members() on a channel's active threads
pine veldt
#

Hy someone here, I am looking for a discord bot dev to work with me as partner

shy eagle
#

so im testing the slash commands and i got a few bugs/errors ill show one of them for now and the rest later on

#
discord.app_commands.errors.TransformerError: Failed to convert giannakis.og to Member```
#

!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.

shy eagle
#

heres the code btw

hushed galleon
#

though that particular error would suggest you didn't sync your command, which would have made the option show a member list and prevent you from inputting an invalid member

shy eagle
#

gotten alot of errors from almost commands ive made so far

#

since i tried making them slash commands

#

would you like me to send the whole code of the test bot for you to see what i should fix up?

#

!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.

shy eagle
#

too many problems that need to be solved i need serious help ๐Ÿ˜‚

hushed galleon
# shy eagle https://paste.pythondiscord.com/NPHQ
  • embed() since your color argument is a string, if color == 0x8300FF: will never be true
  • clear() channel.purge() can take a few seconds to return and might exceed the 3s timeout for interaction responses, making your command appear to fail
    • i suggest you use interaction.response.defer() before purging to avoid the timeout, and then interaction.followup.send() after purging is done
  • kick() should have a permissions check of some form, like @app_commands.default_permissions(kick_members=True), to prevent abuse
  • ban() same as above
  • unban() : discord.user should be : discord.User, but discord only shows users in the current guild anyway so this won't be useful
    • the best you can do is accept a string and loop through guild.bans() to find a name or user ID that matches their input, then use guild.unban()
  • mute() member.mute() isn't a valid method, you're looking for member.timeout()
  • unmute() same as above
  • help() commands usually aren't needed for slash commands since users can already see all slash commands at once
  • feedback() channel.send_message() isn't a valid method, should be .send()
shy eagle
#

what exactly do i replace in unban with what you told me

#

because i didnt quite understand

wanton current
shy eagle
#

alr

wanton current
#

if u wanna unban by username though, you'd have to loop through the bans like in the message above

shy eagle
#

no i wanna unban by the id

#

this command i just made also doesnt work

wanton current
#

What doesn't work specifically?

shy eagle
#

my whois command

shy eagle
wanton current
#

Yes, but what in it?

shy eagle
#

one sec

wanton current
#

You need to do url=member.avatar.url insetad instead of member.avatar

shy eagle
#

should i just import the rest of the commands i have and then send the code to check whats wrong one by one?

hushed galleon
wanton current
#

may be

slate swan
#
async def jjk_fight():
    payload["content"] = "jjk fight"
    requests.post(url, payload, headers=header)
    time.sleep(10)

asyncio.run(jjk_fight())

I want to execute this every 10s, why its showing me
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

wanton current
#

full traceback?

#

also what's the point of having an async function if you're not doing anything async inside of it

shy eagle
#
                             ^^^^^^^^^^
SyntaxError: invalid syntax```
#

got this error

scarlet tiger
shy eagle
#

oh didnt notice

#

!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.

shy eagle
#

anything i should change here?

fast osprey
#

I really suggest not making commands that are thin wrappers over simple operations that are already available in the client. You're effectively degrading the security and auditing of them

shy eagle
#

so i should keep a simple prefix?

shy eagle
#

sorry for the ping btw

#

wili maybe?

#

@wanton current

inner glade
#

Permissions and logging

shy eagle
#

ill add permissions later on

#

trying to see why most of the commands wont do as they are tol

#

told*

shy eagle
#

Well i ahve sent the link and i would recommend check them all because there might be mistakes i might have not noticed

hushed galleon
#

if you're able to, you should try out an IDE with type checking support since they can tell you about non-existent methods or improper usage of parameters without having to test your code manually

#

vscode's pylance extension has an optional type checking setting you can turn on:

shy eagle
#

Ia that possible on replit?

#

Also what exactly do i replace in the code

hollow kraken
vapid parcel
#

The Verify command that is in the rework has the arguments of:

channel
log_channel
role
role2
remove_role

You can see in the screenshot which each one does, should I keep the max of 2 roles? Or do you think other servers would have a verification system that might need more than 2 roles needed for a person..?

pale zenith
vapid parcel
#

Yeah its a bad practice ik xD

pale zenith
#

Fair

#

Not โ€œbadโ€ per se but that's just ugly looking being 3x the size

vapid parcel
#

Well yeah

#

I guess I could refactor all my commands to do it that way

#

Would be "better" in a sense lol. But what type of view are you thinking?

fast osprey
#

docstrings >>>>

vapid parcel
fast osprey
#

You can

vapid parcel
#

You can??

#

Didn't know that, mb lol

#

I use docstrings to describe the commands only n show usage n examples.

pale zenith
#

Dpy supports uhhhhh

#

checks source

vapid parcel
#

๐Ÿ˜ญ

pale zenith
vapid parcel
#

ah okay then

#

thats cool didn't know dpy did that for arguments lol

golden portal
vapid parcel
#

Is there a channel where I can get ideas for my bot?

hollow kraken
# golden portal you need to be more specific here, there are a lot of way to do what you're tryi...

i am using image embeds on all embeds, in the configuration command for my bot the set_icon function is called first before all other functions which are using image embeds, the set icon function is called using await set_icon(ctx) and i have some functions beneath it but before the icon can be set the functions below it are called (and since the icon is stored as a variable which is currently None) is returning an error

untold orbit
#
@client.event
async def on_message(message):
    if "discord.gg" in message.content:
     anti = db.find_one({"_id": message.guild.id})["antiraid"]
     if anti is True:
        white = db.find_one({"_id": message.guild.id})["whitelisted"]
        logs = db.find_one({"_id": message.guild.id})["logschannel"]
        if message.author.id not in white:
         await message.delete()
         await message.channel.send(f"{message.author.mention} You are not allowed to send links here.")
         embed = discord.Embed(title="Anti-Raid", description=f"**{message.author}** has sent a link in {message.channel.mention}\n{message.content}", color=embedc)
         c = await client.fetch_channel(logs)
         await c.send(embed=embed)
    else:
      pass``` 
**im making an anti-link and the anti-link itself is working but i literally cannot use any commands while this code is in my workspace. may someone help me**
#

the logs are also working. just that none of my commands or events will work besides this event. please ping or dm me if you can help.

hushed galleon
#

i would go with the @client.listen("on_message") decorator instead cause it doesn't have those same gotchas

hushed galleon
untold orbit
#

it was such a struggle to get ts to work.

plush glen
#

yo anyone here?

slate swan
#

Look all the messages above..

plush glen
slate swan
#

Don't know, can you?

plush glen
#

i mean i need a quick help

#

in a single line of code

#

can you help me?

#

@slate swan

quick gust
#

Just ask bro

shy eagle
#

TypeError: 'timeout_members' is not a valid permission name

#

got this error for adding the command to timeout members

#

!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.

shy eagle
upbeat otter
shy eagle
#

well yeah but whats the correct permission?

#

mute_members?

#

because neither did that work

slate swan
#

!d discord.Permissions

unkempt canyonBOT
#

class discord.Permissions(permissions=0, **kwargs)```
Wraps up the Discord permission value.

The properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools. This allows you to edit permissions.

Changed in version 1.3: You can now use keyword arguments to initialize [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions) similar to [`update()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.update).
slate swan
#

Go through them

#

Then see if one is related to timing out (the description, not necessarily the attribute name itself)

unkempt canyonBOT
#

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

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

solid pecan
#

can somebody explain how to use cogs?

#

await bot.load_extension("cogs.super_cog")
what does this do?

quick gust
#

loads a cog

solid pecan
#

"cogs.super_cog" this is its position in a folder right?

#

cogs is the name of the folder and super_cog is the name of the python file?

fast osprey
#

That does not load a cog. That loads an extension. That's literally the method name

#

These are two entirely separate concepts

#

load_extension will load an extension based on module name. This is distinct from path or file name

quick gust
fast osprey
#

It's important to call out this distinction so people don't use the terms interchangeably, since they're not

quick gust
#

thanks for the tip :)

chilly cloud
#

why do I get this error when I call discord.ui.Button?

@discord.ui.Button(label="Test", style=discord.ButtonStyle.green)
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

TypeError: 'Button' object is not callable

chilly cloud
#
import discord
from typing import Callable, Optional

class Pagination(discord.ui.View):
    def __init__(self, pages):
        super().__init__()
        self.page = 0
        self.pages = pages

        # self.add_item(discord.ui.Button(label='<', style=discord.ButtonStyle.green, custom_id="prev"))
        # self.add_item(discord.ui.Button(label='>', style=discord.ButtonStyle.green, custom_id="next"))

    @discord.ui.button(label="<", style=discord.ButtonStyle.green)
    async def prev_button(self, interaction: discord.Interaction, button: discord.ui.Button):
        if self.page > 0:
            self.page -= 1
            await interaction.response.edit_message(content=self.pages[self.page])

    @discord.ui.button(label=">", style=discord.ButtonStyle.green)
    async def prev_button(self, interaction: discord.Interaction, button: discord.ui.Button):
        if self.page < len(self.pages) - 1:
            self.page += 1
            await interaction.response.edit_message(content=self.pages[self.page])```
anyone know why only the next page button works
wanton current
#

because you're overwriting the first function with the second one by naming them the same thing

chilly cloud
#

oh also, I currently have 1 database for storing information on guild currency and shop stuff, if I want to make an inventory system, it is advices to start a new database, or to just make a new table?

wanton current
#

table

chilly cloud
#

alr bet

shy eagle
#

whats the right name for this error? raise TypeError(f'{key!r} is not a valid permission name.') TypeError: 'manage_server' is not a valid permission name.

wanton current
#

manage_guild

shy eagle
#

alr thanks

#

how is this even possible? ``` @app.commands.default_permissions(manage_channels=True)
NameError: name 'app' is not defined

#

it works perfectly in other commands

wanton current
#

app_commands instead of app.commands

shy eagle
#

shoot

wanton current
#

lol

shy eagle
#

think ive got more errors coming soon

wanton current
#

dw

shy eagle
#

these slash commands are a great feature but a pain in my ....

#

here's another errordiscord.app_commands.errors.CommandInvokeError: Command 'addrole' raised an exception: AttributeError: 'Interaction' object has no attribute 'send_message'

#
discord.app_commands.errors.CommandInvokeError: Command 'clear' raised an exception: NotFound: 404 Not Found (error code: 10015): Unknown Webhook```
#

discord.app_commands.errors.CommandInvokeError: Command 'createcategory' raised an exception: AttributeError: 'CategoryChannel' object has no attribute 'create'

#

actually should i just send the whole code to see what other issues there are instead of sending one by on?

wanton current
wanton current
shy eagle
shy eagle
#

would you mind checking the code i send? maybe find some other errors

slate swan
# shy eagle would you mind checking the code i send? maybe find some other errors
@client.tree.command(name="lockall", description="Lock all channels")
@app_commands.default_permissions(manage_channels=True)
async def lockall(interaction):
  await interaction.channel.set_permissions(interaction.guild.default_role, send_messages=False)
  await interaction.send_message(f"Locked all channels")

@client.tree.command(name="unlockall", description="Unlock all channels")
@app_commands.default_permissions(manage_channels=True)
async def unlockall(interaction):
  await interaction.channel.set_permissions(interaction.guild.default_role, send_messages=True)
  await interaction.send_message(f"Unlocked all channels")
``` i dont see how you expect this to affect all channels
shy eagle
#

it actually works to be honest

#

idk i just thought of it

slate swan
#

yea it will only "lock" the channel that the command was sent in not all of the channels

#

i hope you are aware of this

#

not so hard to see that lock is the same as lockall and unlock is the same as unlockall

#

just the messages sent differ

shy eagle
#

yeah nvm it doesnt work for all channels ๐Ÿ˜… yeah you have a point

#

my bad i thought it actually worked.

left dew
#

after the developer portal update i cant find out how to add my bot to my server. when i try and select a guild install it wont let me save changes and keeps saying Private application cannot have a default authorisation link

slate swan
#

either make it public or generate one time oauth url

left dew
shy eagle
#

when i try to unban a user it gave me this error discord.app_commands.errors.CommandInvokeError: Command 'unban' raised an exception: NameError: name 'guild' is not defined

slate swan
#

tbh i just went on discord dev portal

#

and its my first time seeing this installation so

#

but the oauth2 tab looks unchanged

#

do you have to do something in installation tho

shy eagle
left dew
#

i dont have a clue ive been trying all types of stuff but nothing works

slate swan
#

i had the invite button in bio for a year now in my bot

shy eagle
left dew
shy eagle
#

๐Ÿ˜‚

slate swan
slate swan
#

you generate the url paste it in the browser and select guild where to add to

left dew
slate swan
left dew
slate swan
#

set it to None

#

and use OAuth2 tab

left dew
#

thanks that worked

shy eagle
#

didnt get that.

slate swan
unkempt canyonBOT
# slate swan !e ```py guild.some_method() ```

:x: Your 3.12 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     guild.some_method()
004 |     ^^^^^
005 | NameError: name 'guild' is not defined
slate swan
#

how is it supposed to know what guild is you never told it

#

same with the user_id ?

#

you never defined this

shy eagle
#

so what exactly do i type to define them

slate swan
#

๐Ÿ’€

#

you prolly want interaction.guild :)

shy eagle
#

k

#

let me see

#

nice it worked!

#

heya got another issue

#
async def avatar(interaction: discord.Interaction, member: discord.Member):
  embed = discord.Embed(title=f"{member.name}'s Avatar", color=0x8300FF)
  embed.set_image(url=member.avatar)
  await interaction.response.send_message(embed=embed)```
#

so its not sending the image and its sending only the embed

#

discord.app_commands.errors.CommandInvokeError: Command 'avatar' raised an exception: AttributeError: 'Interaction' object has no attribute 'send_message'

fast osprey
#

And what's the traceback? It should have your own code in it

chilly cloud
#

also, anyone know how to format an embed in columns of 2

timber dragon
#

add_field has an inline kwarg

#

You can mess with that

#

If you can still add an empty field by setting the name and value to \u200b

chilly cloud
#
        if number % 4 == 0 and number != 0:
            pages.append(new_page)
            new_page = discord.Embed(title=name, description=description)
            new_page.add_field(name=f"{item_dict['item_name']}: ${item_dict['item_price']}",
                               value=f"{item_dict['item_description']} (Stock: {item_dict['item_quantity']})")
        elif number % 2 != 0:
            new_page.add_field(name=f"{item_dict['item_name']}: ${item_dict['item_price']}",
                               value=f"{item_dict['item_description']} (Stock: {item_dict['item_quantity']})", inline=True)
        else:
            new_page.add_field(name=f"{item_dict['item_name']}: ${item_dict['item_price']}",
                               value=f"{item_dict['item_description']} (Stock: {item_dict['item_quantity']})", inline=False)```
#

I get something like this

shy eagle
chilly cloud
# shy eagle what do i replace

mine just looks like this

@tree.command(name="avatar", description="Get a user's avatar")
@app_commands.describe(member='member')
async def avatar(interaction: discord.Interaction, member: discord.Member = None):
    if member:
        await interaction.response.send_message(member.display_avatar)
        return
    await interaction.response.send_message(interaction.user.display_avatar)```
timber dragon
#
member = member or interaction.user
await interaction.response.send_message(member.display_avatar.url)

works too

timber dragon
#
# first line
add_field(), add_field()
# fake third field for first row
add_field(name="\u200b", value="\u200b", inline=True)
# second line
add_field(), add_field()

iirc

shy eagle
#

thing is i want it to be an embed

hushed galleon
shy eagle
#

sure

#

want me to send you my whole code?

#

!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.

shy eagle
#

i've been trying to make this code work without any errors since yesterday till midnight and havent even finished it, always been having different errors. so tired

hushed galleon
#

can you send the traceback too?

#

starting from Traceback (most recent call last): or something like that

wanton current
#

Yeah, your code doesn't match your error

tardy pollen
#

Can I share my own work here?

wanton current
#

?

tardy pollen
#

I made a discord bot based on a multimodal language model
But I'm not doing very well yet

hushed galleon
#

as long as it doesn't fall under advertising or another rule, that should be fine

tardy pollen
wanton current
#

just posting a github link?

tardy pollen
#

ya

wanton current
#

nothing else?

tardy pollen
#

Then ask for advice

hushed galleon
#

imo i would think it's advertising if it's sent without context or trying to promote the usage of some project

wanton current
tardy pollen
#

Is there any way other than changing the IP so that the discord robot can play YouTube music normally?

#

I currently use lavalink

shrewd apex
#

!ytdl cant help with that here sorry

unkempt canyonBOT
#
Our youtube-dl, or equivalents, policy

Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.

For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:

The following restrictions apply to your use of the Service. You are not allowed to:

1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service;  (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;

3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTubeโ€™s robots.txt file; (b) with YouTubeโ€™s prior written permission; or (c) as permitted by applicable law;

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
chilly cloud
#

yo guys, im making an inventory system where people can buy stuff. I currenly have a database for currency handling and shop info, it is better to create a seperate database, or make a new table to store inventory info?

pale zenith
chilly cloud
pale zenith
#

Nah

#

If you're at a point where your database is getting overloaded you have bigger problems

chilly cloud
#

bruh, how am I being rate limited ๐Ÿ˜ญ

snow coral
#

can you make certain users immune to @commands.cooldown(commands_per_cooldown, cooldown_seconds, commands.BucketType.user)

hushed galleon
#

if you're using discord.py, you'll need a dynamic cooldown instead

#

!d discord.ext.commands.dynamic_cooldown

unkempt canyonBOT
#

@discord.ext.commands.dynamic_cooldown(cooldown, type)```
A decorator that adds a dynamic cooldown to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command)

This differs from [`cooldown()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.cooldown) in that it takes a function that accepts a single parameter of type [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context) and must return a [`Cooldown`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Cooldown) or `None`. If `None` is returned then that cooldown is effectively bypassed.

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.BucketType).

If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandOnCooldown) is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error) and the local error handler.

A command can only have a single cooldown.

New in version 2.0.
hushed galleon
#

ah, dpy forks have the same deco too

simple prawn
#

hii i need help for discord dev portal

wanton current
#

what do you need help with?

simple prawn
wanton current
#

to invite?

simple prawn
wanton current
#

Go to the OAuth2 tab and scroll down to the "OAuth2 URL Generator", and then click the "bot" checkbox (and "application.commands" if your bot uses slash commands), and then select the permissions the new box that comes up when you select "bot".

#

and then the generated url is at the bottom

simple prawn
#

but to copy link it tells me "pls enter a uri link."

#

@wanton current

wanton current
#

Turn off this in your Bot settings

simple prawn
wanton current
#

It's probably not needed for what you're trying to do

simple prawn
#

hehe, tysm

wanton current
#

nw

chilly cloud
#

yo guys, whats a good way to log what discord commands were used? Im currently using a discord webhook but im not sure if thats a good way

cosmic spoke
#

Anyone wanna make a anime boy

#

Bot

chilly cloud
# wanton current why are you logging them

currently only me and a few people are testing the bot rn before we start seriously testing it, I wanna use it to see if commands used match up with data changed in the database, helped me catch some bugs quite a few times

cosmic spoke
#

Heheheheeh

#

Anyone working on a anime bot? Thank

flat pier
chilly cloud
wanton current
fast osprey
#

Anime

young dagger
#

Is there any way to handle all errors instead of using Forbidden or HTTPException?

#

I want to use try-except for async for msg in message.channel.history(limit=1, before=message):

fading marlin
#

Exception?

#

Though be careful with that one, it quite literally catches all errors

#

There's also DiscordException, which is for all exceptions of the library

young dagger
wanton current
#

The former is any exception in python and the latter is a base exception for the disord.py (or fork) lib

young dagger
wanton current
#

see the hierarchy at the bottom

young dagger
#

Is it necessary to use pass to execute remaining code after the exception?

#

Or will it just raise the error and execute the rest of the code?

wanton current
#

code?

young dagger
# wanton current code?
            try:
                async for msg in message.channel.history(limit=1, before=message):
            except discord.Forbidden:
                print(
                    f"Missing permissions to fetch message history.")
            except discord.HTTPException as e:
                print(f"HTTP error while fetching message history.")

            print("I want to execute this code after the try-except.")```
wanton current
#

yeah, as long as you don't raise or return inside the except, it will continue running

young dagger
#

Just a habit?

wanton current
#

since

except:
    
print("hi")
```Is invalid in python
#

if u wanna do nothing in case of an exception

#

you need something in the clause

young dagger
wanton current
#

there's no reason to pass then

#

it's the equivalent of:

.catch({})

// or

try {
    // abc
} catch {
    // doing nothing
}
#

in js

young dagger
wanton current
#

wdym?

unkempt canyonBOT
#

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

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

young dagger
# wanton current wdym?

Let's say we try to fetch the message with async for msg in message.channel.history(limit=1, before=message): and we get a discord.HTTPException error. How can we retry fetching the message again after 10 seconds?

wanton current
#

like

async def fetch_msg(..., message: discord.Message) -> Optional[discord.Message]:
    msg = [i async for i in message.channel.history(limit=1, before=message)]
    return msg[0]

async def f():
    msg = None
    while not msg:  # should probably set some timeout so it stops eventually, after x retries, or x seconds
        try:
            msg = await fetch_msg(...)
        except discord.HTTPException:
            pass
#

probably something like this im not sure

young dagger
#
    for i in range(0, 10):
        try:
            async for msg in message.channel.history(limit=1, before=message):
            break
        except discord.Forbidden:
            print(f"Missing permissions to fetch message history. Sleeping for 60 secs before next try.")
            await asyncio.sleep(60)
            continue
        except discord.HTTPException as e:
            print(f"HTTP error while fetching message history. Sleeping for 60 secs before next try.")
            await asyncio.sleep(60)
            continue
wanton current
young dagger
#

My bad

wanton current
#

this would break on the first iteration

#

you'd probably want to break inside the try: clause

young dagger
#

There we go

shadow vigil
#

you didn't hide your token correctly and posting the code is better then a screenshot

#

show your imports and code

#

!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.