#discord-bots

1 messages ยท Page 163 of 1

slate swan
#

anyone know why this doesnt set the channel?

#
@client.tree.command()
async def viewdb(ctx: discord.Interaction):
  count = 0
  async with aiosqlite.connect("main.db") as db:
    async with db.cursor() as cursor:
      await cursor.execute("SELECT * FROM users")
      result = await cursor.fetchall()
      embed = discord.Embed(title='DB', description='')
      for i in result:
        count = count + 1
        embed.description += f"\n{count} **<>** {i}"
  await ctx.response.send_message(embed=embed, ephemeral=True)

im using this to see the db

slate swan
#

Just a question, why are all colors in discord.Color functions? Why can't they just be a constant?

naive briar
#

What

shrewd apex
#

also colors class is just there to help u add colors its not really a dictionary to provide u colors so constants are not really needed

slate swan
#

and cuz discord.Color.red() would make more sense than discord.RED

upbeat gust
#

Not for chatGPT no

slate swan
#

Hello

heady verge
#

how to ping a role while sending an embed in the same message?

heady verge
#

uh i mean not in the embed

#

like

<@&ID>
{embed here}

slate swan
#

It's all the same

heady verge
#

how?

#
            await interaction.response.send_message(f"<@&1045668908692164627> Donation Request From <@{interaction.user_id}>")
            await interaction.response.send_message(embed=embed)```

when i use this, it only send the msg not the embed
slate swan
#

I use 1.7.3

heady verge
#

oh okay

naive briar
#

!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, 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.
heady verge
#

oh, lemme check

naive briar
#

!d discord.Interaction.response

unkempt canyonBOT
#

Returns an object responsible for handling responding to the interaction.

A response can only be done once. If secondary messages need to be sent, consider using followup instead.

heady verge
#

so i used ```py
await interaction.response.send_message(content=f"<@&1045668908692164627> Donation Request From <@{interaction.user_id}>", embed=embed)

but it isn't responding when i use the cmd
slate swan
#

I try to delete data from my database with a command but I can't

#
def remove_verification(self, guild_id : int, role_id : int):
        cursor = self.con.cursor()
        query = "DELETE FROM verif WHERE guild_id =? AND role_id =?;"
        cursor.execute(query, (guild_id, role_id))
        cursor.close()```
#
@slash.slash(name = "delete_verification", description = "Delete verification and channel")
async def delete_verification(ctx, role_id):
    guild_id = ctx.guild.id
    guild = ctx.guild
    if (not ctx.author.guild_permissions.ban_members):
        await ctx.send(f"You are not authorized to use this command {ctx.author.mention}")
        return
    database_verif.remove_verification(guild_id, role_id)
    channel = guild.find_channel('verification')
    await channel.delete()
    await ctx.send("The verification is removed successfully")
#
@slash.slash(name = "create_verification", description = "Create the verification and enter the id of the role to assign")
async def create_verification(ctx, role_id):
    guild_id = ctx.guild.id
    guild = ctx.guild
    if (not ctx.author.guild_permissions.ban_members):
        await ctx.send(f"You are not authorized to use this command {ctx.author.mention}")
        return
    if database_verif.get_verification(guild_id, role_id) is None:
        database_verif.add_verification(guild_id, role_id)
        channel = await guild.create_text_channel('verification')
        embed = discord.Embed(title = "Verification", description = "Send `.verif` for access all channels.")
        embed.set_footer(text=f"Verfication for {guild.name}")
        await channel.send(embed=embed)
        await ctx.send("Embed verification send")
    else:
        await ctx.send("The verification is already in place")```
upbeat otter
#

self.con.commit()

#

and use aiosqlite really, sqlite3 will block your bot's actions

slate swan
#

oh yes

#

I test

slate swan
shrewd fjord
shrewd fjord
#

u can set the values to null if u want

upbeat gust
shrewd fjord
#

nothing xd

somber sky
#

how wouuld i use or for something like if role or role2 or role3 in user.roles:

#

^ cause that way doesnt work

#

so idk how

shrewd fjord
#

any of em

somber sky
#

i tried for it didnt work.

#

ill try again

shrewd fjord
#

what did u try

#

xd

somber sky
#

i did this

#

if FORole or GMrole or HCRole in user.roles:

#

they are all defined ^

shrewd fjord
#

i hope the user is a member object

somber sky
#

yup.

#

user: discord.Member

shrewd fjord
#

try this xd

heady verge
#
if interaction.channel_id == 1045668910604754984:
        
            if {bot.value} == 1:
                await interaction.response.send_message(embed=embed, content=f"<@&1045668908692164627> Donation Request From <@{interaction.user.id}>")
                return

        else:
            await interaction.response.send_message('You cannot use this command in this channel.', ephemeral=True, delete_after=5)``` the bot doesnt respond
shrewd fjord
#

what's bot.value?

#

also else statement is outside of if statement xd

heady verge
#
@app_commands.command(name="ddonate", description="Sponsor A Giveaway!")
    @app_commands.choices(bot=[
        discord.app_commands.Choice(name="Dank Memer", value=1),
        discord.app_commands.Choice(name="OwO", value=2),
        discord.app_commands.Choice(name="Pokemon", value=3),
        discord.app_commands.Choice(name="AniGame", value=4),
    ])```
heady verge
heady verge
#

yeah

shrewd fjord
#

so how's your bot defined?

#

client or bot

heady verge
#

client

#

other all commands work, not this

shrewd fjord
#

show async def part

heady verge
#
if {bot.value} == 1:
                await interaction.response.send_message(embed=embed, content=f"<@&1045668908692164627> Donation Request From <@{interaction.user.id}>")
                return```
when i use this, the bot doesnt respond, else it does
shrewd fjord
heady verge
#
    @app_commands.command(name="ddonate", description="Sponsor A Giveaway!")
    @app_commands.choices(bot=[
        discord.app_commands.Choice(name="Dank Memer", value=1),
        discord.app_commands.Choice(name="OwO", value=2),
        discord.app_commands.Choice(name="Pokemon", value=3),
        discord.app_commands.Choice(name="AniGame", value=4),
    ])
    async def ddonate(self, interaction: discord.Interaction, bot:discord.app_commands.Choice[int], prize:str, duration:str, winners:int, requirement:str = None, message:str = None):
        gchannel = interaction.guild.get_channel(1045668910604754984)
        embed=discord.Embed(
            title="Giveaway Donation",
            description=f"**Bot: ** {bot.name}\n**Prize: ** {prize}\n**Duration: **{duration}\n**Winners: ** {winners}\n**Requirement: ** {requirement}\n**Message: ** {message}",
            color=0xff0000)

        if interaction.channel_id == 1045668910604754984:
        
            if {bot.name} == 1:
                await interaction.response.send_message(embed=embed, content=f"<@&1045668908692164627> Donation Request From <@{interaction.user.id}>")
                return

        else:
            await interaction.response.send_message('You cannot use this command in this channel.', ephemeral=True, delete_after=5)```
shrewd fjord
#

it will be bot.value

heady verge
#

yeah, i tried

shrewd fjord
#

also remove {}

heady verge
#

mhm, let me try

#

working tysm!

shrewd fjord
#

;-;

heady verge
#

?

slate swan
#

How can I get only 1 column in my database out of the 2 (I want to get the role_id according to guild_id)

somber sky
shrewd fjord
#

simple

slate swan
#

On my file database_verif.py ?

shrewd fjord
#

i dont know, just told u the query

bright wedge
shrewd fjord
#

select the role_id from the table and put the guild_id as condition

slate swan
#
def get_role_id(self, guild_id : int, role_id : int):
        cursor = self.con.cursor()
        query = "SELECT role_id FROM verif WHERE guild_id =? AND role_id =?;"
        cursor.execute(query, (guild_id, role_id))
        result = cursor.fetchone()
        cursor.close()
        return result```
#

Is good ?

shrewd apex
#

... bro u already know role id what's the query for then

shrewd fjord
shrewd fjord
bright wedge
#

โคด๏ธ

shrewd fjord
#

^

shrewd fjord
bright wedge
slate swan
shrewd fjord
shrewd apex
#

then u need to update ur "up to par " standards

#

๐Ÿ—ฟducky_drawing

shrewd fjord
#

UPDATE query :ducky:

bright wedge
ember nest
#

Would easy-pil make my bot laggy etc if I made it public bot (using it for on_member_join image send

shrewd apex
ember nest
shrewd fjord
#

pasting a image on a image is pretty heavy already ๐Ÿ’€

shrewd apex
#

i meant cpu wise not memory wise

#

but it should be fine ig yeah

shrewd fjord
#

ayo asher

#

come dm and help me ๐Ÿ”ซ

shrewd apex
#

use pil bro easypil for nubs

shrewd apex
#

pil is faster and maintenained regularly and huge community

ember nest
#

Oh

#

I'll try

shrewd apex
#

easy pil uses pil in background

ember nest
#

1 GB of RAM
4 GB of Disk Space
1 CPU Core

This enough to make bot run without lags or delay etc?

ember nest
#

@shrewd apex

shrewd apex
ember nest
#

I mean I will make it a public bot so idk how many ppl would use it

slate swan
shrewd apex
ember nest
#

Alright

#

I'll try use pil instead of pil though

shrewd fjord
slate swan
# shrewd fjord show code xd
def get_role_id(self, guild_id : int):
        cursor = self.con.cursor()
        query = "SELECT role_id FROM verif WHERE guild_id =?;"
        cursor.execute(query, (guild_id))
        result = cursor.fetchone()
        cursor.close()
        return result```
