#discord-bots

1 messages · Page 261 of 1

buoyant crescent
#

ok

sharp whale
silk wasp
#

ok in main.py
remove the setup_hook()

and in the def load(), first line add a

await bot.wait_until_ready()
hasty pike
#

@sharp whale https://youtu.be/hMuQJnFNm78 refer this until I'm busy

Welcome to #codekar , In this latest video, Learn about implementing discord modals or forms in your discord.py bot.

Discord Server [Must Join] - https://discord.gg/e3dXAmqqHf

Discord.py Example Reference:
https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Modal

Homework Reference: https://github.com/quotientbot/Quot...

▶ Play video
silk wasp
#

first make sure ur bot can run once before running ur cogs

buoyant crescent
silk wasp
#

ya that what confuses me

hasty pike
#

either use setup_hook() or def load()

#

Both will give you same result

silk wasp
#

or still twice

buoyant crescent
silk wasp
#

ohhhhh

buoyant crescent
silk wasp
#

so basically u saying when u do like example: !aide
it output twice?

silk wasp
#

.-.

buoyant crescent
#

;-;

silk wasp
#

sorry miscommunication

sharp whale
buoyant crescent
slate swan
#

what library are you using

sharp whale
#

i did import it

slate swan
#

yeah so you need to import this class

slate swan
#

!d discord.TextStyle

unkempt canyonBOT
#

class discord.TextStyle```
Represents the style of the text box component.

New in version 2.0.
hasty pike
#

I don't think this is mandatory works with or without

sharp whale
#

discord.ui

#

works

slate swan
unkempt canyonBOT
#
Huh? No.

No documentation found for the requested symbol.

slate swan
#

hm

silk wasp
#

When you create an instance of MyBot, it automatically runs the bot using bot.run(), so there's no need to call it again.

hasty pike
slate swan
buoyant quail
#

It is TextInput i believe

slate swan
slate swan
hasty pike
silk wasp
#

but then i dont really like using class super when im dealing with main.py so i usually dont add that in

buoyant quail
slate swan
hasty pike
#

@sharp whale code needed

sharp whale
sharp whale
# hasty pike <@707943196927197196> code needed
import discord
from discord.ext import commands
from discord import ui
from config import suggestion_channel
from config import TOKEN



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

@bot.event
async def on_ready():
  print(f"bot is ready and logged on: {bot.user.name}")




# COMMANDS


class suggest(ui.Modal, title="Suggestions"):
  type = ui.InputText(label="Type of suggestion")
  suggestionbox = ui.InputText(label="Enter Your Suggestion", style=TextStyle.paragraph)
  async def on_submit(self, interaction: discord.Interaction):
    await interaction.response.send_message(f'Thanks for your response, {self.name}!', ephemeral=True)
    async def on_submit(self, interaction):
      await suggestion_channel.send(f"The type is {self.type}")




@bot.command(name="test", description="test command")
async def test(ctx):
  button1= discord.ui.Button(label="Click me", style=discord.ButtonStyle.primary, emoji="⭐")
  view = discord.ui.View()
  view.add_item(button1)
  await ctx.send("testing", view=view)



#START UP




bot.run(TOKEN)```
slate swan
# sharp whale TextInput

suggestionbox = ui.InputText(label="Enter Your Suggestion", style=TextStyle.paragraph) literally your code

#

there is InputText

slate swan
slate swan
silk wasp
#

@buoyant crescent

#

wait no

sharp whale
slate swan
unkempt canyonBOT
#

class discord.TextStyle```
Represents the style of the text box component.

New in version 2.0.
sharp whale
slate swan
silk wasp
#
import discord
from discord.ext import commands
import os

from apikeys import BOTTOKEN

class MyBot(commands.Bot):
    def __init__(self):
        super().__init__(command_prefix='!', intents=discord.Intents.all())

    async def setup_hook(self):
        await load()

bot = MyBot()

async def load():
    for filename in os.listdir("./cogs"):
        if filename.endswith(".py"):
            cog_name = filename[:-3]
            bot.load_extension(f"cogs.{cog_name}")
            print(f'Extension: {cog_name} successfully loaded')

@bot.event
async def on_ready():
    await bot.change_presence(status=discord.Status.do_not_disturb, activity=discord.Streaming(name="Pokemon Unite", url="https://www.twitch.tv/mysterymom__"))
    print("The bot is now ready")
    print("--------------------")

@bot.command()
async def test(ctx):
    await ctx.send("This is a text command")

bot.run(BOTTOKEN)

@buoyant crescent try this?

sharp whale
slate swan
slate swan
#

can you do pip show discord.py in terminal?

sharp whale
#

wait

#
Version: 2.3.1
Summary: A Python wrapper for the Discord API
Home-page: https://github.com/Rapptz/discord.py
Author: Rapptz
Author-email: None
License: MIT
Location: /home/runner/papernodes-suggestion-bot/venv/lib/python3.10/site-packages
Requires: aiohttp
Required-by: discord```
slate swan
#

wait why am I seeing TextInput in discord.py when he is doing InputText

sharp whale
#

its latest

slate swan
#

are they different?

sharp whale
slate swan
#

after you import discord obviously

buoyant crescent
silk wasp
#

await it

slate swan
silk wasp
#

add a await infront of bot.load

#

zzz

buoyant crescent
#

ok

hasty pike
#

@sharp whale

slate swan
buoyant crescent
silk wasp
#

bnruh

slate swan
silk wasp
#

hmmmm

slate swan
unkempt canyonBOT
slate swan
#

newest is 2.3.1

cloud dawn
#

!pypi py-cord

unkempt canyonBOT
slate swan
#

py-cord joeCollapse

silk wasp
#

@buoyant crescent can we not add a class MyBot or u want it like that?

cloud dawn
#

EWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW

slate swan
#

from all libraries py-cord is the worst one

cloud dawn
buoyant crescent
silk wasp
#

.-.

buoyant crescent
buoyant crescent
cloud dawn
sharp whale
sharp whale
slate swan
sharp whale
#

pycord hmm

silk wasp
slate swan
cloud dawn
#

py-cord*

hasty pike
slate swan
hasty pike
#

I read pycord documentation for interaction

cloud dawn
#

Except py-cords core is messed up

hasty pike
slate swan
#

pycord is different

cloud dawn
hasty pike
cloud dawn
#

Hikari is king

silk wasp
#

because the code shouldnt run twice unless it your ide or a duplicate instances of running the script

slate swan
#

i use nextcord for personal projects Sleeping

