#discord-bots

1 messages ยท Page 282 of 1

rapid rain
#
bot.run(Configurations['Information']['Token'])
sweet steeple
#

yes bro

#

thats wha i wrote โ˜ ๏ธ

sick birch
#

Print it out again and see

harsh orbit
#
@bot.command()
@has_permissions(moderate_members=True)
async def timeout(ctx, member: discord.Member, time):
  if "s" in time:
    gettime = time.strip("s")
    if int(gettime) > 2419200:
      await ctx.reply("Timeout time can't be more than 28 days")
    else:
      newtime = datetime.timedelta(seconds=int(gettime))
      await member.edit(timed_out_until=discord.utils.utcnow() + newtime)
      await ctx.reply(member.mention + " Has been timed out for " + time)

  elif "m" in time:
    gettime = time.strip("m")
    if int(gettime) > 40320:
      await ctx.reply("Timeout time can't be more than 28 days")
    else:
      newtime = datetime.timedelta(minutes=int(gettime))
      await member.edit(timed_out_until=discord.utils.utcnow() + newtime)
      await ctx.reply(member.mention + " Has been timed out for " + time)

  elif "h" in time:
    gettime = time.strip("h")
    if int(gettime) > 672:
      await ctx.reply("Timeout time can't be more than 28 days")
    else:
      newtime = datetime.timedelta(hours=int(gettime))
      await member.edit(timed_out_until=discord.utils.utcnow() + newtime)
      await ctx.reply(member.mention + " Has been timed out for " + time)

  elif "d" in time:
    gettime = time.strip("d")
    if int(gettime) > 28:
      await ctx.reply("Timeout time can't be more than 28 days")
    else:
      newtime = datetime.timedelta(days=int(gettime))
      await member.edit(timed_out_until=discord.utils.utcnow() + newtime)
      await ctx.reply(member.mention + " Has been timed out for " + time)

@timeout.error
async def say_error(ctx, error):
   if isinstance(error, commands.MissingPermissions):
     await ctx.reply("**You don't Have permissions to use this command**")

   elif isinstance(error, commands.MissingRequiredArgument) or (error, commands.BadArgument):
     await ctx.reply(f"Please use the command in the correct way \n `{prefix}timeout (member) (time)`")


   elif isinstance(error, commands.BotMissingPermissions):
     await ctx.reply("**The bot does not have permissions to make this action**")โ€Š

What you advice me to add or edit in this command

night crater
#

Why does your command break if i put sss, s or anything which is missing a integer, or 9s9

Also why can't I do 1s 55m etc...

harsh orbit
#

There is bad argument error

night crater
#

I mean thats my point

#

I can be more specific about the duration, which you dont support

harsh orbit
#

Who will type 10ssssss

night crater
#

Users will always break something

tall temple
#

guys i lost my usb key where i run all my scripts, does smn know how can i get them back with computer memory or logs idk ..?

harsh orbit
#

When them breake it the bot will reply to them to type it in the right way

night crater
#

Does BadArgument catch value errors?

harsh orbit
#

I'll try

night crater
#

I also dont think that error catch works...

#

isinstance(error, commands.MissingRequiredArgument) or (error, commands.BadArgument) will always be true, because you're doing if condition or <tuple> so I think you've missed a isinstance

harsh orbit
#

Look at what happend

night crater
#

oh yeah I forget strip behaves like that

#

do 100as

#

or just 100sec

harsh orbit
#

Sec will work also

#

I will try as

night crater
#

!e ```py
print("100sec".strip("s"))

print(int("100sec".strip("s")))

unkempt canyonBOT
#

@night crater :x: Your 3.11 eval job has completed with return code 1.

001 | 100sec
002 | Traceback (most recent call last):
003 |   File "/home/main.py", line 3, in <module>
004 |     print(int("100sec".strip("s")))
005 |           ^^^^^^^^^^^^^^^^^^^^^^^^
006 | ValueError: invalid literal for int() with base 10: '100sec'
harsh orbit
#

as broke the command but it easy to solve

#

Nah didn't broke

#

It was just offline

#

And I will solve the 10ssss thing

harsh orbit
proud charm
#

Hi, I was making a discord music bot, and eveything is fine but when I try to make slash commands and I'm importing a discord_slash it's says it isnt installed but I installed everything.

this is my code:

import pytube
from discord.ext import commands
from discord_slash import SlashCommand, SlashContext

ffmpeg_path = "ffmpeg.exe"
ffmpeg_version_cmd = [ffmpeg_path, "-version"]

intents = discord.Intents.default()
intents.typing = False
intents.message_content = True
intents.members = True

client = commands.Bot(command_prefix='?', intents=intents)

its pretty empty beacuse i'm doing it from start again, if you want I can send the full code where the same issue also was. Thanks for all help!

#

(and pls ping me when you repling)

slate swan
#

Why use an additional package when discord.py supports slash commands

#

We cant help anyways

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

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

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

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

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

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

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

Guys I Need Discord Ticket Claim Script python

marble prism
#

Anyone know if it's possible to silence the "This form is being submitted to XXXXX Bot" on modals? I'm running the bot on my own server. It makes sense why it's there, though!

marble prism
#

Makes sense, thanks!

slate swan
#

๐Ÿ‘

harsh orbit
#
@bot.command()
@has_permissions(moderate_members=True)
async def timeout(ctx, member: discord.Member, time):
  if "s" in time:
    gettime = time.strip("s")
    if int(gettime) > 2419200:
      await ctx.reply("Timeout time can't be more than 28 days")
    else:
      newtime = datetime.timedelta(seconds=int(gettime))
      await member.edit(timed_out_until=discord.utils.utcnow() + newtime)
      await ctx.reply(member.mention + " Has been timed out for " + time)

  elif "m" in time:
    gettime = time.strip("m")
    if int(gettime) > 40320:
      await ctx.reply("Timeout time can't be more than 28 days")
    else:
      newtime = datetime.timedelta(minutes=int(gettime))
      await member.edit(timed_out_until=discord.utils.utcnow() + newtime)
      await ctx.reply(member.mention + " Has been timed out for " + time)

  elif "h" in time:
    gettime = time.strip("h")
    if int(gettime) > 672:
      await ctx.reply("Timeout time can't be more than 28 days")
    else:
      newtime = datetime.timedelta(hours=int(gettime))
      await member.edit(timed_out_until=discord.utils.utcnow() + newtime)
      await ctx.reply(member.mention + " Has been timed out for " + time)

  elif "d" in time:
    gettime = time.strip("d")
    if int(gettime) > 28:
      await ctx.reply("Timeout time can't be more than 28 days")
    else:
      newtime = datetime.timedelta(days=int(gettime))
      await member.edit(timed_out_until=discord.utils.utcnow() + newtime)
      await ctx.reply(member.mention + " Has been timed out for " + time)

@timeout.error
async def say_error(ctx, error):
   if isinstance(error, commands.MissingPermissions):
     await ctx.reply("**You don't Have permissions to use this command**")

   elif isinstance(error, commands.MissingRequiredArgument) or (error, commands.BadArgument):
     await ctx.reply(f"Please use the command in the correct way \n `{prefix}timeout (member) (time)`")


   elif isinstance(error, commands.BotMissingPermissions):
     await ctx.reply("**The bot does not have permissions to make this action**")โ€Š
sick birch
sick coyote
#

i can fetch a message from a channel from my own bot, even with message content intent disabled right?

sick birch
slate swan
#

anyone willing to help me combine some discord bots source codes .-.

hushed galleon
winter token
#
@commands.command()
    async def profile(self, ctx, member: discord.Member = None):
        member = member or ctx.author
        id = str(member.id)
        data = collection.find_one({"_id": id})

        if not data:
            return
        else:
            userBal = data.get("bal")
            userPokeDex = data.get("inv")

            if ',' in userPokeDex:
                pokemonList = userPokeDex.split(',')
                pokemonCount = len(pokemonList)
            elif userPokeDex==None:
                pokemonCount=0
            else:
                pokemonCount=1

            description = f"**Current Balance:** {userBal:,} PokeCoins\n**Pokemons Caught:** {pokemonCount}"
            embed = discord.Embed(title=f"{member.name}'s Profile", description=description, colour=discord.Colour.orange())
            embed.set_thumbnail(url=member.avatar or member.default_avatar)
            embed.set_footer(text=f"{time.strftime('%I:%H %p', time.localtime())}")
            await ctx.reply(embed=embed)
#

bot won't respond when the user's inv is None

upbeat gust
winter token
upbeat gust
#

Ah, do you get an error then?

hushed galleon
fast jackal
#

hi im learning python to learn how to make discord bots. what other things do I need to learn to be proficent in discord bots?

shrewd apex
#

perhaps a db too if u want to make any extensive bot

shrewd apex
#

object oriented programming

maiden fable
#

You need help?

#

Lemme see

#

Nothing happens as in?

#

It doesn't send the embed?

#

Do u have an error handler?

#

Do u have an else statement in there?

#

Show the whole traceback

#

In the else statement, instead of writing print(error), do raise error

sick birch
#

!e [1][1]

unkempt canyonBOT
#

@sick birch :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     [1][1]
004 |     ~~~^^^
005 | IndexError: list index out of range
maiden fable
#

But u r not directly indexing it

#

I get that

#

Show the whole traceback after doing what I told

#

Robin showed you above

#

!e
list = ['a','b','c']
list[6]

unkempt canyonBOT
#

@maiden fable :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 2, in <module>
003 |     list[6]
004 |     ~~~~^^^
005 | IndexError: list index out of range
sick birch
#

It means you're trying to access an item in a list that doesn't exist

#

For instance, trying to get the 10th item of a list that only has 5 items

maiden fable
#

raise error

#

Simple as that

#

else clause

#

Okay let's see

turbid condor
#

Can u show the code for on_command_error

maiden fable
#

The random.choice is raising the error for some reason

#

@sick birch any idea?

sick birch
#

nope, could be a pydroid thing

maiden fable
#

Most suitable explanation tbh ^

#

Try the same code on yr laptop

#

Issues can popup all of a sudden sometimes

#

Don't tell me the list was empty

#

Breh

#

Oh so like u cut and pasted the whole list outside the function?

#

Heh

#

That's cz u removed the random.choice line...

#

It isn't in the screenshot ๐Ÿคท

#

Weird but okay if it works

tepid dagger
#

how do you make a parameter optional, idk if thats worded properly but an input field that isnโ€™t required to be filled out

lucid current
#

trying to make a bot that changers discord server pfp and it giving me async with outside async function syntax error dk why

async def serverpfp(session):
    print("Changing server pfp...")
    url = f'https://discord.com/api/v9/guilds/{guild_id}'
    headers = {
        'Content-Type': 'application/json'
    }  
async with session.patch(url, headers=headers, json=payload)
    await session.guild.edit(name="testing rename and redit",
                             description="hi",
                             reason="test",
                             icon=icon,
                             banner=None)
naive briar
#

It's not inside the async function you defined

#

Look at its indentation

lucid current
naive briar
#

Indent it?

#
def a():
    print(...) # inside
def a():
print(...) # outside
naive briar
unkempt canyonBOT
#

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

001 | 0
002 | 1
tepid dagger
#

ok

#

=None works right

lucid current
# naive briar ```py def a(): print(...) # inside ``` ```py def a(): print(...) # outside `...
async def serverpfp(session):
    async with session.patch(url, headers=headers, json=payload)
    await session.guild.edit(name="testing rename and redit",
                             description="hi",
                             reason="test",
                             icon=icon,
                             banner=None)
    print("Changing server pfp...")
    url = f'https://discord.com/api/v9/guilds/{guild_id}'
    headers = {
        'Content-Type': 'application/json'
    } 