somber sky
#

and when i do, it still says that i cant do it even if i have the roles

shrewd fjord
#

how did u create the table?

shrewd apex
#

wait u just said code for verification stuff right so why are u still using a sync database?

slate swan
slate swan
shrewd apex
somber sky
somber sky
#

still

shrewd apex
#

i said why are u using a sync db

shrewd fjord
somber sky
#
    if Coach_List not in user.roles:
        await ctx.response.send_message(f"You are not a coach", ephemeral=True)```
slate swan
shrewd fjord
slate swan
somber sky
naive briar
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 "discord.Role")s.

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

want the full command?

#

!paste

naive briar
#

in doesn't work like that

slate swan
heady verge
#

what is the block (smthg) used to create a webhook?

somber sky
shrewd apex
naive briar
#

!d discord.TextChannel.create_webhook

unkempt canyonBOT
#

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

Creates a webhook for this channel.

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

Changed in version 1.1: Added the `reason` keyword-only parameter.
heady verge
#

oki!

naive briar
slate swan
somber sky
#

thats what they suggested. I'm just trying to do this.

if FORole GMRole or HCRole isnt in the ctx.user then do something.

#

but if i do,

if FORole or GMRole or HCRole not in ctx.user.roles:

#

it doesnt work properly.

naive briar
#

!e

wanted_roles = ["meow"]
user_roles = ["cat", "kitten"]

print(user_roles, wanted_roles in user_roles)

user_roled.append("meow")
print(user_roles, wanted_roles in user_roles)
unkempt canyonBOT
#

@naive briar :x: Your 3.11 eval job has completed with return code 1.

001 | ['cat', 'kitten'] False
002 | Traceback (most recent call last):
003 |   File "<string>", line 6, in <module>
004 | NameError: name 'user_roled' is not defined. Did you mean: 'user_roles'?
naive briar
#

F

unkempt canyonBOT
#

When checking if something is equal to one thing or another, you might think that this is possible:

# Incorrect...
if favorite_fruit == 'grapefruit' or 'lemon':
    print("That's a weird favorite fruit to have.")

While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.

So, if you want to check if something is equal to one thing or another, there are two common ways:

# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
    print("That's a weird favorite fruit to have.")

# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
    print("That's a weird favorite fruit to have.")
somber sky
#

that doesnt really help lol

wanton fern
#

Hi I have problem when I want install discord for python. Can you help me please

naive briar
#
if FORole not in ctx.user.roles or GMRole not in ctx.user.roles or HCRole not in ctx.user.roles
#

It should be like this

somber sky
#

I did that.

#

it didnt work

naive briar
#

Show the actual code

naive briar
#

No

#

The one that you did the
if FORole or GMRole or HCRole not in ctx.user.roles

#

Or the thing I showed it show be

somber sky
#

no i did both.,

#

I have FORole.

#

and it still does that

naive briar
#

Why don't you try it

heady verge
#

how do i take the option's value? like by using which block

somber sky
#

thats with the command u just gave me

heady verge
#
    @app_commands.command(name="gaw", description="Ping for the giveaway.")
    async def gaw(self, interaction: discord.Interaction, sponsor: str, message: str = None):
        await interaction.channel.create_webhook(name={.sponsor})```
#

name = {.sponsor}

naive briar
#

Show the code when you used that command

somber sky
#
   if FORole not in ctx.user.roles or GMRole not in ctx.user.roles or HCRole not in ctx.user.roles:
        await ctx.response.send_message(f"You are not a coach", ephemeral=True)
    else:
        async with aiosqlite.connect("main.db") as db:
            async with db.cursor() as cursor:
                await cursor.execute(
                    'SELECT settransactionschannel FROM users WHERE guild = ?',
                    (ctx.guild.id, ))
                data = await cursor.fetchone()
                if not data:
                    pass
                else:
                    channel = client.get_channel(int(data[0]))
            if any(role in [FORole, GMRole, HCRole] for role in ctx.user.roles):
                if any(role.name in nflRoleListNames
                       for role in ctx.user.roles):
                    await user.add_roles(teams)
                    await ctx.response.send_message(f"Signed {user.mention}",
                                                    ephemeral=True)
                    await channel.send(embed=signembed)
                    await user.send(embed=signdm, view=view)

                    async def button_callback(interaction):
                        view.stop()
                        await interaction.response.send_message(
                            "Successuflly Confirmed Sign.", ephemeral=True)
                        await user.add_roles(teams)

                    button.callback = button_callback

                    async def force_callback(interaction):
                        view.stop()
                        await interaction.response.send_message(
                            "Succesfully Removed Role.", ephemeral=True)
                        await user.remove_roles(teams)

                    force.callback = force_callback```
naive briar
heady verge
#

wdym

naive briar
#

!f-string

unkempt canyonBOT
#

Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.

>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."

Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.

heady verge
#

ah ic

naive briar
#

Or literally just pass the variable in

heady verge
#

how to get the avatar url of the user mentioned?

naive briar
#

!d discord.User.avatar

unkempt canyonBOT
#

property avatar```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Asset "discord.Asset") for the avatar the user has.

If the user does not have a traditional avatar, `None` is returned. If you want the avatar that a user has displayed, consider [`display_avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.display_avatar "discord.User.display_avatar").
naive briar
#

I'm trying to understand what you're trying to get from it

somber sky
naive briar
naive briar
unkempt canyonBOT
#

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

001 | False
002 | True
somber sky
#

im checking if it has any of the roles

heady verge
#

sponsor: discord.Member
avatar = discord.sponsor.avatar
is it going to work?

somber sky
#

would if any(role in [FORole, GMRole, HCRole] not in ctx.user.roles): work?

heady verge
naive briar
unkempt canyonBOT
#

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

001 | True
002 | True
003 | False
naive briar
#

Just keep testing until you get what you want ๐Ÿคท

somber sky
naive briar
#

Change role in wanted roles to role not in wanted roles

#

Or put not in front of any

somber sky
#
if (any((role not in [FORole, GMRole, HCRole] for role in ctx.user.roles))):```
white citrus
#

Can someone help me please

somber sky
#

How would I make a whitelist command? Pretty much,

The bot will leave the server if it is not whitelisted. If it whitelisted by doing /whitelist guildid, Then it wont leave the server.

slate swan
#
@bot.event
async def on_message(ctx):
    user = ctx.author
    if ctx.channel.name != "verification":
        return
    if user.bot:
        if not ctx.embeds:
            await ctx.delete()
    elif not user.bot:
        if ctx.content != ".verif":
            await ctx.reply("Deleting because it's not .verif")
            time.sleep(3)
            await ctx.delete()
        if ".verif" in ctx.content:
            guild_id = ctx.guild.id
            role_id = database_verif.get_role_id(guild_id)
            await ctx.author.add_roles(role_id)
            embed = discord.Embed(title = "You have passed the verification", description = "Role successfully added")
            embed.set_footer(text = f"Added for {ctx.guild.name}")
            await ctx.reply(embed=embed)
            time.sleep(3)
            await ctx.delete()```
naive briar
#

!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 "discord.Role")s.

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

Read

#

And don't use time.sleep, it's blocking

#

!d asyncio.sleep - use this instead

unkempt canyonBOT
#

coroutine asyncio.sleep(delay, result=None)```
Block for *delay* seconds.

If *result* is provided, it is returned to the caller when the coroutine completes.

`sleep()` always suspends the current task, allowing other tasks to run.

Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.

Example of coroutine displaying the current date every second for 5 seconds:
slate swan
naive briar
#

Your bot won't be being to do anything else in that 5 second if you use time.sleep

#

!blocking

unkempt canyonBOT
#

Why do we need asynchronous programming?
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.

What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:

import discord

# Bunch of bot code

async def ping(ctx):
    await ctx.send("Pong!")

What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.

async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!

slate swan
white citrus
#

@naive briar

naive briar
slate swan
naive briar
#

I literally just said

#

The roles argument needs to be a role object or literally any object with id attribute

heady verge
#
    @app_commands.command(name="avatar", description="see avatar")
    async def avatar(self, interaction:discord.Interaction, member: discord.Member):
        avatar = member.avatar_url
        await interaction.response.send_message(avatar)```
doesnt give any output
naive briar
#

!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 "discord.Role")s.

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

!d discord.User.avatar

unkempt canyonBOT
#

property avatar```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Asset "discord.Asset") for the avatar the user has.

If the user does not have a traditional avatar, `None` is returned. If you want the avatar that a user has displayed, consider [`display_avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.display_avatar "discord.User.display_avatar").
heady verge
#

oh..

#

so like

    @app_commands.command(name="avatar", description="see avatar")
    async def avatar(self, interaction:discord.Interaction, member: discord.Member):
        avatar = member.avatar_url
        await interaction.response.send_message(avatar)```?
#

wait uhh not that

heady verge
#
        avatar = discord.member.avatar```??
naive briar
#

You need an instance

heady verge
#

wdym

slate swan
naive briar
#

Also sqlite3 is blocking

#

!pypi aiosqlite

unkempt canyonBOT
slate swan
#
role_id = database_verif.get_role_id(guild_id)
role = discord.Object(id=role_id)
await ctx.author.add_roles(role)``` ?
#

@naive briar

white citrus
naive briar
white citrus
#

If i timeout a user for 1 hour the bot timeouts him for 2 hours

slate swan
naive briar
#
datetime.fromtimestamp(min(int((nextcord.utils.utcnow() + timedelta(days=28)).timestamp()),int((now + timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds)).timestamp())))