hasty pike
#

I used it when dpy was discontinued

slate swan
#

me too

cloud dawn
#

I used disnake.

sharp whale
#

i deleted pycord

hasty pike
#

But does nextcord have hybrid commands?

silk wasp
#

.-.

sharp whale
silk wasp
sharp whale
#

but still not working

slate swan
hasty pike
hasty pike
cloud dawn
silk wasp
hasty pike
#

I personally like nextcord so much

slate swan
hasty pike
hasty pike
sharp whale
#
  File "main.py", line 9, in <module>
    intents = discord.Intents.all()
AttributeError: module 'discord' has no attribute 'Intents'```
#

bro wat

slate swan
#

what did you install

sharp whale
hasty pike
#

😭😭

sharp whale
hasty pike
#

His errors

cloud dawn
slate swan
#

print its version

#

again

sharp whale
silk wasp
#

@buoyant crescent any status?

slate swan
cloud dawn
sharp whale
hasty pike
slate swan
#

oh yeah maybe you named file discord.py

hasty pike
#

Stats gonna go down

sharp whale
slate swan
#

do pip list

cloud dawn
slate swan
#

and send output

hasty pike
cloud dawn
#

We're screwed

slate swan
silk wasp
hasty pike
cloud dawn
#

lmao

slate swan
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

sharp whale
hasty pike
#

Panda is hurt

sharp whale
silk wasp
#

what is this

discord 2.3.1
discord-py 2.3.1

slate swan
#

you have so many random libraries installed

silk wasp
#

what is this

slate swan
#

like discord or discord-py

#

the library you want is discord.py

sharp whale
#

should i make a new repl

cloud dawn
#

Yes

slate swan
#

!pypi discord-py

unkempt canyonBOT
cloud dawn
#

I always throw my container away when I don't feel like fixing that bug.

buoyant crescent
slate swan
#

!pypi discord

unkempt canyonBOT
silk wasp
unkempt canyonBOT
silk wasp
cloud dawn
#

Then you know it was on twice.

sand flicker
#

Hi everybody.
I am using adb to control android devices and am having a problem where there is no way for adb to recognize more than 15 devices
Does anyone know how to fix it?

slate swan
cloud dawn
#

ngl mirror packages should be dissalowed except for bs4 since i always spell it wrong.

slate swan
#

@sharp whale now install discord**.**py

slate swan
#

with a dot

unkempt canyonBOT
#

7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.

silk wasp
cloud dawn
#

!pypy discordpy

slate swan
#

pypy joeCollapse

cloud dawn
#

pipi

slate swan
#

!pypi replit

unkempt canyonBOT
slate swan
#

mhm

sharp whale
slate swan
silk wasp
#

first uninstall all discord

slate swan
#

what is the question?

#

oh there is an error

#

did not see that

sharp whale
silk wasp
#

remove self.

slate swan
#

well you are trying to access attribute that does not exist on your object

silk wasp
#

in self.interaction

slate swan
#

you prolly want just interaction since you get it in the callback function

sharp whale
#

b r u h

silk wasp
#

waht it say

slate swan
silk wasp
#

can i see the full code?

slate swan
sharp whale
#

wait

slate swan
#

your function wants user param

#

show your function definition

silk wasp
#

can i see this function code?

slate swan
#

is it inside a class?

#

doesnt look like when you call it

#

what does that mean?

sharp whale
#

OK

slate swan
#

show code

sharp whale
#

it ran

slate swan
#

i dont get the not indented part like if it is indented into class then its inside class else its not

buoyant quail
#

It's not the cogs, but the classes. And if your function is not indented, it is not inside the class.

slate swan
#

you only put self when its inside class

#

looks like it is not inside class since you get this error

#

then its not inside class

#

if its in global scope

buoyant quail
#

Then just put that inside class if you need it

buoyant crescent
slate swan
#

keep in mind if you put it inside class you need to be in that class or have class instance to run this method

#

then you just remove the self but you wont be able to use self.bot.something

hasty pike
slate swan
#

which you prolly need

cloud dawn
slate swan
#

could be

silk wasp
#

await self.open_account(interaction.user)

#

wait no

buoyant quail
#

||Learn python before making bots||

buoyant crescent
silk wasp
#

is ur open_account and the command in same file or differeccn file?

hasty pike
slate swan
#

.rp oop

#

ok

cloud dawn
buoyant crescent
# cloud dawn Whatever is being done twice.
import discord
from discord.ext import commands


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


    @commands.command()
    async def aide(self, ctx):
        help = discord.Embed(title="Liste des commandes :", url=None, description=None, color=0x7434EB)
        help.set_author( name="Menu Help du bot", url=None, icon_url="https://cdn.discordapp.com/attachments/1122145321535930499/1122145393032040519/20230624_142400_0000.png")
        help.add_field(name="Musiques :", value="!join | !play | !stop | !resume | !pause | !music", inline=False)
        help.add_field(name="Modération :", value="!ban | !kick", inline=False)
        help.set_image(url="https://media.discordapp.net/attachments/1120608535672270939/1123258060983509124/pu.gif?width=747&height=312")
        help.set_footer(text="Demandé par : {}".format(ctx.author.display_name))
        await ctx.send(embed=help)


    @commands.command()
    async def music(self, ctx):
        await ctx.send("La liste des musiques : black_clover, black_rover, demon_slayer_3, night_dancer")


    @commands.Cog.listener()
    async def on_member_join(self, member):
        channel = self.bot.get_channel(1121386561150386276)
        join = discord.Embed(title="Bienvenue dans le serveur de la Neo Destiny ! ", url=None, description=f":tada: Bienvenue {member} :tada:", color=0x7434EB)
        join.set_image(url=member.avatar.url)
        join.set_footer(text=f"Nous sommes désormais : {member.guild.member_count}")
        await channel.send(embed=join)


async def setup(bot):
    await bot.add_cog(Greetings(bot))```
silk wasp
#

@slate swan if it in a diff file use this instead

await open_account(self, interaction.user)

#

then it should work

slate swan
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

buoyant quail
#
function()
sharp whale
#

eh

buoyant quail
#

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

its case sensitive

sharp whale
#

heh

#

error: Traceback (most recent call last): File "/home/runner/sugg-bot/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 235, in wrapped ret = await coro(*args, **kwargs) File "main.py", line 45, in modal await Interaction.response.send_modal(suggest()) AttributeError: 'CachedSlotProperty' object has no attribute 'send_modal'

slate swan
#

not random Classes