``` like this? mb if its a dumb question one of my first times playing around with bots
glad cradle
tepid dagger
#

ok

glad cradle
lucid current
#

edited it i think

#

yeah fixed it but new error

wispy pasture
#

my code:
https://sourceb.in/ByGWtr5qr2

my error:

2023-08-07 07:05:03 ERROR    discord.ui.view Ignoring exception in view <TrashButton timeout=None children=1> for item <Button style=<ButtonStyle.danger: 4> url=None disabled=False label='Delete the ticket' emoji=<PartialEmoji animated=False name='๐Ÿšฎ' id=None> row=None>
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/ui/view.py", line 427, in _scheduled_task
    await item.callback(interaction)
  File "/home/container/main.py", line 464, in trash
    open_tickets -= 1
UnboundLocalError: local variable 'open_tickets' referenced before assignment```
#

ik i m doing something stupid so please help this stupid person

lucid current
naive briar
#

Totally not because you define the variable after the code where you need to use it

lucid current
#

changed

#

will it still work with a .gif file or has to be a png

naive briar
#

If your server have level 1 boost, then yes

#

If not, no

lucid current
#

how do i create a clientsession object attribute for guild

shrewd apex
lucid current
shrewd apex
#

why do u want on for guild make it for the bot or cog no?

lucid current
shrewd apex
#

thats a basic python error

#

!e None.guild_url

unkempt canyonBOT
#

@shrewd apex :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     None.guild_url
004 | AttributeError: 'NoneType' object has no attribute 'guild_url'
shrewd apex
#

attribute dosent exist

lucid current
#
async def serverpfp(session):
    guild_url = f'https://discord.com/api/v9/guilds/{guild_id}'
    url = f'https://discord.com/api/v9/guilds/{guild_id}'
    headers = {
        'Content-Type': 'application/json'
    } 
    async with session.patch(url, headers=headers, json=payload)
        await session.guild_url.edit(name="testing rename and redit",
                             description="hi",
                             reason="test",
                             icon=icon,
                             banner=None)
    print("Changing server pfp...")
    ```
lucid current
lucid current
hollow ice
#

Anyone, can you give me sample discord bot for moderate and music in GitHub???๐Ÿ˜ข

harsh orbit
#
@bot.command()
@has_permissions(moderate_members=True)
async def timeout(ctx, member: discord.Member, time):
  if "s" in time:
    gettime = time.strip("s")
    if int(gettime) > 2419200:
      await ctx.reply("Timeout time can't be more than 28 days")
    else:
      newtime = datetime.timedelta(seconds=int(gettime))
      await member.edit(timed_out_until=discord.utils.utcnow() + newtime)
      await ctx.reply(member.mention + " Has been timed out for " + time)

  elif "m" in time:
    gettime = time.strip("m")
    if int(gettime) > 40320:
      await ctx.reply("Timeout time can't be more than 28 days")
    else:
      newtime = datetime.timedelta(minutes=int(gettime))
      await member.edit(timed_out_until=discord.utils.utcnow() + newtime)
      await ctx.reply(member.mention + " Has been timed out for " + time)

  elif "h" in time:
    gettime = time.strip("h")
    if int(gettime) > 672:
      await ctx.reply("Timeout time can't be more than 28 days")
    else:
      newtime = datetime.timedelta(hours=int(gettime))
      await member.edit(timed_out_until=discord.utils.utcnow() + newtime)
      await ctx.reply(member.mention + " Has been timed out for " + time)

  elif "d" in time:
    gettime = time.strip("d")
    if int(gettime) > 28:
      await ctx.reply("Timeout time can't be more than 28 days")
    else:
      newtime = datetime.timedelta(days=int(gettime))
      await member.edit(timed_out_until=discord.utils.utcnow() + newtime)
      await ctx.reply(member.mention + " Has been timed out for " + time)

@timeout.error
async def say_error(ctx, error):
   if isinstance(error, commands.MissingPermissions):
     await ctx.reply("**You don't Have permissions to use this command**")

   elif isinstance(error, commands.MissingRequiredArgument) or (error, commands.BadArgument):
     await ctx.reply(f"Please use the command in the correct way \n `{prefix}timeout (member) (time)`")


   elif isinstance(error, commands.BotMissingPermissions):
     await ctx.reply("**The bot does not have permissions to make this action**")โ€Š

What the errors I should add to this command to be perfect?

slate swan
#

i would just make a Converter for time and handle errors about it in the converter

harsh orbit
#

Wdym by time converter

slate swan
#

check the link ducky_sus

#

how do i exactly get at using python to make a discord bot in the first place?

slate swan
slate swan
#

i know how to use the discord dev portal and stuff

slate swan
#

Its needed in order to start making a discord bot

vale wing
#

And imo you're making too many unnecessary checks

#

!pypi durations-nlp just use this

unkempt canyonBOT
slate swan
civic pivot
#

Finished writing my first ever discord bot shipit . Honestly, it was easier than I expected thanks to very well written documentation from discord.py

maiden fable
#

discord.py is one of the best documented modules out there

cold sonnet
#

I saw a guy on fiverr who makes discord bots for 750 dollars

vale wing
cold sonnet
#

can I send it here

thin raft
#

I dont see why not

cold sonnet
#

I don't think so

glad cradle
thin raft
#

wtf

glad cradle
thin raft
#

140 orders

cold sonnet
#

yeah nah

glad cradle
cold sonnet
#

140 orders 8 in queue

thin raft
#

you can get a bot for only 1.1k!

glad cradle
#

what boosts your orders on fiverr are reviews so...

cold sonnet
#

lowest price 230 dollars premium 760

#

bro we could all be so fucking rich

#

๐Ÿ˜ญ๐Ÿ˜ญ

thin raft
#

they are not even hard bots lmao

glad cradle
#

yeah but no you have to make false orders and reviews at the start

thin raft
#

people have too much money

glad cradle
thin raft
#

I want to start on fiverr tbh
idk where tho

glad cradle
cold sonnet
#

that man doesn't even speak english

#

please give me the enough permissions to do the commands

thin raft
#

man

#

wth, imma become a millionare mining in minecraft

cold sonnet
#

that's tough

glad cradle
thin raft
#

some people are too lonely

#

you gotta be kidding me rn

#

make a dict instead of replacing 26 times

#

3d screen

cold sonnet
#

that is officially the most useful thing on discord

sick coyote
#

what is a partial interaction message? im just tryna get a message id from a message my bot sent

#

I did msg = await ctx.send(...)
msg.id

sick coyote
#

got it, needed to fetch the message

sick coyote
#

most of the attribute from discord.Message arent there

#

like the id

naive briar
#

What library are you using

harsh orbit
#
@bot.command()
@has_permissions(moderate_members=True)
async def timeout(ctx, member: discord.Member, time):
  if "s" in time:
    gettime = time.strip("s")
    if int(gettime) > 2419200:
      await ctx.reply("Timeout time can't be more than 28 days")
    else:
      newtime = datetime.timedelta(seconds=int(gettime))
      await member.edit(timed_out_until=discord.utils.utcnow() + newtime)
      await ctx.reply(member.mention + " Has been timed out for " + time)

  elif "m" in time:
    gettime = time.strip("m")
    if int(gettime) > 40320:
      await ctx.reply("Timeout time can't be more than 28 days")
    else:
      newtime = datetime.timedelta(minutes=int(gettime))
      await member.edit(timed_out_until=discord.utils.utcnow() + newtime)
      await ctx.reply(member.mention + " Has been timed out for " + time)

  elif "h" in time:
    gettime = time.strip("h")
    if int(gettime) > 672:
      await ctx.reply("Timeout time can't be more than 28 days")
    else:
      newtime = datetime.timedelta(hours=int(gettime))
      await member.edit(timed_out_until=discord.utils.utcnow() + newtime)
      await ctx.reply(member.mention + " Has been timed out for " + time)

  elif "d" in time:
    gettime = time.strip("d")
    if int(gettime) > 28:
      await ctx.reply("Timeout time can't be more than 28 days")
    else:
      newtime = datetime.timedelta(days=int(gettime))
      await member.edit(timed_out_until=discord.utils.utcnow() + newtime)
      await ctx.reply(member.mention + " Has been timed out for " + time)

@timeout.error
async def say_error(ctx, error):
   if isinstance(error, commands.MissingPermissions):
     await ctx.reply("**You don't Have permissions to use this command**")

   elif isinstance(error, commands.MissingRequiredArgument) or (error, commands.BadArgument):
     await ctx.reply(f"Please use the command in the correct way \n `{prefix}timeout (member) (time)`")


   elif isinstance(error, commands.BotMissingPermissions):
     await ctx.reply("**The bot does not have permissions to make this action**")โ€Š

How can I add timeout reason

naive briar
#

!d discord.Member.timeout

unkempt canyonBOT
#

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

Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta).

You must have [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members) to do this.

This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit).
naive briar
#

The reason argument ๐Ÿคท

harsh orbit
#

Ok

sick coyote
toxic moat
#
from discord import app_commands

class button_view(discord.ui.View):
    def __init__(self) -> None:
        super().__init__(timeout = None)

    discord.ui.button(label = 'verify', style = discord.ButtonStyle.green, custom_id = "verify")
    async def verify(self, interaction: discord.Interaction, button: discord.ui.Button):
        if type(client.role) is not discord.Role:
            client.role = interaction.guild.get_role(1138104211876356217)
        if client.role not in interaction.user.roles:
            await interaction.user.add_role(client.role)
            await interaction.response.send_message(f"I have given you {client.role.mention}!", ephermal=True)
        else: await interaction.response.send_message(f"You already have {client.role.mention}!", ephermal=True)
    

class aclient(discord.Client):
    def __init__(self):
        super().__init__(intents = discord.Intents.default)
        self.synced = False
        self.role = 1138104211876356217
        self.added = False


    async def on_ready(self):
        await self.wait_until_ready()
        if not self.synced:
            #await tree.sync(guild = discord.Objectt(id=))
            self.synced = True
        if not self.added:
            self.add_view(button_view())
            self.added = True
            print(f"logged in as {self.user}")

client = aclient()
tree = app_commands.Command.Tree(client)

@tree.command(guild = discord.Object(id=1138103534101987348), name = "test", description = "role button")
async def button(interaction: discord.Interaction):
    await interaction.response.send_message(view = button_view())

client.run("")```
dreamy dune
#