What is this abomination

heady verge
#
    @commands.command()
    async def some(self, ctx) -> None:
        fmt = await ctx.bot.tree.sync(guild=ctx.guild)
        await ctx.send(f'Synced {len(fmt)} commands.')```
nothing happens when i execute the cmd
shrewd fjord
#

not ctx.bot xd

heady verge
#

oh

shrewd fjord
slate swan
shrewd fjord
#

whats your code?

slate swan
# shrewd fjord whats your code?
@bot.event
async def on_message(ctx):
    user = ctx.author
    if ctx.channel.name != "verification":
        return
    if user.bot:
        if not ctx.embeds:
            await ctx.delete()
    elif not user.bot:
        if ctx.content != ".verif":
            await ctx.reply("Deleting because it's not .verif")
            await asyncio.sleep(3)
            await ctx.delete()
        if ".verif" in ctx.content:
            guild_id = ctx.guild.id
            role_id = database_verif.get_role_id(guild_id)
            role = discord.Object(id=role_id)
            await ctx.author.add_roles(role)
            embed = discord.Embed(title = "You have passed the verification", description = "Role successfully added")
            embed.set_footer(text = f"Added for {ctx.guild.name}")
            await ctx.reply(embed=embed)
            await asyncio.sleep(3)
            await ctx.delete()```
naive briar
#

Only if people knows how to read tracebacks

shrewd fjord
#

database_verif whats this bro

slate swan
# shrewd fjord database_verif whats this bro
import os
import sqlite3

class Verification:
    def __init__(self, database_name : str):
        self.con = sqlite3.connect(f"{os.path.dirname(os.path.abspath(__file__))}/{database_name}")
        self.con.row_factory = sqlite3.Row

    def add_verification(self, guild_id : int, role_id : int):
        cursor = self.con.cursor()
        query = "INSERT INTO verif (guild_id, role_id) VALUES (?, ?);"
        cursor.execute(query, (guild_id, role_id))
        cursor.close()
        self.con.commit()

    
    def get_verification(self, guild_id : int, role_id : int):
        cursor = self.con.cursor()
        query = "SELECT * FROM verif WHERE guild_id =? AND role_id =?;"
        cursor.execute(query, (guild_id, role_id))
        result = cursor.fetchone()
        cursor.close()
        return result

    def get_role_id(self, guild_id : int):
        cursor = self.con.cursor()
        query = "SELECT role_id FROM verif WHERE guild_id =?;"
        cursor.execute(query, (guild_id,))
        result = cursor.fetchone()
        cursor.close()
        return result

    def remove_verification(self, guild_id : int, role_id : int):
        cursor = self.con.cursor()
        query = "DELETE FROM verif WHERE guild_id =? AND role_id =?;"
        cursor.execute(query, (guild_id, role_id))
        cursor.close()
        self.con.commit()```
shrewd fjord
#

there is no database_verif????

slate swan
#

If

shrewd fjord
#

nvm

#

query = "SELECT role_id FROM verif WHERE guild_id =?"

#

return result[0] try this i think it's going to return tuple

slate swan
#

The ; at the end of the query ๐Ÿ™‚

white citrus
shrewd fjord
#

atleast i dont use

slate swan
#

Is good very thanks

#

How to delete a message after 3 seconds with asyncio.sleep ?

shrewd fjord
shrewd fjord
unkempt canyonBOT
#

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

Deletes the message.

Your own messages could be deleted without any proper permissions. However to delete other peopleโ€™s messages, you must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages").

Changed in version 1.1: Added the new `delay` keyword-only parameter.
somber sky
#

how would i make an emoji through a command?

shrewd fjord
#

creating a emoji u mean?

somber sky
#

ye

naive briar
#

Eh

shrewd fjord
#

tf

naive briar
#

!d discord.Guild.create_custom_emoji

unkempt canyonBOT
#

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

Creates a custom [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji") for the guild.

There is currently a limit of 50 static and animated emojis respectively per guild, unless the guild has the `MORE_EMOJI` feature which extends the limit to 200.

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

thanks

shrewd fjord
slate swan
#

hello, this error means discord py isn't installed?

shrewd fjord
#

a variable named bot u r using not even defined

vernal finch
#

Why i am not able to chat in voice channels

naive briar
#

Most basic error you could've get

slate swan
#
import discord
from discord.ext import commands

@bot.tree.command(name="ping", description="Show the bot's ping in ms")
async def ping(inreraction: discord.Interaction):
    bot_ms = round(client.latency * 1000)
    await interaction.response.send_message("Pong!", bot_ms, "ms")
    
@bot.event
async def on_ready():
    await client.tree.sync()
    print("Bot online")
shrewd fjord
slate swan
#

this is my code

#

() are missing?

#

How do I delete the embed sent by my bot along with my message ?

shrewd fjord
slate swan
#

or bot.tree.commands?

naive briar
shrewd fjord
#

also bot and client both are same lmao

naive briar
shrewd fjord
somber sky
slate swan
#

ahhhh i forgot the line with prefix etc

somber sky
#

what that mean

slate swan
#

nvm i found why

unkempt canyonBOT
#

str.startswith(prefix[, start[, end]])```
Return `True` if string starts with the *prefix*, otherwise return `False`. *prefix* can also be a tuple of prefixes to look for. With optional *start*, test string beginning at that position. With optional *end*, stop comparing string at that position.
shrewd fjord
#

error tells u everything ๐Ÿ’€

vernal finch
steel mango
#

Idk why I'm getting rate limit error from discord

naive briar
#

Replit?

steel mango
#

Yh

shrewd fjord
#

AYO GIVING FREE REPLIT HACKER PLAN

#

for christmas gift ๐Ÿ’€

shrewd fjord
#

and thus get ratelimited

steel mango
#

Right

#

Well just got to wait for it then

shrewd fjord
#

take or ๐Ÿ”ซ

#

@steel mango ๐Ÿ’€

steel mango
#

Nope I don't need

vernal finch
#

help meee

#

i cannot type in the chat box of voice channel

shrewd fjord
shrewd fjord
naive briar
somber sky
shrewd fjord
#

voice verify

vernal finch
#

i did it

slate swan
#
import discord
from discord.ext import commands

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

@bot.tree.command(name="ping", description="Show the bot's ping in ms")
async def ping(inreraction: discord.Interaction):
    bot_ms = round(client.latency * 1000)
    await interaction.response.send_message("Pong!", bot_ms, "ms")
    
@bot.event
async def on_ready():
    await bot.tree.sync()
    print("Bot online")
    
bot.run(token)
#

why application isn't responding

#

what's wrong with what i did?

cloud dawn
#

You are using a bot but you are using client.

upbeat gust
#

You've defined bot, not client

vernal finch
vernal finch
#

you do not have permission to send messages to this channel

slate swan
#

now interaction error

shrewd fjord
#

u mispelled it xd

slate swan
#

ahaha just found the error

#

at the same time

shrewd fjord
#

it will be
async def ping(interaction: discord.Interaction):

#

xd

slate swan
#

yes ty

ember nest
#

C++ bots are good?

shrewd fjord
#

๐Ÿ’€

naive briar
slate swan
#

someone can tell me what's the difference between : app_commands.command, client.tree.commands and bot.slash_command

#

do they do the same thing or there are differences

naive briar
#

bot.slash_command is outdated

slate swan
#

okay and app_commands.command?

naive briar
#

That's new in v2.0

#

Used to create extension

#

So not outdated

slate swan
#

okay

#

thanks

ember nest
naive briar
#

Yes, and what about it

heady verge
#
    @commands.command()
    async def sync(self, ctx) -> None:
        fmt = await ctx.bot.tree.sync(guild=ctx.guild)
        await ctx.send(f'Synced {len(fmt)} commands.')```
not syncing
naive briar
#

!d discord.ext.commands.Context.bot

unkempt canyonBOT
heady verge
#

for me?

heady verge
#

when i do s!sync no response and no error

slate swan
#
@client.tree.command(name="say",description="Say whatever word you want")
async def say(message, interaction: discord.Interaction):
    await interaction.response.send_message("U asked me to say", message)
#

i don't understand this error

ember nest
naive briar
#

Probably, C++ is faster but you need to manage the memory that your program used yourself

naive briar
#

Interaction always comes before other argument

shrewd fjord
shrewd fjord
heady verge
#

wdym

#

it used to work before

slate swan
heady verge
#

it all started not working after the webhook thing

slate swan
#

i switched the arg position

heady verge
# slate swan i switched the arg position
@client.tree.command(name="say",description="Say whatever word you want")
async def say(interaction: discord.Interaction, message: str):
    await interaction.response.send_message(f"U asked me to say, {message}")```
try this
shrewd fjord
#

also

#

message: str
this

heady verge
#

ahh ye forgot

naive briar
# slate swan

Every argument in slash command callbacks needs a type annotation

#

(or type hint)

vocal snow
heady verge
#

is there any other way to sync slash commands?

lethal elbow
heady verge
#

nono, he was right i edited it

lethal elbow
#

oh

heady verge
#