#

ok

sharp whale
#

._.

slate swan
#

!d discord.InteractionResponse.send_modal

unkempt canyonBOT
#

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

Responds to this interaction by sending a modal.
sharp whale
#

uh what

buoyant quail
#

It should be interaction instance, not just class

sharp whale
#

i know

#

i know this exists, i read the doc

#

i imported the interaction class too

buoyant quail
#

You get instance from the library as the first argument when you call the command

sharp whale
#

sorry, my english isn't good

buoyant quail
#

Interaction is a variable holding an instance made from class Interaction

sharp whale
slate swan
#

so why use Interaction

sharp whale
#

ok i named the argument in upercase

slate swan
#

no

sharp whale
#

._.

slate swan
#

dont named varriables like classes

sharp whale
#

what

slate swan
#

use lowercase interaction

sharp whale
#

okay

#
  File "/home/runner/sugg-bot/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 235, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 44, in modal
    await interaction.response.send_modal(suggest())
AttributeError: 'Context' object has no attribute 'response'```
#

._.

slate swan
#

thats prefixed command you get Context not Interaction

sharp whale
#

hmm

#

HMM

hasty pike
sharp whale
#

we register a slash command with @bot.tree.command() decorator

#

right?

hasty pike
#

Yes

shrewd apex
#

if ur not in cogs yes

sharp whale
#
async def modal(interaction: discord.Interaction):
  await interaction.response.send_modal(suggest())```
hasty pike
#

Doesn't seem to work for me

sharp whale
#

hmm

#

its not working

twilit grotto
#

send the error

sharp whale
#

it doesnt throw any error

naive briar
#

What's not working

sharp whale
#

command not working

buoyant quail
#

You need to sync your commands

naive briar
#

That didn't explain anything

sharp whale
#

like, its not listed in the slash command listh thingy

hasty pike
sharp whale
#

how do i sync

hasty pike
#

Make sync command

#

You can use this whenever you want to sync your commands with discord

#

Make sure command is owner (developer) only

sharp whale
#

what if

#

i did it in on_ready event

#

yea it worked

hasty pike
naive briar
#

It will unnecessarily sync almost every time you restart the bot

hasty pike
sharp whale
#

then why not sync everytime

naive briar
#

That's not the point of my message

hasty pike
#

You only need to sync after updating your code

sharp whale
#

I meant, nothing bad will happen if it syncs everytime it starts right?

hasty pike
#

And discord will timeout it

sharp whale
hasty pike
#

Use proper ways to do it

sharp whale
#

yk, lazyness

hasty pike
#

Happens but you've to do it you can't skip things

buoyant quail
#

Just typehint channel as forum channel i think?

slate swan
#

Or a union where you have both I guess

hasty pike
thin raft
#

show code

#

show entire code

slate swan
#

you cant annotate option as ForumChannel

#

means that you cant type hint the option as ForumChannel cause discord does not support it

slate swan
#

discord

#

Discord mentions in their docs

Includes all channel types + categories

#

Not sure why you shouldn't be able to

#

you have a server with bot that has jishaku

#

I stopped coding in Python for over 2 years LULW

#

Just interested that discord documentation mentions all channel types are accepted

#

Which, according to what you say, is wrong

#

yeah i wanted to test it using jishaku

#

i guess i need to host one myself

#

is it for slash command or select component

#

Guild Forums are channel type 15 and public/private threads 11 and 12. Can probably try it out

thin raft
#

dopn't use forumchannel

slate swan
#

the forum channel select

thin raft
#

what's the command for?

slate swan
#

That

thin raft
#

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

slate swan
#

Is the bot in the thread already? Dunno if it matters

#

And it's a thread channel if you want them to send in threads

#

!d discord.Thread

unkempt canyonBOT
#