Run pip freeze

dreamy dune
#

Yeah that's an old version

toxic moat
dreamy dune
dreamy dune
#

Add () after discord.Intents.default

toxic moat
#

๐Ÿคฆโ€โ™‚๏ธ

toxic moat
naive briar
#

CommandTree not Command.Tree

toxic moat
cloud dawn
#

Did you sync it?

toxic moat
#

i should of i dont have a print

cloud dawn
#

Could you show the sync?

toxic moat
#
from discord import app_commands

class button_view(discord.ui.View):
    def __init__(self) -> None:
        super().__init__(timeout = None)

    discord.ui.button(label = 'verify', style = discord.ButtonStyle.green, custom_id = "verify")
    async def verify(self, interaction: discord.Interaction, button: discord.ui.Button):
        if type(client.role) is not discord.Role:
            client.role = interaction.guild.get_role(1138104211876356217)
        if client.role not in interaction.user.roles:
            await interaction.user.add_role(client.role)
            await interaction.response.send_message(f"I have given you {client.role.mention}!", ephermal=True)
        else: await interaction.response.send_message(f"You already have {client.role.mention}!", ephermal=True)
    

class aclient(discord.Client):
    def __init__(self):
        super().__init__(intents = discord.Intents.default())
        self.synced = False
        self.role = 1138104211876356217
        self.added = False


    async def on_ready(self):
        await self.wait_until_ready()
        if not self.synced:
            #await tree.sync(guild = discord.Objectt(id=))
            self.synced = True
        if not self.added:
            self.add_view(button_view())
            self.added = True
            print(f"logged in as {self.user}")

client = aclient()
tree = app_commands.CommandTree(client)

@tree.command(guild = discord.Object(id=1138103534101987348), name = "test", description = "role button")
async def button(interaction: discord.Interaction):
    await interaction.response.send_message(view = button_view())```
#

didnt mean to send everything

cloud dawn
#

Is this all your code?

toxic moat
cloud dawn
#

You aren't even starting the bot.

slate swan
#

discord.ui.button(label = 'verify', style = discord.ButtonStyle.green, custom_id = "verify") this should be decorator -> add @ before

toxic moat
dreamy dune
#

tree is app_commands.CommandTree

cloud dawn
#

I just asked if this was all your code ๐Ÿ˜ข

slate swan
#

i see the aclient class like 3rd time ๐Ÿ˜ตโ€๐Ÿ’ซ

dreamy dune
#

Although I'd recommend using commands.Bot instead of discord.Client if you want commands

toxic moat
#

i just want my slash cmds to work

cloud dawn
#

For slash commands I recommend Client.

slate swan
#

no need for Bot if not using prefixed commands

cloud dawn
toxic moat
slate swan
#
    async def on_ready(self):
        await self.wait_until_ready()
        if not self.synced:
            #await tree.sync(guild = discord.Objectt(id=))
            self.synced = True
        if not self.added:
            self.add_view(button_view())
            self.added = True
            print(f"logged in as {self.user}")
``` you never sync
#

the only line that would sync it commented out

cloud dawn
slate swan
toxic moat
#

i can just make a sync command right

slate swan
#

not mentioning it shouldnt be done in on_ready just saying why its not syncing up now

cloud dawn
cloud dawn
#

Hikari auto syncs it ๐Ÿ˜

toxic moat
#

idk how to sync my slash command i thought they were all good

slate swan
#

just sync it in setup_hook

toxic moat
#

and how

glad cradle
slate swan
#

nextcord too LC_yawning

slate swan
#

just move it to setup_hook

toxic moat
#

'just move' move what exactly

slate swan
#

the part that syncs the commands?

toxic moat
#

yea ik

#

but idk which part to move

slate swan
#

the part that syncs the command

toxic moat
#

alr bro just keep saying the part

slate swan
#

didnt you code it?

glad cradle
#

๐Ÿฅถ

green glacier
#

anyone here can help me run this discord bot file i will screenshare

ornate sapphire
#

im trying to make the bot add a role to new users when they join my server

#

I have this event all setup but for some reason it doesnt add the role with no errors

slate swan
#

!d discord.Guild.fetch_channel

unkempt canyonBOT
#

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

Retrieves a [`abc.GuildChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel) or [`Thread`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Thread) with the specified ID.

Note

This method is an API call. For general usage, consider [`get_channel_or_thread()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.get_channel_or_thread) instead.

New in version 2.0.
formal basin
slate swan
#

using string not int*

ornate sapphire
formal basin
ornate sapphire
#

when someone joins it sends the message in the right channel

formal basin
#

what verision are you on?

ornate sapphire
#

so yes. But I did the same thing for the role but it doesnt work

ornate sapphire
slate swan
ornate sapphire
slate swan
#

but you never add the role to member

#

!d discord.Guild.fetch_roles

unkempt canyonBOT
#

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

Retrieves all [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role) that the guild has.

Note