can u help me?

naive briar
#

C++ doesn't have garbage collector like Python

#

At least without third party library

slate swan
#

How to specify the type of the argument in the arguments of a command.
Example :

@client.command()
async def say(ctx, message, time):
    for i in range(times):
        await ctx.reply(message)

it will return a TypeError because the arg times need to an integer. But when I do

(ctx, message, int(time)): ```

it returns a SyntaxError
#

please help me I'm lost ๐Ÿ˜ญ

fading marlin
#

type hints

@bot.command()
def foo(ctx: commands.Context, arg: str): ...

@bot.command()
def bar(ctx: commands.Context, abc: int): ...
#

just because we're in the context of dpy does it try to convert the arguments to the given type, normally this is just used for linter/documentation and doesn't do anything at runtime

slate swan
#

so in my case time: int ?

fading marlin
#

sure

#

it can raise an error if you don't provide a valid integer when you execute the command though

slate swan
#

ahahaha it works

#

thanks man!!

fading marlin
#

no problem

slate swan
#

yes ill have to manage the error later with a try: expect

fading marlin
#

no, you have to use an error handler

slate swan
#

what is that?

naive briar
#

!d discord.on_error

unkempt canyonBOT
#

discord.on_error(event, *args, **kwargs)```
Usually when an event raises an uncaught exception, a traceback is logged to stderr and the exception is ignored. If you want to change this behaviour and handle the exception for whatever reason yourself, this event can be overridden. Which, when done, will suppress the default action of printing the traceback.