class discord.Thread```
Represents a Discord thread.

x == y Checks if two threads are equal.

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

hash(x) Returns the thread’s hash.

str(x) Returns the thread’s name.

New in version 2.0.
slate swan
#

how do you sync slash commands in discord py

#

im noob

#

tree.sync I guess

#

!d discord.app_commands.CommandTree.sync

unkempt canyonBOT
#

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

Syncs the application commands to Discord.

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

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

awaitable PepoG

#

Yeah that

#

It's as bot.tree

#

yeah i know but how do you set testing guild in it

#

o there is guild keyword

#

well works then

#

there is x command with no errors but i have no threads to check on

#

Probably want discord.Thread

#

As they're independent I suppose

#

A forum channel contains threads and they want to send in threads

hasty pike
slate swan
#

!d isinstance

unkempt canyonBOT
#

isinstance(object, classinfo)```
Return `True` if the *object* argument is an instance of the *classinfo* argument, or of a (direct, indirect, or [virtual](https://docs.python.org/3/glossary.html#term-abstract-base-class)) subclass thereof. If *object* is not an object of the given type, the function always returns `False`. If *classinfo* is a tuple of type objects (or recursively, other such tuples) or a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union) of multiple types, return `True` if *object* is an instance of any of the types. If *classinfo* is not a type or tuple of types and such tuples, a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") exception is raised. [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") may not be raised for an invalid type if an earlier check succeeds.

Changed in version 3.10: *classinfo* can be a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union).
slate swan
#

!e ```py
print(isinstance(5, int))

unkempt canyonBOT
#

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

True
buoyant quail
#

ForumChannels are fine

slate swan
#

how about threads i cant check rn

buoyant quail
#

Ye, works too

hasty pike
slate swan
#

is it possible to run a bot inside another one?

slate swan
slate swan
slate swan
#

technically yes but doesnt look like a good solution what is your case

#

ok i'll try to run another python file when the command is done

#

Sometimes I wonder what atrocities people do

twin wave
#

If you set it one bot up on a different server then it is possible

buoyant quail
slate swan
buoyant quail
#

Recursively

slate swan
#

the token will be a parameter on the command

#

That's more than an atrocity

slate swan
#

That's like 21/20 design

#

lol

buoyant quail
#

100% safe

slate swan
#

awesome hosting idea i would say

#

LMFAO

slate swan
#

Would trust 21/20 in giving a token to some random bot

#

Especially if when they save it

#

And then probably run it on Replit

slate swan
#

not about token imagine someone makes a bot that all does is delete all files ☠️

twin wave
#

Actually I tried to do it once but each discord bot needs its own running instance to work

slate swan
#

lmfao

#

How about just inviting your bot omegakeklmao

slate swan
#

If it's to run 1 to 1 the same kek

#

Sounds like shit

slate swan
hasty pike
buoyant quail
#

I got it, that's like these videos, but you don't even need to do something. Just get a token.

slate swan
slate swan
#

everything is possible but not everything should be done

slate swan
hasty pike
buoyant quail
hasty pike
slate swan
slate swan
#

good bye .-.

#

isnt it goodbye

#

Could be both

#

But you'd put a comma in-between

#

okay but thats not a comma

buoyant quail
#

Bad bye brainmon

slate swan
#

,

slate swan
dense barn
#

i want to add a hyperlink to an embed but the link has parentheses, too. like
https://smth.ssm.smthing/file(x).zip
and since the format for the hyperlink is [Text](Link) I'm wondering if my link will cut off on the x part and if so, what do I do to fix it?

slate swan
#

you can try escaping that ()

#

using \

hasty pike
dense barn
hasty pike
dense barn
#

Ah yeah that\

slate swan
#

you put backslash before

dense barn
#

You sound condescending.

buoyant quail
#

Why didn't you even try it before asking..
It works fine with just that string

slate swan
#

**hello**

buoyant quail
#

[hello](https://smth.ssm.smthing/file(x).zip)
(copy link gives the valid link)

slate swan
#

yeah i could have just tested it joeCollapse

hasty pike
#

hello

hasty pike
buoyant quail
#

**hello**

hasty pike
#

hello

buoyant quail
slate swan
#

i cant even show you that cause i have links masking on my server

hasty pike
buoyant quail
#

yeah

slate swan
#

yes

silk wasp
#

yes

hasty pike
#

Well i didn't know that

slate swan
#

\*\*hello\*\*

#

technically you dont need to escape last two stars

buoyant quail
#

49. 49. 49. 49. 49. wat

slate swan
buoyant quail
#

i like how discord works with markdown

naive briar
#

Amogus ducky_sus

slate swan
#

how did you broke it like this

buoyant quail
#

# 49. 49. 49. 49. 49. wat

#

||# big boi spoiler ||

hasty pike
slate swan
#

the View takes 1 argument but you gave two

#

Why did you give a bot variable in that

naive briar
slate swan
#

oh yeah its self

naive briar
#

Why wouldn't you know

#

So, you don't even know if a class you created take arguments?

#

Amazing

slate swan
#

😵‍💫

hasty pike
#

Channel is sleeping rn

#

😴

slate swan
#

🗿

hasty pike
#

Lemme drop a question then a brain exercise

#

Can we change server vanity with bot

slate swan
#

I would say no

hasty pike
#

Ig I've seen someone doing that

hasty pike
#
async def callback(self, select, interaction: discord.Interaction):
    if 'enable' in select.values[0]:
          await interaction.response.edit_message(embed=discord, view=self)
#

@slate swan

sick birch
#

interaction is 2nd argument

hasty pike
#

select.values give me list?

#

Right

sick birch
#

Yes

marble rampart
#

with discord.py anyone knows how can i use slash commands as sub commands ?

slate swan
#

Create a command group

#

Add commands to that group

marble rampart
slate swan
#

Just like you add commands to a bot tree

marble rampart
#

right now i have this

    @commands.group(name="verify",invoke_without_command=True)
    async def verify(ctx):
        return
    
    @verify.command(name="setup",description="setup a verify channel")
    async def setup(self, interaction: discord.Interaction):
        view = SetupView()
        embed = Embed(title="Verification setup",colour=discord.Colour.brand_green(),description="``yaml\nuse the next drop down menu to select the roles that will be given to users after verification (MAX: 3)\n``")
        
        await interaction.response.send_message(view=view,embed=embed)  
#

how do i make it slash

slate swan
#

That's not a slash command, that's a prefix command

marble rampart
#

i know thats what im asking because its in a cog and i dont know what the hell am i doing

#

nvm i found something thanks for trying to help me

slate swan
marble rampart
#

just found the same thing lol

slate swan
#

can anyone help me fix this " import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.typing = False
intents.presences = False

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

#

Save your file

dense barn
#

i'm having trouble right now trying to use local files for images.

./images
  img.png
./cogs
  code.py
bot.py

So I want to put an author image img.png to my embed from code.py. How exactly do I access a file one parent directory then another folder in? I saw this

f = discord.File("some_file_path", filename="img.png")
e = discord.Embed()
e.set_image(url="attachment://image.png")
await ctx.send(file=f, embed=e)

but how exactly do I change some_file_path ? Should it be ../images/ or something else entirely

hushed galleon
#

relative filepaths are based on your CWD (current working directory) regardless of where the script is, so if your CWD is the folder containing bot.py, the relative path to your image would be images/img.png

slate swan
#

Don't remove what you had before with intents

formal basin
#

!d discord.Embed

unkempt canyonBOT
#

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

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

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

New in version 2.0.

x == y Checks if two embeds are equal.

New in version 2.0...
slate swan
#

I told you to save, not delete lines

slate swan
#

Add those lines back Facepalm

#

they are alr in

#

on the bottom

#

Where are they?

#

Can't see intents=intents there

#

Maybe I'm blind though

tired pine
#

in discord.py how do you know whether an interaction is coming from a mobile device user or desktop

slate swan
#

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

You need to define it once, at the top.

slate swan
#

the names are in most cases self explainatory so you will find what you need

slate swan
turbid condor
#

Welp lot of ppl do that now idk why

slate swan
#

so i jus change everything to bot? dont thibk that will affect it g

turbid condor
slate swan
slate swan
turbid condor
#

Idk why but ppl should go to docs or the dpy gist for examples

slate swan
#

so what shall i do

turbid condor
#

But instead they all go to yt

slate swan
turbid condor
slate swan
slate swan
slate swan
unkempt canyonBOT
#
Using intents in discord.py

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

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

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

from discord import Intents
from discord.ext import commands

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

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

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

slate swan
#

Already told you holy moly

#

Remove that code and just keep the code below

#

You don't need to define twice client

#

You don't need to import everything twice

#

Once. At the top.

turbid condor
#

Yeah that is the problem since u are defining client twice where in one of them u haven't put the intents

#

Replace line 13 with line 44

#

And then delete the line 37 to 44

#

This should fix your problem

tired pine
slate swan
turbid condor
slate swan
#

i belive his question was if the user is on mobile or desktop

turbid condor
#

Yeah there is a method to check that in dpy

slate swan
#

yeah i know

#

i want him to go to docs and just look on the methods

#

the names are self explainatory

tired pine
turbid condor
#

Then try looking at docs

#

I'm pretty sure u will find it easily

kindred iron
#
    async def lock(self, ctx : commands.Context,
                    channel : Optional[discord.abc.GuildChannel],
                    time : Optional[TimeConverter],
                    *,
                    reason : str = "No Reason Provided"):
        if not channel :
            channel = ctx.channel



        await channel.set_permissions(ctx.guild.default_role, reason=reason, send_messages = False)
        await ctx.send("channel locked",delete_after = 15 , ephemeral = True)

        if time
            await asyncio.sleep(time)
            # unlock the channel

So , I'm trying to temp locking a channel.
I'm wondering if this is the way to go.

( I mean the sleep method)

slate swan
#

it is good but has one con

  • when you restart the bot and there was one channel locked ongoing it will stop waiting for it and will never unlock it
kindred iron
#

So what's the solution

tired pine
#

bruh

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`).
tired pine
#

