#discord-bots

1 messages · Page 257 of 1

shrewd apex
#
@bot.command()
async def foo(ctx):
  view = View()
  names = ["a", "b", "c"]
  for name in names:
    button = Button(label=name, value=name, custom_id=name)
    async def callback(inter):
      value = inter.data["values"][0]
      await inter.response.send_message(f"Switching to {value}!")
    button.callback = callback
    view.add_item(button)
  await ctx.send("Press one of these", view=view)

this should work but pls print inter.data to check where the value is if it dosent work, its a dictionary i really cant remember

#

@full cosmos

full cosmos
#

thank you!

formal basin
#

same error

#
for child in view.children:  
           child.disabled = True
          view.message = await interaction.original_response()
          view.message.edit(content=f"we both picked {rock} so it is a tie {interaction.user.mention}", view=view)```
shrewd apex
#

what error?

formal basin
# shrewd apex what error?
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/ui/view.py", line 427, in _scheduled_task
    await item.callback(interaction)
  File "/Users/zagzag/vscode/zagzag.py", line 153, in button_callback2
    view.message=await interaction.original_response()
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/interactions.py", line 397, in original_response
    data = await adapter.get_original_interaction_response(
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/webhook/async_.py", line 219, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook
shrewd apex
#

yeah cause this interaction did not send a message

#

i meant the message sent in the command which has the view attached to it

#

for example

#
view = MyView()
view.message = await ctx.send("whatever", view=view)

now u can use view.message inside ur interaction callback

formal basin
shrewd apex
#

value i mean

full cosmos
#

okay

shrewd apex
#

i confused it with selectoption

shrewd apex
shrewd apex
#

i dont remember how the data was stored in that

#

index it from that

formal basin
full cosmos
#

Oh yeah I forgot about that sorry

shrewd apex
#

not in the callback

formal basin
#

ok

full cosmos
shrewd apex
full cosmos
#

is a dictionary the same as an array or a list?

formal basin
#

this is what i did

full cosmos
shrewd apex
#

yeah below that last line add this

view.message = await interaction.original_response()

@formal basin

shrewd apex
full cosmos
#

ok thanks

shrewd apex
#

np

blissful badge
#

Quick question....got this code here

    @commands.command()
    async def mccommand(self, ctx, args):
        arguments = ' '.split(args)
        role = discord.utils.get(ctx.guild.roles, name="admin")
        if role in ctx.author.roles:
            print(arguments)

I was using it to send commands like "whitelist add username" for a minecraft server and it was working fine splitting the words up but now its only sending the first word of what I ask it to. did something change with python that I need to fix as well?

thin raft
#

you should do

#

self, ctx, *, args

#

every word in a message command, for example !test hello world

#

test is the name of the command, hello is parameter 1, world is parameter 2

#

using * will tell that the rest of parameters is only 1

blissful badge
#

ahhhhhhhhhhhhhh i see i see

#

Ok let me mess with that, thank you Akex

thin raft
#

np

stuck cosmos
#

I have a question how do i pin messages on the Latest Discord PY version with interactions?

#

do i need the message id, i dont think the docs make it pretty clear and theres nothing online about it

#

i want to send a embed and i want it to pin itself, any help would be appericated 🙏

primal token
#

when you send the message with the embed, save the message and pin it

#

!d discord.Message.pin

unkempt canyonBOT
#

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

Pins the message.

You must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") to do this in a non-private channel context.
stuck cosmos
primal token
#

Not exactly

stuck cosmos
#

or am i completely wrong? I managed to get code working to pin on like ctx before but im totally new to using interactions

#

😭 ah alr

#

i tried like await InteractionMessage.pin(msg, Reason=None) and that wouldnt work

#

when i looked on the docs that was the only thing i could find

primal token
#
msg = await ctx.send(embed=myembed)
await msg.pin()

If you dont want to provide a reason then dont call the kwarg

stuck cosmos
#

ah i see

#

lemme try that 1 sec, thanks for the help

primal token
#

You can one line it but im just showing you it the cleanest way possible in my opinion

stuck cosmos
#

thats what i got when i tried that

primal token
stuck cosmos
#

    a = await interaction.response.send_message(embed=embed)
    ephermal=True
    await a.pin()

#

Traceback (most recent call last):
File "C:\Users\con13\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord\app_commands\tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\con13\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord\app_commands\commands.py", line 867, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "C:\Users\con13\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord\app_commands\commands.py", line 860, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'donodone' raised an exception: AttributeError: 'NoneType' object has no attribute 'pin'

slate swan
#

.send_message does not return message object

stuck cosmos
#

i remember this being much easier on 1.7.3 🤣

stuck cosmos
slate swan
#

i mean that a is None

#

its not message that was sent

#

if you want to gather message you need to use this:

primal token
#

!d discord.Interaction.original_response

unkempt canyonBOT
#

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

Fetches the original interaction response message associated with the interaction.

If the interaction response was a newly created message (i.e. through [`InteractionResponse.send_message()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.send_message "discord.InteractionResponse.send_message") or [`InteractionResponse.defer()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.defer "discord.InteractionResponse.defer"), where `thinking` is `True`) then this returns the message that was sent using that response. Otherwise, this returns the message that triggered the interaction (i.e. through a component).

Repeated calls to this will return a cached value.
slate swan
#

!d discord.Interaction.original_response

unkempt canyonBOT
#

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

Fetches the original interaction response message associated with the interaction.

If the interaction response was a newly created message (i.e. through [`InteractionResponse.send_message()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.send_message "discord.InteractionResponse.send_message") or [`InteractionResponse.defer()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.defer "discord.InteractionResponse.defer"), where `thinking` is `True`) then this returns the message that was sent using that response. Otherwise, this returns the message that triggered the interaction (i.e. through a component).

Repeated calls to this will return a cached value.
stuck cosmos
#

oh

primal token
#

!d discord.InteractionMessage.pin

unkempt canyonBOT
#

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

Pins the message.

You must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") to do this in a non-private channel context.
stuck cosmos
#

so like this?

primal token
#

Yup

slate swan
#

await the original message call

primal token
#

miss that lol

stuck cosmos
#

@primal token @slate swan thank you both for your help ❤️

primal token
#

Cheers!

slate swan
#

is there any way i can do this

!changecashapp <test>

then when the user tyes "cashapp" it will send the cashapp we defined above?

#

ofc you can

#

could you give me a idea how i can, my brain is so flooded i cant think of any way

#

example can be found here

#

!botvar

unkempt canyonBOT
#
Bot variables

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!

lethal drift
#

How do I get message ID from an interaction command?

slate swan
thin raft
#

!d discord.Interaction.message

unkempt canyonBOT
slate swan
#

ok

#

oh its the command that triggered

thin raft
#

only components

#

so meaning, the button message for example

#

not app commands

lethal drift
#

when I do
/greet

And it responds with "hey"
I was trying to get the id of "hey"

slate swan
unkempt canyonBOT
lethal drift
primal token
unkempt canyonBOT
#

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

Fetches the original interaction response message associated with the interaction.

If the interaction response was a newly created message (i.e. through [`InteractionResponse.send_message()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.send_message "discord.InteractionResponse.send_message") or [`InteractionResponse.defer()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.defer "discord.InteractionResponse.defer"), where `thinking` is `True`) then this returns the message that was sent using that response. Otherwise, this returns the message that triggered the interaction (i.e. through a component).

Repeated calls to this will return a cached value.
primal token
#

🤔

slate swan
#

why would you name Interaction object Context

thin raft
slate swan
# lethal drift

yeah so same problem as the guy above .send_message does not return the message sent

slate swan
primal token
#

!d discord.InteractionMessage.fetch

unkempt canyonBOT
#

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

Fetches the partial message to a full [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message").
thin raft
#

why would it not return a message

slate swan
thin raft
#

iik

slate swan
#

!d discord.InteractionResponse.send_message

unkempt canyonBOT
#

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

Responds to this interaction by sending a message.
thin raft
#

but why lol

slate swan
#

to make life harder

#

for example in nextcord it does return smileh

#

!d nextcord.InteractionResponse.send_message

unkempt canyonBOT
#

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

Responds to this interaction by sending a message.

Changed in version 2.4: `ephemeral` can now accept `None` to indicate that `flags` should be used.
torpid frigate
#

"Choice" is not definedPylance. anyone why this not working?

slate swan
torpid frigate
#

my imports are working fine import discord from discord import app_commands

thin raft
#

have you imported it?

#

you didn't import it

slate swan
#

well this Choice class wont appear out of nowhere you need to import it

#

!d discord.app_commands.Choice

unkempt canyonBOT
#

class discord.app_commands.Choice(*, name, value)```
Represents an application command argument choice.

New in version 2.0.

x == y Checks if two choices are equal.

x != y Checks if two choices are not equal.

hash(x) Returns the choice’s hash.
slate swan
#

either add this import:
from discord.app_commands import Choice

or

replace your code like this

- Choice(...)
+ app_commands.Choice(...)
thin raft
thin raft
#

I usually search a web for doing it

slate swan
#

but if you want to do custom colors there is a way

#

and there even is a message about it in this channel let me find it for you

thin raft
#
+ asd
- hello
slate swan
slate swan
thin raft
#

thanks

#

I understood diff as difference

slate swan
#

thats what it is short for

thin raft
#

oh makes sense ngl

tawdry tundra
#

What is the line of all intents?

#

@slate swan

#

Pls help me

slate swan
#

ah man why everybody chooses me

slate swan
tawdry tundra
#

Because you are good

tawdry tundra
slate swan
tawdry tundra
#

I want just the right line

slate swan
#

oh

#

its discord.Intents.all()

#

!d discord.Intents.all

unkempt canyonBOT
#

classmethod all()```
A factory method that creates a [`Intents`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents "discord.Intents") with everything enabled.
tawdry tundra
#

Thx you

slate swan
#

👍

tawdry tundra
#

Can I put ctx in on_ready event?

slate swan
#

no cause there is no context invoking it

torpid frigate
#
async def pick_a_class(interaction: discord.Interaction, class: str):
        if class == 'bard': 
            await interaction.response.send_message("the message the user types")```
tawdry tundra
#

So how I can make the bot send a message when it is on

torpid frigate
#

"the message the user types" do I user the original_message?

slate swan
#

!d discord.ext.commands.Bot.get_channel

unkempt canyonBOT
tawdry tundra
#

Ok

torpid frigate
#

I want to send the exact text the user wrote to the bot

slate swan
#

!d discord.TextChannel.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 "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 "(in Python v3.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "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 "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 "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
tawdry tundra
#

Is know it

slate swan
torpid frigate
#

yes

slate swan
#

then just pass this argument to .send_message ?

torpid frigate
#

await interaction.response.send_message(roll1(interaction.response)) like this? my roll1 function changes certain words the user has written

slate swan
#

!d discord.Interaction

unkempt canyonBOT
#

class discord.Interaction```
Represents a Discord interaction.

An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.

New in version 2.0.
slate swan
#

not interaction.response

#

you wanted the class

#

class: str

#

thats how you named it

torpid frigate
#

if I do roll1(class) it just outputs bard. sorry im new to coding :/

slate swan
#

what does your function do

torpid frigate
#

changes the font

#

ive tested it that function works

slate swan
#

send the function code

torpid frigate
#
    normal = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-=()"
    roll1 = "ᴬᴮᶜᴰᴱᶠᴳᴴᴵᴶᴷᴸᴹᴺᴼᴾQᴿˢᵀᵁⱽᵂˣʸᶻᵃᵇᶜᵈᵉᶠᵍʰᶦʲᵏˡᵐⁿᵒᵖ۹ʳˢᵗᵘᵛʷˣʸᶻ⁰¹²³⁴⁵⁶⁷⁸⁹⁺⁻⁼⁽⁾"
    res = x.maketrans(''.join(normal), ''.join(roll1))
    return x.translate(res)```
slate swan
#

!e ```py
def roll1(x):
normal = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-=()"
roll1 = "ᴬᴮᶜᴰᴱᶠᴳᴴᴵᴶᴷᴸᴹᴺᴼᴾQᴿˢᵀᵁⱽᵂˣʸᶻᵃᵇᶜᵈᵉᶠᵍʰᶦʲᵏˡᵐⁿᵒᵖ۹ʳˢᵗᵘᵛʷˣʸᶻ⁰¹²³⁴⁵⁶⁷⁸⁹⁺⁻⁼⁽⁾"
res = x.maketrans(''.join(normal), ''.join(roll1))
return x.translate(res)

print(roll1("bard"))

unkempt canyonBOT
#

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

ᵇᵃʳᵈ
slate swan
#

works there

torpid frigate
#

yea but I dont want it to reutrn the choice. I want it to ask the user for a respose and then output that response using that font

slate swan
#

mhm

#

you are prolly looking for Modal

torpid frigate
#

Modal?

slate swan
#

here is the example

torpid frigate
#

hmm

#

is there no other way to just store the str the user inputs?

slate swan
#

you can just make another argument field

#

to accept text

primal token
torpid frigate
torpid frigate
slate swan
primal token
slate swan
#

!d str.maketrans

unkempt canyonBOT
#

static str.maketrans(x[, y[, z]])```
This static method returns a translation table usable for [`str.translate()`](https://docs.python.org/3/library/stdtypes.html#str.translate "str.translate").

If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters (strings of length 1) to Unicode ordinals, strings (of arbitrary lengths) or `None`. Character keys will then be converted to ordinals.

If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to `None` in the result.
slate swan
#

funny how its first time i hear about this thing that you can create your own translation tables

primal token
#

Same

#

I used to do them with dicts lol

#

pretty handy

slate swan
#

same here

torpid frigate
slate swan
#

im learning so many things today

#

i also learnt that you can merge strings like this ```py

"a" "b" "c"
"abc"

#

without the +

primal token
#

what in the

slate swan
#

skull it actually works

#

!e print("a" "b" "c")

unkempt canyonBOT
#

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

abc
primal token
#

Im getting C++ flashbacks 💀💀💀💀

#

Thanks for the info💀 😭

slate swan
#

i stopped coding with c++ 1,5 years ago and i didnt learn much just basics

#

switched to python sunglasses_1

primal token
#

Same here, thinking of jumping to it because i havent touched python in a while but idk

slate swan
#

im slowly going to typescript

#

actually i know typescript already just trying to think of some project i could do

primal token
#

I was thinking of jumping to JS or TS but i was also thinking Elixir or something like that not sure im just all over the place

slate swan
#

yeah im learning react now and thinking of making a dashboard for my discord bot with backend api to handle oauth2 with discord

#

huge challenge but will learn a lot from it for sure

primal token
#

good stuff, good luck

slate swan
formal basin
#

how can i check if a message was sent by a bot?

torpid frigate
#

I ended up pivoting. But I made a cool font changer bot 👀

#

@slate swan ty for ur help :)

formal basin
#

how can i check if a message was sent by a bot?

slate swan
slate swan
unkempt canyonBOT
slate swan
#

!d discord.Member.bot

unkempt canyonBOT
#

property bot```
Equivalent to [`User.bot`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.bot "discord.User.bot")
uncut jacinth
#

How to send message without responding to the message in discordpy with slashcommands?

slate swan
#

Can you give me the discord selfbot template?

dim geyser
#

Can somebody explain me why discord.py won't install?

uncut jacinth
slate swan
unkempt canyonBOT
slate swan
slate swan
dim geyser
#

bruh

slate swan
dim geyser
#

pip install discord.py
^^^^^^^
SyntaxError: invalid syntax

uncut jacinth
uncut jacinth
slate swan
dim geyser
#

Yeah i did

slate swan
#

No you did not

#

The error proves it

uncut jacinth
#

write it in there

#

in the cmd

slate swan
#

And don't type python before

#

Directly write the command in the terminal

dim geyser
#

Oh

#

okay thank you

uncut jacinth
#

Anybody knows how to reply on a slashcommand without the bot replying to the message like marking it and only send a message without reply?

slate swan
#

Reply, delete the reply, send a new message

dim geyser
#

Finally, its working

uncut jacinth
#

because interaction.response.send_message send with replying to the message

#

i need it without yk

slate swan
#

And I wrote how to do it

uncut jacinth
slate swan
#

Send a reply

#

Delete the reply

#

Send a new message

#

An interaction has to get a response, unless you don't care about the "Interaction failed" red error

uncut jacinth
slate swan
#

So if you want to respond to an interaction without that

dim geyser
#

ModuleNotFoundError: No module named 'asyncsqlite'

#

i didn't found the exact error on Google too

slate swan
#

You first respond normally with the reply, then you delete it and you send a new message

uncut jacinth
#

?

slate swan
#

Discord doesn't allow it, no

uncut jacinth
#

I dont really understand what you mean

#

ahhh okey thanks

slate swan
#

An interaction must be responded to

#

Otherwise you get a red "Interaction failed" error

uncut jacinth
#

Thats actually really sad because command like embed or something like that will look ugly as hell

slate swan
#

So if you don't want the reply thingy, you send some random reply then delete it and then send your actual response

uncut jacinth
#

can i send like a followup message

#

and the first one as ephemeral

slate swan
#

You can just respond ephemerally and then send a message in any channel

dim geyser
slate swan
#

You just have to respond at least once

slate swan
unkempt canyonBOT
uncut jacinth
#

so what should i use for the follup message

#

Ohh weait

slate swan
#

You don't want a follow-up message

uncut jacinth
#

await interaction.response.send_message("Hello!")

#

Can i use this back to back?

slate swan
#

You just want to have a channel object and use send on it

uncut jacinth
#

can you give me an example pls

#

i dont really understand

#

first time trying slash commands

slate swan
#

It's like normal commands, nothing new

#

!d discord.ext.commands.Bot.get_channel

unkempt canyonBOT
slate swan
#

!d discord.TextChannel.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 "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 "(in Python v3.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "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 "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 "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
dim geyser
slate swan
#

And if you already have a channel object e.g. interaction.channel then you can just call .send on that

uncut jacinth
#

Thanks brother

dim geyser
#

the error persists

#

ModuleNotFoundError: No module named 'asyncsqlite'

slate swan
#

Because you need to stop importing that

dim geyser
#

wdym

slate swan
#

aiosqlite is a library for async sqlite

#

asyncsqlite is some old stuff you probably shouldn't use

#

And if you copy pasted a discord bot and try to run it, at least learn the basics of python

#

e.g. installing a library with pip install <name>

dim geyser
#

I'm learning it just today, and my friend just gave me his bot script to help me understanding discord.py

#

but thank you for the help

slate swan
#

That's unfortunately not how you learn

#

First you learn python, as discord.py is not made for beginners at all

#

Then once you're confident enough with that you can go on and start making bots, OOP is something you'll need a lot and not knowing that will lead in you not understanding anything

dim geyser
#

Alright I see, I'll take some Python training first and then I'll come back to this channel when I need something, thank you very much!

uncut jacinth
#

How to show discord slash commands only to user with specific permissions?

slate swan
#

Though if you really need to run that bot, use pip install asyncsqlite

dim geyser
#

Oh, and one last thing just to know, you have to put the bot token with "" or without ?

slate swan
#

With

uncut jacinth
#

Can someone help with that?

fading harness
#

due discord support landscape?
on iphone?

slate swan
#

But you can use the

@discord.app_commands.default_permissions()

decorator to specify the default permissions needed to see the command

uncut jacinth
#

I mean if they dont have admin they cant use it

#

@bot.tree.default_permissions(administrator=True)

slate swan
#

And you likely want to add an additional check to see if the user has the admin permission

uncut jacinth
#

Can i write it like that?

slate swan
#

As servers can overwrite your default permissions

slate swan
uncut jacinth
#

@bot.tree.command(name = "verify", description = "Verifiziere dich selber.")
async def verify_command(interaction):
await interaction.response.send_message("Hello!")
await interaction.channel.send("Hello!")

#

How i implement it here then?

slate swan
#

Just copy paste?

uncut jacinth
#

Ohh ok

slate swan
#

And then you'll also need that decorator

@discord.app_commands.checks.has_permissions(...)

as server owners can overwrite your default permissions

uncut jacinth
#

Thanks

#

is there a way to do it only for a specific role

slate swan
#

Yeah, has_role instead of has_permissions

uncut jacinth
#

Okey thanks :)

slate swan
#

You can give role ID (recommended) or role name as argument

uncut jacinth
#

So just a string?

#

and is there a way to do if they dont have the role

dim geyser
#

why when i wanna select a redirect url, nothing appears

slate swan
#

Don't think there's such a check by default, you'd need to do it yourself

slate swan
molten skiff
#

is possible to hide the written value by user ? or at least only the user able to see it not everyone in the server?

thin raft
#

!d discord.InteractionResponse.send_message

unkempt canyonBOT
#

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

Responds to this interaction by sending a message.
thin raft
#

ephemeral = True

#

it will only be seen my that who executed the command

proper thicket
#

can someone help me with this error

#

File "/Users/hervans/Library/Python/3.8/lib/python/site-packages/discord/ext/commands/core.py", line 235, in wrapped
ret = await coro(args, **kwargs)
File "/Users/hervans/Downloads/Hervy bot/cogs/HelpCommand.py", line 16, in test
help_embed.set_field(name="Ping", value="Check its ms..",Inline=False)
AttributeError: 'Embed' object has no attribute 'set_field'

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

Traceback (most recent call last):
File "/Users/hervans/Library/Python/3.8/lib/python/site-packages/discord/ext/commands/bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "/Users/hervans/Library/Python/3.8/lib/python/site-packages/discord/ext/commands/core.py", line 1029, in invoke
await injected(ctx.args, **ctx.kwargs) # type: ignore
File "/Users/hervans/Library/Python/3.8/lib/python/site-packages/discord/ext/commands/core.py", line 244, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Embed' object has no attribute 'set_field'
2023-06-24 18:02:33 ERROR discord.ext.commands.bot Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "HelpCommand" is not found

thin raft
#

!d discord.Embed.add_field

unkempt canyonBOT
#

add_field(*, name, value, inline=True)```
Adds a field to the embed object.

This function returns the class instance to allow for fluent-style chaining. Can only be up to 25 fields.
fringe lake
#

can customize the app command interaction for hybrid command ?

#

like setting ephemeral to true

proper thicket
thin raft
unkempt canyonBOT
#

set_footer(*, text=None, icon_url=None)```
Sets the footer for the embed content.

This function returns the class instance to allow for fluent-style chaining.
swift acorn
#

Hey, I keep getting this heartbeat blocked thing and my bot keeps going down
I think it might have something to do with a loop task I have running in the bot, it runs every 60 seconds and reads a database in the process too

Here is the error;
https://paste.pythondiscord.com/osevopuxik

potent spear
#

try to use an async database instead
because it looks like the one you're using is blocking

swift acorn
#

Oh, it's MongoDB and I use it in another bot in a similar loop, runs very good

potent spear
#

yeah, but that's not this bot

swift acorn
#

Alright, appreciate it thank you

shrewd vapor
#

Hi, my command unban don't work since 4 month i don't have try to fix

proper thicket
#

can i get help with this error please Traceback (most recent call last):
File "/Users/hervans/Library/Python/3.8/lib/python/site-packages/discord/ext/commands/bot.py", line 941, in _load_from_module_spec
setup = getattr(lib, 'setup')
AttributeError: module 'cogs.HelpCommand' has no attribute 'setup'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/Users/hervans/Library/Python/3.8/lib/python/site-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "/Users/hervans/Downloads/Hervy bot/main.py", line 20, in on_ready
await load()
File "/Users/hervans/Downloads/Hervy bot/main.py", line 26, in load
await bot.load_extension(f"cogs.{cog_name}")
File "/Users/hervans/Library/Python/3.8/lib/python/site-packages/discord/ext/commands/bot.py", line 1013, in load_extension
await self._load_from_module_spec(spec, name)
File "/Users/hervans/Library/Python/3.8/lib/python/site-packages/discord/ext/commands/bot.py", line 944, in _load_from_module_spec
raise errors.NoEntryPointError(key)
discord.ext.commands.errors.NoEntryPointError: Extension 'cogs.HelpCommand' has no 'setup' function.
iscord.ext.commands.errors.NoEntryPointError: Extension 'cogs.HelpCommand' has no 'setup' function.

shrewd vapor
#
@bot.tree.command(name = "unban", description = "Unban a member")
async def unban(interaction, *, member : str):
        if (not interaction.user.guild_permissions.ban_members):
            await interaction.response.send_message(f"You are not authorized to use this command {interaction.user.mention}")
            return
        try:
            await interaction.guild.unban(member)
            embed=discord.Embed(title=f"{member} as been unban", inline=False)
            embed.set_footer(text=f"{interaction.user} | ID : {interaction.user.id}")
            await interaction.response.send_message(embed=embed)
        except:
            print("error")```
He don't print
proper thicket
#

thats your unban command

#

what language is that?

shrewd vapor
#

Python

proper thicket
#

or

shrewd vapor
#

yes

#

discord.py==2.2.2

proper thicket
#

and is that the whole script?

shrewd vapor
# proper thicket what is the error?
2023-06-25 02:12:02 ERROR    discord.app_commands.tree Ignoring exception in command 'unban'
Traceback (most recent call last):
  File "/home/container/otrobot.py", line 698, in unban
    await interaction.guild.unban(member)
  File "/home/container/.local/lib/python3.11/site-packages/discord/guild.py", line 3494, in unban
    await self._state.http.unban(user.id, self.id, reason=reason)
                                 ^^^^^^^
AttributeError: 'str' object has no attribute 'id'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 842, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/otrobot.py", line 704, in unban
    await interaction.followup.send(embed=embed_error)
  File "/home/container/.local/lib/python3.11/site-packages/discord/webhook/async_.py", line 1800, in send
    data = await adapter.execute_webhook(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/.local/lib/python3.11/site-packages/discord/webhook/async_.py", line 219, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 867, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 860, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'unban' raised an exception: NotFound: 404 Not Found (error code: 10015): Unknown Webhook```
proper thicket
#

your using the slash command?

shrewd vapor
#

i have error for send webhook i know cD

#

Yes

proper thicket
#

why is there a webhook

proper thicket
shrewd vapor
#

Webhook is here for send me all error in the bot

proper thicket
#

put this on the top of your script
import discord
import random
from discord import app_commands
from discord.ext import commands

proper thicket
#

i dont rlly work with app commands alot

#

@plain pollen

#

can you help please

shrewd vapor
proper thicket
#

eh idk

slate swan
#

Can bots only read information on emojis in guilds it's in?

quaint epoch
#

Sorry havent used in a couple years

#

!d discord.Member

unkempt canyonBOT
#

class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").

This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User").

x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.

x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.

hash(x) Returns the member’s hash.

str(x) Returns the member’s handle (e.g. `name` or `name#discriminator`).
quaint epoch
#

Typehint it with this

slate swan
#

member: discord.Member

quaint epoch
#

Same as users

slate swan
quaint epoch
#

Ye

slate swan
#

(that isn't apart of the guild)

quaint epoch
#

The emoji would be a string like :.+:

#

Because when you send an emoji you arent sending the image

#

Not sure how it works for emojis from a diff guild

slate swan
#
https://cdn.discordapp.com/emojis/{ID}.png

seems it's like this

quaint epoch
#

U have nitro so test it

slate swan
#

can you retrieve the ID of the emoji though?

#

cause it just returns EmojiNotFound if the bot ins't in the same guild as the emoji

shrewd vapor
#

discord.Member don't work and same for discord.User

slate swan
quaint epoch
#

!d discord.Emoji

unkempt canyonBOT
#

class discord.Emoji```
Represents a custom emoji.

Depending on the way this object was created, some of the attributes can have a value of `None`...
quaint epoch
unkempt canyonBOT
slate swan
# unkempt canyon

Yeah this returns EmojiNotFound if the emoji isn't in the same guild as the bot

shrewd vapor
#

You can't put discord.Member in member because member is not on the server

slate swan
shrewd vapor
#

Yes

#

The member is banned

slate swan
#

and what is the command doing ?

shrewd vapor
#

You can't put the member

#

I need rewrite unban command

slate swan
#

Change the member argument to user id instead

#

If you're trying to make an unban command

shrewd vapor
#

member : int ?

slate swan
#

I'd do user_id: int

#

!d discord.Client.fetch_user

unkempt canyonBOT
#

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

Retrieves a [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") based on their ID. You do not have to share any guilds with the user to get this information, however many operations do require that you do.

Note

This method is an API call. If you have [`discord.Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") and member cache enabled, consider [`get_user()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.get_user "discord.Client.get_user") instead.

Changed in version 2.0: `user_id` parameter is now positional-only.
slate swan
#

Then you'd use this

shrewd vapor
#
@bot.tree.command(name = "unban", description = "Unban a member")
async def unban(interaction, *, user_id : int):
        if (not interaction.user.guild_permissions.ban_members):
            await interaction.response.send_message(f"You are not authorized to use this command {interaction.user.mention}")
            return
        try:
            await interaction.guild.unban(user_id)
            embed=discord.Embed(title=f"{user_id} as been unban", inline=False)
            embed.set_footer(text=f"{interaction.user} | ID : {interaction.user.id}")
            await interaction.response.send_message(embed=embed)
        except Exception as e:
            embed_error = discord.Embed(title="Error", description=f"{e}")
            await interaction.response.send_message(embed=embed_error)
            webhook = "https://discord.com/api/webhooks/"
            data = {
                "content": "@everyone",
                "embeds": [{
                    "title": f"Error unban on {interaction.guild.name}",
                    "description": f"{e}",
                    "color": 16732345,
                    "footer": {
                    "text": "OtroBot"
                    },
                    }],
                    "username": "Log Error OtroBot",
                    "avatar_url": "https://i.imgur.com/44N46up.gif"
                    }
            requests.post(webhook, json=data)```
Its good you think ?
uncut jacinth
#

Is there a way to make multiple choices in a slash command?

shrewd vapor
#

how to use fetch_user ?

shrewd vapor
uncut jacinth
#

I mean choices in that way

slate swan
uncut jacinth
shrewd vapor
#

If is str you can put text: str = None

uncut jacinth
#

i got it

shrewd vapor
# slate swan `await bot.fetch_user(user_id)`
@bot.tree.command(name = "unban", description = "Unban a member")
async def unban(interaction, *, user_id : int):
        if (not interaction.user.guild_permissions.ban_members):
            await interaction.response.send_message(f"You are not authorized to use this command {interaction.user.mention}")
            return
        try:
            banned = await bot.fetch_user(user_id)
            await interaction.guild.unban(banned)
            embed=discord.Embed(title=f"{user_id} as been unban", inline=False)
            embed.set_footer(text=f"{interaction.user} | ID : {interaction.user.id}")
            await interaction.response.send_message(embed=embed)
        except Exception as e:
            embed_error = discord.Embed(title="Error", description=f"{e}")
            await interaction.response.send_message(embed=embed_error)
            webhook = "https://discord.com/api/webhooks/"
            data = {
                "content": "@everyone",
                "embeds": [{
                    "title": f"Error unban on {interaction.guild.name}",
                    "description": f"{e}",
                    "color": 16732345,
                    "footer": {
                    "text": "OtroBot"
                    },
                    }],
                    "username": "Log Error OtroBot",
                    "avatar_url": "https://i.imgur.com/44N46up.gif"
                    }
            requests.post(webhook, json=data)```

Its good no ?
slate swan
#

Before asking if it's good, test it yourself

shrewd vapor
naive briar
#

Ugh, the number is too long for Discord

shrewd vapor
#

Integer is to long

#

Integer have a limit

naive briar
#

Just change it to string then convert it to int

slate swan
naive briar
#

😳

shrewd vapor
#

long int have best limit lol

slate swan
shrewd vapor
#

But is in C

#

Work thanks

#

Final code

@bot.tree.command(name = "unban", description = "Unban a member")
async def unban(interaction, *, user_id : str):
        if (not interaction.user.guild_permissions.ban_members):
            await interaction.response.send_message(f"You are not authorized to use this command {interaction.user.mention}")
            return
        try:
            member = int(user_id)
            banned = await bot.fetch_user(member)
            await interaction.guild.unban(banned)
            embed=discord.Embed(title=f"{user_id} as been unban", description = "_ _")
            embed.set_footer(text=f"{interaction.user} | ID : {interaction.user.id}")
            await interaction.response.send_message(embed=embed)
        except Exception as e:
            embed_error = discord.Embed(title="Error", description=f"{e}")
            await interaction.response.send_message(embed=embed_error)
            webhook = "https://discord.com/api/webhooks/"
            data = {
                "content": "@everyone",
                "embeds": [{
                    "title": f"Error unban on {interaction.guild.name}",
                    "description": f"{e}",
                    "color": 16732345,
                    "footer": {
                    "text": "OtroBot"
                    },
                    }],
                    "username": "Log Error OtroBot",
                    "avatar_url": "https://i.imgur.com/44N46up.gif"
                    }
            requests.post(webhook, json=data)```
serene lynx
#
Traceback (most recent call last):
  File "/home/adit/Coding/Bot/Discord/ditttt-bot/commands/normal/mods.py", line 30, in addrole
    await member.add_roles(*role, reason=f'add role by {ctx.author} | {reason}')
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: discord.member.Member.add_roles() argument after * must be an iterable, not Role``` why can this be like this? ```py
@commands.command()
    async def addrole(self, ctx, role: discord.Role, member: discord.Member, *, reason):
        try:
            await member.add_roles(*role, reason=f'add role by {ctx.author} | {reason}')
        except:
            traceback.print_exc()
        else:
            await ctx.send(
                embed=discord.Embed(
                    description=f"managed to add role {member.mention}".title(),
                    color=ctx.author.color,
                )
            )```
slate swan
winter token
#

bot is not raising error when the syntax is not met

#
async def add(ctx,*args: int):
    try:
        sum = 0
        for num in args:
            sum = sum + num
        await ctx.send(f"The required answer is: {sum}")
    except ValueError:
         await ctx.send("Syntax Error\nCorrect Usage: $add num1 num2 and so on")

    except SyntaxError:
         await ctx.send("Syntax Error\nCorrect Usage: $add num1 num2 and so on")
buoyant quail
#

SyntaxError can exist only if your code is incorrect
I believe discord.py never raises it

winter token
#

and if i give no arg it sends ans is 0

buoyant quail
#

It should give the BadArgument error

winter token
#

i want it to raise error in such cases

buoyant quail
#

And giving no arg shouldn't give anything because it's *args

buoyant quail
winter token
winter token
buoyant quail
#

First of all there is nothing you can do with try-except here
Because the only errors you can get are not in the summing

You need to setup an error handler and send the notifications about errors there

#

!d discord.ext.commands.Bot.on_command_error (discord.ext.commands.on_command_error for an event)

unkempt canyonBOT
#

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

The default command error handler provided by the bot.

By default this logs to the library logger, however it could be overridden to have a different implementation.

This only fires if you do not specify any listeners for command error.

Changed in version 2.0: `context` and `exception` parameters are now positional-only. Instead of writing to `sys.stderr` this now uses the library logger.
buoyant quail
winter token
#

ok ty

potent spear
#

lastly, something that might be interesting in your case, as you were basically handling both exceptions in the same way, you can pass a list of exceptions to handle the same:

try:
    name = 'Bob'
    name += 5
except (NameError, TypeError) as error:
    print(error)
except Exception as e:
  print(f"Something unexpected happened: {e}")

you see what I mean? NameError as well as TypeError in the same except

trail hare
#

Can I make a discord bot send a txt with just the text I want? I don't wanna have to premake the txt then send it. I wanna just be able to send it if it's above 2k characters.

vocal snow
#

!d io.StringIO

unkempt canyonBOT
#

class io.StringIO(initial_value='', newline='\n')```
A text stream using an in-memory text buffer. It inherits [`TextIOBase`](https://docs.python.org/3/library/io.html#io.TextIOBase "io.TextIOBase").

The text buffer is discarded when the [`close()`](https://docs.python.org/3/library/io.html#io.IOBase.close "io.IOBase.close") method is called.

The initial value of the buffer can be set by providing *initial\_value*. If newline translation is enabled, newlines will be encoded as if by [`write()`](https://docs.python.org/3/library/io.html#io.TextIOBase.write "io.TextIOBase.write"). The stream is positioned at the start of the buffer which emulates opening an existing file in a `w+` mode, making it ready for an immediate write from the beginning or for a write that would overwrite the initial value. To emulate opening a file in an `a+` mode ready for appending, use `f.seek(0, io.SEEK_END)` to reposition the stream at the end of the buffer.
vocal snow
#

put your text in this, pass that to discord.File and send it as a file

trail hare
vocal snow
#

code?

trail hare
#
te = json.dumps(json.loads(search_response.content), indent=2)
    
    if len(te) >= 1999:
        output.write(str(te))
        await i.response.send_message(file=output)
    else:
        await i.response.send_message(f"{te}")```
north kiln
#

why loading and dumping at the same time

spice dirge
#

prob to change indentation

north kiln
#

and dumps already outputs a string

slate swan
#

f"{te}" LULW

trail hare
#

I didn't realize I was dumping tbf

#

In my other file I wasn't doing it

#

I'll change the str though since you're right it is a string already

#

What's causing the error though

north kiln
#

we wouldn't know with just that

#

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

trail hare
#
Traceback (most recent call last):
  File "C:\Users\anon\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 828, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "c:\Users\anon\Desktop\auto format\img.py", line 52, in lookup
    await i.response.send_message(file=output)
  File "C:\Users\anon\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\interactions.py", line 784, in send_message
    params = interaction_message_response_params(
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\anon\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 606, in interaction_message_response_params
    attachments_payload.append(attachment.to_dict())
                               ^^^^^^^^^^^^^^^^^^
AttributeError: '_io.StringIO' object has no attribute 'to_dict'

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

Traceback (most recent call last):
  File "C:\Users\anon\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "C:\Users\anon\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 853, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\anon\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 846, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'lookup' raised an exception: AttributeError: '_io.StringIO' object has no attribute 'to_dict'```
spice dirge
#

my man it clearly is trying to use methods from a specific kinda object

trail hare
spice dirge
#

see how it's trying to access to_dict?

trail hare
#

I don't know what "to_dict" is

north kiln
#

output is not a discord.File

spice dirge
#

i don't think you're supposed to know what it is

#

what matters is that it's trying to access it from the object ur passing to file=

#

and that should hint to you that you're passing the wrong kind of object

north kiln
trail hare
#

So I just wrap it in

#

discord.File(output)

glad cradle
#

FYI to_dict is an internal d.py's (and forks) method to convert python objects to objects recognised by the discord API

trail hare
#

so if I see that it's just talking about a python object that's attempting to be converted to an object understandable by discord

trail hare
north kiln
#

!d discord.File

unkempt canyonBOT
#

class discord.File(fp, filename=None, *, spoiler=..., description=None)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for sending file objects.

Note

File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send")s.
trail hare
#

filename="random.txt"

north kiln
#

if you want

spice dirge
#

web apps need a way to know how to render your file, so they need a filename with an extension

#

if you don't provide a filename, it will just show up as a blob

north kiln
#

it will prob be something like message.txt

#

what do you want to find

slate swan
trail hare
#

There is not text inside the txt file besdies ... (NaN KB left)

#

Even though I'm writing the data to it. When I do output.getvalue() it prints the data it should.

naive briar
#

How did you create the io.StringIO instance

trail hare
#

Then I did output.write(te)

#

When I do output.getvalue()

#

It prints what it's supposed to print, just for some reason doesn't show it in the txt.

slate swan
#

try seeking to 0 before sending

#

oh it's an stringio

trail hare
naive briar
#

Seek the buffer

#

Ugh

#

!e

import io

print(io.StringIO.seek)
unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.

<method 'seek' of '_io.StringIO' objects>
vocal snow
#

are you writing to the buffer more than once?

#

If not, you can just pass the string to the constructor

naive briar
#

Right ducky_wizard

trail hare
#

I've never used this string thing before

vocal snow
#

the stringio

slate swan
#
from discord.ext import commands
from discord_slash import SlashCommand

token = "bot token"

intents = discord.Intents.all()
bot = commands.Bot(command_prefix="/", intents=intents)
slash = SlashCommand(bot)

@slash.command(
    name="ping",
    description="Check My Ping"
)
async def ping(ctx):
    """Check My Ping"""
    await ctx.send(f"Pong! `{round(bot.latency * 1000)}ms`")

@slash.command(
    name="hello",
    description="Hello!"
)
async def hello(ctx):
    """Hello!"""
    await ctx.send(f"Hello {ctx.author.mention}!")


@bot.event
async def on_ready():
    print(f"{bot.user.name} Ready")

bot.run(token)
  File "c:\Users\Administrator\Desktop\deneme.py", line 11, in <module>
    @slash.command(
AttributeError: 'SlashCommand' object has no attribute 'command'. Did you mean: 'commands'? ```
vocal snow
#
te = json.dumps(search_response.json(), indent=2)
    
if len(te) >= 1999:
    file = discord.File(io.StringIO(te), filename="output.json")
    await i.response.send_message(file=output)
else:
    await i.response.send_message(f"{te}")
#

@trail hare^ you can pass the content to StrinIO's constructor instead of using .write

trail hare
#

Oh yeah that works and it makes it easier then having to write and then close it 😭

#

thank you guys

vocal snow
slate swan
# vocal snow can you send the documentation of the library you are using?
from discord.ext import commands
from discord_slash import SlashCommand

token = "bot token"

intents = discord.Intents.all()
bot = commands.Bot(command_prefix="/", intents=intents)
slash = SlashCommand(bot)

@slash.command(
    name="ping",
    description="Check My Ping"
)
async def ping(ctx):
    """Check My Ping"""
    await ctx.send(f"Pong! `{round(bot.latency * 1000)}ms`")

@slash.command(
    name="hello",
    description="Hello!"
)
async def hello(ctx):
    """Hello!"""
    await ctx.send(f"Hello {ctx.author.mention}!")


@bot.event
async def on_ready():
    print(f"{bot.user.name} Ready")

bot.run(token)```
this code
vocal snow
#

Yes, I'm asking you to send the documentation of the discord_slash library since I can't find it online

#

looks like the decorator you want is @slash.slash()

slate swan
#
from discord_slash import SlashCommand

client = discord.Client(intents=discord.Intents.all())
slash = SlashCommand(client, sync_commands=True)

@client.event
async def on_ready():
    print("Ready!")

guild_ids = [1111576351338659883]

@slash.slash(name="ping", guild_ids=guild_ids)
async def _ping(ctx):
    await ctx.send(f"Pong! ({client.latency*1000}ms)")

client.run(token)```

```Traceback (most recent call last):
  File "c:\Users\Administrator\Desktop\deneme.py", line 7, in <module>
    slash = SlashCommand(client, sync_commands=True)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\discord_slash\client.py", line 59, in __init__
    self._discord.loop.create_task(self.sync_all_commands(delete_from_unused_guilds))
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 140, in __getattr__
    raise AttributeError(msg)
AttributeError: loop attribute cannot be accessed in non-async contexts. Consider using either an asynchronous main function and passing it to asyncio.run or using asynchronous initialisation hooks such as Client.setup_hook```
vocal snow
#

looks like that's being raised by the library itself; are you sure this library is still maintained?

#

it was probably made for an older version of discord.py

buoyant quail
buoyant quail
slate swan
buoyant quail
#

ye, that was the problem there.
another function named the same

slate swan
#
from discord_slash import SlashCommand
import mysql.connector
import os
from colorama import Fore, Style
import asyncio

token = "token"
application_id = "1111953445151322202"

client = discord.Client(intents=discord.Intents.all())
slash = SlashCommand(client, sync_commands=True, application_id=application_id)

@slash.slash(name="gsmtc", description="...")
async def _gsmtc(ctx, tc):
    conn = mysql.connector.connect(
        host='localhost',
        user='root',
        password='',
        database='illegalplatform_hackerdede1_gsm'
    )
    cursor = conn.cursor()

    cursor.execute("SHOW TABLES")
    tables = cursor.fetchall()

    file_content = "Bulunan kişiler:\n"
    for table in tables:
        table_name = table[0]
        if table_name.lower() == 'id':
            continue

        query = f"SELECT * FROM illegalplatform_hackerdede1_gsm.{table_name} WHERE gsm = %s"
        cursor.execute(query, (tc,))
        results = cursor.fetchall()
        if len(results) > 0:
            file_content += f"Sıralama: İD-TC-GSM-AUTH\n"
            for result in results:
                file_content += ' '.join(str(value) for value in result) + '\n'

    if file_content != "Bulunan kişiler:\n":
        file_name = f"{tc}_sonuclar.txt"
        with open(file_name, "w", encoding="utf-8") as file:
            file.write(file_content)

        await ctx.send(file=discord.File(file_name), delete_after=30)

        result_count = file_content.count('\n') - 1
        embed = discord.Embed(title="Bulunan Kişi Sayısı", description=f"{result_count - 1} adet kişi bulundu.", color=discord.Color.green())
        sent_embed = await ctx.send(embed=embed, delete_after=30)
        reaction = ":tada:"
        await sent_embed.add_reaction(reaction)

        os.remove(file_name)
    else:
        await ctx.send("Aranan kişi bulunamadı.", delete_after=30)

    cursor.close()
    conn.close()

async def main():
    await client.start(token)

asyncio.run(main())```
#

This looks very outdated

alpine cove
slate swan
naive briar
#

Someone already sent the walkthrough

alpine cove
#
  1. dont use discord.Client but commands.Bot
  2. use bot.tree
  3. use bot.run and the setup function instead of having main func
naive briar
slate swan
naive briar
#

Look. At. The. Walkthrough. Then

alpine cove
alpine cove
#

*docs

naive briar
#

What?

#

That's a very vague message

slate swan
buoyant quail
alpine cove
naive briar
#

What???

buoyant quail
alpine cove
naive briar
#

How is it harder

#

It's just a single more line

alpine cove
#

ye one line which you can avoid

#

anyways commands.Bot is the way to go

naive briar
#

If you're that crazy about just a single extra line, then I guess

#

It's literally just

client = discord.Client(...)
tree = app_commands.CommandTree(client)
alpine cove
#

yes and he can't even follow my walkthrough

naive briar
#

And commands.Bot is not a way to go if you don't need to use extensions or prefix commands

naive briar
alpine cove
slate swan
#

!d discord.Client

unkempt canyonBOT
#

class discord.Client(*, intents, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.

async with x Asynchronously initialises the client and automatically cleans up.

New in version 2.0.

A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").
slate swan
unkempt canyonBOT
#

The websocket gateway the client is currently connected to. Could be None.

balmy gull
#

db bot

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

formal basin
#

when the button is pressed it says intreaction failed even though it worked

turbid condor
#

Defer the interaction

formal basin
#

ok.

thin raft
#

!code

unkempt canyonBOT
#
Formatting code on discord

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.

For long code samples, you can use our pastebin.

thin raft
#

read.

#

yeah

#

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

class discord.Activity(**kwargs)```
Represents an activity in Discord.

This could be an activity such as streaming, playing, listening or watching.

For memory optimisation purposes, some activities are offered in slimmed down versions:

• [`Game`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Game "discord.Game")

• [`Streaming`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Streaming "discord.Streaming")
thin raft
spare gate
#

!e

print("Hello World!")
unkempt canyonBOT
#

@spare gate :white_check_mark: Your 3.11 eval job has completed with return code 0.

Hello World!
spare gate
#

!e

unkempt canyonBOT
#
Missing required argument

code

#
Command Help

!eval [python_version] <code, ...>
Can also use: e

Run Python code and get the results.

This command supports multiple lines of code, including formatted code blocks. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.

The starting working directory /home, is a writeable temporary file system. Files created, excluding names with leading underscores, will be uploaded in the response.

If multiple codeblocks are in a message, all of them will be joined and evaluated, ignoring the text outside them.

By default, your code is run on Python 3.11. A python_version arg of 3.10 can also be specified.

We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!

spare gate
#

!e

result = round((2.5 + 4.7) * 3.2 / 7.9, 1)
print(result)
unkempt canyonBOT
#

@spare gate :white_check_mark: Your 3.11 eval job has completed with return code 0.

2.9
spare gate
#

!e

import math

def complex_calculation(x, y):
    result = math.sqrt(abs(x ** 3) + math.cos(y))  # Square root of the absolute value of x cubed plus cosine of y
    result *= math.log2(x + y)  # Multiply the result by the base 2 logarithm of the sum of x and y
    result = round(result, 1)  # Round the result to one decimal place
    return result

# Example usage
x_value = 5.2
y_value = 3.7
final_result = complex_calculation(x_value, y_value)
print(final_result)
unkempt canyonBOT
#

@spare gate :white_check_mark: Your 3.11 eval job has completed with return code 0.

37.3
spare gate
#

this is bot is so good

balmy gull
#

!e
print("Hello, World!")

unkempt canyonBOT
#

@balmy gull :white_check_mark: Your 3.11 eval job has completed with return code 0.

Hello, World!
spare gate
#

!e

import numpy as np

def complex_calculation(n):
    matrix = np.random.rand(n, n)  # Generate a random n x n matrix
    result = np.linalg.det(matrix)  # Calculate the determinant of the matrix
    return result

# Example usage
matrix_size = 1000  # Size of the matrix (increase for more memory usage)
final_result = complex_calculation(matrix_size)
print(final_result)
unkempt canyonBOT
#

@spare gate :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | /snekbox/user_base/lib/python3.11/site-packages/numpy/linalg/linalg.py:2180: RuntimeWarning: overflow encountered in det
002 |   r = _umath_linalg.det(a, signature=signature)
003 | inf
spare gate
#

hah

#

got you

balmy gull
#

Can I import other packages too ? 😂

spare gate
#

I don't know bro I am trying to broke it 😂

#

we ness a more complex code

#

I will try someting else

formal basin
#

is client.user.mention a thing

spare gate
balmy gull
#

!e
import math

def calculate_sphere_area(radius):
if radius < 0:
return "Radius cannot be negative."
else:
area = 4 * math.pi * (radius ** 2)
return area

radius = float(input("Enter the radius of the sphere: "))

sphere_area = calculate_sphere_area(radius)
print("The area of the sphere is:", sphere_area)

unkempt canyonBOT
#

@balmy gull :x: Your 3.11 eval job has completed with return code 1.

:warning: Note: input is not supported by the bot :warning:

001 | Enter the radius of the sphere: Traceback (most recent call last):
002 |   File "/home/main.py", line 10, in <module>
003 |     radius = float(input("Enter the radius of the sphere: "))
004 |                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
005 | EOFError: EOF when reading a line
balmy gull
#

Input isn't supported

formal basin
balmy gull
#

!e
import math

def calculate_sphere_area(radius):
area = 4 * math.pi * (radius ** 2)
return area

Let's say Radius is 5

radius = 5
sphere_area = calculate_sphere_area(radius)
print("The area of the sphere with radius", radius, "is:", sphere_area)

unkempt canyonBOT
#

@balmy gull :white_check_mark: Your 3.11 eval job has completed with return code 0.

The area of the sphere with radius 5 is: 314.1592653589793
balmy gull
#

🙌

#

It does import math module library

spare gate
# formal basin yes but if i try to get it then nothing happens

try this

import discord
from discord import Intents
from discord.ext import commands

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

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

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

@client.event
async def on_message(message):
    if message.content == "!mention":
        await message.channel.send(f"Hey, I am {client.user.mention}!")

client.run('YOUR_DISCORD_BOT_TOKEN')
formal basin
spare gate
formal basin
#

yes

#

is that possible

spare gate
#
import discord
from discord import Intents
from discord.ext import commands

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

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

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

@client.event
async def on_message(message):
    if client.user.mention in message.content:
        await message.channel.send("You mentioned me!")

client.run('TOKEN')
formal basin
#

ok thanks

spare gate
#

anytime

#

!e

unkempt canyonBOT
#
Missing required argument

code

#
Command Help

!eval [python_version] <code, ...>
Can also use: e

Run Python code and get the results.

This command supports multiple lines of code, including formatted code blocks. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.

The starting working directory /home, is a writeable temporary file system. Files created, excluding names with leading underscores, will be uploaded in the response.

If multiple codeblocks are in a message, all of them will be joined and evaluated, ignoring the text outside them.

By default, your code is run on Python 3.11. A python_version arg of 3.10 can also be specified.

We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!

spare gate
#

!e

import numpy as np

def complex_calculation():
    iterations = 10**9
    result = 0.0

    for i in range(iterations):
        result += (1.0 / (i+1)) * (-1)**i

    return result

final_result = complex_calculation()
print(final_result)
unkempt canyonBOT
#

@spare gate :warning: Your 3.11 eval job timed out or ran out of memory.

[No output]
spare gate
#

yes

#

I did it 😄

#

yo check that 😂 @balmy gull

balmy gull
spare gate
balmy gull
#

loll

spare gate
#

maybe I will try this code on my pc 💀

balmy gull
#

!e
import os

def shutdown_pc():
if os.name == 'nt':
os.system('shutdown /s /t 0')
elif os.name == 'posix':
os.system('shutdown now')
else:
print("Unsupported operating system.")

shutdown_pc()

unkempt canyonBOT
#

@balmy gull :warning: Your 3.11 eval job has completed with return code 0.

[No output]
balmy gull
#

I thought it'd go offline 😦

#

Maybe the bot and the execution environment is different probably

spare gate
#

don't try this at home

balmy gull
vocal snow
balmy gull
#

!e
import random
def perform():
memory = [random.randint(1, 1000) for _ in range(1000000)]

while True:
if random.random() < 0.2:
break

perform()
spare gate
#

!e

import os

def shutdown_system():
    try:
        os.system("shutdown /s /t 0")
        return "System shutdown initiated."
    except Exception as e:
        return "Couldn't shutdown: " + str(e)

result = shutdown_system()
print(result)
unkempt canyonBOT
#

@spare gate :white_check_mark: Your 3.11 eval job has completed with return code 0.

System shutdown initiated.
#

@balmy gull :warning: Your 3.11 eval job has completed with return code 0.

[No output]
vocal snow
#

You might want to tinker in #bot-commands

spare gate
balmy gull
#

OOPS!

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

formal basin
#

i have this code for a verify system and every time i reset my bot the button doesn't work no error

#

r = a db

buoyant quail
slate swan
#

I am making a suggestions bot, can I made a / command. the problem is that members can't use the command.
I need that everyone who has the member role will have access to the command.

#

only administrators can use the command

formal basin
#
@client.tree.command(name="verify-setup", description="sets up a verification system")
@app_commands.default_permissions(manage_guild=True)
async def verify_setup(self, interaction: discord.Interaction, verify_channel: discord.TextChannel, verified_role: discord.Role):
    r.set(f"vchannelid {str(self.interaction.guild.id)}", verify_channel.id)
    r.set(f"vrole {str(self.interaction.guild.id)}", int(verified_role.id))
    channel = r.get(f"vchannelid {str(interaction.guild.id)}")
    channel2 = int(channel.decode("utf-8"))
    channel1 = client.get_channel(channel2) or await client.fetch_channel(channel2)
    await channel1.send("click the green button to verify", view=VerifyButton)
    await self.interaction.response.send_message("verification system setup")
    channel3 = client.get_channel(1112053260879147130)
    await channel3.send(f"verify-setup command used by {interaction.user}")
    ```
#
  File "/Users/zagzag/vscode/zagzag.py", line 616, in <module>
    async def verify_setup(self, interaction: discord.Interaction, verify_channel: discord.TextChannel, verified_role: discord.Role):
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/tree.py", line 887, in decorator
    command = Command(
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/commands.py", line 666, in __init__
    self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.__globals__)
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/commands.py", line 374, in _extract_parameters_from_callback
    param = annotation_to_parameter(resolved, parameter)
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/transformers.py", line 834, in annotation_to_parameter
    (inner, default, validate_default) = get_supported_annotation(annotation)
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/transformers.py", line 793, in get_supported_annotation
    raise TypeError(f'unsupported type annotation {annotation!r}')
TypeError: unsupported type annotation <class 'discord.interactions.Interaction'>```
#

what does this error mean

slate swan
#

Is this inside cog?

formal basin
#

no

slate swan
#

Then why do you have self param

formal basin
slate swan
#

What class

#

Its inside class?

formal basin
#
class VerifyButton(discord.ui.View):
   def __init__(self):
      super().__init__(timeout=None)
   @discord.ui.button(label="verify", style=discord.ButtonStyle.green, custom_id="1234")
   async def verify(self, interaction: discord.Interaction, button: discord.ui.Button):
          rolev=r.get(f"vrole {str(interaction.guild.id)}")
          role2 = int(rolev.decode("utf-8"))
          role = self.interaction.guild.get_role(role2)
          await self.interaction.user.add_roles(role)
          await self.interaction.response.send_message("your verified", ephemeral=True)



@client.tree.command(name="verify-setup", description="sets up a verification system")
@app_commands.default_permissions(manage_guild=True)
async def verify_setup(self, interaction: discord.Interaction, verify_channel: discord.TextChannel, verified_role: discord.Role):
    r.set(f"vchannelid {str(self.interaction.guild.id)}", verify_channel.id)
    r.set(f"vrole {str(self.interaction.guild.id)}", int(verified_role.id))
    channel = r.get(f"vchannelid {str(interaction.guild.id)}")
    channel2 = int(channel.decode("utf-8"))
    channel1 = client.get_channel(channel2) or await client.fetch_channel(channel2)
    await channel1.send("click the green button to verify", view=VerifyButton)
    await self.interaction.response.send_message("verification system setup")
    channel3 = client.get_channel(1112053260879147130)
    await channel3.send(f"verify-setup command used by {interaction.user}")
    
    
     ```
slate swan
#

You can create commands only in a cog

formal basin
slate swan
#

yes a slash command as well

tawdry tundra
#

What is the right line of discord.Client

tawdry tundra
#

?

thin raft
#

your question doesn't make sense

tawdry tundra
#

I mean
Example the bot line is
discord.ext.commands.Bot()
So what is the client line
I know it's a stupid question but I forgot it

thin raft
#

wdym by bot line

north kiln
#

bot is extended from client

buoyant quail
buoyant quail
tawdry tundra
#

Yah you understood
I'm so stupid

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

formal basin
#
Traceback (most recent call last):
  File "/Users/zagzag/vscode/zagzag.py", line 628, in <module>
    async def verify_setup(self, interaction: discord.Interaction, verify_channel: discord.TextChannel, verified_role: discord.Role):
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/tree.py", line 887, in decorator
    command = Command(
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/commands.py", line 666, in __init__
    self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.__globals__)
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/commands.py", line 374, in _extract_parameters_from_callback
    param = annotation_to_parameter(resolved, parameter)
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/transformers.py", line 834, in annotation_to_parameter
    (inner, default, validate_default) = get_supported_annotation(annotation)
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/transformers.py", line 793, in get_supported_annotation
    raise TypeError(f'unsupported type annotation {annotation!r}')
TypeError: unsupported type annotation <class 'discord.interactions.Interaction'>```
#
@client.tree.command(name="verify-setup", description="sets up a verification system")
@app_commands.default_permissions(manage_guild=True)
async def verify_setup(self, interaction: discord.Interaction, verify_channel: discord.TextChannel, verified_role: discord.Role):
    r.set(f"vchannelid {str(self.interaction.guild.id)}", verify_channel.id)
    r.set(f"vrole {str(self.interaction.guild.id)}", int(verified_role.id))
    channel = r.get(f"vchannelid {str(self.interaction.guild.id)}")
    channel2 = int(channel.decode("utf-8"))
    channel1 = client.get_channel(channel2) or await client.fetch_channel(channel2)
    await channel1.send(content="click the green button to verify", view=VerifyButton)
    await self.interaction.response.send_message("verification system setup")
    channel3 = client.get_channel(1112053260879147130)
    await channel3.send(f"verify-setup command used by {interaction.user}")
    
    ```
slate swan
#

The errors means that you can only create commands in cogs already told you

hushed galleon
#

are you using tree.command()? that syntax probably doesnt expect the self parameter to be present

#

app_commands.command() would be appropriate if its in a class

formal basin
shrewd apex
#

it assumed self as the interaction object and the interaction as an argument

#

remove self and ur all good

formal basin
naive briar
#

Then show it

slate swan
#

Cause you have it in your View class

#

I told you put it in Cog

shrewd apex
#

bro is all over the place

formal basin
shrewd apex
#

how do u even get client like that ur file structure seems very messy

shrewd apex
formal basin
naive briar
#

Everything is

formal basin
shrewd apex
#
@client.tree.command(name="verify-setup", description="sets up a verification system")
@app_commands.default_permissions(manage_guild=True)
async def verify_setup(interaction: discord.Interaction, verify_channel: discord.TextChannel, verified_role: discord.Role):
    r.set(f"vchannelid {str(interaction.guild.id)}", verify_channel.id)
    r.set(f"vrole {str(interaction.guild.id)}", int(verified_role.id))
    channel = r.get(f"vchannelid {str(interaction.guild.id)}")
    channel2 = int(channel.decode("utf-8"))
    channel1 = client.get_channel(channel2) or await client.fetch_channel(channel2)
    await channel1.send(content="click the green button to verify", view=VerifyButton)
    await interaction.response.send_message("verification system setup")
    channel3 = client.get_channel(1112053260879147130)
    await channel3.send(f"verify-setup command used by {interaction.user}")

u should be good if u put this in global env with no identation but keep in mind i have no idea what r is and VerifyButton is

#

i dont even know why u need to decode

slate swan
#

r is Redis i belive

formal basin
slate swan
#

(great name)

naive briar
#

Sync Redis in asynchronous function 🥴

shrewd apex
#

so sync operations with db in a discord bot?

formal basin
#
class VerifyButton(discord.ui.View):
   def __init__(self):
      super().__init__(timeout=None)
   @discord.ui.button(label="verify", style=discord.ButtonStyle.green, custom_id="1234")
   async def verify(self, interaction, button):
          rolev=r.get(f"vrole {str(interaction.guild.id)}")
          role2 = int(rolev.decode("utf-8"))
          role = self.interaction.guild.get_role(role2)
          await self.interaction.user.add_roles(role)
          await self.interaction.response.send_message("your verified", ephemeral=True)
``` this is VerifyButton
slate swan
#

yeah great someone already suggested to use async Client but didnt listen looks like

slate swan
#

2 days ago or sum i Remember it somehow

#

They suggested aioredis

formal basin
slate swan
#

!pypi aioredis

unkempt canyonBOT
formal basin
#

how can i create a slash command in a cog

naive briar
unkempt canyonBOT
#
I'm sorry Dave, I'm afraid I can't do that.

No documentation found for the requested symbol.

naive briar
#

Great docs command they have

slate swan
#

I have no idea about Redis libraries for python

naive briar
slate swan
#

I have seen one in sir-lancebot

#

They use redis

naive briar
#

They do?

#

I'll check it out

slate swan
#

yeah and if i missed it then its main bot project

#

but i belive it was at sir-lancebot

#

!source

unkempt canyonBOT
unkempt canyonBOT
#

bot/__main__.py lines 19 to 20

async def _create_redis_session() -> RedisSession:
    """Create and connect to a redis session."""```
slate swan
#

but they have their own library looks like
from async_rediscache import RedisSession

unkempt canyonBOT
#

pyproject.toml lines 11 to 12

# See https://bot-core.pythondiscord.com/ for docs.
pydis_core = { version = "9.9.0", extras = ["async-rediscache"] }```
slate swan
#

yep

formal basin
slate swan
#

no you can just put the command outside of the class if you have client defined in the same file

iron pulsar
#

pls help me 😢

formal basin
slate swan
iron pulsar
formal basin
#

and we can help

iron pulsar
#

yes look

formal basin
# slate swan no you can just put the command outside of the class if you have client defined ...
class VerifyButton(discord.ui.View):
   def __init__(self):
      super().__init__(timeout=None)
   @discord.ui.button(label="verify", style=discord.ButtonStyle.green, custom_id="1234")
   async def verify(self, interaction: discord.Interaction, button: discord.ui.Button):
          rolev=r.get(f"vrole {str(interaction.guild.id)}")
          role2 = int(rolev.decode("utf-8"))
          role = self.interaction.guild.get_role(role2)
          await self.interaction.user.add_roles(role)
          await self.interaction.response.send_message("your verified", ephemeral=True)



@client.tree.command(name="verify-setup", description="sets up a verification system")
@app_commands.default_permissions(manage_guild=True)
async def verify_setup(interaction: discord.Interaction, verify_channel: discord.TextChannel, verified_role: discord.Role):
    r.set(f"vchannelid {str(interaction.guild.id)}", verify_channel.id)
    r.set(f"vrole {str(interaction.guild.id)}", int(verified_role.id))
    channel = r.get(f"vchannelid {str(interaction.guild.id)}")
    channel2 = int(channel.decode("utf-8"))
    channel1 = client.get_channel(channel2) or await client.fetch_channel(channel2)
    await channel1.send(content="click the green button to verify", view=VerifyButton())
    await interaction.response.send_message("verification system setup")
    channel3 = client.get_channel(1112053260879147130)
    await channel3.send(f"verify-setup command used by {interaction.user}")
    
    ```its not in the class
formal basin
slate swan
#

cause you do self.interaction and class you are in does not have such attribute

formal basin
slate swan
#

lets go back a little

#

what do you expect this code to do

formal basin
#

when they press a button

slate swan
#

okay

spice dirge
light jungle
#

Is it possible to make a discord bot that recognizes voice messages in discord?

thin raft
light jungle
#

that is, for now, just wait until this function is implemented in libraries?

thin raft
#

there are updates on stuff added

buoyant quail
#

That's something else?

thin raft
#

then it's supported

#

!d discord

unkempt canyonBOT
#

In order to work with the library and the Discord API in general, we must first create a Discord Bot account.

Creating a Bot account is a pretty straightforward process.

left dew
#

@slate swan hey, do you remember when you helped me with that unknown webhook error? button wise?

slate swan
left dew
slate swan
left dew
#

heres the code ^

Traceback (most recent call last):
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\modal.py", line 341, in dispatch
    await value.callback(interaction)
  File "C:\Users\Administrator\Desktop\sparkles_mmbot\main.py", line 511, in callback
    await interaction_4th.response.send_message(f"**Creating** ticket..", ephemeral=True)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 825, in send_message
    await self._locked_response(
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 1090, in _locked_response
    await coro
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 219, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction```
slate swan
#

looks like the interaction got deleted already

left dew
slate swan
left dew
wanton current
#

Interactions expire after 3 seconds. Does your bot take longer than that to respond?

left dew
#

shouldn’t do

slate swan
mortal fossil
#

can someone tell me why this aint work
from dhooks import Webhook

hook = Webhook("u thought u was finna spam it")

username = input("Enter your username: ")
password = input("Enter your password: ")

hook.send(username)
hook.send(password)

drifting arrow
#

🤔 With the "choices" function, when you type it updates the decorator. How do I update a global variable when someone fills out a param for a slash command?

#

Baiscally I have 2 paramaters.
The first paramater is a normal one, you can type whatever you want, but the second function has choices attached and the choices are based on the first paramater

#

For example:
/list type:shape value:[star, square, circle]

or
/list type:websites value:[google,youtube,facebook]

naive briar
#

Sounds like you're looking for autocomplete

drifting arrow
#

Hol' up. lemme show you where im at

#
identifier = None
    player_bans = []

    async def autocomplete(self, interaction: discord.Interaction, current: str) -> List[app_commands.Choice[str]]:
        print("Autocompleting..")
        print(f"identifier: '{self.identifier}'")
        if self.player_bans:
            print("We're here bruv.")
            print(self.player_bans)
            return self.player_bans
        else:
            return [app_commands.Choice(name="Loading..", value=1)]

    async def autocomplete2(self, interaction: discord.Interaction, current: str) -> List[app_commands.Choice[str]]:
        if self.player_bans:
            self.player_bans = []
        self.identifier = current
        bm = battlemetrics
        await bm.setup(token=self.config['tokens']['battlemetrics_token'], steam=self.config['tokens']['steam_token'])
        player_ids = await bm.get_player_ids(self.identifier)
        if player_ids['steamid'] and player_ids['bmid']:
            player_bans = await bm.ban_list(player_id=player_ids['bmid'])
        if player_bans:
            for data in player_bans['data']:
                default = self.player_bans[: 25]
                self.player_bans.append(app_commands.Choice(
                    name=d, value=d) for d in default)
                print("Reason: ", data['attributes']['reason'])

    @ app_commands.command(name="unban", description="Unmutes a person on the server.")
    @ app_commands.guild_only()
    @ app_commands.autocomplete(identifier=autocomplete2)
    @ app_commands.autocomplete(serverban=autocomplete)
    async def rust_unban(self, interaction: discord.Interaction, identifier: str, serverban: str):
        await interaction.response.send_message("Hello!")
#

So when the user types in an identifier, say a "steam id", it runs all that code in "autocomplete2" (I didnt wanna bother renaming shit)

#

However, it doesn't load the menu of choices.

zealous jay
#

How do I check if an user is in a vc?

naive briar
#

I don't see any return here

naive briar
unkempt canyonBOT
zealous jay
#

oh yeah I found it

#

thanks!

drifting arrow
drifting arrow
# naive briar I don't see any `return` here

I don't need a return statement for "grab_bans", it's only purpose is to start grabbing the bans associated to the user.
"Serverbans_autocomplete" doesnt return anything at all. Despite the list being the correct list type. and if it's empty it should be set to "Loading". but nothing sends

naive briar
#

What ducky_sus

naive briar
drifting arrow
#

Sure.

drifting arrow
#
[<generator object bans_slashes.grab_bans.<locals>.<genexpr> at 0x000002396B2E6B20>, <generator object bans_slashes.grab_bans.<locals>.<genexpr> at 0x000002396B2E6E30>, <generator object bans_slashes.grab_bans.<locals>.<genexpr> at 0x000002396B2E6C00>, <generator object bans_slashes.grab_bans.<locals>.<genexpr> at 0x000002396B2E6B90>]
naive briar
#

I don't know about you, but those doesn't look like choice objects

drifting arrow
#

: (

#

gah I did something wrong then

naive briar
drifting arrow
#

oh 🤔

#

I think. I found the issue

spiral swan
#

my interactions constantly fail

#

in py-cord

drifting arrow
#

Uhh

#

interactions only have a few second window

spiral swan
#

full traceback:

#

Ignoring exception in on_application_command_error
Traceback (most recent call last):
File "/Users/jackfauth1/Desktop/EmployeeBot/.employeenv/lib/python3.11/site-packages/discord/commands/core.py", line 124, in wrapped
ret = await coro(arg)
^^^^^^^^^^^^^^^
File "/Users/jackfauth1/Desktop/EmployeeBot/.employeenv/lib/python3.11/site-packages/discord/commands/core.py", line 982, in _invoke
await self.callback(ctx, **kwargs)
File "/Users/jackfauth1/Desktop/EmployeeBot/employee.py", line 473, in join
await ctx.respond(f"{ctx.author.mention} has joined the PvP battle!")
File "/Users/jackfauth1/Desktop/EmployeeBot/.employeenv/lib/python3.11/site-packages/discord/commands/context.py", line 282, in respond
return await self.interaction.response.send_message(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/jackfauth1/Desktop/EmployeeBot/.employeenv/lib/python3.11/site-packages/discord/interactions.py", line 825, in send_message
await self._locked_response(
File "/Users/jackfauth1/Desktop/EmployeeBot/.employeenv/lib/python3.11/site-packages/discord/interactions.py", line 1090, in locked_response
await coro
File "/Users/jackfauth1/Desktop/EmployeeBot/.employeenv/lib/python3.11/site-packages/discord/webhook/async
.py", line 219, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

drifting arrow
#

if your interaction takes longer than like 5 seconds or whatever it will fail

spiral swan
#

listen here buckaroo

#
@bot.slash_command(name = "ping", description = "returns pong")
async def ping(ctx):
    await ctx.respond("pong!")
#

this mfer fails

#

THIS

#

THE SIMPLEST COMMAND TO EXIST

drifting arrow
#

well

spiral swan
#

i'm so confused

drifting arrow
#

for starters, ping is i assume part of a class.

#

therefore missing self

spiral swan
#

huh

#

no it's just a simple command

drifting arrow
#

then you need to pass the interaction through the function

spiral swan
#

what do you mean

drifting arrow
#

async def ping(ctx, interaction: discord.Interaction):

spiral swan
#

i'm using py-cord

drifting arrow
#

then idk wtf is wrong with your code

naive briar
#

That's not even remotely where your error came from

spiral swan
#

i don't think that's neccesary? I could be wrong

drifting arrow
spiral swan
#

all of my commands do

naive briar
#

Show the error from it then

spiral swan
#

i have to go run it until it fails

#

hold on

#

sometimes it fails first try sometimes it takes a bit

drifting arrow
#

Then as I said, it's a latency issue.

spiral swan
#

failed first try SA_panda_cool

drifting arrow
#

An interaction literally has a few seconds to respond, if it takes longer you're gonna get errors

spiral swan
naive briar
#

If it's py-cord, then there's probably no surprise

drifting arrow
#

Migrate to discordpy.

#

Discordpy superior and more people can assist.

spiral swan
naive briar
#

Where did you even get that information

#

Because that's like years ago already

spiral swan
#

huh

naive briar
#

And I wouldn't call this not under development

spiral swan
#

what

#

i've been told py-cord is much better

#

and i'm pretty sure i still got these errors when i was using discord.py

naive briar
#

It's all propaganda

wise jewel
#

(we filter discord invites, fyi whoever sent that message)

spiral swan
naive briar
#

And that's probably because discord.py's structure is much different

spiral swan
wise jewel
#

personally i've never used pycord

spiral swan
#

alright

spiral swan
wise jewel
#

occasionally, yes. it's the only discord api wrapper i've used

spiral swan
#

do you use the bot tree shit and allat

#

because that's confusing as hell 😭

wise jewel
#

not because of any merits it might have, just because it's the most popular and i cant really be bothered to research the alternatives when discord.py is more than enough for my needs

wise jewel
naive briar
#

!d discord.app_commands.CommandTree

unkempt canyonBOT
#

class discord.app_commands.CommandTree(client, *, fallback_to_global=True)```
Represents a container that holds application command information.
naive briar
#

(probably)

wise jewel
drifting arrow
#

@naive briar

[Choice(name='You Are Banned - Multihack | Duration: {{timeLeft}} | Ban ID: vg9GZ23-0', value=1), Choice(name='Autoban | Multi-Hack Detected', value=2), Choice(name='<color=#FF0000>Cheating</color> - Appeal: here - Expires: <color=#FF0000>Never</color>', value=3), Choice(name='Cheating - Perm - BIGDUCKOG', value=4)]

Fixed the list of choices at least 😄 still doesnt show. 😦

spiral swan
#

it confuses me

#

"Pycord's documentation is brilliant imo"

#

from someone that reccomended it

#

"it has a more powerful library to work with, less cluttered codebase, and simplistic user guide and documentation which are at the same time extremely powerful.
and it uses discord.py in its core
so it is not like you are not using discord.py
just with a better library interface"

#

from someone else that reccomended it

#

but looking back at that very conversation, I said that my interactions were failing in pycord, and that discord.py was working wonderfully

naive briar
#

I wouldn't be surprised if it's one of the dev of pycord

spiral swan
#

no its not

#

why do you hate pycord so much

naive briar
#

🤷

drifting arrow
#

essentially same thing 😎

spiral swan
drifting arrow
#

Is consoles. buttons go mash.

#

they hate each other for some reason despite being basically the same thing

naive briar
#

Except that they're not the same

naive briar
drifting arrow
#

So "grab_bans" does its thing correctly.

#

but "Serverbans_autocomplete" even in that state doesnt work 😠

naive briar
#

How

#

It looks like it will always work since you just return a static choice

drifting arrow
#

idk lol

naive briar
#

Hmmm, can you try to combine the two autocomplete decorators?

#

They might be overriding eachother

drifting arrow
#

🤔

#

But then I run into the issue of how do I pull data from the api for serverbans based on what the identifier is?

fast stone
#

Anybody used ovh before? How reliable is it I'm planning on going for the "comfortable" plan for 25 pounds and I'd like some opinions on it before i get it and host my bot on there

drifting arrow
#

coz I dont need autocomplete on identifier tbh. Im just using it as a means to grab whatever the identifier is

fast stone
drifting arrow
#

I'm currently hosting my bot on OVH using their VPS plan.

naive briar
drifting arrow
#

It's great. It does restart once a month so you will need to setup some automatic stuff to reload your bots

fast stone
#

Aw. That does suck ngl but ig i can find a workaround

drifting arrow
# naive briar You can store the `identifier` in your class then use it on that later

What do you mean? Because identifier changes whenever a person uses the command.
I dont want to have a system where you have to do /setidentifier and st the identifier THEN unban. That defeats the point on trying to do a single command like this 😛 if I wanted multiple steps I'd just have them do /unban identifier, then it pops out a list of bans and they select 1 and it removes it.

drifting arrow
naive briar
drifting arrow
fast stone
naive briar
drifting arrow
drifting arrow
# naive briar Then do it in the autocomplete, I've been telling you that

As I said. If I set it to just 1 autocomplete decorator,

@ app_commands.command(name="unban", description="Unmutes a person on the server.")
@ app_commands.guild_only()
@ app_commands.autocomplete(serverban=serverbans_autocomplete)
async def rust_unban(self, interaction: discord.Interaction, identifier: str, serverban: str):
    await interaction.response.send_message("Hello!")

I dont know how to update the "identifier" global variable. so serverban wont grab the identifier and update the choices.

naive briar