The information of the exception raised and the exception itself can be retrieved with a standard call to [`sys.exc_info()`](https://docs.python.org/3/library/sys.html#sys.exc_info "(in Python v3.11)").

Note

`on_error` will only be dispatched to [`Client.event()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.event "discord.Client.event").

It will not be received by [`Client.wait_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_for "discord.Client.wait_for"), or, if used, [Bots](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#ext-commands-api-bot) listeners such as [`listen()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.listen "discord.ext.commands.Bot.listen") or [`listener()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog.listener "discord.ext.commands.Cog.listener").

Changed in version 2.0: The traceback is now logged rather than printed.
slate swan
#

ah I know that

#
@bot.event
async def on_message_delete(ctx):
    guild_id = ctx.guild.id
    channel_send = database_log_message.get_channel(guild_id)
    embed=discord.Embed(title = f"Message deleted in {ctx.channel}".format(ctx.channel), description = f"{ctx.author.name} Message deleted", color=discord.Color.dark_purple())
    embed.add_field(name="Message :",value=ctx.content, inline=False)
    embed.add_field(name = "Account created :", value = ctx.author.created_at)
    await channel_send.send(embed=embed)```
#

You can help me please ?

fading marlin
#

what's database_log_message?

slate swan
# fading marlin what's `database_log_message`?
import os
import sqlite3

class LogMessage:
    def __init__(self, database_name : str):
        self.con = sqlite3.connect(f"{os.path.dirname(os.path.abspath(__file__))}/{database_name}")
        self.con.row_factory = sqlite3.Row

    def add_channel_log(self, guild_id : int, channel_id : int):
        cursor = self.con.cursor()
        query = "INSERT INTO log_message (guild_id, channel_id) VALUES (?, ?);"
        cursor.execute(query, (guild_id, channel_id))
        cursor.close()
        self.con.commit()
    
    def get_channel_log(self, guild_id : int, channel_id : int):
        cursor = self.con.cursor()
        query = "SELECT * FROM log_message WHERE guild_id =? AND channel_id =?;"
        cursor.execute(query, (guild_id, channel_id))
        result = cursor.fetchone()
        cursor.close()
        return result

    def get_channel(self, guild_id : int):
        cursor = self.con.cursor()
        query = "SELECT channel_id FROM log_message WHERE guild_id =?;"
        cursor.execute(query, (guild_id,))
        result = cursor.fetchone()
        cursor.close()
        return result

    def delete_channel_log(self, guild_id : int, channel_id : int):
        cursor = self.con.cursor()
        query = "DELETE FROM log_message WHERE guild_id =? AND channel_id =?;"
        cursor.execute(query, (guild_id, channel_id))
        cursor.close()
        self.con.commit()```
fading marlin
# slate swan ah I know that

you can also use a local error handler for your command

@bot.command()
async def foo(ctx: commands.Context, arg: int):
    ...

@foo.error
async def foo_error(ctx: commands.Context, exception: commands.CommandInvokeError):
    if isinstance(exception, commands.BadArgument):
        ...
hushed galleon
# slate swan

you need a discord.TextChannel object in order to call send(), but you only returned a row from your sqlite database rather than getting the actual channel

naive briar
#

Imagine

slate swan
#

How to do it ?

hushed galleon
#

after you get the channel_id, you can combine it with get_guild()/get_channel(), e.g. ```py
row = cursor.fetchone()

assuming self.bot = <your commands.Bot instance>:

guild = self.bot.get_guild(guild_id)
channel = guild.get_channel(row[0])```

fading marlin
#

you don't need the guild pithink

hushed galleon
#

technically you dont, but its a bit more optimized than Client.get_channel() since the connection state doesnt store a global mapping of channels

unkempt canyonBOT
#

discord/state.py lines 1580 to 1591

def get_channel(self, id: Optional[int]) -> Optional[Union[Channel, Thread]]:
    if id is None:
        return None

    pm = self._get_private_channel(id)
    if pm is not None:
        return pm

    for guild in self.guilds:
        channel = guild._resolve_channel(id)
        if channel is not None:
            return channel```
hushed galleon
#

well thats your decision, either in LogMessage.get_channel() or directly in your on_message_delete event

slate swan
#

?

hushed galleon
#

you need self.bot assigned in your init too

slate swan
#
class LogMessage:
    def __init__(self, database_name : str):
        self.con = sqlite3.connect(f"{os.path.dirname(os.path.abspath(__file__))}/{database_name}")
        self.con.row_factory = sqlite3.Row```?
hushed galleon
#

yeah

#

also worth noting that fetchone(), get_guild(), and get_channel() might return None, which can lead to future errors if you dont handle them

slate swan
hushed galleon
#

well i said you needed to assign self.bot, otherwise LogMessage cant use self.bot...

slate swan
#

But how to use it I don't see where to put it ?

naive briar
#

Basic python class knowledge

slate swan
hushed galleon
#

so you see how you wrote self.con = sqlite3.connect(...)? you've assigned the self.con attribute on your LogMessage instance, and that lets you use it in your instance methods (thats why cursor = self.con.cursor() works)

hushed galleon
#

so if you want to use your commands.Bot instance, you should assign it as an attribute on LogMessage, and then add a parameter to __init__() so you can provide that bot instance when you're creating LogMessage(...)

slate swan
hushed galleon
#

perhaps this example will explain what's going on ```py
class MyClass:
def init(self, bot):
# ^^^ defines a parameter for the class
self.bot = bot # assigns the bot as an attribute of self

def do_something(self):
    # Now all instance methods have access to `self.bot`
    channel = self.bot.get_channel(1234)
    print('channel name is:', channel.name)

After you create your bot instance, you can pass it as an argument to MyClass

bot = commands.Bot(...)
my_class_instance = MyClass(bot)

@bot.event
async def on_ready():
my_class_instance.do_something()```

#

or you can go through a guide to Object Oriented Programming like this one by corey schafer
https://www.youtube.com/watch?v=ZDa-Z5JzLYM&list=PL-osiE80TeTsqhIuOqKhwlXsIBIdSeYtc

In this Python Object-Oriented Tutorial, we will begin our series by learning how to create and use classes within Python. Classes allow us to logically group our data and functions in a way that is easy to reuse and also easy to build upon if need be. Let's get started.

Python OOP 1 - Classes and Instances - https://youtu.be/ZDa-Z5JzLYM
Python...

โ–ถ Play video
quick gust
#

W helper

slate swan
slate swan
#
@bot.event
async def on_message_delete(ctx):
    guild_id = ctx.guild.id
    if database_log_message.get_channel(guild_id) is None:
        return
    channel_send = database_log_message.get_channel(guild_id)
    embed=discord.Embed(title = f"Message deleted in {ctx.channel}".format(ctx.channel), description = f"{ctx.author.name} Message deleted", color=discord.Color.dark_purple())
    embed.add_field(name="Message :",value=ctx.content, inline=False)
    embed.add_field(name = "Account created :", value = ctx.author.created_at)
    await channel_send.send(embed=embed)```
maiden fable
#

row is None in get_channel method @slate swan

loud flicker
#

Hello guys, I have a question: Is there a way to check if the message (sent by the user) is a reply to the bot? I've found "message.reference" but this checks if the message is a reply to anything, I want to check if the message is a reply to the bot only. I'm using PyCord.

upbeat otter
#

!d discord.Message.reference

unkempt canyonBOT
#

The message that this message references. This is only applicable to messages of type MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.

New in version 1.5.

loud flicker
#

wha-

maiden fable
maiden fable
#

I remember doing something like this for my bot lemme get it

upbeat otter
# loud flicker wha-

discord.Message.reference will return a MessageReference object on which you can use the author attribute on it and compare it to your bot using bot.user or you can even comparing their ids just by comparing message.author.id and bot.user.id

#

author == bot.user will automatically compare their ids so that's cool and all

maiden fable
upbeat otter
#

that's sad

loud flicker
#

Okay so I cannot check if the user replies to my bot's message?

maiden fable
#

Okay I forgot my VPS creds rip

#

Lemme find another way to login

maiden fable
upbeat otter
#

I saw ๐Ÿ’€

#

My internet's too slow ๐Ÿ˜” it simply loaded discord.Message docs for some reason

maiden fable
#

Well @loud flicker there is a hacky way for this

#

!d discord.MessageReference.resolved

unkempt canyonBOT
#

The message that this reference resolved to. If this is None then the original message was not fetched either due to the Discord API not attempting to resolve it or it not being available at the time of creation. If the message was resolved at a prior point but has since been deleted then this will be of type DeletedReferencedMessage.

Currently, this is mainly the replied to message when a user replies to a message.

New in version 1.6.

loud flicker
#

Okay so what's this

maiden fable
#

This returns the message object to which the reply was done

#

you can do smth like if msg.reference.resolved.author == bot.user or smth

loud flicker
#

Okay, I'll see if it works:

maiden fable
#

But then u will first have to check if the msg.reference.resolved is an instance of discord.DeletedReferencedMessage, which, if True, won't have an author attr then

#

But a common way to do this (how I would have done) is by using the above thing and adding another condition (with an or), which checks if the message reference exists, the bot is mentioned but the bot mention isn't in the list of raw_mentions or smth

#

Hacky but would work

loud flicker
#

'NoneType' object has no attribute 'resolved'

#
elif any(word in blacklisted_words for word in split) and (message.author.bot == False) and message.reference.resolved.author == self.bot.user:
maiden fable
#

the message was never replied to any message

loud flicker
#

Okay, I'll try again

maiden fable
#

that is why message.reference is None

white citrus
#

Can someone help me, I've been waiting for more than 24 hours

loud flicker
maiden fable
maiden fable
#

What is the issue u r facing?

heady verge
#
    @commands.command()
    async def sync(self, ctx) -> None:
        fmt = await ctx.bot.tree.sync(guild=ctx.guild)
        await ctx.send(f'Synced {len(fmt)} commands.')``` doesnt give any output
maiden fable
#

Did you forget to load the cog?

heady verge
#

nope

#
Donate Cog Loaded
Fun Cog Loaded
Giveaway Cog Loaded
Moderation Cog Loaded```
it is in fun cog
delicate pilot
#

i want start bot command

slate swan
#

How can I send a deleted embed as I do with deleted messages in an embed ?

heady verge
#

it doesnt respond...

delicate pilot
maiden fable
#

Do u have an error handler>

maiden fable
heady verge
maiden fable
maiden fable
heady verge
maiden fable
#

Can u do print(x.name for x in bot.commands) on startup?

slate swan
shrewd fjord
#

๐Ÿ—ฟ

heady verge
#

bot.commands?

maiden fable
#

Just access the embed using message.embeds and do await log_channels.send(embeds=message.embeds)

shrewd fjord
#

Depends on how you defining the bot

maiden fable
heady verge
#

<generator object on_ready.<locals>.<genexpr> at 0x00000203A42C43C0>

#

it printed that

shrewd fjord
#

Wifi is tooo slow lul

maiden fable
heady verge
#

if i use bot , it is not defined

shrewd fjord
#

U r printing x only i am pretty sure

heady verge
#

print(x.name for x in client.commands)

shrewd fjord
heady verge
#

@client.event
async def on_ready():
    print("Bot is online.")
    print(x.name for x in client.commands)```ye
maiden fable
#

Hm

shrewd fjord
#

wait u r using slash commands?

heady verge
#

yeah

shrewd fjord
#

If yes then it's walk_commands()

maiden fable
#

Okay I ain't familiar with slash commands, sorry

heady verge
shrewd fjord
#

client.walk_commands()

slate swan
#

!d discord.app_commands.CommandTree.walk_commands

unkempt canyonBOT
shrewd fjord
#

Wait ahh forgir

slate swan
#

Bot.walk_commands is for prefix cmds

shrewd fjord
#

Forgot ๐Ÿ’€ sarth always here to get my back

heady verge
#

lol

#

so.. what do i use

slate swan
#

bot.tree.walk_commands()

heady verge
#

<generator object on_ready.<locals>.<genexpr> at 0x00000276A6FC4430>

#

for py @client.event async def on_ready(): print("Bot is online.") print(x.name for x in client.tree.walk_commands())

#

..

maiden fable
#

Not the appropriate channel
You might wanna delete the message

shrewd fjord
#

17 xd

alpine cove
#

~ 24

maiden fable
#

Thanks

snow stratus
maiden fable
#

About 24

shrewd fjord
#

approx 24

#

he meant that

alpine cove
#

^

snow stratus
#

Ok guys thanks for sharing

maiden fable
#

But ot, so take it to one of the OT channels

snow stratus
#

Your opinion

snow stratus
#

Your all helpful

maiden fable
#

@slate swan

slate swan
maiden fable
#

channel_send.send @slate swan

slate swan
heady verge
#

i dont understand Cry

slate swan
#

!e ```py
print(a for a in (1,2)) #generator object
print(list(a for a in (1,2))) # an actual iter

unkempt canyonBOT
#

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

001 | <generator object <genexpr> at 0x7f444e5ec1e0>
002 | [1, 2]
slate swan
heady verge
#

mhm

maiden fable
heady verge
#

so how do i fix

slate swan
#
@bot.event
async def on_message_delete(ctx):
    guild_id = ctx.guild.id
    if database_log_message.get_channel(guild_id) is None:
        return
    channel_send = database_log_message.get_channel(guild_id)
    if ctx.content == ".verif":
        return
    if ctx.embeds:
        await channel_send.send(ctx.embeds)
    embed=discord.Embed(title = f"Message deleted in {ctx.channel}".format(ctx.channel), description = f"{ctx.author.name} Message deleted", color=discord.Color.dark_purple())
    embed.add_field(name="Message :",value=ctx.content, inline=False)
    embed.add_field(name = "Account created :", value = ctx.author.created_at.strftime('%d %B %Y at %H:%M'))
    await channel_send.send(embed=embed)```
slate swan
#

ctx replace message for me

heady verge
slate swan
#

your generator?

slate swan
#

are you aware of difference between a generator and a list comprehension?

heady verge
#
    @commands.command()
    async def sync(self, ctx) -> None:
        fmt = await ctx.bot.tree.sync(guild=ctx.guild)
        await ctx.send(f'Synced {len(fmt)} commands.')```
#

it doesnt sync, this was my problem

slate swan
maiden fable
#

first field

slate swan
quick gust
#

he is saying the message content is empty

maiden fable
#

You are tryna send the deleted embed to the log channel, so there is no message content

slate swan
#

I don't see ๐Ÿ˜ฆ

maiden fable
#

Bro

#

This isn't the appropriate channel for these questions

snow stratus
#

Kk last one so how old

maiden fable
#

No idea
I am bad at guessing ages

snow stratus
#

Just give yo opiniob

slate swan
#

how old are you for not being able to read the channel topic

#

!ot

unkempt canyonBOT
snow stratus
#

Im 16

#

Channel topic channel schmopic

honest shoal
#

use == instead

maiden fable
#

Sure

maiden fable
slate swan
honest shoal
#

consistency

maiden fable
#

PEP 8 crying in a corner

quick gust
slate swan
white citrus
gray prairie
#

hey
is it necessary to add this into the path?

#

if yes
how to do it ?

slate swan
gray prairie
quick gust
#

first thing to do is google your problem

quick gust
visual canyon
#

I have a modal issue. if i comment out this section of my modal child class ```py
repo = discord.ui.Select(
options=[
components.SelectOption(label="Project MMO", value="Project-MMO-2.0", default=True),
components.SelectOption(label="AugmentsBot", value="AugmentsBot", default=False)
],
row=0
)

the modal works fine.  When it's in though, i get `discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.0.components.0: Value of field "type" must be one of (4,).`
#

i'm not sure what i'm doing wrong here

#

My other two fields in the modal are of type TextInput. They work fine.

slate swan
#

you can't have a select inside a modal

visual canyon
#

ah. that makes sense then. is there another way to have a set of options the user selects from in a modal?

quick gust
#

I don't think so

slate swan
#

sadly not, only possible thing in a Modal for now is getting text inputs

#

you could utilise that ๐Ÿคทโ€โ™‚๏ธ

visual canyon
#

๐Ÿค” okay. i might just have separate commands for my options then. i only have the two so far.

white citrus
fading marlin
#

Discord already provides a timeout slash command... why reinvent the wheel?

white citrus
honest shoal
#

it's too complicated

white citrus
honest shoal
#

if it was me I'd use it like 3d4h6m (i.e. 3 days 4 hours 6 minutes) with string slicing

white citrus
honest shoal
#

and what if all the duration fields are left empty

white citrus
thin trout
#

someone know how can use cogs in the correct way

fading marlin
#

how are you currently using them?

thin trout
#

i saw a few guides and tutorial but no one works correctly

thin trout
fading marlin
#

are you getting any errors? what makes you think that you aren't using them correctly?

thin trout
#

no errors, when i try to run a command the console says that command don't exists

fading marlin
#

!paste can you send your code please?

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.

thin trout
#

ok

#

i just start using python so i don't know how to code well

fading marlin
#

send your entire code please

thin trout
#

i remove the cog, i just got the main

#

i need a way to use cogs

fading marlin
thin trout
#

thanks

slate swan
#

What is the @bot.event of the members who already join ?

fading marlin
#

!d discord.Guild.members

unkempt canyonBOT
fading marlin
#

there's no event that gets dispatched to get every single member inside a guild... otherwise it'd get dispatched infinitely in an infinite amount of times

slate swan
#
@bot.event
async def on_member_join(message):``` Is good no ?
fading marlin
#

that will get dispatched every time a new member joins the guild, and it's not the correct signature

#

!d discord.on_member_join

unkempt canyonBOT
#

discord.on_member_join(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") joins a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").

This requires [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
somber sky
#

How would I make a whitelist command? Pretty much,

The bot will leave the server if it is not whitelisted. If it whitelisted by doing /whitelist guildid, Then it wont leave the server.

rustic edge
#

Hello!

I was wondering if it was possible to restart the bot from within itself without having to kill the python script then re-running it as this is causing mounds of issues on my server.

unkempt canyonBOT
#

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

This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
somber sky
sick birch
somber sky
#

yea but like it would be through a command

#

/whitelist serverid

#

then it would go in the list

#

idk how to do that

sick birch
#

pretty simple

novel dove
somber sky
#

i use it but its not good lol

novel dove
#

Why?

somber sky
#

bot goes offline a lot

novel dove
#

My bot is working 9 months

#

I want to make discord bot with discord.py i made already 1 with discord.js

somber sky
#

well i mean if its working for u go ahead

#

for me the bot goes offline a lot

novel dove
somber sky
#

depends what you like more

#

whatever is easier for you

#

i think py is better

winged coral
#

They both boil down to the same thing really

#

Depends what language you're better versed in

slate swan
#

dpy provides you with a lot of additional features like prefix command handling, better app command implementation and a bunch of utils ๐Ÿ•บ

#

!d discord.Message.reply

unkempt canyonBOT
#

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

A shortcut method to [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") to reply to the [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message").

New in version 1.6.

Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.11)") or [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.11)") instead of `InvalidArgument`.
silent ermine
#

Why do I keep getting this error?

    nextcord.opus.load_opus()
TypeError: load_opus() missing 1 required positional argument: 'name'```
#

I tried putting "opus" inside of the () but it gives me the error:
OSError: dlopen(opus, 0x0006): tried: 'opus' (no such file), '/System/Volumes/Preboot/Cryptexes/OSopus' (no such file), '/usr/lib/opus' (no such file, not in dyld cache), 'opus' (no such file), '/usr/lib/opus' (no such file, not in dyld cache)

winged coral
#

You need to give it the name of the Opus library file to be loaded

#

And that file has to exist, hence the second error

silent ermine
winged coral
#

But it has to exist like I said

#

!d nextcord.opus.load_opus

unkempt canyonBOT
#

nextcord.opus.load_opus(name)```
Loads the libopus shared library for use with voice.

If this function is not called then the library uses the function [`ctypes.util.find_library()`](https://docs.python.org/3/library/ctypes.html#ctypes.util.find_library "(in Python v3.11)") and then loads that one if available.

Not loading a library and attempting to use PCM based AudioSources will lead to voice not working.

This function propagates the exceptions thrown.

Warning

The bitness of the library must match the bitness of your python interpreter. If the library is 64-bit then your python interpreter must be 64-bit as well. Usually if thereโ€™s a mismatch in bitness then the load will throw an exception...
silent ermine
#

Apprently its in my local/lib. Cant move it though. Tried doing this but says it doesnt exist.
nextcord.opus.load_opus('/usr/local/lib/opus')

winged coral
#

Are you on Windows?

#

I assume not just checking

#

Oh mac

#

Homebrew

#

Ignore me

silent ermine
#

See, its in the local/lib but it doesnt detect it some reason

winged coral
#

Have you tried omitting the function call altogether and letting the library use ctypes to find it for you?

silent ermine
winged coral
#

Try ctypes.util.find_library('libopus')

#

Oh no it shouldn't matter

#

Ctypes wants that omitted anyway

#

Huh this is weird then if it does 100% exist

#

I'm not entirely sure where to go next

#

Have you tried asking someone in the Nextcord discord?

silent ermine
silent ermine
winged coral
#

Yeah, sorry I couldn't help more

silent ermine
slate swan
#

How would I go bout calling a list from another file?

I did import examplelist, and then I did

narr = examplelist.get(ctx,key) but then I get a warning saying that examplelist has no attribute "get"?

#

I want to organise my list by having it in another file

winged coral
#

To ping a channel you use the format <#ID_HERE>

winged coral
#

Dicts do, because k maps to v so dict.get(k) returns v

#

๐Ÿ‘ _ _

slate swan
#

Ah thanks

winged coral
#

Yeah, seems like you want a dict or perhaps an Enum

#

!d enum.Enum

unkempt canyonBOT
#

class enum.Enum```
*Enum* is the base class for all *enum* enumerations.
alpine cove
#

enumsssss

polar wigeon
#

TypeError: Client.__init__() missing 1 required keyword-only argument: 'intents' Why do I need this?

#

what are intents needed for? I copy the exact code from The youtube tutorials and I have a problem running

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.

torn sail
#

from enum import Enum

alpine cove
#

lol dea

#

*yea

#

I somehow always forget

polar wigeon
#

Now I get another error

#

its just error on error for no reason

#
aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:997)')```
slate swan
#

channel = client.get_channel(343944376055103488)
channel.send(text, file=file)

'NoneType' object has no attribute 'send'

polar wigeon
#

like wtf

#

its literally code I coppied word for word from a tutorial lmao

#

well the tutorial is months old to be fair

#

Im just trying to have my discord bot send a message on the server

#

whenever someone types

#

and another whenever I use a command word

#

but their 2 seperate practice

#
import discord

BOT_PREFIX = ("?")
TOKEN = ""
intents= discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)

@client.event
async def on_message(message):
    possible_response = ['yo Duke is lame foe on gang', 'Bruh This bot shit easy fr fr ong', 'I want milk mommy pweeeeeazeee']
    username= str(message.author)
    message(message.content)
    await client.send(random.choice(possible_response))

client.run(TOKEN)```
#

this is my simple code

#

that gives me errors

polar wigeon
#

yeah that fixed that issue

#

but I am having trouble on the code

cold sonnet
#

youtube tutorials are factually horrible

polar wigeon
#

yeah dude its terrible I wish I know where to get actual information for learning discord bts

cold sonnet
#

if you have python knowledge, just the API reference

#

else, get python knowledge, then check the API reference

#

not in the way of studying every class, just when you have for example a channel, but you don't know how to send a message, then you check the discord.TextChannel class in the API reference

#

the discord.py github page has examples, that's a start too

polar wigeon
#

Well I dont have object oriented experience

#

not sure how valuable that is in this case

polar wigeon
cold sonnet
polar wigeon
#

Okay well I'll go ahead and do a course on it

dense merlin
#

File "main.py", line 484, in join
VoiceCl = discord.VoiceClient()
TypeError: init() missing 2 required positional arguments: 'client' and 'channel'

#

wut

#

...

sick birch
#

Every time you run the warn command it gets reset to 0

#

You might want to store the warns somewhere else

#

Like a database

#

You can do that but it'll get reset to 0 when you restart the bot

#

Create a dict and bind it to your bot instance

#

The key will be user ID the value the number of warns they have

#
bot = commands.Bot(...)
bot.warns = {}
#

Then whenever you need to add a warn for a user:

bot.warns[123] += 1
#

Where 123 is the user ID

slate swan
#

How can i add cooldown on_raw reaction_add evet?

somber sky
#

@sick birch what host do you recommend

sick birch
#

AWS

#

I use it for my website, pretty handy

leaden jasper
slate swan
#

But if user didnt spam

#

Its work fine

#

Hey, when I do !rijal mufaddal, i dont even get a traceback, no message sends

@fiqhbot.command()
async def rijal(ctx, gh):
gh = ["Mufaddal"]
message = ctx.message.content
if str(message) in ghulat:
await ctx.send("e")

leaden jasper
#

add them to a list, wait 5 seconds and remove from list

slate swan
slate swan
#

Can u show me whats that and how?

leaden jasper
# slate swan What

make a global list, add their user id to the list when they react, wait 5 seconds, then remove from the list

slate swan
#

Hmm

leaden jasper
#

and check if they try to react again but their id is still in the list, it shouldn't let them

leaden jasper
slate swan
#

Nope, nothing

silk robin
#

how do i put 2 images in the embed?

#

cause when i do this it only sends the bottom image

upbeat gust
#

โš ๏ธ Requires 2.0 to use without webhooks

URL = 'https://www.google.com/'
IMAGE_1 = 'https://cdn.discordapp.com/embed/avatars/1.png'
IMAGE_2 = 'https://cdn.discordapp.com/embed/avatars/2.png'

# embeds must have the same url
# works with more up to 4 images on desktop
# does not show more than 1 on mobile

embed1 = discord.Embed(
    title='TITLE 1',
    description='DESCRIPTION 1',
    url=URL # <<< same url as other embeds
)
embed1.set_image(url=IMAGE_1)

embed2 = discord.Embed(
    title='TITLE 2', 
    description='DESCRIPTION 2', 
    url=URL # <<< same url as other embeds
)
embed2.set_image(url=IMAGE_2)

await channel.send(embeds=[embed1, embed2])
```https://cdn.discordapp.com/attachments/559455534965850142/908123289904357386/unknown.png
dense merlin
#

is make music bot and then error vine boom
clientException: ffmpeg.exe was not found.

#

what do

upbeat gust
#

Why don't you just use timeout?

#

!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 "(in Python v3.11)").