asking for the name is bad nowadays cuz people won't answer you when they know

slate swan
#

here are the docs

tired pine
#

you know what nvm

slate swan
#

its not about i dont wanna show you the answer its about i wanna show you how to look for solutions

tired pine
slate swan
# kindred iron So what's the solution

easiest one:
you can have infinite loop ongoing for example each 30 seconds which will check if there is any channel locked and if there is if the duration has passed

turbid condor
#

Zzz

slate swan
#

There's a wonderful search bar

slate swan
#

why you need to know it so bad now when you cant code on mobile anyways

kindred iron
#

Thanks

slate swan
dense barn
#

Why is this not working?

f = discord.File("../images/bot_icon.png", filename="bot_icon.png")
        embed.set_thumbnail(url="attachment://bot_icon.png")
        embed.set_footer(text=f"Requested by {context.author}", icon_url = context.author.avatar.url)
        await context.send(file = f, embed=embed)

It's giving me No such file or directory, this worked before but I don't know where I went wrong this time. My bot_icon is not being found.

turbid condor
#

Ok just look for something called is_on_mobile that might help

dense barn
kindred iron
# slate swan 👍

Btw should i use while loop or task.ext ( i can check if duration is passed bc bot send embed with duration)

slate swan
tired pine
dense barn
slate swan
#

How do you run the file

kindred iron
dense barn
# hushed galleon ^

yeah it worked before but somehow while i was changing stuff up I messed up and now it's not working.

slate swan
turbid condor
tired pine
slate swan
slate swan
#

It's very hard I know

#

Don't get scared when you see how complicated it is

shrewd apex
#

gpt trigger ducky_skull

slate swan
buoyant crescent
#

hi i got an issue with my events ```python
ERROR discord.client Ignoring exception in on_member_remove
Traceback (most recent call last):
File "C:\Program Files (x86)\Python38-32\lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "c:\Users\MYOUSSEF\Desktop\bot\cogs\Greetings.py", line 36, in on_member_remove
channel = self.bot.get_channel(1080174110459580428)
AttributeError: 'Greetings' object has no attribute 'bot'
2023-06-29 21:02:17 ERROR discord.client Ignoring exception in on_member_join
Traceback (most recent call last):
File "C:\Program Files (x86)\Python38-32\lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "c:\Users\MYOUSSEF\Desktop\bot\cogs\Greetings.py", line 28, in on_member_join
channel = self.bot.get_channel(1037041281504903181)
AttributeError: 'Greetings' object has no attribute 'bot'

slate swan
#

maybe this method existed that days

shrewd apex
buoyant crescent
#
 @commands.Cog.listener()
    async def on_member_join(self, member):
        channel = self.bot.get_channel(1037041281504903181)
        join = discord.Embed(title="Bienvenue dans le serveur de la Neo Destiny ! ", url=None, description=f"🎉 Bienvenue {member} 🎉", color=0x7434EB)
        join.set_image(url=member.avatar.url)
        join.set_footer(text=f"Nous sommes désormais : {member.guild.member_count}")
        await channel.send(embed=join)

    @commands.Cog.listener()
    async def on_member_remove(self, member):
        channel = self.bot.get_channel(1080174110459580428)
        leave = discord.Embed(title="Un membre a quitté le serveur !", url=None,
                              description=f"Oh non aurevoir {member} 👋", color=0x7434EB)
        leave.set_image(url=member.avatar.url)
        leave.set_footer(text=f"Nous sommes désormais : ")
        await channel.send(embed=leave)

slate swan
hushed galleon
tired pine
slate swan
#

Not a bad thing

buoyant crescent
tired pine
#

if ChatGPT only has knowledge from before 2021 it wouldn't be able to give me proper 2.2 dpy code

slate swan
#

no the cog you just sent sample code of

slate swan
buoyant crescent
#
import discord
from discord.ext import commands


class Greetings(commands.Cog):
    def init(self, bot):
        self.bot = bot


    @commands.command()
    async def aide(self, ctx):
        help = discord.Embed(title="Liste des commandes :", url=None, description=None, color=0x7434EB)
        help.set_author( name="Menu Help du bot", url=None, icon_url="https://cdn.discordapp.com/attachments/1122145321535930499/1122145393032040519/20230624_142400_0000.png%22_")
        help.add_field(name="Musiques :", value="!join | !play | !stop | !resume | !pause | !music", inline=False)
        help.add_field(name="Modération :", value="!ban | !kick", inline=False)
        help.set_image(url="https://media.discordapp.net/attachments/1120608535672270939/1122594030241460336/20230624_142400_0000.png?width=1051&height=658")
        help.set_footer(text="Demandé par : {}".format(ctx.author.display_name))
        await ctx.send(embed=help)



    @commands.Cog.listener()
    async def on_member_join(self, member):
        channel = self.bot.get_channel(1037041281504903181)
        join = discord.Embed(title="Bienvenue dans le serveur de la Neo Destiny ! ", url=None, description=f"🎉 Bienvenue {member} 🎉", color=0x7434EB)
        join.set_image(url=member.avatar.url)
        join.set_footer(text=f"Nous sommes désormais : {member.guild.member_count}")
        await channel.send(embed=join)

    @commands.Cog.listener()
    async def on_member_remove(self, member):
        channel = self.bot.get_channel(1080174110459580428)
        leave = discord.Embed(title="Un membre a quitté le serveur !", url=None,
                              description=f"Oh non aurevoir {member} 👋", color=0x7434EB)
        leave.set_image(url=member.avatar.url)
        leave.set_footer(text=f"Nous sommes désormais : ")
        await channel.send(embed=leave)


async def setup(bot):
    await bot.add_cog(Greetings(bot))```