This method is an API call. For general usage, consider [`roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.roles) instead.

New in version 1.3.
slate swan
#

it just returns all roles

#

!d discord.Member.add_roles

unkempt canyonBOT
#

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

Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role)s.

You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles) to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role)s must appear lower in the list of roles than the highest role of the member.
ornate sapphire
#

ohhhh

#

so its gotta be

await member.guild.add_roles(role_ID)```
formal basin
#

await member.guild.add_roles(role)

ornate sapphire
#

ohhh oke

slate swan
#

or could be discord.Object(id=role_ID)

cloud dawn
#

Was boutta say just use snowflakes

ornate sapphire
#

this is what I did

slate swan
ornate sapphire
#

?

slate swan
formal basin
#

is it await member.add_roles(role)

cloud dawn
#

You cannot add roles to guild only create them.

ornate sapphire
ornate sapphire
ornate sapphire
#

but how do I fix it

upbeat ice
ornate sapphire
#

ikkk

formal basin
ornate sapphire
slate swan
#

await member.add_roles(role) is not the same as await member.guild.add_roles(role)

lyric sigil
#

hey guys ! do someone know a way to add a music system using slash commands to my discord bot ?

slate swan
lyric sigil
#

thx i'll check it later

slate swan
runic loom
#

Is there a way to make it so that for a slash command when you have a certain role, the output of the command is diff

unkempt canyonBOT
#

@discord.app_commands.check(predicate)```
A decorator that adds a check to an application command.

These checks should be predicates that take in a single parameter taking a [`Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction"). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure "discord.app_commands.CheckFailure") exception is raised and sent to the appropriate error handlers.

These checks can be either a coroutine or not.

Examples

Creating a basic check to see if the command invoker is you...
slate swan
#

more like

#

ok

#

!d discord.app_commands.checks.has_role

unkempt canyonBOT
#

@discord.app_commands.checks.has_role(item, /)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.

If a string is specified, you must give the exact name of the role, including caps and spelling.

If an integer is specified, you must give the exact snowflake ID of the role.

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

New in version 2.0...
runic loom
# slate swan !d discord.app_commands.checks.has_role

If there a way to make it so for example if a user has a role called โ€œ1โ€ they do a command and it gives them an output message of 1, but if he had a role called โ€œ2โ€ the command gives them an output message of 2

#

Im thinking ifs and elifs also im a beginner to python so im still figuring stuff out

slate swan
#

In this case i would do custom check

#

Or just if elif inside command

runic loom
#

Alr ty

ornate sapphire
#

take away the guild part and it works?

slate swan
#

Try and see

ornate sapphire
#

thanks

gilded harness
#

Hey I need some help

#

the discord bot doesn't delete its message after it tells the user to not swear

#
import time
import discord

# Define the required intents
intents = discord.Intents.default()
intents.message_content = True

bad_words = ["fuck", "shit", "bitch"]

client = discord.Client(intents=intents)

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if message.content.startswith('$hello'):
        await message.channel.send('Hello!')

    # Swears function to check and delete messages containing swear words
    async def swears(user_say):
        if any(word in user_say.lower() for word in bad_words):
            response_message = await message.channel.send("Hey!, don't swear")
            await message.delete()
            time_to_delete = 5  # Specify the time in seconds after which the response message will be deleted
            time.sleep(time_to_delete)
            await response_message.delete()

    await swears(message.content)

    await swears(message.content)```
#

Here's the code. The delete code is near the bottom

#

and the bad_words list is at the top near the intents variable.

#

I am using the time.sleep

#

to make it delete after 5 seconds

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

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

delete_after kwarg

gilded harness
#

where would I put that

slate swan
#

when you send

gilded harness
#

Alr

stray flax
#

Hey! i needed some help. I want to start make a custom bot for discord. But i dont now where and how i can started. Where do i need to make mine scripts and where can i make mine bot? So much quistions....

#

Tag me if someone answer

slate swan
#

in order to make a discord bot you need good knowledge of python

#

topics like OOP or async/await programming should be familiar to you

stray flax
#

i am a noob for making discords bots on progamma like this. I used always a simple app but i want to make it harder and better for me.

slate swan
#

start learning async/await syntax and maybe OOP and you are good to go

#

if you know basics already

#

also decorators, just know what they are no need to know how to define one

stray flax
#

how can i learn that? sorry for my dump quistions

slate swan
#

well online has many resources

#

!res

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

slate swan
#

maybe here is something

#

if no just search Python OOP guide or something

stray flax
#

Ok ty!

cloud dawn
#

The resource page includes OOP.

slate swan
#

thats the one i found on this list

cloud dawn
#

And it's all you need.

slate swan
#

i even watched one of those ๐Ÿ˜ณ

#

the last one

slate swan
#

cant help with it due to rule 5

#

!ytdl

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

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

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

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

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

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

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

thats not how it works

lyric sigil
#

like it work but its not playing music

cloud dawn
slate swan
cloud dawn
lyric sigil
#

no i pasted the code from the page and filled it with my infos

cloud dawn
#

I can't tell more without being smitten by the Discord mods. But it's not yet complete.

thin raft
cloud dawn
cloud dawn
#

That people got slain by the !ytdl some years ago.

thin raft
cloud dawn
#

There was also this one tutorial that a lot of people used that was just bad.

#

It was a nightmare.

thin raft
#

literally his tutorial (idk if he copeid code or if it was from him, I just watched that tutorial)

upbeat gale
#

dm if you can make a bloxflip bot i pay 10 dollars to 50 dollars

unkempt canyonBOT
#

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

slate swan
#

10 dollars

thin raft
#

I use it as my main programming language

#

id love that networking and microcontroller channels where as active as this one

slate swan
#

i saw once activity stats and the discord-bots channel had the most activity

#

is it somewhere here

glad cradle
#

data should be stored either in .txt files on in discord channels lmao

thin raft
#

python general is unbeatable

#

there's no stop

slate swan
#

i sent like 5 messages here

thin raft
#

when I need data I start the bot and make it send it's username to an api

glad cradle
#

cool

thin raft
#

is there something worse than json for storing stuff?

slate swan
thin raft
#

I sent 860

glad cradle
cloud dawn
thin raft
#

is rapptz in here?

cloud dawn
thin raft
glad cradle
cloud dawn
slate swan
#

danny

thin raft
#

just saw that

slate swan
#

but hes not here

glad cradle
#

tf is this a new thing?

slate swan
#

yeah

glad cradle
#

integrations can edit your profile and show information

slate swan
#

apparently its here for 8 months at least

#

first time seeing that

slate swan
#

?

thin raft
#

try it out

slate swan
#

this apply button is scary

thin raft
slate swan
#

yo what the

thin raft
#

he got a point ngl

slate swan
#

what the hell is build override

#

and how do i make one

cloud dawn
#

Lmao idk I just found thjis out.

#

Lemme put it in general just for funsies

thin raft
slate swan
#

this C# right

thin raft
cloud dawn
#

@slate swan It has been in Discord since v8 appereantly.

slate swan
#

and what is it now

#

v10?

cloud dawn
#

Dunno

#

But v8 was like dpy 1.6

slate swan
#

if talking about api version then v10 is latest

cloud dawn
#

ye

slate swan
#

but looks like you cant make your own build override

cloud dawn
#

Yep just saw you will get a 403

slate swan
#

im alpha android tester and never seen this

cloud dawn
#

Not alpha enough

slate swan
#

whats before alpha then

cloud dawn
#

Experiments settings have this

slate swan
#

experiments settings?

cloud dawn
cloud dawn
#

Yeah found that one too

slate swan
cloud dawn
slate swan
cloud dawn
#

My name isn't there, not proof, maybe I'll slip up once.

#

If I had it which I don't

#

๐Ÿ—ฟ

slate swan
#

what even error 1101 is

green glacier
slate swan
unkempt canyonBOT
#
Pasting large amounts of code

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

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

green glacier
#

i can screenshare in a vc

slate swan
green glacier
slate swan
#

yeah so why dont you paste the main.py code to paste service

#

did you get it from github repo by any chance

green glacier
#

i wanna see if it can run

thin raft
#

What project structure do you guys usually do?

slate swan
thin raft
#

where do you have the db?

#

bytecode at the end of the file?

slate swan
#

oh i dont use the db

#

just the .txt file

slate swan
thin raft
slate swan
thin raft
#

could you use the .py file to store permanent info?

#

bad idea that ill try

green glacier
slate swan
#

with open(".") as f:

thin raft
#

yeah

#

storing an sqlitedatabase inside the .py

#

at the end of it, idk if possible

slate swan
#

what stops you from trying

thin raft
#

im playing valo

#

ill try later, want a ping if I succeed?

slate swan
#

sure thing

slate swan
#

judging from the Notice in readme This project is currently a work in progress and should not be utilized at this time. it is not finished

green glacier
#

idk he wont show me

bleak brook
#

is something wrong with this command? It doesnt work

upbeat ice
bleak brook
upbeat ice
thin raft
#

lol

bleak brook
#

oh xD

#

yea, it just nothing happens

upbeat ice
#

no errors?

bleak brook
#

yea

upbeat ice
#

do you have an error handler?

bleak brook
#

no, how can I make one?

upbeat ice
#

well i was just wondering if it was throwing an error that was being consumed by an error handler

bleak brook
#

ah okay

upbeat ice
#

can you show your full code minus your token

bleak brook
#

terminal output

upbeat ice
#

hmm i think hybrid_commands get command context instead of interactions

thin raft
#

yup

upbeat ice
#

try async def sync(ctx: commands.Context)

grand charm
#

So anyone experienced with Python Discord bots who could help me?

I need to combine two commands, into 1 functio/command

grand charm
#

Do you want to come discord channel & help me?

upbeat gust
#

we are in a discord channel

grand charm
#

Yes, but my code has value

#

Im not going to put it in here for 500k people to copy it

#

if you want to help, you want to help, if not thats fine

upbeat gust
#

no ones taking ur code lmao

grand charm
#

Sure there are

#

this discord channel sure is full of rude piss kids

#

Forgive me asking

bleak brook
#

still does nothing..

upbeat ice
#

try adding await bot.process_commands(message) to your on_message call

upbeat gust
#

or change @bot.event to @bot.listen()

bleak brook
#

:D

#

is it also possible to "unsync" commands?

#

because there are some commands synced that i dont have in the code anymore

upbeat gust
upbeat gust
bleak brook
#

ah thanks

dense mesa
#

Okie dokies. Im back for more abuse ๐Ÿ˜œ๐Ÿซ ๐Ÿคฃ

#

I have finished creatibg my ERC20 with the functions I need.

Next up is creating a Discord bot to have functions to interact with the contract to purform token purchases through discord.

valid elbow
#

What is the main interest in discord bots? Why do them ?

sick birch
valid elbow
#

can you make home automation alert via a bot to you ?

#

or does it need to connect to a server

hushed galleon
#

if you need real-time information from discord or certain information not provided by their API like member statuses, then you'd have to stay connected to their websocket gateway

valid elbow
wispy pasture
#
@commands.guild_only()
@bot.hybrid_command(name="unban", description="Unban a user with a reason")
@app_commands.describe(member="The user ID to unban")
@app_commands.describe(reason="The reason for unbanning")
async def unban(ctx, member: int, reason: str):
    # Check if the user invoking the command has the allowed role
    allowed_role = discord.utils.get(ctx.guild.roles, id=MODERATOR_ROLE)
    if allowed_role in ctx.author.roles:
        try:
            user = await bot.fetch_user(member)
            await ctx.guild.unban(user, reason=reason)
            await ctx.send(f"{user.mention} has been unbanned for {reason}")
        except discord.NotFound:
            await ctx.send("User not found.")
    else:
        await ctx.send("You do not have permission to use this command.")```

not sure why its saying that
glad cradle
#

it's funny but discord IDs are too big so you should annotate it as str

wispy pasture
glad cradle
#

!d str.isdigit

unkempt canyonBOT
#

str.isdigit()```
Return `True` if all characters in the string are digits and there is at least one character, `False` otherwise. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the Kharosthi numbers. Formally, a digit is a character that has the property value Numeric\_Type=Digit or Numeric\_Type=Decimal.
wispy pasture
#

thank you

glad cradle
wispy pasture
glad cradle
#

you're welcome

wispy pasture
#

so i m getting this:
An error occurred while trying to ban the user: 403 Forbidden (error code: 50007): Cannot send messages to this user

but i am unsure if its my bots perms or my alts privacy.... the bot has all the intents and all perms from the dev portal, in the privacy of my alt the dms can be sent by anyone

naive briar
#

It cannot DM a user it doesn't share a mutual server with

wispy pasture
hasty coral
#

Anyone looking to work collaboratively on a Discord.PY bot? Iโ€™m not looking to lead the project, only looking to help develop it.
Pm me if you need someone. (Iโ€™m not charging)

slate swan
#

๐Ÿ—ฟ ๐Ÿ‘

dreamy dune
#

You should use aiohttp for discord bots

bleak brook
#

Is this a good way to storage data for every User, Guild and Member?```python

Storage System

database = {'guilds':{}, 'users':{}}

class GuildData:
def init(self, guild_data:dict) -> None:
self.members = {}
self.dict.update(guild_data)

def as_dict(self):
    data = self.__dict__
    return data

class MemeberData:
def init(self, member_data:dict) -> None:
self.dict.update(member_data)

def as_dict(self):
    data = self.__dict__
    return data

class UserData:
def init(self, user_data:dict) -> None:
self.dict.update(user_data)

def as_dict(self):
    data = self.__dict__
    return data

def load_data():
for guild in bot.guilds: # Load GuildData + MemberData
print(guild.name, guild.id)
if guild.id not in database['guilds']:
database['guilds'][guild.id] = GuildData({}).as_dict() #{'members':{}}
guild.data:GuildData = GuildData(database['guilds'][guild.id])

    for member in guild.members:
        if member.id not in database['guilds']['members']:
            database['guilds']['members'][member.id] = MemeberData({}).as_dict()
        member.data:MemeberData = MemeberData(database['guilds'][guild.id][member.id])

for user in bot.users: # Load UserData
    if user.id not in database['users']:
        database['users'][user.id] = UserData({}).as_dict()
    user.data:UserData = UserData(database['users'][user.id])
#

so that you can access the data like this: bot.get_user(2187412712386).data

#

I would be happy if someone would give their opinion on this :D

thin raft
#

I suppose you want it temporary right?

#

and why would you do that?

#

if someone leaves or joins a guild you're outdated

bleak brook
#

no, like i want to store the "database" in a file

thin raft
#

use a real database

#

although idk if that's against discords tos

bleak brook
#

why?

thin raft
#

its a privilege intent

#

have you tried the code @bleak brook?

bleak brook
#

not yet

bleak brook
cold sonnet
#

it is as long as the members know about it

#

depends on what you're storing

bleak brook
#

i think i know what you mean..

#

i just want to store like settings?

cold sonnet
#

that's cool

bleak brook
#

no xD i mean is it fine?

cloud dawn
thin raft
#

not all users will use the bot once

cloud dawn
#

Discord does request that if the bot is no longer in the guild to remove the data.

bleak brook
#

Yes, I will add that, of course, but actually I was concerned with whether the concept is good ๐Ÿ˜…

cloud dawn
bleak brook
#

yes

cloud dawn
#

But yeah I recommend using a database like postgres

bleak brook
#

hm, I'm actually not a fan of databases..

#

but i will try it

#

thanks

vocal snow
vocal snow
#

ORMs, nosql databases

meager rock
#

!e ```py
import dataclasses

@dataclasses.dataclass(repr=True)
class Member:
id: int
name: str
discrim: str

m = Member(1, "hello", "0123")
print(m)

unkempt canyonBOT
#

@meager rock :white_check_mark: Your 3.11 eval job has completed with return code 0.

Member(id=1, name='hello', discrim='0123')
bleak brook
#

can a dataclass be transformed to json format?

naive briar
#

Just make a method for that

meager rock
unkempt canyonBOT
#

src/utils.py lines 6 to 9

class AttrsClassToPayload:
    def to_payload(self) -> typing.Dict[str, typing.Any]:
        attrs: list[str] = [a.name for a in self.__attrs_attrs__ if not a.name.startswith("_")]  # type: ignore
        return {key: getattr(self, key) for key in attrs}```
meager rock
#

just replace attrs_attrs to __dataclass_params__ here

glad cradle
#

attrs ๐Ÿ˜๐Ÿ˜

bleak brook
#

It's so complicated ๐Ÿฅฒ

naive briar
#

!e

from dataclasses import dataclass

@dataclass(slots=True)
class A:
    b: int
    c: int

print(A.__dataclass_fields__)
unkempt canyonBOT
#

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

{'b': Field(name='b',type=<class 'int'>,default=<dataclasses._MISSING_TYPE object at 0x7f3e2fa6c850>,default_factory=<dataclasses._MISSING_TYPE object at 0x7f3e2fa6c850>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'c': Field(name='c',type=<class 'int'>,default=<dataclasses._MISSING_TYPE object at 0x7f3e2fa6c850>,default_factory=<dataclasses._MISSING_TYPE object at 0x7f3e2fa6c850>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD)}
meager rock
#

They use a different attribute name hmm

meager rock
bleak brook
#

i think we have to switch channels to -> databases

slate swan
weak ingot
#
class VerifyButton(discord.ui.View):
    @discord.ui.button(label="ใ€Ž๐Ÿ”ฐ ใ€Verify.", style=discord.ButtonStyle.success)
    async def button_callback(self, button, interaction):
        await interaction.response.send_message("you are verified!")

@bot.tree.command(name = 'verify', description = 'Makes the verify area in a spesific channel.')
async def test(interaction: discord.Interaction):
   await interaction.response.send_message('Click the "Verify" button to get verifird.', view = VerifyButton())

I get this when i click the button

23-08-08 13:50:44 ERROR    discord.ui.view Ignoring exception in view <VerifyButton timeout=180.0 children=1> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='ใ€Ž๐Ÿ”ฐ ใ€Verify.' emoji=None row=None>
Traceback (most recent call last):
  File "/home/fady/.local/lib/python3.10/site-packages/discord/ui/view.py", line 427, in _scheduled_task
    await item.callback(interaction)
  File "<string>", line 4, in button_callback
AttributeError: 'Button' object has no attribute 'response'
slate swan
#

You have swapped arguments

#

interaction is first and button is second

weak ingot
#

okay thanks

#

2023-08-08 14:03:50 ERROR discord.ui.view Ignoring exception in view <VerifyButton timeout=180.0 children=1> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='ใ€Ž๐Ÿ”ฐ ใ€Verify.' emoji=None row=None>
Traceback (most recent call last):
File "/home/fady/.local/lib/python3.10/site-packages/discord/ui/view.py", line 427, in _scheduled_task
await item.callback(interaction)
File "<string>", line 4, in button_callback
File "/home/fady/.local/lib/python3.10/site-packages/discord/member.py", line 1051, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'str' object has no attribute 'id'

#

class VerifyButton(discord.ui.View):
@discord.ui.button(label="ใ€Ž๐Ÿ”ฐ ใ€Verify.", style=discord.ButtonStyle.success)
async def button_callback(self, interaction: discord.Interaction, button):
await interaction.user.add_roles('verify')

@bot.tree.command(name = 'verify', description = 'Makes the verify area in a spesific channel.')
async def test(interaction: discord.Interaction):
await interaction.response.send_message('Click the "Verify" button to get verifird.', view = VerifyButton())

slate swan
#

can you format it?

#

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

weak ingot
#

sry

#
class VerifyButton(discord.ui.View):
    @discord.ui.button(label="ใ€Ž๐Ÿ”ฐ ใ€Verify.", style=discord.ButtonStyle.success)
    async def button_callback(self, interaction: discord.Interaction, button):
        await interaction.user.add_roles('verify')

@bot.tree.command(name = 'verify', description = 'Makes the verify area in a spesific channel.')
async def test(interaction: discord.Interaction):
   await interaction.response.send_message('Click the "Verify" button to get verifird.', view = VerifyButton())
slate swan
#

yeah so .add_roles expects Snowflake but you gave it string

#

!d discord.Member.add_roles

unkempt canyonBOT
#

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

Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role)s.

You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles) to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role)s must appear lower in the list of roles than the highest role of the member.
slate swan
#