You must have [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "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 "discord.Member.edit").
dense merlin
# upbeat gust So do you have ffmpeg?

i tried isnatllint with pip, npm, importing it, adding a blank ffmpeg.exe file, but as of right nwow, I use replit (imgetting hardware anyways for it so dont lecture) so not sure how

dense merlin
upbeat gust
#

you put it where you want to timeout the member?

upbeat gust
dense merlin
upbeat gust
#

mm I'm not gonna waste my time teaching basic python sorry

upbeat gust
#

You do know that's already a built-in command right

#

Those already exist

#

They are built in to discord

#

If you can't make something super special or better, don't bother

#

cool

young dagger
sick birch
#

Does it basically "combine" the two embeds?

upbeat gust
upbeat gust
sick birch
#

Agreed..

upbeat gust
#

Especially with it only sometimes working

young dagger
#

I think I found it: def rank_to_number(rank):

torn sail
young dagger
young dagger
#

I'm still wondering why 'tier, rank = tier_and_rank.split()' is causing issues when using special characters

naive briar
#

What special characters

#

!e

print("string".split())
print("string 1".split())
unkempt canyonBOT
#

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

001 | ['string']
002 | ['string', '1']
young dagger
naive briar
#

What's the issue it's causing

sick birch
#

who pinged me PINGRE

slate swan
#

Not me but hello

gleaming island
somber sky
gleaming island
#

@somber sky

somber sky
#

i replied to a message

#

on accident

#

i didnt realize it pinged you

sick birch
#

ah no worries it happens

naive briar
#

There's no error message

#

And you're getting a guild named Member

#

It doesn't work doesn't help people understand your question either โ˜•

slate swan
#

I'd use the built-in timeout feature if I were you, adding/removing certain roles is an outdated way of muting members and a hassle for server admins to set up correctly

upbeat otter
#

plus adding/removing roles is worse since it removes all the roles from the users and would require a db to store them all and assigning them after unmuting would require a lot more api calls

ocean leaf
#

overwrites just change all other permissions to default and changes the mentioned one to false. Is there any way to leave the other ones as they are and ONLY work with the one mentioned?

heady verge
#
@client.event
async def on_ready():
    print("Bot is online.")
    synced = await client.tree.sync()
    await client.sync(guild=discord.Object(id=1045668908536954911))
    print("Slash CMD's Synced" + str(len(synced)) + "Commands")``` 
nothing gets printed..
#

this is the code in main.py

upbeat gust
#

Using dpy 2.0 and not getting any errors? This is on purpose, the library now uses logging to send errors but only if you're using Client/Bot.run. More about that in ?tag defaultlogging.

It's recommended to setup logging yourself if you aren't using .run or use the utils.setup_logging helper function: just put discord.utils.setup_logging() anywhere in your running file. Docs: https://discordpy.readthedocs.io/en/stable/api.html#discord.utils.setup_logging

but I can't use Client/Bot.run!
You can! You can load cogs and do other stuff in the newly added setup_hook method that is called once after the bot logs in, more about that and how to implement it in ?tag setuphook.

wide lagoon
#

why does only the last part of my code work? the full thing worked before, idk why it doesnt work anymore, heres my code ```py
import discord

import random

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

client = discord.Client(intents=intents)

Insults = []
Insults.append("I bet your parents change subject whenever their friends ask about you.")
Insults.append("You aren't the dumbest person in the world but you better hope they don't die.")
Insults.append("You are the human equivalent of participation trophy.")
Insults.append("I envy those who've never met you.")
Insults.append("You've got two brain cells, and they're are both fighting for third place.")
Insults.append("Trees are tirelessly producing oxygen so your ass can complain, I think you owe them an apology.")
Insults.append("You're the reason why shampoo has instructions.")
Insults.append("I don't care what others say, I think you're great.")
Insults.append("I wouldn't want to be your mirror.")
Insults.append("You're like the end pieces of a loaf of bread. Everyone touches you but nobody wants you.")
Insults.append("You're not cute enough to be this stupid.")
Insults.append("You seem like the type of guy to wash his hand after a shower.")
Insults.append("I had 0 expectations of you and somehow I was still let down.")
Insults.append("You're the best pro-abortion argument I've ever met.")
Insults.append("I bet you drop common loop when defeated.")
Insults.append("You're the reason the power ranger say their colors everytime.")
Insults.append("I thought about you the other day, reminded me of taking out my trash.")
Insults.append("Someday youโ€™ll go far. And I really hope you stay there.")
Insults.append("Youโ€™re the reason God created the middle finger.")
Insults.append("Iโ€™m busy right now, can I ignore you another time?")
Insults.append("I hope your wife brings a date to your funeral")
Insults.append("Mirrors can't talk, lucky for you, they can't laugh either.")
Insults.append("Itโ€™s impossible to underestimate you.")
Insults.append("Your face makes onions cry.")

goodbye = []
goodbye.append("Bye")
goodbye.append("bye")
goodbye.append("Cya")
goodbye.append("cya")
goodbye.append("GoodBye")
goodbye.append("goodbye")
goodbye.append("Goodbye")
goodbye.append("Adios")
goodbye.append("adios")

Values = [1, 2, 3, 4, 5, 6]

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

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

if message.author.id in [491212588768821281, 650415406955102228]:
    insult = random.choice(Insults)
    await message.channel.send(insult)

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

if any(goodbyes in message.content for goodbyes in goodbye):
    await message.channel.send("Bye, I hope to see you never")

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

if message.content == "!Random":
    await message.channel.send(random.choice(Values))

client.run('my discord token')```

#

only the !Random command works now idk why

vocal snow
#

the last event is going to override the first two

#

why don't you just put them all in 1 event

wide lagoon
#

i could

#

but even when the 3 were seperated it worked

#

weird

vocal snow
#

and why are you using .append to add every single item instead of just declaring the list with those items

wide lagoon
#

its too long when i do that

vocal snow
#

what

#

you know you can put them on seperate lines

heady verge
#
client = aclient()
tree = app_commands.CommandTree(client)

@client.event
async def load():
    for filename in os.listdir("./cogs"):
        if filename.endswith(".py"):
            # cut off the .py from the file name
            await client.load_extension(f"cogs.{filename[:-3]}")```
#

'aclient' object has no attribute 'load_extension'

vocal snow
#

what is aclient?

vocal snow
# wide lagoon its too long when i do that
insults = [
    "I bet your parents change subject whenever their friends ask about you.",
    "You aren't the dumbest person in the world but you better hope they don't die.",
    "You are the human equivalent of participation trophy.",
    "I envy those who've never met you.",
    "You've got two brain cells, and they're are both fighting for third place.",
    "Trees are tirelessly producing oxygen so your ass can complain, I think you owe them an apology.",
    "You're the reason why shampoo has instructions.",
    "I don't care what others say, I think you're great.",
    "I wouldn't want to be your mirror.",
    "You're like the end pieces of a loaf of bread. Everyone touches you but nobody wants you.",
    "You're not cute enough to be this stupid.",
    "You seem like the type of guy to wash his hand after a shower.",
    "I had 0 expectations of you and somehow I was still let down.",
    "You're the best pro-abortion argument I've ever met.",
    "I bet you drop common loop when defeated.",
    "You're the reason the power ranger say their colors everytime.",
    "I thought about you the other day, reminded me of taking out my trash.",
    "Someday youโ€™ll go far. And I really hope you stay there.",
    "Youโ€™re the reason God created the middle finger.",
    "Iโ€™m busy right now, can I ignore you another time?",
    "I hope your wife brings a date to your funeral",
    "Mirrors can't talk, lucky for you, they can't laugh either.",
    "Itโ€™s impossible to underestimate you.",
    "Your face makes onions cry.",
]
heady verge
#
class aclient(discord.Client):
    def __init__(self):
        super().__init__(intents=discord.Intents.default())
        self.synced = False

    async def on_ready(self):
        """await self.wait_until_ready()
        if not self.synced:
            await tree.sync(guild = discord.Object(id=1045668908536954911))
            self.synced = True"""
        print(f"We have logged in as {self.user}."```
wide lagoon
vocal snow
#

that's part of the commands extension

#

so discord.ext.commands.Bot has it

heady verge
#

oh

wide lagoon
#

Thanks man i put them all in one event and it worked, i appreciate your help

vocal snow
#

welcome, have a good day

heady verge
#

discord.ext.commands.load_extension?

vocal snow
vocal snow
heady verge
#

oh

#
Extension 'cogs.fun' raised an error: TypeError: object.__init__() takes exactly one argument (the instance to initialize)
#
class Fun(commands.Cog):
    def __init__(self, bot: commands.Bot):
        super().__init__(intents=discord.Intents.default())
        self.bot = bot

async def setup(client):
    await client.add_cog(Fun(client), guilds=[discord.Object(id=1045668908536954911)])```
slate swan
#

pls

vocal snow
heady verge
#

oh my mistake

vocal snow
#

I suppose that's the Client _init_

heady verge
#

ye

#

my bad

#

so I ran the file, and it succeded but the slash commands aren't showing

vocal snow
#

are you syncing the tree?

heady verge
#

ye

#
        await self.wait_until_ready()
        if not self.synced:
            await tree.sync(guild = discord.Object(id=1045668908536954911))
            self.synced = True
        print(f"We have logged in as {self.user}.")```
#

also uhh

    @commands.Cog.listener()
    async def on_ready(self):
        print('Giveaway Cog Loaded')``` this doesnt get printed
#

uhh i gtg i will be back in 40 mins

somber sky
#

How would I make a command where, if the guild ID you invite the bot to is not in a list then leave the server

#
@client.event
async def on_join():
 if guild.id not in f.whitelistedservers:
   await guild.leave()```

thats what i have its probably not even close. `f.whitelistedservers` is a file, and its imported at the top `import whitelistedservers as f`
vocal snow
#

The event is on_guild_join iirc

waxen granite
#
    @tasks.loop(minutes= 30)
    async def statscounter(self):
        for key in self.serverstats.keys():
            guild = self.bot.get_guild(int(key))
            try:
                server_stats = self.serverstats[str(guild.id)]
            except KeyError:
                server_stats = {}
            category = discord.utils.get(guild.categories, name="STATS")
            botcount = 0
            membercount = 0
            members = guild.members
            textchannelscount = len(guild.text_channels)
            voicechannelscount = len(guild.voice_channels)
            for member in members:
                if member.bot == True:
                    botcount += 1
                else:
                    membercount += 1
            users_text = f"Users: {membercount}"
            bots_text = f"Bots: {botcount}"
            channels_text = f"Text Channels: {textchannelscount}"
            channels_voice = f"Voice Channels: {voicechannelscount}"
            tier = f"Premium Tier: Level {guild.premium_tier}"
            uc = guild.get_channel(server_stats['member_count'])
            bc = guild.get_channel(server_stats['bot_count'])
            tc = guild.get_channel(server_stats['text_count'])
            vc = guild.get_channel(server_stats['voice_count'])
            pt = guild.get_channel(server_stats['tier'])```
#
            if uc.name != users_text:
                await asyncio.sleep(1)
                await uc.edit(name=users_text, category=category)
            if bc.name != bots_text:
                await asyncio.sleep(1)
                await bc.edit(name=bots_text, category=category)
            if tc.name != channels_text:
                await asyncio.sleep(1)
                await tc.edit(name=channels_text, category=category)
            if vc.name != channels_voice:
                await asyncio.sleep(1)
                await vc.edit(name=channels_voice, category=category)
            if pt.name != tier:
                await asyncio.sleep(1)
                await pt.edit(name = tier, category=category)```
whats wrong , it doesnt update the channels
vocal snow
#

get_channel takes an int; looks like you're passing str

#

are you sure the if statements are running as expected and have you set up logging though?

alpine cove
#

^

heady verge
#

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

    async def on_ready(self):
        await self.wait_until_ready()
        if not self.synced:
            await tree.sync(guild = discord.Object(id=1045668908536954911))
            self.synced = True
        print(f"We have logged in as {self.user}.")

intents = discord.Intents.default()
client = aclient()
tree = app_commands.CommandTree(client)
bot = commands.Bot(command_prefix="s!", intents=intents, application_id='1056541924556816494')

@client.event
async def load():
    for filename in os.listdir("./cogs"):
        if filename.endswith(".py"):
            # cut off the .py from the file name
            await bot.load_extension(f"cogs.{filename[:-3]}")

async def main():
    await load()
    await client.start(credentials.TOKEN1)

@tree.command(name="ping", description="Gives the bot latency.", guild=discord.Object(id=1045668908536954911))
async def self(interaction: discord.Interaction):
    await interaction.response.send_message(f"Pong!")

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

this all works fine... but cogs aren't loading

#
class Fun(commands.Cog):
    def __init__(self, bot: commands.Bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_ready(self):
        print('Fun Cog Loaded')

    @app_commands.command(name="ping", description="Gives the bot latency.")
    async def ping(self, interaction: discord.Interaction):
        await interaction.response.send_message(f"Pong!")

    @app_commands.command(name="8ball", description="Gives you an answer.")
    @app_commands.describe(question="What do you want to ask the 8ball?")
    async def eightball(self, interaction: discord.Interaction, question:str):
        responses = ["As I see it, yes.", "Ask again later.", "Better not tell you now.", "Cannot predict now.", "Concentrate and ask again.",
                "Donโ€™t count on it.", "It is certain.", "It is decidedly so.", "Most likely.", "My reply is no.", "My sources say no.",
                "Outlook not so good.", "Outlook good.", "Reply hazy, try again.", "Signs point to yes.", "Very doubtful.", "Without a doubt.",
                "Yes.", "Yes โ€“ definitely.", "You may rely on it."]
        await interaction.response.send_message(f"**Question: ** {question}\n**Answer: ** {random.choice(responses)}")


async def setup(client):
    await client.add_cog(Fun(client), guilds=[discord.Object(id=1045668908536954911)])```
#
    @commands.Cog.listener()
    async def on_ready(self):
        print('Fun Cog Loaded')```

when i run the code, this does not print
alpine cove
#

?

#

!d discord.TextChannel.send

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

Sends a message to the destination with the content given.

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

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

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

what r u trying to achieve

#

!d discord.Message.reply

unkempt canyonBOT
#

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

A shortcut method to [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") to reply to the [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message").

New in version 1.6.

Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.11)") or [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.11)") instead of `InvalidArgument`.
alpine cove
#

!d discord.ext.commands.Context.reply

unkempt canyonBOT
#

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

A shortcut method to [`send()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.send "discord.ext.commands.Context.send") to reply to the [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") referenced by this context.

For interaction based contexts, this is the same as [`send()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.send "discord.ext.commands.Context.send").

New in version 1.6.

Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.11)") or [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.11)") instead of `InvalidArgument`.
alpine cove
#

alias

white citrus
#
future: <Task finished name='discord-ui-view-timeout-160f5a8f4ed3d684e890407cd770847d' coro=<admin_role_select_role_test.on_timeout() done, defined at c:\Discord\Maja Projekt\MajaSystem_Test\modules\setup_new_v2_00\view.py:113> exception=NotFound('404 Not Found (error code: 10008): Unknown Message')>
Traceback (most recent call last):
  File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\setup_new_v2_00\view.py", line 116, in on_timeout
    await self.message.edit(view=self)
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\interactions.py", line 1150, in edit
    message = await self._state._interaction.edit_original_message(
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\interactions.py", line 434, in edit_original_message
    data = await adapter.edit_original_interaction_response(
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\webhook\async_.py", line 182, in request
    raise NotFound(response, data)
nextcord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message```

I have no idea where the error comes from
alpine cove
#

nextcord eewww

white citrus
#

Are you able to help?

somber imp
#

show your on timeout code

#
  File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\setup_new_v2_00\view.py", line 116, in on_timeout
    await self.message.edit(view=self)
white citrus
#
class admin_role_select_role_test(nextcord.ui.View):
    def __init__(self, ctx_or_interaction, *, timeout=20):
        super().__init__(timeout=timeout)
    @nextcord.ui.role_select(placeholder="Please choose a role", max_values=1)
    async def on_select(self, select: nextcord.ui.RoleSelect, inter: nextcord.Interaction):
        roles = select.values.roles
        for role in roles:
            print(role.id)
        
        async with aiosqlite.connect("maja.db") as db:
            async with db.cursor() as cursor:
                await cursor.execute('SELECT id FROM setup WHERE id = ?', (inter.guild.id,))
                data_a = await cursor.fetchone()
                
                if data_a is None:
                    await cursor.execute('INSERT INTO setup (id, access_one) VALUES (?, ?)', (inter.guild.id, role.id,))
                    await db.commit()
                    
                if data_a is not None:
                    if inter.guild.id in data_a:
                        await cursor.execute("UPDATE setup SET access_one = ? WHERE id = ?", (role.id, inter.guild.id,))
                        await db.commit()
        
        
                eb = self.children[0]
                eb.disabled = True
                eb.placeholder = f"You selected @{role.name}"
                reply = nextcord.Embed(title="Admin role has been set", description=f"The Admin Role is now \n"f"{role.mention}\n `{role.id}`", colour=config.blurple)
                await inter.response.edit_message(embed=reply, view=self)
                await inter.delete_original_message(delay=7)
    
    async def on_timeout(self):
        eb = self.children[0]
        eb.disabled = True
        await self.message.edit(view=self)
        await self.message.delete(delay=5)    ```
#

@somber imp

somber imp
#

you need to set the message yourself after you send the view

somber imp
#

if you are doing it, then are you sending the view in an interaction response?

vague zephyr
#

discordpy is garbage

somber imp
#

And for delete to self.message.delete_original_message

slate swan
white citrus
alpine cove
somber imp
alpine cove
alpine cove
alpine cove
somber imp
alpine cove
somber imp
alpine cove
#

it sucks ass

white citrus
somber imp
#

Although pycord as pre alpha V3 rn that's a full rewrite

slate swan
#

so is nextcord

alpine cove
#

they just changed namespaces and made stuff wrose

slate swan
#

nah, they are actually doing a rewrite in a private repo.

somber imp
alpine cove
somber imp
slate swan
#

is it? i left the server a while ago so wasn't aware

somber imp
slate swan
vague zephyr
alpine cove
somber imp
vague zephyr
#

what does it have to do with what i said