dense barn
buoyant crescent
tired pine
slate swan
#

wow, reading docs woah_patrick

slate swan
#

thought you cant do that on mobile

dense barn
tired pine
slate swan
#

thats awesome i guess

#

oh you got a pc already look how awesome

tired pine
#

second, I said I was on mobile because I'm at my grandma's for a week

slate swan
#

you can scroll docs already yourself

#

no need my help now

tired pine
#

I didn't even use my PC

dense barn
#

the time you spent here arguing you could have spent scrolling through docs

slate swan
#

you read something on a PC without having a PC thats odd

tired pine
#

No because I am sitting next to some people rn and waiting for them to go

dense barn
turbid condor
#

And I already told u what u should look in docs

tired pine
slate swan
#

mysterious

buoyant crescent
#

hi i have seen people talking about nextcord, is it better than discord.py

tired pine
slate swan
turbid condor
#

They are equal

slate swan
#

Both are different and doing things differently, choose whatever you want

buoyant crescent
slate swan
#

In the end you end up with the same features

buoyant crescent
#

ok thank's

tired pine
turbid condor
#

I'd say go with what u feel comfortable with

tired pine
slate swan
buoyant crescent
#

ok ok

turbid condor
tired pine
turbid condor
#

I already did if u noticed

slate swan
#

Maybe if you would read it'd be useful

tired pine
slate swan
#

for example:

# discord.py
@bot.tree.command()
@app_commands.describe(
    first_value='The first value you want to add something to',
    second_value='The value you want to add to the first value',
)
async def add(interaction: discord.Interaction, first_value: int, second_value: int):
    """Adds two numbers together."""
    await interaction.response.send_message(f'{first_value} + {second_value} = {first_value + second_value}')



# nextcord
@bot.slash_command()
async def add(interaction: nextcord.Interaction, first_value: int = SlashOption(description="The first value you want to add something to", second_value: int = SlashOption(description="The value you want to add to the first value")))
    """Adds two numbers together."""
    await interaction.send(f'{first_value} + {second_value} = {first_value + second_value}')

turbid condor
#

Same

slate swan
#

Slapping everything like that in the parameters, meh..

#

Just horrible imo

#

in this example it might be more readable for discord.py but knowing all features of it i still stick with nextcord

turbid condor
#

Welp it comes down to what u feel comfortable with

tired pine
#

If it's your first discord library in python I suggest you start with dpy

turbid condor
#

You can start with any of them some ppl find one easier then other

slate swan
#

I thought you had to go

turbid condor
#

XD

dense barn
fringe lake
#

idk if this is the correct channel but, whenever i click "ctrl + c" to stop the file, it wont allow me to write commands again

#

can someone mention me if he knows the solution pls ?

slate swan
#

so the bot will stop

buoyant quail
# slate swan for example: ```py # discord.py @bot.tree.command() @app_commands.describe( ...
# disnake
@bot.slash_command()
async def add(interaction: disnake.Interaction, first_value: int, second_value: int):
    """
    Adds two numbers together.

    Parameters
    ----------
    first_value: The first value you want to add something to
    second_value: The value you want to add to the first value
    """
    await interaction.send(f'{first_value} + {second_value} = {first_value + second_value}')

or you can do the same as in nextcord

first_value: int = commands.Param(description=...)
slate swan
#

now we need to wait for some py-cord expert

#

(not gonna happen)

buoyant quail
#

hikari

slate swan
#

maybe thats cause i was used to nextcord style

#

@buoyant quail you use disnake daily?

buoyant quail
#

yes

slate swan
#

this valid? ```py
@commands.slash_command()
@blocked_command()
async def quiz(
self,
inter: disnake.GuildCommandInteraction,
category: str = commands.Param(choices=QUIZ_CATEGORY_CHOICES, default="images"), # type: ignore
) -> None:

spice dirge
#

im just lurking but since the topic is on api wrappers, i recently made one https://aiocord.readthedocs.io, would be cool if yall could check it out and give some feedback :>

slate swan
slate swan
spice dirge
slate swan
slate swan
#

That's instantly a no-go

spice dirge
#

it can also be set via a environment variable

slate swan
#

At least don't put it in the front page

#

That's one of the worst thing to do

spice dirge
#

how come?

slate swan
#

i was thinking about env varriables but since there is a way

#

Your token is in the history in plaintext

#

Either read from stdin or don't do it at all

spice dirge
#

what's the difference than it being somewhere in a file?

slate swan
#

Ideally showcase the environment variable method on the home page, that's how you store secrets these days

slate swan
spice dirge
buoyant quail
slate swan
#

Environment variables are not always .env files fyi

spice dirge
slate swan
#

Yeah that's always the case

spice dirge
#

idk i put the command line method in the front page cause it's the easiest to use, i'm sure whoever decides to use this in production will have looked into the other options as well

slate swan
#

Still better than using a command line

#

I'd at least showcase the environment variable method on the home page

#

And mention you can pass the token via a flag

spice dirge
slate swan
#

Also there are some overall CSS issues

spice dirge
#

it's my first time doing custom css with sphinx

slate swan
spice dirge
#

i get a scroll bar for it?

slate swan
#

And shouldn't syntax highlight highlight more?

slate swan
spice dirge
#

i could use a different stynax highlighter

spice dirge
slate swan
#

I'd change the font for inline code to monospaced as well

fringe lake
# slate swan so the bot will stop

i mean, when the bot stop it should allow me to excute commands, but yasterday this problem happened, it just keep that blank and not allow me to type anything

spice dirge
slate swan
#

And yeah I'll check out the rest tomorrow and play around with the library when on PC, if you want to remind me just ping me in case I forget KEKW

spice dirge
#

u seem like ur good at giving feedback so i'll make sure to poke again :'>

slate swan
#

Only place I found while scrolling a bit

spice dirge
#

oh that's not meant to be code, just special highlighting-ish

#

like it doesn't have the :code: directive for rst

#

but that's still monospaced :O same font as the black thingies

slate swan
#

Maybe my browser/mobile that shows brew install ffmpeg non monospaced

slate swan
#

try pressing ctrl + c few times

spice dirge
#

ur browser just kinda gave up there

slate swan
#

Yeah then I guess my browser

kindred iron
fringe lake
fringe lake
#

thank you guys

sharp whale
#

Hi, i want to send the users name, and profile picture as author line in embed, how do i access name and icon (in a modal class)

#

i think its Tasks

slate swan
sharp whale
#

not tasks

#

!discord.ext.Tasks

slate swan
#

its not capital for sure

#

and it is tasks

sharp whale
#

it is tasks

slate swan
slate swan
sharp whale
slate swan
#

!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`).
sharp whale
slate swan
#