either get the role id and do discord.Object(id=YOUR_ROLE_ID) or if you only have the name use discord.utils.get helper method

weak ingot
#

thx

slate swan
#

hello

#

how can i host my python bot for free ?

weak ingot
#
2023-08-08 14:13:22 ERROR    discord.app_commands.tree Ignoring exception in command 'purge'
Traceback (most recent call last):
  File "/home/fady/.local/lib/python3.10/site-packages/discord/app_commands/commands.py", line 828, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
  File "<string>", line 13, in purge
  File "/home/fady/.local/lib/python3.10/site-packages/discord/interactions.py", line 778, in send_message
    flags.ephemeral = ephemeral
  File "/home/fady/.local/lib/python3.10/site-packages/discord/flags.py", line 87, in __set__
    instance._set_flag(self.flag, value)
  File "/home/fady/.local/lib/python3.10/site-packages/discord/flags.py", line 198, in _set_flag
    raise TypeError(f'Value to set for {self.__class__.__name__} must be a bool.')
TypeError: Value to set for MessageFlags must be a bool.

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

Traceback (most recent call last):
  File "/home/fady/.local/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/fady/.local/lib/python3.10/site-packages/discord/app_commands/commands.py", line 853, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/home/fady/.local/lib/python3.10/site-packages/discord/app_commands/commands.py", line 842, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'purge' raised an exception: TypeError: Value to set for MessageFlags must be a bool.