there are docs for a reason

sharp whale
#

discord.Member.Avatar

sharp whale
slate swan
#

it just works?

#

its logging system

sharp whale
#

its not an error, it just logs the work done

slate swan
#

it means that ClientUser does not have avatar_url attribute

#

!d discord.ClientUser

unkempt canyonBOT
#

class discord.ClientUser```
Represents your Discord user.

x == y Checks if two users are equal.

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

hash(x) Return the user’s hash.

str(x) Returns the user’s handle (e.g. `name` or `name#discriminator`).
slate swan
#

go check yourself what it has and sort out what you need

sharp whale
#

hmm, what if i want the avatar as url

slate swan
sharp whale
#

yes

slate swan
#

and what is that

sharp whale
#

it isnt url

#

Command raised an exception: AttributeError: 'ClientUser' object has no attribute 'avatar_url'

#

it really says the error

slate swan
#

im asking what type is it

sharp whale
slate swan
#

type

sharp whale
#

asset

slate swan
#

oh nice and what attributes does asset have

sharp whale
#

LMAO

#

i didnt realise that

slate swan
#

now you know how to use the docs

#

icon_url=bot.user.avatar_url

#

there is no such thing as avatar_url

#

!d discord.ClientUser

unkempt canyonBOT
#

class discord.ClientUser```
Represents your Discord user.

x == y Checks if two users are equal.

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

hash(x) Return the user’s hash.

str(x) Returns the user’s handle (e.g. `name` or `name#discriminator`).
sharp whale
slate swan
#

go to the docs and see what is has and how can you get the avatar url now

slate swan
sharp whale
#

i dont know.

slate swan
#

so show me the code

sharp whale
#

i used this discord.Member.display_avatar.url

slate swan
sharp whale
#

dont laugh

#

or die

slate swan
#

you need to get some member object instance

sharp whale
#

using emoji

slate swan
#

not a whole class

sharp whale
#

uh what

slate swan
#

go to the docs i linked and search how to gather avatar url

slate swan
#

you need to know this before doing discord bot

formal basin
#

!d discord.Embed

unkempt canyonBOT
#

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

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

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

New in version 2.0.

x == y Checks if two embeds are equal.

New in version 2.0...
formal basin
#

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

!e ```py
class MyClass:
def init(self, value):
self.value = value

def get_value(self):
    return self.value

good:

myclass = MyClass(15)
print(myclass.get_value())

bad (wont work):

print(MyClass.get_value())

unkempt canyonBOT
#

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

001 | 15
002 | Traceback (most recent call last):
003 |   File "/home/main.py", line 14, in <module>
004 |     print(MyClass.get_value())
005 |           ^^^^^^^^^^^^^^^^^^^
006 | TypeError: MyClass.get_value() missing 1 required positional argument: 'self'
slate swan
#

first one worked

#

second did not

#

to use methods you need a class object unless its static method (its not in your case so does not matter)

#

@whole hull

#

also i should mention that you dont create Member object yourself library gives them to you

#

for example when you have the Context you get into your slash command there is .author attribute which is of type Member

sharp whale
slate swan
#

and you can use it

formal basin
#

!d

slate swan
sharp whale
#

how do i get the avatar url brehhhh

slate swan
#

ok

slate swan
#

when did you write it

slate swan
#

cause avatar_url is old attribute

#

that does not exist any more

slate swan
sharp whale
#

discord.Member.display_avatar.url

slate swan
sharp whale
slate swan
#

learn OOP its mandatory for a discord bot

sharp whale
#

are you talking about variable

slate swan
sharp whale
#

this?

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

why dont you check yourself

sharp whale
#

my brain not braining

#

but theres no ctx or anything to get the user

slate swan
#

yeah totally there is no user

tired pollen
sharp whale
#

wao

#

bot.user.display_avatar.url

#

it sends bot's avatar bruh

slate swan
#

maybe cause bot.user returns the bot itself

#

who would imagine it wont give you random member the bot wont even know

#

duh what a library isnt it

sharp whale
#

._.

sick birch
#

@sharp whale are you looking to get the avatar URL of the user who invoked the command?

#

(Sorry I just got here and I'm missing context)

sharp whale
sick birch
#

Can you show your entire code file?

sharp whale
#

@sick birch

sick birch
#

Acknowledged. One moment

#

Yeah so as the others have pointed out you need to call the .display_avatar property on an instance of discord.Member, not the class itself. This is what you have:

avatar = discord.Member.display_avatar

For example, if you wanted to get the username of the user who submitted the modal, you'd do interaction.user.name where interaction.user is the discord.Member object who submitted the modal

The same concept applies to getting a .display_avatar

sharp whale
#
  File "/home/runner/sugg-bot/venv/lib/python3.10/site-packages/discord/ui/modal.py", line 188, in _scheduled_task
    await self.on_submit(interaction)
  File "main.py", line 31, in on_submit
    avatar = Interaction.User.display_avatar
AttributeError: type object 'Interaction' has no attribute 'User'```
#

sorry, my english is bad

slate swan
#

Even copy paste doesn't work LULW

sick birch
#

Interaction is the class, not the instance
If you'll notice on line 27 of your code, you have:

  async def on_submit(self, interaction: discord.Interaction):

interaction: discord.Interaction indicates 2 things:

  1. interaction is the variable containing the instance
  2. discord.Interaction is the type (or the class) of the variable interaction
#

You (usually) always call methods and properties on instances

sharp whale
#

hmm

sick birch
sharp whale
sick birch
#

You can get the url of a discord.Asset object by calling the .url property on an instance of discord.Asset

#

You can, in turn, get an instance of discord.Asset by calling the .display_avatar property on an instance of discord.Member

sharp whale
#

works 👍

#

ty robin

hasty pike
#

Mistake

#

Intents

#

discord.Intents.all()

#

Np

uneven ice
#

anybody know how to fix this error? C:\Users\Metal\AppData\Local\Temp\tmp9s8v2jv2.wav: Permission denied

#

its for my discord tts bot

slate swan
#

I'm getting a error with this error is below

austere prairie
slate swan
#

i normally use client :v

winter token
#
async def unban(self, ctx, member: discord.Member, *, reason = "Not Specified"):

        description = f"**Unbanned:** {member.mention}\n**Unbanned by:** {ctx.author.mention}\n**Reason:** {reason}"
        embed = discord.Embed(title = "Unbanned Successfully!", description = description, colour = colour)
        guild = ctx.guild
        ban_entry = await guild.fetch_bans()

        try:
            for bans in ban_entry:
                if bans == member:
                    await member.unban(reason = reason)
                    await ctx.send(embed = embed)
                else:
                    await ctx.send("The member is not banned.")

        except commands.MemberNotFound:
            await ctx.send("Please give a valid user ID to unban.")
#

Error occured: Member "1043451874164092968" not found.

#

why the bot is not reading the members id

silk wasp
winter token
#

and yes the member is banned, id is valid

sick birch
#

You probably should attempt to parse it as an int by typehinting it as such, then passing in a discord.Object into guild.unban

slate swan
tough kernel
#

so i've been working on a little discord bot game, i've had to restart when i started formatting it to slash commands, but recently i've been getting this:
Error: 404 Not Found (error code: 10015): Unknown Webhook
does anyone have an idea about whats causing this? it began when i was trying to implement a check for timeouts as i was getting them alot and was suggested that i put in lines to catch it

winter token
#
async def unban(self, ctx, id: int, *, reason = "Not Specified"):

        guild = ctx.guild
        member = await guild.fetch_member(id)
        description = f"**Unbanned:** {member.mention}\n**Unbanned by:** {ctx.author.mention}\n**Reason:** {reason}"
        embed = discord.Embed(title = "Unbanned Successfully!", description = description, colour = colour)
        
        try:

            await guild.fetch_ban(member)
            await guild.unban(member, reason = reason)
            await ctx.send(embed = embed)
                    
        except commands.MemberNotFound:
            await ctx.send("Please give a valid user ID to unban.")

        except discord.NotFound:
            await ctx.send("The member is not banned."
slate swan
#

@winter token try replacing id with user

winter token
#

Error occured: Command raised an exception: NotFound: 404 Not Found (error code: 10007): Unknown Member

sick birch
#

You actually don't need a member object to unban someone
You can pass in discord.Object(id=user_id) directly into guild.unban

slate swan
winter token
#

what does it do?

sick birch
#

It just represents a generic ID

winter token
#

so id is in built and user_id is the input we give

#

ty

winter token
slate swan
winter token
#
async def mute(self, ctx, member: discord.Member, duration: time_conv, *, reason = "Not Specified"):

        description = f"**Muted:** {member.mention}\n**Muted by:** {ctx.author.mention}\n**Duration:** {duration}\n**Reason:** {reason}"
        embed = discord.Embed(title = "Muted Successfully!", description = description, colour = colour)
        guild = ctx.guild
        guild_roles = await guild.fetch_roles()
        mute_role = discord.utils.get(guild_roles, name = 'Muted')
        user_roles = member.roles
 
        try:
            if mute_role is None:
                mute_role = await guild.create_role(name = 'Muted', premissions = 0, send_messages = False)
                for channel in guild.channels:
                    await channel.set_permissions(mute_role, send_messages = False)
            
            if mute_role in user_roles:
                await ctx.send("The member is already muted.")
            else:
                await member.add_roles(mute_role)
                await ctx.send(embed = embed)
                await asyncio.sleep(duration)
                await ctx.send(f"{member.mention} has been unmuted.")

        except discord.NotFound:
            await ctx.send('Please mention a valid member to mute.')
#

def time_conv(duration):
    total = 0
    duration_pattern =  r'(\d+)([dhms])'
    duration_values = re.findall(duration_pattern, duration)

    for value, unit in duration_values:
        if unit == 'd':
            total += value * 86400
        elif unit == 'h':
            total += value * 3600
        elif unit == 'm':
            total += value * 60
        elif unit == 's':
            total += value
        return total
#

Error occured: Converting to "time_conv" failed for parameter "duration".

silk wasp
winter token
silk wasp
#

u cant just put a function callable method to a function args

winter token
silk wasp
#

u can treat the duration as a str

duration: str

#

duration_seconds = time_conv(duration)

#

await asyncio.sleep(duration_seconds)

#

^^^^

winter token
#

ok but it worked yesterday in my wierd code

#

when i passed function as an arg

silk wasp
#

????? i should have work

#

but eh

#

idk what u do man

winter token
#

but it did work

silk wasp
#

eh hmmm lemme see

winter token
#

now im getting confused abt manual converter

#

    @commands.command()
    @commands.has_permissions(manage_roles = True)
    @commands.bot_has_permissions(manage_roles = True)
    @commands.cooldown(1, 3, commands.BucketType.user)
    async def mute(self, ctx, member: discord.Member , duration: converter,  *, reason = None):
        guild = ctx.guild
        description = f"**Muted:** {member.mention}\n**Muted by:** {ctx.author.mention}\n**Reason:** {reason}"
        embed = discord.Embed(title = "Muted Successfully!", description = description, colour = self.colour)
        permissions = discord.Permissions(permissions = 0, read_message_history = True, view_channel = True, send_messages = False)
        guild_roles = await guild.fetch_roles()
        user_role = member.roles
        mute_role = discord.utils.get(guild_roles, name = "Muted")

        if mute_role is None:
            mute_role = await guild.create_role(name = "Muted", permissions = permissions)
            for channel in guild.channels:
                await channel.set_permissions(mute_role, send_messages = False)
        if mute_role in user_role:
            await ctx.send("The user has been already muted!")
        else:
            try:
                    await member.add_roles(mute_role)
                    await ctx.send(embed = embed)
                    if duration == True:
                        await asyncio.sleep(duration)
                        await member.remove_roles(mute_role)
                        await ctx.send(f"{member.mention} has been unmuted succesfully.")
            except discord.NotFound:
                await ctx.send("Please give a valid user ID to mute!")
silk wasp
#

u did this what and it works right?

silk wasp
winter token
little ether
silk wasp
#

u need to learn this call type hint

#

is basically an annotations that specify the expected type of values for variables, function parameters, and return values.

little ether
#

!d discord.ext.commands.Converter

unkempt canyonBOT
#

class discord.ext.commands.Converter(*args, **kwargs)```
The base class of custom converters that require the [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context") to be passed to be useful.

This allows you to implement converters that function similar to the special cased `discord` classes.

Classes that derive from this should override the [`convert()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Converter.convert "discord.ext.commands.Converter.convert") method to do its conversion logic. This method must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.11)").