#
@bot.tree.command(name = 'purge', description = 'Deletes a set amount of messages from this channel.')
@app_commands.describe(amount = 'How many messages should we delete(max = 1000, min = 1)?')
async def purge(ctx, amount: int):
    if amount < 1:
        await ctx.send('The amount must be grater than 1.', ephemeral = True)
        return

    elif amount > 1000:
        await ctx.send('The amount must be less than 1000.', ephemeral = True)
        return

    await ctx.channel.purge(limit=amount)
    await ctx.response.send_message(f'Succsessfuly deleted {amount}.', ephemeral = 'True')
#

it deletes the messages

#

but it doesnt semd the "Succsessfuly deleted {amount}." message

slate swan
#

the ephemeral is expected to be bool

#

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

what do i need to do ??

slate swan
#

you pass it as string

weak ingot
#

oh

#

thx

weak ingot
# slate swan you pass it as string

023-08-08 14:21:22 ERROR discord.app_commands.tree Ignoring exception in command 'purge'
Traceback (most recent call last):
File "/home/fady/.local/lib/python3.10/site-packages/discord/app_commands/commands.py", line 828, in _do_call
return await self.callback(interaction, **params) # type: ignore
File "<string>", line 13, in purge
File "/home/fady/.local/lib/python3.10/site-packages/discord/interactions.py", line 801, in send_message
await adapter.create_interaction_response(
File "/home/fady/.local/lib/python3.10/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

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

Traceback (most recent call last):
File "/home/fady/.local/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/fady/.local/lib/python3.10/site-packages/discord/app_commands/commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/fady/.local/lib/python3.10/site-packages/discord/app_commands/commands.py", line 846, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'purge' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction

#
@bot.tree.command(name = 'purge', description = 'Deletes a set amount of messages from this channel.')
@app_commands.describe(amount = 'How many messages should we delete(max = 1000, min = 1)?')
async def purge(ctx, amount: int):
    if amount < 1:
        await ctx.send('The amount must be grater than 1.', ephemeral = True)
        return

    elif amount > 1000:
        await ctx.send('The amount must be less than 1000.', ephemeral = True)
        return

    await ctx.channel.purge(limit=amount)
    await ctx.response.send_message(f'Succsessfuly deleted {amount}.', ephemeral = True)
slate swan
#

how about you do ctx.channel.send

gilded harness
#
    async def swears(user_say):
        if any(word in user_say.lower() for word in bad_words):
            response_message = await message.channel.send("Hey!, don't swear")
            await message.delete()
            await response_message.delete(delay=5)  # Delete the response message after 5 seconds

    await swears(message.content)

    await swears(message.content)``` When the user swears it's supposed to delete the bot message 5 seconds after it posted the message of not to swear. But instead it posts that same message 5 times.
slate swan
#

didnt i already tell you the solution

#

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

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

delete_after kwarg ^

gilded harness
#

Bro im new to discord bots

#

Idk what you're talking about

#

"Delete_after kwarg"

#

Bro like Idk what that does

slate swan
#

if you dont understand what that means you shouldnt be making a discord bot project

#

you need intermediate knowledge about python to make one

gilded harness
#

??? The whole point of making a discord bot is to learn

slate swan
#

its not a good project to learn trust me

gilded harness
gilded harness
vocal snow
#

!kindling

unkempt canyonBOT
#
Kindling Projects

The Kindling projects page on Ned Batchelder's website contains a list of projects and ideas programmers can tackle to build their skills and knowledge.

gilded harness
#

I hate that site

slate swan
vocal snow
slate swan
#

delete_after (float) โ€“ If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.

gilded harness
#

Theres no projects

slate swan
gilded harness
#

Oh the other one was bugged

#

Now I see

#

What's Mad-libs?

#

Oh nvm I get it

tepid dagger
#

im trying to send an embed as a dm to a user but i get an error saying that i can't

#

code: embed = discord.Embed(title="text", color=000000) embed.add_field(name = None, value=f"text") await user.send(embed=embed)

#

what's wrong with the code

upbeat gust
#

Probably just means you literally can't send a message to them, dms closed, no shared server, etc.

tepid dagger
#

oh

#

can you send embeds to users though?

#

in the way i did

upbeat gust
tepid dagger
#

the way i did should work right

upbeat gust
#

Can you send normal messages?

tepid dagger
#

yes

#

i think

#

lemme try with another user

upbeat gust
#

Do it with the same one

#

99% sure this is because dms closed

tepid dagger
#

yea it is

#

wait how do you turn on dms to all members for bots

#

like so they can accept dms

upbeat gust
#

what

tepid dagger
#

the dm was to a bot

#

how do you allow a bot to accept dms from all users

#

do you need to be in a server with the bot

#

to dm the bot

lyric sigil
#

how do i install subprocess w/ requirements.txt ?

upbeat gust
lyric sigil
#

what

#

like what do i put to install it with requirements.txt cuz i use pterodactyl for hosting the bot

upbeat gust
naive briar
#

!d subprocess

unkempt canyonBOT
#

Source code: Lib/subprocess.py

The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several older modules and functions:

os.system
os.spawn*
```  Information about how the [`subprocess`](https://docs.python.org/3/library/subprocess.html#module-subprocess) module can be used to replace these modules and functions can be found in the following sections.
lyric sigil
#

but like its for running 2 bots on the same hoster

#

and i wanted to find how to do that

upbeat gust
lyric sigil
#

and what system do i choose ?

upbeat gust
lyric sigil
upbeat gust
#

Where are you starting the task?

upbeat gust
lyric sigil
upbeat gust
#

what

lyric sigil
#

like if i install windows on it it will not run 24/7

upbeat gust
lyric sigil
#

the vps

lyric sigil
upbeat gust
#

if you don't turn off a computer, it will stay on

#

๐Ÿ˜ฑ

lyric sigil
naive briar
#

If you don't implement it, no

upbeat gust
lyric sigil
upbeat gust
#

Oh you mean that

#

Fyi people don't usually use windows for servers, usual Linux distros like debian

lyric sigil
upbeat gust
#

that's fine

lyric sigil
turbid condor
#

As a whole or dedicated for bot?

upbeat gust
turbid condor
#

๐Ÿ‘€

lyric sigil
upbeat gust
lyric sigil
upbeat gust
#

well, there is

lyric sigil
#

dont have it there

upbeat gust
#

ยฏ_(ใƒ„)_/ยฏ

lament mesa
meager rock
lament mesa
formal basin
#
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/container/.local/lib/python3.10/site-packages/discord/app_commands/commands.py", line 849, in _invoke_with_namespace
    if not await self._check_can_run(interaction):
  File "/home/container/.local/lib/python3.10/site-packages/discord/app_commands/commands.py", line 987, in _check_can_run
    return await async_all(f(interaction) for f in predicates)
  File "/home/container/.local/lib/python3.10/site-packages/discord/utils.py", line 705, in async_all
    elem = await elem
  File "/home/container/.local/lib/python3.10/site-packages/discord/app_commands/checks.py", line 407, in predicate
    raise CommandOnCooldown(bucket, retry_after)
discord.app_commands.errors.CommandOnCooldown: You are on cooldown. Try again in 95.41s
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1089, in wrapper
    await self._call(interaction)
  File "/home/container/.local/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1252, in _call
    await self.on_error(interaction, e)
  File "/home/container/zagzag.py", line 1122, in on_app_command_error
    await interaction.followup.send(error, ephemeral=True)
  File "/home/container/.local/lib/python3.10/site-packages/discord/webhook/async_.py", line 1805, in send
    data = await adapter.execute_webhook(
  File "/home/container/.local/lib/python3.10/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```
#
@tree.error
async def on_app_command_error(interaction: discord.Interaction, error: AppCommandError):
     
      command = interaction.command.name
      channel2 = client.get_channel(1112053260879147130)
      if isinstance(error, app_commands.CommandOnCooldown):
        await interaction.followup.send(error, ephemeral=True)
      else:
       button = Button(label="support server", url="")
       view = View()
       view.add_item(button)
       embed = discord.Embed(title="An error has occured", description="If you need help with this error join the support server. ", colour=discord.Colour.red())
       embed.add_field(name="",value="Reasons why you might have gotten this error")
       embed.add_field(name="Reason 1  ", value=""
        "Make sure the bot role is is on the top. Server settings > Roles > Drag the bot role (zagzag) to the top")
       embed.add_field(name="Reason 2", value=""
        "Make sure the bot has the right permissions. The permissions this bot needs: ``send messages``, ``read channel history``, ``time out members``, ``kick members``, ``ban members``, ``manage server``, ``manage messages``, ``attach files``, ``add reactions``, ``manage nicknames``")
       embed.add_field(name="", value="If you have Done all the steps above and the bot and you still get this error join the support server. ")
       await interaction.followup.send(embed=embed, view=view)
       await channel2.send(f"{command} command used by {interaction.user} but an error occured")
       traceback.print_exc(limit=None, file=None, chain=True)

the error doesnt send

upbeat gust
#

Use response.send_message

formal basin
#

ok

#

thanks

weak ingot
#
@bot.tree.command(name = 'kick', description='Kicks a user from this server.')
@app_commands.describe(user = 'Who do you want to kick?', reason = 'Why do you want to kick them?')
@commands.has_permissions(kick_members=True) 
async def kick(interaction: discord.Interaction, user: discord.User, reason: str = None):
    await user.kick(reason=reason)
    await interaction.response.send_message(f'Succsesfuly kicked {user} by {interaction.user.mention}!', ephemeral = True)
        ```

it doesnt check for the permissio
turbid condor
weak ingot
#

is there a way here???

turbid condor
#

!d discord.app_commands.check

unkempt canyonBOT
#

@discord.app_commands.check(predicate)```
A decorator that adds a check to an application command.

These checks should be predicates that take in a single parameter taking a [`Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction"). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure "discord.app_commands.CheckFailure") exception is raised and sent to the appropriate error handlers.

These checks can be either a coroutine or not.

Examples

Creating a basic check to see if the command invoker is you...
turbid condor
meager rock
#

!pip hikari

unkempt canyonBOT
meager rock
#

the RestBot provides a HTTP interface

slate swan
#

Hikari GIGACHAD

sweet steeple
#

pls help

cold sonnet
#

just remove the 7th line

#

you don't need two clients/bots

#

you only run one anyway

#

and you can remove line 5 too

#

don't need to enable members intent when you already have all intents

#

wdym SelfBotManager

#

is it a self bot that manages or a bot that detects self bots

#

@sweet steeple

slate swan
#

!rule 5

unkempt canyonBOT
#

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

slate swan
#

We wont help with self bots

sweet steeple
#

i think im too bad at python to even start making that tho

#

my server got raided by bots so

cold sonnet
#

not sure how you can detect self bots

#

except if it's not a bot but sends embeds

#

that's a self bot for sure

naive briar
#

Didn't Discord fixed that already?

sweet steeple
#

i guess not

#

i got raided 3 days ago โ˜ ๏ธ

#

mfs kicked

#

800 memebrs in 2 minutes

cold sonnet
#

don't give motherfuckers mod

sweet steeple
#

yeah

naive briar
#

Why do you even give some random people kick permissions

sweet steeple
#

i figured that out

sweet steeple
naive briar
#

How did someone even get the account's both email and password

sweet steeple
naive briar
#

Do people just share their Discord account's token as a habit

sick birch
sweet steeple
#

ig

#

ill prob js end up paying a bot developer

sick birch
#

Don't do that either, there are plenty of reputable anti-raid bots on the marketplace

sweet steeple
#

free?

sick birch
#

Probably

sweet steeple
#

cool

#

ill take a look

#

man i miss lua coding this python shi is dumb

sick birch
#

you can make discord bots in pretty much any language

sweet steeple
#

is there a discord driver for lua?

naive briar
#

Have anyone made a Discord bot in BF yet?

sick birch
sweet steeple
#

roblox coding flipped discord

#

lua moment

slate swan
slate swan
cloud dawn
lyric sigil
#

can i host discord python bot with ubuntu server ?

slate swan
#

yeah

lyric sigil
#

how ?

slate swan
#

like you would do on every other server

#

just run it and leave server on

lyric sigil
#

but i can't install python3-pip

slate swan
#

dam

formal basin
#

how can I start using modals

cold sonnet
#

this server really needs less moderation bru

slate swan
unkempt canyonBOT
#

class discord.ui.Modal(*, title=..., timeout=None, custom_id=...)```
Represents a UI modal.

This object must be inherited to create a modal popup window within discord.

New in version 2.0.

Examples...
slate swan
#

just start using them i guess

formal basin
lyric sigil
cold sonnet
#

isn't ubuntu the os

#

doesn't matter

glad cradle
weak ingot
#
Traceback (most recent call last):
  File "/home/fady/Documents/Code/public/FlareMod/bot.py", line 46, in <module>
    exec(f.read())
  File "<string>", line 15, in <module>
  File "/home/fady/.local/lib/python3.10/site-packages/discord/app_commands/commands.py", line 1975, in decorator
    return Command(
  File "/home/fady/.local/lib/python3.10/site-packages/discord/app_commands/commands.py", line 666, in __init__
    self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.__globals__)
  File "/home/fady/.local/lib/python3.10/site-packages/discord/app_commands/commands.py", line 374, in _extract_parameters_from_callback
    param = annotation_to_parameter(resolved, parameter)
  File "/home/fady/.local/lib/python3.10/site-packages/discord/app_commands/transformers.py", line 833, in annotation_to_parameter
    (inner, default, validate_default) = get_supported_annotation(annotation)
  File "/home/fady/.local/lib/python3.10/site-packages/discord/app_commands/transformers.py", line 792, in get_supported_annotation
    raise TypeError(f'unsupported type annotation {annotation!r}')
TypeError: unsupported type annotation <class 'discord.interactions.Interaction'>
fady@debian-hffn1at:~/Documents/Code/public/FlareMod$ 

This is my code

formal basin
#

Yes

weak ingot
#
@app_commands.command(name="embed_message", description="Create a embed message")
@app_commands.describe(title="The title of your message", message="Your message", color="Embed color", image="Add an image to your message (with image's url : http(s)://...)", url="Add an url to your message (http(s)://....)")
@app_commands.choices(color=[
                app_commands.Choice(name="๐Ÿ”ด Red", value=0xff0000),
                app_commands.Choice(name="๐Ÿ”ต Blue", value=0x0000ff),
                app_commands.Choice(name="๐ŸŸข Green", value=0x00ff00),
                app_commands.Choice(name="๐ŸŸฃ Purple", value=0x883af1),
                app_commands.Choice(name="๐ŸŸก Yellow", value=0xffe34d),
                app_commands.Choice(name="๐ŸŸ  Orange", value=0xff8000),
                app_commands.Choice(name="๐ŸŸค Brown", value=0x845321),
                app_commands.Choice(name="โšซ๏ธ Black", value=0xffffff),
                app_commands.Choice(name="โšช๏ธ White", value=0x000000),
                ])
@app_commands.checks.has_permissions(administrator=True) 
async def embed_message(self, interaction: discord.Interaction, title: str, message: str, image: str = None, url: str = None, color:int = 0xff0000):
    await interaction.response.defer()
    if title!="" or message!="":
        embed = discord.Embed(title = title, description = message, color = color)
        if image!="":
            embed.set_thumbnail(url=image)
        if url!="":
            embed.url=url
        await interaction.followup.send(embed=embed)

    else:
        await interaction.followup.send("You must enter at least one title or message", ephemeral=True)

@embed_message.error
async def on_embed_message_error(interaction: discord.Interaction, error: app_commands.AppCommandError):
    if isinstance(error, app_commands.MissingPermissions):
        await interaction.response.send_message(f"{interaction.user.mention}, you don't have the required permission(s) to use this command.", ephemeral=True)
glad cradle
#

atm modals accept only text as an input

formal basin
#

Oh

slate swan
#

i remember times when you could have dropdown inside

weak ingot
#

no**

slate swan
weak ingot
#

idk

slate swan
#

me neither

weak ingot
#

but why do i get that error

slate swan
#

cause you have self

#

also if you use @app_commands.command this decorator outside Cog class you will need to add this command manually to bot

weak ingot
#

okay

#
@app_commands.command(name="embed", description="Create a embed message")
@app_commands.describe(title="The title of your message", message="Your message", color="Embed color", image="Add an image to your message (with image's url : http(s)://...)", url="Add an url to your message (http(s)://....)")
@app_commands.choices(color=[
                app_commands.Choice(name="๐Ÿ”ด Red", value=0xff0000),
                app_commands.Choice(name="๐Ÿ”ต Blue", value=0x0000ff),
                app_commands.Choice(name="๐ŸŸข Green", value=0x00ff00),
                app_commands.Choice(name="๐ŸŸฃ Purple", value=0x883af1),
                app_commands.Choice(name="๐ŸŸก Yellow", value=0xffe34d),
                app_commands.Choice(name="๐ŸŸ  Orange", value=0xff8000),
                app_commands.Choice(name="๐ŸŸค Brown", value=0x845321),
                app_commands.Choice(name="โšซ๏ธ Black", value=0xffffff),
                app_commands.Choice(name="โšช๏ธ White", value=0x000000),
                ])
@app_commands.checks.has_permissions(administrator=True) 
async def embed(interaction: discord.Interaction, title: str, message: str, image: str = None, url: str = None, color:int = 0xff0000):
    await interaction.response.defer()
    if title!="" or message!="":
        embedmsg = discord.Embed(title = title, description = message, color = color)
        if image!="":
            embed.set_thumbnail(url=image)
        if url!="":
            embed.url=url
        await interaction.followup.send(embed=embedmsg)

    else:
        await interaction.followup.send("You must enter at least one title or message", ephemeral=True)

@embed.error
async def on_embed_error(interaction: discord.Interaction, error: app_commands.AppCommandError):
    if isinstance(error, app_commands.MissingPermissions):
        await interaction.response.send_message(f"{interaction.user.mention}, you don't have the required permission(s) to use this command.", ephemeral=True)
#

it dosent sync

slate swan
#

what did i just say?

weak ingot
#

okie

sick coyote
#

so i have a tasks.loop its kinda complicated, but as soon as 1 thing gets stuck the whole loop doesnt run anymore, what is the problem?

weak ingot
#

Traceback (most recent call last):
File "/home/fady/Documents/Code/public/FlareMod/bot.py", line 46, in <module>
exec(f.read())
File "<string>", line 17
embedmsg = discord.Embed(title = title, description = message, color = color)
IndentationError: unexpected indent

unkempt canyonBOT
#
Indentation

Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.

Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.

Example

def foo():
    bar = 'baz'  # indented one level
    if bar == 'baz':
        print('ham')  # indented two levels
    return bar  # indented one level

The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.

Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines

More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation

weak ingot
#

Test
Test\nTest

it didnt make a new line

@bot.tree.command(name="embed", description="Create a embed message")
@app_commands.describe(title="The title of your message", message="Your message", color="Embed color", image="Add an image to your message (with image's url : http(s)://...)", url="Add an url to your message (http(s)://....)")
@app_commands.choices(color=[
                app_commands.Choice(name="๐Ÿ”ด Red", value=0xff0000),
                app_commands.Choice(name="๐Ÿ”ต Blue", value=0x0000ff),
                app_commands.Choice(name="๐ŸŸข Green", value=0x00ff00),
                app_commands.Choice(name="๐ŸŸฃ Purple", value=0x883af1),
                app_commands.Choice(name="๐ŸŸก Yellow", value=0xffe34d),
                app_commands.Choice(name="๐ŸŸ  Orange", value=0xff8000),
                app_commands.Choice(name="๐ŸŸค Brown", value=0x845321),
                app_commands.Choice(name="โšซ๏ธ Black", value=0xffffff),
                app_commands.Choice(name="โšช๏ธ White", value=0x000000),
                ])
@app_commands.checks.has_permissions(administrator=True) 
async def embed(interaction: discord.Interaction, title: str, message: str, image: str = None, url: str = None, color:int = 0xff0000):
    await interaction.response.defer()
    embedmsg = discord.Embed(title = title, description = message, color = color)
    if image != None:
        embed.set_thumbnail(url=image)
    if url != None:
        embed.url=url
    await interaction.followup.send(embed=embedmsg)

@embed.error
async def on_embed_error(interaction: discord.Interaction, error: app_commands.AppCommandError):
    if isinstance(error, app_commands.MissingPermissions):
        await interaction.response.send_message(f"{interaction.user.mention}, you don't have the required permission(s) to use this command.", ephemeral=True)```
glad cradle
slate swan
glad cradle
sick coyote
#

i dont want to send anything, but i want to complete the interaction, otherwise it shows an error taht the interaction failed, is send_autocomplete the right function to use

slate swan
formal basin
thin raft
slate swan
thin raft
#

dont give discord ideas pls

lyric sigil
#

Guys i have a problem with my vps

slate swan
#

unfortunate

lyric sigil
#

like i've figured out how to run a bot on it but when i close the browser he stops running

lyric sigil
formal basin
#

make a support ticket then

slate swan
#

Use screen or make some cron job or whatever, use Google

slate swan
lyric sigil
#

!d discord screen

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.

lyric sigil
#

bruh

slate swan
#

It's a command, use Google

slate swan
#

or screen yeah

lyric sigil
glad cradle
formal basin
formal basin
slate swan
#

sounds legit

formal basin
#

i use it

glad cradle
#

I have read cp as c++

lyric sigil
#

and its free forever ?

slate swan
#

free only for first hour

formal basin
slate swan
#

so you need to create new accounds each hour

lyric sigil
glad cradle
#

@vale wing i wish I could use bobux to pay an host, tbh most websites and companies should recognize that as a method of payment

formal basin
vale wing
#

However course of usd to bobux is unknown

slate swan
#

Payment method:

  • PayPal
  • Credit Card
  • Bobux
  • Gift Card
formal basin
glad cradle
lyric sigil
slate swan
glad cradle
vale wing
granite agate
#

@slate swan i fixed the problem

slate swan
granite agate
#

๐Ÿซก

vale wing
glad cradle
vale wing
#

Better lootbox in daily and votes

slate swan
vale wing
#

Yeah basic features + some premium commands

glad cradle
#

this chat is now our HQ

slate swan
#

its about discord bots indeed swag

glad cradle
#

can't wait the time when we'll need to shard @vale wing

#

and can't wait the time when we'll need to do clustering

#

(that time will never come)

sullen moon
#

Guys I am trying to get my discord bot to run a script for me in discord. anyone know if it is even possible?

vale wing
#

Yeah

sullen moon
#

could you help me to understand this?

vale wing
#

!source e

unkempt canyonBOT
#
Command: eval

Run Python code and get the results.

Source Code
vale wing
#

That's for general python script running

sullen moon
#

thank you.

slate swan
vale wing
#

For interacting with bot code during runtime see this, might be not the finest piece but alright

sullen moon
#

so to make my script work in discord. what do I exactly need to do?

unkempt canyonBOT
#

ext/system.py line 179

async def _exec(self, inter: disnake.ApplicationCommandInteraction, code: str):```
sullen moon
#

I have been watching tutorials for couple of hours, I am not familiar with python

slate swan
vale wing
sullen moon
#

yeah

vale wing
#

If you are new to python, we do not recommend starting learning from a discord bot, as you need this knowledge:

  • basics (variables, loops, math, basic types)
  • simple data structures (dicts, lists)
  • modules and libraries
  • functional programming
  • object-oriented programming
  • async programming principles
#

Encouraging learning, just not from discord bot

sullen moon
#

Well I have a discord bot with few working commands already done

glad cradle
# slate swan when you even need to

when you see that the Bot takes too much time to respond to commands or when the resources of your host are near 70/80% even though the Bot is under normal load

#

asynchronous code is powerful but it has his limitations!

vale wing
#

Bobux eats 200mb

keen trail
keen trail
vale wing
slate swan
#

200 micro bytes

glad cradle
keen trail
sullen moon
#

So exenifix, this script Im trying to get to work in discord is some kind of encrypting software? that can encrypt and decrypt messages

vale wing
#

What encryption method

sullen moon
#

can I just send the script to you?

#

I do not know how to explain

slate swan
#

Caesar Cipher method op

sullen moon
#

I found it in youtube ๐Ÿ’€

sullen moon
cloud dawn
#

!d string.ascii_lowercase

unkempt canyonBOT
#

string.ascii_lowercase```
The lowercase letters `'abcdefghijklmnopqrstuvwxyz'`. This value is not locale-dependent and will not change.
cloud dawn
#

My eyes

slate swan
#

your eyes what

cloud dawn
#

letters = 'abcdefghijklmnopqrstuvwxyz'

slate swan
#

ah where is that

sullen moon
#

familiar looking

slate swan
vale wing
#

@cloud dawn sorry for being annoying but update system when

slate swan
#

never

keen trail
#

YES FINNALY I FUCKING MADE THE DISCORD AUTH WORKINH

sullen moon