#discord-bots

1 messages ยท Page 202 of 1

slate swan
#

๐Ÿ’€

#

what do i doooooo

#

how to fix

sick birch
#

Does this sort of make sense? I know it looks a bit confusing

#

I can break it down so it's not a list comp

slate swan
#

lol

#

i dont want to print it tho

sick birch
#
my_2d_list = [["row 1 col 1", "row 1 col 2"], ["row 2 col 1", "row 2 col 2"]]
display = ""

for row in my_2d_list:
  display += " ".join(row) # joins the contents of ONE row with a space
  display += "\n" # Add a line break

Pretty much does the same thing

sick birch
#

The logic is the same, however

slate swan
#

ok

#

ima try it

young dagger
#

How can I send the embed message only once for all the banned members?

        # Check if the maximum number of new members has been exceeded
        await asyncio.sleep(5)
        if new_members_count > max_new_members:
            # Ban all members in the list of new members
            for member in new_members_list:

                await member.ban(reason="Exceeded maximum number of new members in allowed time period.")

            # Send an embedded message to the specified channel
            channel = client.get_channel(745832392404762695)
discord.Embed(description=f'Server Raided:\n\nRaid Size: **{len(new_members_list)} accounts**', timestamp=datetime.datetime.now(), color=discord.Color.red())
            embed.set_author(name="Anti Raid Detected", icon_url=avatar_url)
            await channel.send(embed=embed)```
slate swan
#

@smoky sinew @sick birch do i remove the return grid_str

smoky sinew
slate swan
#

bc if i do the embed just says none

#

def predict():
mine_locations = get_mine_locations()
grid = get_safe_spots(mine_locations)
grid_str = ""
for row in grid:
grid_str += " ".join(row)
grid_str += "\n"

  return grid_str
#

is this right loll

#

it still only shows 1 line

#

or am i just dumb

slate swan
smoky sinew
smoky sinew
slate swan
#

๐Ÿ˜ญ

#

what to do

smoky sinew
#

that's why i replied to beerhunter

slate swan
#

lol

#

but what should i do

#

do i remove the return?

#

๐Ÿ’€

sick birch
#

Oh, you have to return grid_str after the loop is completely done

slate swan
sick birch
#

Right now it just returns on the first loop iteration

pliant gulch
unkempt canyonBOT
#

@pliant gulch :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | row 1 col 1 row 1 col 2
002 | row 2 col 1 row 2 col 2
slate swan
#

then

sick birch
unkempt canyonBOT
#

@sick birch :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | row 1 col 1 row 1 col 2
002 | row 2 col 1 row 2 col 2
sick birch
#

I did

slate swan
#

โšก

#

โญ

vital glacier
#

Anyone in here who can help me proper setup my pool connection for postgresql & asyncpg using a setup_hook?

ionic garden
#

is there a command listener for commands that are only in a single cog?

golden portal
unkempt canyonBOT
#

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

A special method that acts as a cog local pre-invoke hook.

This is similar to [`Command.before_invoke()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command.before_invoke "discord.ext.commands.Command.before_invoke").

This **must** be a coroutine.
ionic garden
#

is this an inherited method

golden portal
#

sure, its just a method you override in the cog

slate swan
#

read the server name mate

#

thank you

slate swan
#

my bot is online, but won't ping zzz
it says it still says [2023-02-24 18:46:50] [WARNING ] discord.ext.commands.bot: Privileged message content intent is missing, commands may not work as expected. even though they are all turned on

#
from discord.ext import commands

intents = discord.Intents.default()
intents.members = True
intents.presences = True

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

@bot.event
async def on_ready():
    print(f'{bot.user.name} has connected to Discord!')

@bot.event
async def on_message(message):
    if message.content == 'hi':
        await message.channel.send('hello')
    await bot.process_commands(message)

bot.run('token')```
#

bot it online in server, has admin

naive briar
#

!d discord.Intents.message_content

unkempt canyonBOT
#

Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:

โ€ข The message was sent by the client

โ€ข The message was sent in direct messages

โ€ข The message mentions the client

This applies to the following events...

slate swan
# naive briar I don't see you enabling `message_content` intent anywhere in that code
from discord.ext import commands

intents = discord.Intents.default()
intents.members = True
intents.presences = True
intents.messages = True

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

@bot.event
async def on_ready():
    print(f'{bot.user.name} has connected to Discord!')

@bot.event
async def on_message(message):
    if message.content == 'hi':
        await message.channel.send('hello')
    await bot.process_commands(message)

bot.run('token')```
#

same error

naive briar
#

message_content not messages

slate swan
#

message.content = True ?

naive briar
#

No, message_content

#

Exactly that, no changes

slate swan
#

where?

#

under intents?

naive briar
#

Enable it

slate swan
naive briar
#

In the code

#
intents = discord.Intents.default()
...
intents.message_content = True
slate swan
#

that's kind of what I asked, it's just incorrect spelling

#

holy shit

#

I love you ๐Ÿ˜

sacred vigil
#

Can i edit an embed after its sent? Like change the color depending on the status etc

slate swan
#

yessss

slate swan
#

Hello, how do I fix this error?

bright wedge
slate swan
bright wedge
slate swan
slate swan
slate swan
slate swan
#

what is the followup webhook?

#

@slate swan

#

!d discord.Interaction.followup

unkempt canyonBOT
slate swan
#

basically the webhook used to create slash responses

slate swan
#

I have a little question please, how can I make it that the user can either mention someone in a slash commands, and it optional

#
    @app_commands.command(name="berries", description="to know how much Berries you got")
    @app_commands.describe(user="if you want to check the berries of someone else you can mention them")
    async def cardinfo(self, interaction: discord.Interaction, user: discord.member=None):
    # Connect to the database

        if user== None:
            user_id= interaction.user.id
        else: 
            user_id= interaction.user.mention.id```
#

I am trying this

#

but the error is that interaction.user.mention got no attribut id

#

Can someone help me with my code

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36',
    'X-Auth-Token': auth_token
}

params = {'size': '2', 'page': '0'}

def get_mine_locations():
    response = requests.get('https://rest-bf.blox.land/games/mines/history', headers=headers, params=params)
    data = json.loads(response.text)
    return [location for game in data['data'] for location in game['mineLocations']]

import requests
import random



def get_safe_spots(mine_locations):
    # Create a set of all safe spots
    all_spots = set(range(25))
    mine_spots = set(mine_locations)
    safe_spots = all_spots - mine_spots
    
    # Choose 5 random safe spots
    safe_spots_list = list(safe_spots)
    random_safe_spots = random.sample(safe_spots_list, 5)
    
    # Sort the mine locations by row then column
    sorted_mine_locations = sorted(mine_locations, key=lambda loc: (loc // 5, loc % 5))
    
    # Create the grid with emojis
    grid = []
    for i in range(5):
        row = []
        for j in range(5):
            index = i * 5 + j
            if index in random_safe_spots:
                row.append('๐Ÿ’ฃ')
            elif index in mine_locations:
                row.append('โ”')
            else:
                row.append('โญ')
        grid.append(row)
    
    return grid

def predict():
    mine_locations = get_mine_locations()
    grid = get_safe_spots(mine_locations)
    grid_str = ""
    for row in grid:
      
      return grid

predict()

@bot.slash_command(name="minesplay_bomb")
@commands.has_role("Buyer")
async def bloxflip(ctx):
  raid = predict()
  embed = discord.Embed(title="**Radiant Predictor**", description=f"{raid}")
  await ctx.respond(embed=embed)```
#

when i run it and use the command it looks like this:

#

i want it to be a 5x5 grid

slate swan
#

With a for loop with range

maiden fable
#

Just use join

unkempt mauve
#
@client.event
async def on_message(message):
    if message.author == client.user:
        return
    if message.content.startswith('siam'):
        await message.channel.send('Hi there!')```
#

bot is not sending any msg

#

it has admin

slate swan
#

Did u enable message intents?

unkempt mauve
naive briar
#

Enable it in the code also

#

!d discord.Intents.message_content

unkempt canyonBOT
#

Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:

โ€ข The message was sent by the client

โ€ข The message was sent in direct messages

โ€ข The message mentions the client

This applies to the following events...

unkempt mauve
#

worked lol

#

i am coding a chatbot

slate swan
#

Oh great!

upbeat otter
#

idts many people would actually use a chatbot anymore

#

we need a bot that teaches people real social interaction skill

unkempt mauve
naive briar
#

Make it tell them try to interact with actual people

upbeat otter
gloomy bramble
#
@tree.command(name="object", description="Randomly uploads a picture from a specific directory.")
async def object(int: discord.Interaction):
    directory_path = "/path/to/directory" # replace with the path to your directory of images
    image_files = [f for f in os.listdir(directory_path) if os.path.isfile(os.path.join(directory_path, f)) and f.endswith(".jpg")] # replace ".jpg" with the file extension of your images
    if len(image_files) == 0:
        await int.response.send_message("No images found in directory.")
        return
    selected_image = random.choice(image_files)
    with open(os.path.join(directory_path, selected_image), "rb") as f:
        file = discord.File(f)
        await int.response.send_file(file, content=f"Here's a picture: {selected_image}")
#

btw guys what's wrong here

quick gust
#

not a great idea to name the arg int...

quick gust
gloomy bramble
#

error is "has no attribute send_file"

gloomy bramble
quick gust
#

Send the complete error please

#

!traceback

unkempt canyonBOT
#

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

A full traceback could look like:

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

If the traceback is long, use our pastebin.

gloomy bramble
#

that's the complete error lol

quick gust
#

No it's not

gloomy bramble
#

@quick gust

quick gust
#

The screenshot crops out main parts of the error... Please copy paste the entire thing

gloomy bramble
desert badger
#

how do i start a loop that is inside a cog

#

everythig works fine and the cog gets loaded

#

the loop just doesnt start

wind plank
#

it's the same thing but better

#

discord has a lot of errors

desert badger
feral frost
#

code

async def on_submit(interaction: discord.Interaction):
            await interaction.response.send_message(f"New password set!")
            if result is None:
                sql = ("INSERT INTO pass(user_id, platform, acc_name, pass_name) VALUES(?, ?, ?, ?)")
                val = (interaction.user.id, plat, acc, pas)

            elif result is not None:
                sql = ("UPDATE pas SET plat = ?, acc_name = ?, pass_name = ? WHERE user_id = ?")
                val = (plat, acc, pas, interaction.user.id)

            await cursor.execute(sql, val)
            await db.commit()

        async def button_callback(interaction: discord.Interaction):
            create_account = Modal(title="Password setup")
            create_account.on_submit = on_submit

            create_account.add_item(plat)
            create_account.add_item(acc)
            create_account.add_item(pas)

            await interaction.response.send_modal(create_account)```
error
```line 81, in on_submit
    await cursor.execute(sql, val)```
#

pls help

maiden fable
feral frost
feral frost
maiden fable
#

This is the error

desert badger
#

can anyone here tell me how to start a loop inside a cog rq, i have my whole loop, the cog gets loaded but it doesnt start, do i have to put a start function somewhere ?

glad cradle
#

!d discord.ext.commands.Cog.cog_load

unkempt canyonBOT
#

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

A special method that is called when the cog gets loaded.

Subclasses must replace this if they want special asynchronous loading behaviour. Note that the `__init__` special method does not allow asynchronous code to run inside it, thus this is helpful for setting up code that needs to be asynchronous.

New in version 2.0.
desert badger
#

as i have already said in my message

#

the loop just doesnt start

#

hi willi

wanton current
#

Are you starting the loop in cog_load?

#

hi

desert badger
#

uh

#

idfk

#

i just load the cog

wanton current
#

cog_load gets called when the cog is loaded

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

    async def cog_load(self): # Doesn't matter if it's an async function if you're not doing async stuff in it
        # start your loop here

Should work.

desert badger
#

or just some loop.start

wanton current
#

.start

desert badger
lament depotBOT
#

That's not very nice @desert badger

desert badger
#

love u <3

sick birch
#

I sense a lurker admin

#

and I know who it is ๐Ÿ‘€

smoky sinew
#

why would you force a certain library on someone

smoky sinew
wind plank
smoky sinew
#

it's a discord bot development channel, you should be able to get help no matter what library you use

hushed galleon
#

id consider "should" as a suggestion, though i would like to hear details on discord.py having lots of errors

wind plank
#

after all it was just an advice not "Force".

vocal snow
#

that was a long time ago

#

just peeking at the discord.py commit history should let you know that it obviously wasn't dropped

hushed galleon
clear elm
#

cna someone send me the docs for creating channels

#

nvm got it

burnt imp
#

Is there a way to check what messages I'm sending to a user just from the dm?

young dagger
#

How do you clear the users list users = [] if it's a global variable?

#

!e

users = ["Alice", "Bob", "Charlie"]

def clear_users():
    global users
    users = []
    print(users)

clear_users()```
unkempt canyonBOT
#

@young dagger :white_check_mark: Your 3.11 eval job has completed with return code 0.

[]
young dagger
#

Hmh

#

Unresolved reference 'clear_users'

naive briar
#

!e

a = list(range(10))

def func():
    a.clear()
    print(a)

print(a)
func()
unkempt canyonBOT
#

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

001 | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
002 | []
young dagger
#

Thanks

young lintel
#

does anyone know how to make a transcript cmd for tickets

smoky sinew
#

loop over all the messages in the ticket and write them to a text file

young lintel
#

alr

clear elm
#

i've got a ticket command, i want to make it so you can only create one ticket at a time and if you have one open it sends an ephemeral message and it doesn't create a channel but if you don't have one it creates it. if anyone could help, that'd be great, this is my cuurrent code

@bot.tree.command(name="order", description="Creates a ticket to order a bot.")
async def _order(interaction, title:str):
  guild = interaction.guild
  category = discord.utils.get(guild.categories, name="Tickets")
  if category is None:
    await guild.create_category_channel(name="Tickets")
  channel = await guild.create_text_channel(f'ticket-{interaction.user}', category=category)
  
  await interaction.response.send_message(f'Your ticket has been created. {channel.mention}', ephemeral=True)
  orderEmbed=discord.Embed(title="New ticket!", color=0x23B425)
  orderEmbed.add_field(name=f'{title}', value=f'Thanks for creating a ticket {interaction.user.mention}, please wait for one of our staff members to assist you!', inline=False)
  orderEmbed.set_footer(text="Corpotics")
  await channel.send("<@&1078464006433542154>", embed=orderEmbed)```
fading marlin
#

Before creating the text channel, check if a channel with the name "ticket-user-0000" exists ๐Ÿคท

Also, might want to assign category to what create_category_channel returns

if category is None:
    await guild.create_category_channel(name="Tickets")
clear elm
#

would this work?

    if not interaction.channel.name.startswith(f'ticket-{interaction.user}'):
      channel = await guild.create_text_channel(f'ticket-{interaction.user}', category=category)
    return
    await interaction.response.send_message("You already have ticket open!", ephemeral=True)
fading marlin
#

That doesn't check whether a channel already exists. You're returning early too, so the send_message will never be executed.

clear elm
#

what about this?

  if channel.name == f'ticket-{interaction.user}':
     await ctx.send(f'You already have an open ticket! {channel.mention}', ephemeral=True)
  else:
  channel = await guild.create_text_channel(f'ticket-{interaction.user}', category=category)```
fading marlin
#

Check if the name of any channel in the "Tickets" category matches what you have. Do note that text channels can't have special characters, and interaction.user includes a #

vital glacier
#

Anyone that can help me?
This is what I keep getting in my console:

list index out of range

Every time someone types in a server where my bot is in, I assume it's connected to my database, but the only 3 things with database code in it, are my prefix command. my afk command and the way my bot gets the prefix, which is this:

async def prefix(bot, message):
    data = await bot.db.fetchval('SELECT prefix FROM prefix WHERE guild_id = $1', message.guild.id)
    if data:
        return commands.when_mentioned_or(data[0])(bot, message)
    else:
        return commands.when_mentioned_or(',')(bot, message)
unkempt canyonBOT
#

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

A full traceback could look like:

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

If the traceback is long, use our pastebin.

vital glacier
#

There is no "traceback"

#

Or else I would've included it. this is all i'm getting in my console.

naive briar
#

Then I can't tell where exactly the error came from

fading marlin
#

You want to exclude it

fading marlin
clear elm
pliant gulch
#

I would say keep the discrim part otherwise, it'll error with common usernames

vital glacier
#

But it still doesn't give me the error of what the problem is

#
    @commands.Cog.listener()
    async def on_message(self, message):

        ctx = await self.bot.get_context(message)
        if message.author.bot: return
        data = await self.bot.db.fetch('SELECT * FROM afk WHERE user_id = $1', message.author.id,)
        if data:
            print(data)
            timestamp = data[0][2]
            time = humanize.precisedelta(timestamp - discord.utils.utcnow().timestamp(), format='%0.f')
            await self.bot.db.execute('DELETE FROM afk WHERE user_id = $1', message.author.id,)
            await ctx.success(f'Welcome back, you were away for **{time}**')
        if message.mentions:
            for mention in message.mentions:
                data = await self.bot.db.fetch('SELECT * FROM afk WHERE user_id = $1', mention.id,)
                if data and mention.id != message.author.id:
                    print(data)
                    timestamp = data[0][2]
                    time = humanize.precisedelta(timestamp - discord.utils.utcnow().timestamp(), format='%0.f')
                    await ctx.success(f'**{mention}** is currently **AFK**: {data[0][1]} - {time} ago')
#

This is my afk event handler

clear elm
vital glacier
#

But it's not sending the welcome back message if the person who is in the afk database types or when they get mentioned

#

Which makes 0 sense to me

clear elm
#
  if channel.name == f'ticket-{interaction.user}':
     await ctx.send(f'You already have an open ticket! {channel.mention}', ephemeral=True)
  else:
      channel = await guild.create_text_channel(f'ticket-{interaction.user}', category=category)```
it continues to make a ticket even if i have a ticket open
naive briar
#

Send the full code

clear elm
#
@bot.tree.command(name="order", description="Creates a ticket to order a bot.")
async def _order(interaction, title:str):
  guild = interaction.guild
  category = discord.utils.get(guild.categories, name="Tickets")
  if category is None:
    await guild.create_category_channel(name="Tickets")
  channel = discord.utils.get(guild.channels)

  if channel.name == f'ticket-{interaction.user}':
     await ctx.send(f'You already have an open ticket! {channel.mention}', ephemeral=True)
  else:
      channel = await guild.create_text_channel(f'ticket-{interaction.user}', category=category)
  
  await interaction.response.send_message(f'Your ticket has been created. {channel.mention}', ephemeral=True)
  orderEmbed=discord.Embed(title="New ticket!", color=0x23B425)
  orderEmbed.add_field(name=f'{title}', value=f'Thanks for creating a ticket {interaction.user.mention}, please wait for one of our staff members to assist you!', inline=False)
  orderEmbed.set_footer(text="Corpotics")
  await channel.send("<@&1078464006433542154>", embed=orderEmbed)```

this code creates the ticket but it doesn't check if they already have a ticket open. it creates the channel even if htey have one open, no errors. can someone help?
clear elm
ocean leaf
#

Hi, I'm making a rob command where the user has some chances to win (they can use power ups to increase the chances) and the target user also has some defence chances (which they can increase). I need a true/false value to check if the user won or not. Can anyone suggest a good method to do it? Sorry for my English :)

naive briar
#

!e

import random

for _ in range(10):
    n = random.randint(1, 2)
    print(n, n == 1)
unkempt canyonBOT
#

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

001 | 2 False
002 | 1 True
003 | 2 False
004 | 1 True
005 | 2 False
006 | 2 False
007 | 2 False
008 | 2 False
009 | 2 False
010 | 1 True
naive briar
#

50/50 ๐Ÿฅค

ocean leaf
#

No, the user can use powerups

#

To increase their chances

naive briar
#

!d random.random

unkempt canyonBOT
#

random.random()```
Return the next random floating point number in the range `0.0 <= X < 1.0`
naive briar
#

!e

import random

n = random.random()
print(n, n >= 0.5)

n = random.random() + 0.1 # increases the chance by 10% or whatever it's called
print(n, n >= 0.5)
unkempt canyonBOT
#

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

001 | 0.48633593873984005 False
002 | 1.0745200817226221 True
smoky sinew
#

pretty sure you can just use guild = bot.get_channel(id)

clear elm
#

would that fix the code?

shrewd fjord
#

U can do
guild.get_channel too tho i prefer it most xd

vital glacier
#

Anyone that knows humanize properly?
For some odd reason this line in my afk event handler broke: ```time = humanize.precisedelta(timestamp - discord.utils.utcnow().timestamp(), format='%0.f')

#

and i've got no clue on why

smoky sinew
clear elm
#

would it be category = bot.get_channel(1078823637609631765) because if i leave it as guild = bot.get_channel(1078823637609631765) category would be undefined

quick gust
vital glacier
quick gust
#

great

clear elm
#

it doesn't work

#

just c\reates the tickets still

#

even if i have one open

smoky sinew
clear elm
#

no

smoky sinew
#

the reason is discord.utils.get with one parameter will just return the first text channel it sees

smoky sinew
# clear elm no

yes you do, because how else will you check if the user has already opened a channel

clear elm
#

cant i do it by the name?

smoky sinew
#

sure

#

but you aren't doing that right now

clear elm
#

how would i?

#
@bot.tree.command(name="order", description="Creates a ticket to order a bot.")
async def order(interaction):
  guild = interaction.guild
  category = bot.get_channel(1078823637609631765)
  if category is None:
    await guild.create_category_channel(name="Tickets")
  channel = discord.utils.get(guild.channels)

  if channel.name == f'ticket-{interaction.user}':
     await interaction.response.send_message(f'You already have an open ticket! {channel.mention}', ephemeral=True)
  else:
      channel = await guild.create_text_channel(f'ticket-{interaction.user}', category=category)
  
  await interaction.response.send_message(f'Your ticket has been created. {channel.mention}', ephemeral=True)
  orderEmbed=discord.Embed(title="New ticket!", color=0x23B425)
  orderEmbed.add_field(name="", value=f'Thanks for creating a ticket {interaction.user.mention}, please wait for one of our staff members to assist you!', inline=False)
  orderEmbed.set_footer(text="Corpotics")
  await channel.send("<@&1078464006433542154>", embed=orderEmbed)```
this is the current code
smoky sinew
#

!d discord.utils.get

unkempt canyonBOT
#

discord.utils.get(iterable, /, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.utils.find "discord.utils.find").

When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.

To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.

If nothing is found that matches the attributes passed, then `None` is returned.

Changed in version 2.0: The `iterable` parameter is now positional-only.

Changed in version 2.0: The `iterable` parameter supports [asynchronous iterable](https://docs.python.org/3/glossary.html#term-asynchronous-iterable "(in Python v3.11)")s...
smoky sinew
#

look at the arguments, you have to pass something to look for

#

you can pass name

clear elm
#

would the name be the name of the category

smoky sinew
#

no, you are looking for the user's ticket channel

#

discord.utils.get(list, attribute=value) just returns an item inside list that has an attribute equal to value

vocal snow
#

!d discord.utils.get

unkempt canyonBOT
#

discord.utils.get(iterable, /, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.utils.find "discord.utils.find").

When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.

To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.

If nothing is found that matches the attributes passed, then `None` is returned.

Changed in version 2.0: The `iterable` parameter is now positional-only.

Changed in version 2.0: The `iterable` parameter supports [asynchronous iterable](https://docs.python.org/3/glossary.html#term-asynchronous-iterable "(in Python v3.11)")s...
vocal snow
#

there are examples in the docs as well ^^

clear elm
#

channel = discord.utils.get(guild.channels)

clear elm
#

im confused

vital glacier
#
    @commands.command(
        name='kick',
        usage='kick (user) <reason>',
        description='void#0480 calm down',
        aliases=['boot'])
    @commands.has_permissions(kick_members=True)
    async def kick(self, ctx, user: discord.Member, *, reason: str = 'No reason provided'):
        """Kick a user from the server"""

        if user is ctx.author:
            return await ctx.success('You\'re unable to **kick** yourself')
        if user is ctx.guild.owner:
            return await ctx.success('You\'re unable to kick the **guild owner**')
        if user.top_role >= ctx.author.top_role:
            return await ctx.success('You\'re unable to kick a user with **superior roles** than you')
        if user.top_role >= ctx.guild.me.top_role:
            return await ctx.success('You\'re unable to kick a user with **superior roles** than me')
        else:
            await user.kick(reason=f"{str(ctx.author)} ({ctx.author.id}) | {reason}")
            await ctx.reply('๐Ÿ‘๐Ÿพ')

How do I make it so the server owner can ALWAYS ban someone with the same role as them and if the bot is below the server owners role

smoky sinew
#

i'm not sure what you're saying, the bot can only ban people with lower roles

vital glacier
#

Well yes either that and it also cant ban people with the same role

#

but for instance, server owners, they normally can ban anyone even tho they have the same role

smoky sinew
#

so what's the issue? the bot is already able to ban people below it isn't it?

vital glacier
#

But i'm trying to make it that it can bot can ban/kick someone with the same role as the owner if the command is issued by the owner

clear elm
#

@smoky sinew im trying to make it so if you use /order and you already have a ticket open, it sends an ephemeral message. if you dont have one open, it will open a ticket. im trying to make it detect whether they have a ticket open by the name

smoky sinew
#
channel = discord.utils.get(category.channels, name = "channel name")

if channel:
    # error
else:
    # create the channel
naive briar
vital glacier
#

Because that's not what I'm trying to do

#

I'm trying to code it into the bot, not use the button

#

Using the button is way too much effort mate

smoky sinew
clear elm
smoky sinew
#

what's even the point of having the return statements? @vital glacier

smoky sinew
#

if it can't find a channel with name utils.get will just return none

vital glacier
#

The return statements are there because it'll spam ever single embed if they're not there

vital glacier
#

genuinely i keep forgetting that that's a thing

smoky sinew
smoky sinew
clear elm
clear elm
smoky sinew
clear elm
#
channel = discord.utils.get(category.channels, name=f'ticket-{interaction.user}')

if channel:
    await interaction.response.send_message(f'You already have an open ticket! {channel.mention}'
else:
      channel = await guild.create_text_channel(f'ticket-{interaction.user}', category=category)```
#

?

shrewd fjord
#

if channel means it didn't return None
and else means it did return None

#

!e
a = None
if a:
print("it's not None!")
else:
print("it's None")

unkempt canyonBOT
#

@shrewd fjord :white_check_mark: Your 3.11 eval job has completed with return code 0.

it's None
shrewd fjord
#

!e
a = 2234
if a:
print("it's not None!")
else:
print("it's None")

unkempt canyonBOT
#

@shrewd fjord :white_check_mark: Your 3.11 eval job has completed with return code 0.

it's not None!
clear elm
#

so ```py
channel = discord.utils.get(category.channels, name=f'ticket-{interaction.user}')

if channel:
await interaction.response.send_message(f'You already have an open ticket! {channel.mention}')
else:
channel = await guild.create_text_channel(f'ticket-{interaction.user}', category=category)``` should work?

shrewd fjord
#

Kinda simple

shrewd fjord
clear elm
#

oh yeah, iwas gona do that

shrewd fjord
clear elm
#

let me just test it

#

it still made one

#

even if i had one opened

shrewd fjord
#

Tho sometime it may not work because of bad symbols on name

clear elm
#

oh

#

so like mine

shrewd fjord
#

To check if thr code is working or not

clear elm
#

yeah id would be better

#

that way even if they do change it, id will stay the same

shrewd fjord
#

Yep

#

Oh also, if they changes the name, they can no longer create ticket kek

#

Or access it

clear elm
#

wait why?

#

i changed it to id

shrewd fjord
#

Discriminator would be good too, but sometimes the discriminator is same, but maybe you can use channel's description, and set the description to user id

shrewd fjord
clear elm
#

yeah it works

shrewd fjord
#

Nice

clear elm
#

if its id and they cahnged their name, theyd still be able to access it, right?

shrewd fjord
#

Some of ticket bots use this method

clear elm
#

ok

#

ill use id and then i can set the description to their user+discrim

shrewd fjord
#

Lemme check the docs tho ๐Ÿ’€

clear elm
#

but if i did that and they cahnged their name, wouldnt they not be able to access it?

shrewd fjord
#

Hmm

shrewd fjord
clear elm
#

how would i do that

shrewd fjord
shrewd fjord
clear elm
#

ok

shrewd fjord
#

!d discord.TextChannel.topic

unkempt canyonBOT
shrewd fjord
#

This

#

channel=discord.utils.get(...., topic=....)

#

Btw it's string

clear elm
#

mhm

#
channel = discord.utils.get(category.channels, name=f'ticket-{interaction.user}', topic=f'This ticket is for {interaction.user.id}!')```
shrewd fjord
#

!d discord.Guild.create_text_channel

unkempt canyonBOT
#

await create_text_channel(name, *, reason=None, category=None, news=False, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=..., default_auto_archive_duration=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

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

Note that you must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") to create the channel.

The `overwrites` parameter can be used to create a โ€˜secretโ€™ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.11)") of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite") as the value.

Note

Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
clear elm
#

isnt name the title of the channel?

shrewd fjord
#

Only topic

shrewd fjord
#

Check up of the image, the texts in small sizes are topic

#

"For questions ....."

clear elm
#

mhm

shrewd fjord
#

So u can just set the channel topic on
create_text_channels

#

Btw this all stuff is for making the ticket channel name good kek

#

Giving id as ticket channel name looks ugly

clear elm
#

yeah ikr

#
  channel = discord.utils.get(category.channels, topic=f'This ticket is for {interaction.user.id}!')```
shrewd fjord
shrewd fjord
#

The topic SHOULD BE the same while creating the channel

clear elm
#

wait so what will the name be

#
  channel = discord.utils.get(category.channels, topic=f'This ticket is for {interaction.user.id}!')

  if channel:
      await interaction.response.send_message(f'You already have an open ticket! {channel.mention}', ephemeral=True)
  else:
        channel = await guild.create_text_channel(topic=f'This ticket is for {interaction.user.id}!', category=category)```
shrewd fjord
#

Using topic, now the name doesn't matter that much

clear elm
#
  channel = discord.utils.get(category.channels, name=f'ticket-{interaction.user.name}', topic=f'This ticket is for {interaction.user.id}!')

  if channel:
      await interaction.response.send_message(f'You already have an open ticket! {channel.mention}', ephemeral=True)
  else:
        channel = await guild.create_text_channel(name=f'ticket-{interaction.user.name}', topic=f'This ticket is for {interaction.user.id}!', category=category)```
shrewd fjord
#

Add
global count, top of the function

shrewd fjord
#

No sec

#

Fk keyboard

clear elm
# shrewd fjord Remove the name=... From utils.get()
  channel = discord.utils.get(category.channels, topic=f'This ticket is for {interaction.user.id}!')

  if channel:
      await interaction.response.send_message(f'You already have an open ticket! {channel.mention}', ephemeral=True)
  else:
        channel = await guild.create_text_channel(name=f'ticket-{interaction.user.name}', topic=f'This ticket is for {interaction.user.id}!', category=category)```
shrewd fjord
#

@bot.event
async def on_message(message):
global count
global bot.chat

clear elm
shrewd fjord
#

Now there will be no e4ror

shrewd fjord
clear elm
#

by any chance, do you know how to make transcripts?

shrewd fjord
#

Ah, remove the
global bot.chat then lol

shrewd fjord
#

Yeah i forgor

#

!d discord.TextChannel.history

unkempt canyonBOT
#

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") that enables receiving the destinationโ€™s message history.

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

Examples

Usage...
shrewd fjord
#

Here,
There is an example too

clear elm
#

is limit for however much messages the transcript will get?

clear elm
#

ok

shrewd fjord
#

What the ๐Ÿ’€๐Ÿ’€

clear elm
#

am i able to make it so the transcript is sent to dms and a logging channel when /close deletes the channel?

shrewd fjord
#

Can u try removing
bot.chst={}?

#

bot.chat*

clear elm
#

can u give me an example?

shrewd fjord
#

Just wait some 5 secs, then generate all messages in a txt file with the history() method and send that ti the dm

shrewd fjord
#

Pretty simple

#

Just name it
chat={}

shrewd fjord
#

the messages is a discord.Message object i forgot xd

clear elm
shrewd fjord
#

This isn't good but try

clear elm
#

so rather than topic=f'This ticket is for {interaction.user.id}! ill make it topic=str(interaction.user.id)?

shrewd fjord
#

Wait for someone to help fr xd

clear elm
#

ok

shrewd fjord
#

Then u can do,
member=guild.get_member(int(channel.topic))
await member.send(...)

clear elm
#

where do i do that?

#

oh nvm

#
channel=interaction.channel
message=""
async for messages in channel.history(....):
message+=f"{messages.author.name}: {messages.content}\n"
member=guild.get_member(int(channel.topic))
await member.send(...)```
shrewd fjord
#

Yeah

clear elm
#

so then how would i make it so it sends when the ticket is closed

shrewd fjord
shrewd fjord
#

Simple...

#

What error?

shrewd fjord
clear elm
shrewd fjord
#

Give full code fr

#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

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

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

clear elm
#
    channel=interaction.channel
    message=""
    async for messages in channel.history(....):
      message+=f"{messages.author.name}: {messages.content}\n"
      await interaction.user.send(message)```
#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

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

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

green barn
#

I'm stuck with my inrole command, this is what i've got right now and i'm not completely sure how it works. I've got no errors either.

        name='inrole',
        aliases=['members'],
        usage='inrole',
        description=''
    )
    async def inrole(self, ctx, role: discord.Role = None):
        """View the users in a role"""
        
        await ctx.typing()
        embeds = []
        ret = []
        num = 0
        pagenum = 1
        for m in ctx.guild.members:
            if role in m:
                num += 1
                ret.append(f'**{num}.** {m.mention} ({m.id})')
                pages = [p for p in discord.utils.as_chunks(ret, 10)]
        for page in pages:
            pagenum += 1
            embeds.append(discord.Embed(
                color=color, 
                description="\n".join(page))
                )
            
        pag = Paginator(self.bot, embeds, ctx, invoker=ctx.author.id)

        pag.add_button('prev', emoji='![back](https://cdn.discordapp.com/emojis/1077829978240077896.webp?size=128 "back")')
        pag.add_button('next', emoji='![next](https://cdn.discordapp.com/emojis/1077830055159414816.webp?size=128 "next")')
        pag.add_button('goto', emoji='![enter](https://cdn.discordapp.com/emojis/1077859606681899009.webp?size=128 "enter")')
        pag.add_button('delete', emoji='![stop](https://cdn.discordapp.com/emojis/1077830212982677604.webp?size=128 "stop")')
        return await pag.start()```
clear elm
#
@bot.tree.command(name="close", description="Closes the ticket!")
async def close(interaction, reason:str):
    if not interaction.channel.name.startswith('ticket-'):
        await interaction.response.send_message('This is not a ticket channel.', ephemeral=True)
        return

    await interaction.channel.delete()
    channel=interaction.channel
    message=""
    async for messages in channel.history():
      message+=f"{messages.author.name}: {messages.content}\n"
      await interaction.user.send(message)``` @shrewd fjord is this right
shrewd fjord
clear elm
#

ok

shrewd fjord
#

Also make sure to do
@app_commands.checks.has_permissions(manage or whatever perms)
So that only specified people can delete it

#

Or just check it on the code

#

So that the ticket author can close it too

#

What error u r getting tho?

shrewd fjord
#

It will spam the dm

clear elm
#

yeah i was wondering why it did that

#

i was abt to tell you

shrewd fjord
#

it will be
async for .........:
.....
await member.send(....)

#

You added member.send method inside the loop ๐Ÿ’€

#

Ugh this shouldn't be happening ๐Ÿ’€

clear elm
shrewd fjord
#

Just
indent the member.send

#

async for....:
...
await send()
it was
async for.....:
...
await send()

clear elm
#

ohh

shrewd fjord
#

And thus it spammed the dm

#

Sorry, tankman, I can't help with that error, seems like some internal problem, because the error wasn't supposed to occur

clear elm
#

it sends whatever message was sent first in the ticket channel at the bottom and whatever was sent last at the top, is there a way to invert it?

#

@shrewd fjord

clear elm
#

ohh

shrewd fjord
#

It's default to True tho pithink

clear elm
#

awesome thanks

#

is there a way to send all the messages all in one of these things:

like
this```
because currently they're all seperaate\
shrewd fjord
#

Show the current code

clear elm
#
@bot.tree.command(name="close", description="Closes the ticket!")
async def close(interaction, reason:str):
    if not interaction.channel.name.startswith('ticket-'):
        await interaction.response.send_message('This is not a ticket channel.', ephemeral=True)
        return

    channel=interaction.channel
    message=""
    async for messages in channel.history(oldest_first=True):
      message+=f"```{messages.author.name}: {messages.content}\n```"
    await interaction.user.send(message)
    await interaction.channel.delete()```
shrewd fjord
#

await interaction.user.send(f"```{message}```)

hasty rain
#

Guys, please give me a template for a discord bot

#

๐Ÿฅบ

clear elm
#

-_-

shrewd fjord
clear elm
#

yeah just did

shrewd fjord
#

Nice

clear elm
#

thanks dude

#

ur actually the best

vale wing
shrewd fjord
vale wing
shrewd fjord
#

Postgres ๐Ÿ—ฟ

clear elm
shrewd fjord
#

Ticket closed by {interaction.user}

#

Str not needed actually xd

#

Bro fr, when i was just a beginner, struggled so much to get transcripts cmd to work ๐Ÿ’€๐Ÿ’€ and ended up giving up lmfao

#

๐Ÿ—ฟ๐Ÿ—ฟ๐Ÿ—ฟ๐Ÿ—ฟ

#

@vale wing handle his problem dude ๐Ÿ—ฟ

#

It isn't impossible, cause i already made a discord chat bot with open ai

shrewd fjord
#

So there is no way to giving this up

vale wing
#

Whose problem

shrewd fjord
vale wing
#

What problem

shrewd fjord
#

Bro the
bot=....
Says unboundlocalerror like fr? ๐Ÿ’€๐Ÿ’€

vale wing
#

All errors make sense unless it is tensorflow

#

Where is bot defined

shrewd fjord
#

Hmm pithink

clear elm
#

@shrewd fjord i just realised

vale wing
#

The answer is "nowhere"

shrewd fjord
clear elm
#

it sends the transcript to the eperson who closed the ticket

vale wing
#

Eh wait

shrewd fjord
vale wing
#

Why do you redefine bot

shrewd fjord
#

I hope, you changed the channel.topic to that format i said

vale wing
#

Lines 92 & 102

shrewd fjord
#

He redefined?

vale wing
shrewd fjord
#

OH LMAO

#

How did i miss that xd

#

Remove the bot=.... Line

vale wing
#

Bot only needs to be defined once

shrewd fjord
#

From the line 102

vale wing
#

They need to remove almost whole except clauses

shrewd fjord
#

Ye

vale wing
#

Because they basically copied code from the beginning into excepts

clear elm
shrewd fjord
#

He redefined the intents too

shrewd fjord
#

Yeah

#

Remove the whole stuff from 98 to 102 something

#

Remove 87-94

#

And 97-104

#

This lines are useless and giving you error

shrewd fjord
#

Or the above code won't work

clear elm
#

yes!

#

it works

shrewd fjord
#

Noice

clear elm
#

everything works, now i just need to do which is easy. tysm @shrewd fjord

#

tbh i didint think i could make a ticket system

shrewd fjord
#

Btw you should handle the errors too
try:
await send(...)
except discord.HTTPException:
return #or whatever you want

clear elm
#

its pretty basic but it has all the essentials

shrewd fjord
shrewd fjord
#

Bro like imagine the member left from the guild

clear elm
#

ture

#

true

shrewd fjord
#

So u r trying to do
await None.send(...)

#

Will return error
NotFound

#

Also imagine his dm is close ๐Ÿ’€

clear elm
#

๐Ÿ˜ญ

shrewd fjord
#

so send it under
try-except block

shrewd fjord
clear elm
#

@shrewd fjord

#

it didnt send the error message after they lefgt

#
@bot.tree.command(name="close", description="Closes the ticket!")
async def close(interaction, reason:str):
    guild = interaction.guild
    if not interaction.channel.name.startswith('ticket-'):
        await interaction.response.send_message('This is not a ticket channel.', ephemeral=True)
        return

    channel=interaction.channel
    message=""
    async for messages in channel.history(oldest_first=True, limit=5000):
      message+=f"{messages.author.name}: {messages.content}\n"
    member=guild.get_member(int(channel.topic))
    try:
      await member.send(f'Your ticket was closed by {interaction.user.mention} for {reason} ```{message}```')
    except discord.HTTPException:
      return await interaction.response.send_message("I couldn't DM the transcript for unkown reasons!")
    await interaction.channel.delete()```
#

error:

  File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 862, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
  File "main.py", line 65, in close
    await member.send(f'Your ticket was closed by {interaction.user.mention} for {reason} ```{message}```')
AttributeError: 'NoneType' object has no attribute 'send'

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

Traceback (most recent call last):
  File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 880, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'close' raised an exception: AttributeError: 'NoneType' object has no attribute 'send'```
shrewd fjord
#

Try...

#

remove try-except

#

And do,
if member:
#send member the message
else:
#send error message with return ....

clear elm
#
if member:
      await member.send(f'Your ticket was closed by {interaction.user.mention} for {reason} ```{message}```')
    else:
      return await interaction.response.send_message("I couldn't DM the transcript for unkown reasons!")```?
clear elm
#

ok

shrewd fjord
#

I thought it will return NotFound

#

Still it's bad way to do ๐Ÿ’€

#

You can catch up all error using
except:

#

But a bare exception is bad lol

clear elm
#

Traceback (most recent call last):
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 65, in close
await member.send(f'Your ticket was closed by {interaction.user.mention} for {reason} {message}')
AttributeError: 'NoneType' object has no attribute 'send'

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

Traceback (most recent call last):
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'close' raised an exception: AttributeError: 'NoneType' object has no attribute 'send'

#

it didnt close the ticket either

shrewd fjord
#

Current code?

shrewd fjord
clear elm
# shrewd fjord Current code?
@bot.tree.command(name="close", description="Closes the ticket!")
async def close(interaction, reason:str):
    guild = interaction.guild
    if not interaction.channel.name.startswith('ticket-'):
        await interaction.response.send_message('This is not a ticket channel.', ephemeral=True)
        return

    channel=interaction.channel
    message=""
    async for messages in channel.history(oldest_first=True, limit=5000):
      message+=f"{messages.author.name}: {messages.content}\n"
    member=guild.get_member(int(channel.topic))
    if member:
      await member.send(f'Your ticket was closed by {interaction.user.mention} for {reason} ```{message}```')
    else:
      return await interaction.response.send_message("I couldn't DM the transcript for unkown reasons!")
    await interaction.channel.delete()```
shrewd fjord
#

Ughhh

#

It's a annoying fr ๐Ÿ’€๐Ÿ’€

#

Idk in which line the problem is

clear elm
#

File "main.py", line 65, in close
await member.send(f'Your ticket was closed by {interaction.user.mention} for {reason}
{message}
')

naive briar
#

Send the full traceback

shrewd fjord
#

ig do this for test:
try:
await member.send(...)
except Exception as e:
print(e)
await interaction.response.send_message(...)

#

This time will not return, and we will catch ALL the errors

shrewd fjord
#

And print it ofc

clear elm
#
@bot.tree.command(name="close", description="Closes the ticket!")
async def close(interaction, reason:str):
    guild = interaction.guild
    if not interaction.channel.name.startswith('ticket-'):
        await interaction.response.send_message('This is not a ticket channel.', ephemeral=True)
        return

    channel=interaction.channel
    message=""
    async for messages in channel.history(oldest_first=True, limit=5000):
      message+=f"{messages.author.name}: {messages.content}\n"
    member=guild.get_member(int(channel.topic))
    try:
      await member.send(f'Your ticket was closed by {interaction.user.mention} for {reason} ```{message}```')
except Exception as e:
    print(e)
    return await interaction.response.send_message("I couldn't DM the transcript for unkown reasons!")
    await interaction.channel.delete()```
shrewd fjord
#

Um?

#

Yeah

#

Wait

#

Dont add
delete line inside except

#

just remove
return word

clear elm
#

?

shrewd fjord
# clear elm ?

except Exception as e:
print(e)
await interaction.response.send_message(...)
await interaction.channel.delete()

#

!d discord.TextChannel.delete

unkempt canyonBOT
#

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

Deletes the channel.

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

Oh i thought there is a delay opt too

#

But nvm

clear elm
#

except Exception as e:
print(e)
await interaction.response.send_message("I couldn't DM the transcript for unkown reasons!")
await interaction.channel.delete()

shrewd fjord
#

Yeah

clear elm
#

it said I couldn't DM the transcript for unkown reasons! then it deleted

clear elm
#

ok

shrewd fjord
#

Check the console, the error maybe showed up

clear elm
#

it didint

shrewd fjord
#

print(e)?

#

The error will be in white color xd

#

Not red ๐Ÿ—ฟ

#

Use asyncio library too, to make some delay on deleting the channel

clear elm
clear elm
shrewd fjord
#

Tho i thought it will raise exception but nvm ig

#

Now u can remove
print(e) line and u r done

clear elm
#

awesome, tysm

shrewd fjord
#

U should create a log channel btw, where u will store the errors

clear elm
#

ill make a ticket-logs channel where it will send who closed the ticket, the reason the transcript and error (if there is one)

shrewd fjord
#

Yeah

#

If u wanna make ur bot public, i strongly recommend you to use databases xd

vale wing
#

Um actually, you should use database even if bot is not public ๐Ÿค“

clear elm
#

a database for what

shrewd fjord
timid field
#

guys can anyone help me?

shrewd fjord
#

Just drop the ques

timid field
clear elm
#

@shrewd fjord

@bot.tree.command(name="close", description="Closes the ticket!")
async def close(interaction, reason:str):
    guild = interaction.guild
    channel = bot.get_channel(1078949152735641650)
    if not interaction.channel.name.startswith('ticket-'):
        await interaction.response.send_message('This is not a ticket channel.', ephemeral=True)
        return

    channel=interaction.channel
    message=""
    async for messages in channel.history(oldest_first=True, limit=5000):
      message+=f"{messages.author.name}: {messages.content}\n"
    member=guild.get_member(int(channel.topic))
    try:
      await member.send(f'Your ticket was closed by {interaction.user.mention} for {reason} ```{message}```')
    except Exception as e:
      await interaction.response.send_message("I couldn't DM the transcript for unkown reasons!")
      await asyncio.sleep(10)
    await interaction.channel.delete()

    ticketlogEmbed=discord.Embed(title="Ticket Closed", color=0xFF5349)
    ticketlogEmbed.add_field(name="Opened by:", value=f'{member.mention}', inline=True)
    ticketlogEmbed.add_field(name="Closed by:", value=f'{interaction.user.mention}', inline=True)
    ticketlogEmbed.add_field(name="Reason:", value=f'{reason}', inline=True)
    ticketlogEmbed.set_footer(text="Made by justin;#6868")
    ticketlogEmbed.set_author(name=f'{interaction.user}', icon_url = f'{interaction.user.display_avatar}')
    await channel.send(f'```{message}```', embed=ticketlogEmbed)``` im trying to make it send to the ticket log channel but it doesnt send to the channel but everything else works
#

i got an error

#
  File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 862, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
  File "main.py", line 78, in close
    await channel.send(f'```{message}```', embed=ticketlogEmbed)
  File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/abc.py", line 1538, in send
    data = await state.http.send_message(channel.id, params=params)
  File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/http.py", line 740, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10003): Unknown Channel

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

Traceback (most recent call last):
  File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 880, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'close' raised an exception: NotFound: 404 Not Found (error code: 10003): Unknown Channel```
shrewd fjord
#

Then send it

clear elm
#

await log_channel.send(f'{message}', embed=ticketlogEmbed)

shrewd fjord
#

Yeaa

clear elm
#

works, thx

#

i forgot how to set the permissions for a channel

shrewd fjord
unkempt canyonBOT
#

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

Edits the channel.

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

Changed in version 1.3: The `overwrites` keyword-only parameter was added.

Changed in version 1.4: The `type` keyword-only parameter was added.

Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead...
shrewd fjord
#

There is a option called overwrites probably

#

Please check the docs

vital glacier
#
    @commands.command(
        name='guilds',
        usage='guilds',
        description=''
    )
    async def guilds(self, ctx):
        """View the servers that the bot is in"""
        
        await ctx.typing()
        embeds = []
        ret = []
        num = 0
        pagenum = 1
        invite = await guild.text_channels[0].create_invite(max_age=0, max_uses=0, unique=True)
        if self.bot.guilds is None:
            return
        for guild in self.bot.guilds:
            num += 1
            ret.append(f'**{num}.** {guild.name} ({guild.id}) - [Invite]({invite})')
            pages = [p for p in discord.utils.as_chunks(ret, 10)]
        for page in pages:
            pagenum += 1
            embeds.append(discord.Embed(
                color=color, 
                description="\n".join(page))
                )
            
        pag = Paginator(self.bot, embeds, ctx, invoker=ctx.author.id)

        pag.add_button('prev', emoji=':back:')
        pag.add_button('goto', emoji=':enter:')
        pag.add_button('next', emoji=':next:')
        pag.add_button('delete', emoji=':stop:')
        return await pag.start()

Any reason this wouldn't work?

#

nvm solved

hasty rain
#

!d help

unkempt canyonBOT
#

help()``````py

help(request)```
Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.

Note that if a slash(/) appears in the parameter list of a function when invoking [`help()`](https://docs.python.org/3/library/functions.html#help "help"), it means that the parameters prior to the slash are positional-only. For more info, see [the FAQ entry on positional-only parameters](https://docs.python.org/3/faq/programming.html#faq-positional-only-arguments).

This function is added to the built-in namespace by the [`site`](https://docs.python.org/3/library/site.html#module-site "site: Module responsible for site-specific configuration.") module.
hasty rain
#

๐Ÿ˜ข

#

ะžะฟัั‚ัŒ ะฐะฝะณะปะธัะบะธะน

slate swan
vale wing
spice zenith
#
@bot.tree.command(name="collect",description="Collect from your stadium  to upgrade your "
                                          "hissatsus")


@app_commands.checks.cooldown(1, 86400.0, key=lambda i: (i.guild_id, i.user.id))

async def collect(interaction: discord.Interaction):


    d2=conn.cursor()
    member_id = interaction.user.id



    try:
        stad = d2.execute(
            f"SELECT stadium FROM games WHERE member_id ={member_id}").fetchone()
        if stad == 'Condor Stadium':
            random_number = random.randint(1, 100)
        elif stad == 'Kujaku Stadium':
            random_number = random.randint(50, 150)
        elif stad == 'Yamaneko Stadium':
            random_number = random.randint(100, 200)
        elif stad == 'Umihebi Stadium':
            random_number = random.randint(150, 250)
        elif stad == 'Titanic Stadium':
            random_number = random.randint(200, 300)
        elif stad == 'Football Stadium':
            random_number = random.randint(250, 350)
        elif stad == 'Cyclone Stadium':
            random_number = random.randint(300, 400)
        elif stad == 'Amano Mikado Stadium':
            random_number = random.randint(350, 450)
        elif stad == 'Desert Stadium':
            random_number = random.randint(400, 500)
        elif stad == 'Holy Road Stadium':
            random_number = random.randint(450, 550)

        d2.execute("""
        UPDATE games
        SET money = money + ?
        WHERE member_id = ?
        """, (random_number, member_id))


        conn.commit()
        await interaction.response.send_message(f"You have added {random_number} $ to "
                                            f"your "
                                            "profile")
    except Exception:
        await interaction.response.send_message('u on cooldown')
``` i have this code but it send u on cooldown as soon as one user use it but i want every user to be able to use it once a day
#

can somenone help me?

shrewd apex
half oxide
#

Hey so... i have a code that my client just sent me and I'm not at home, can anyone test it for me and say if it works? Its a anti-spam system

#
import discord
from discord.ext import commands

bot = commands.Bot(command_prefix='!')

# Define the spam threshold and the number of messages to check
SPAM_THRESHOLD = 5
SPAM_RATELIMIT_SECONDS = 5

# Define a dictionary to keep track of user spam counts
spam_counts = {}

@bot.event
async def on_message(message):
    # Check if the message author is a bot
    if message.author.bot:
        return

    # Check if the message is in a guild/server
    if message.guild is None:
        return

    # Get the author ID of the message
    author_id = message.author.id

    # Check if the author ID is in the spam_counts dictionary
    if author_id in spam_counts:
        # Increment the user's spam count
        spam_counts[author_id] += 1

        # Check if the user has exceeded the spam threshold
        if spam_counts[author_id] >= SPAM_THRESHOLD:
            # Delete the user's messages in the last SPAM_RATELIMIT_SECONDS
            async for past_message in message.channel.history(limit=SPAM_THRESHOLD):
                if past_message.author.id == author_id and (message.created_at - past_message.created_at).seconds < SPAM_RATELIMIT_SECONDS:
                    await past_message.delete()

            # Warn the user
            await message.channel.send(f"{message.author.mention}, please refrain from spamming.")

            # Reset the user's spam count
            spam_counts[author_id] = 0
    else:
        # Add the author ID to the spam_counts dictionary with a spam count of 1
        spam_counts[author_id] = 1

    # Process the message normally
    await bot.process_commands(message)

bot.run('token')
forest oyster
#

does anyone know how to solve this error? In allowed_mentions.replied_user: must be either true or false

#

I have this part of the code

#

view=ticket_options()
AllowedMentions = discord.AllowedMentions(everyone=False, users=False, roles=False, replied_user=False)
await interaction.channel.send(embed=embed_question, allowed_mentions=AllowedMentions, mention_author=interaction.message.author.mention, view=view)

split solstice
#

please

unkempt canyonBOT
#

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

A full traceback could look like:

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

If the traceback is long, use our pastebin.

naive briar
#

!code and this

unkempt canyonBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

hushed galleon
#

i would assume mention_author=interaction.message.author.mention is the issue, given that its meant to take a boolean

naive briar
forest oyster
#

the traceback is in this line

await interaction.channel.send(embed=embed_question, allowed_mentions=AllowedMentions, mention_author=interaction.message.author.mention, view=view)
naive briar
#

Send the traceback

naive briar
#

The whole traceback

hushed galleon
#

why do you want to set both allowed_mentions.replied_user and mention_author at the same time?

forest oyster
#
  File "", line 425, in _scheduled_task
    await item.callback(interaction)
  File "", line 117, in TicketMenu
    await interaction.channel.send(embed=embed_question, allowed_mentions=AllowedMentions, mention_author=interaction.message.author.mention, view=view)
  File "", line 1538, in send
    data = await state.http.send_message(channel.id, params=params)
  File "", line 744, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In allowed_mentions.replied_user: Must be either true or false.
hushed galleon
#

they both mean the same thing, but mention_author takes precedence over replied_user, and the problem is that you've given some string to mention_author instead of the boolean that the discord API was expecting

forest oyster
#

what a dumb mistake

spice zenith
slate swan
#

!d discord.app_commands.CommandTree.on_error

unkempt canyonBOT
#

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

A callback that is called when any command raises an [`AppCommandError`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.AppCommandError "discord.app_commands.AppCommandError").

The default implementation logs the exception using the library logger if the command does not have any error handlers attached to it.

To get the command that failed, [`discord.Interaction.command`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.command "discord.Interaction.command") should be used.
spice zenith
slate swan
#

instead of py if x == "a": num = ... if x == "b": num = ... some other things you can create a dictionary ```py
data = { "a": ..., "b": ... some other things}

num = data[x]

maiden fable
#

Or you can also use match case if on 3.10 ๐Ÿ‘€

slate swan
#

I want to get the rocket league api for the in game stats like what rank is the ctx.author in 2v2. I have searched for it online but there was nothing about it. Is there an import that maybe can help me with this?

spice zenith
#

i didnt know

rose thistle
#

Hello can somone help me

#

!d client = commands.Bot(command_prefix="!")
TypeError: BotBase.init() missing 1 required keyword-only argument: 'intents'

unkempt canyonBOT
#
rose thistle
#

yup somone got help me

#

ye im confuseddd

spice zenith
#

what would that help me with my problem?

slate swan
spice zenith
#

oh xD

slate swan
#

yeah that on_error thing answers your main question

slate swan
unkempt canyonBOT
#

Using intents in discord.py

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

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

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

from discord import Intents
from discord.ext import commands

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

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

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

spice zenith
#

hmmm but my problem is not with the error handlerer

rose thistle
drifting arrow
#

I am trying to add an "update" button to my embed responses, but for some reason I get: Unknown interaction

    @discord.ui.button(label="Next", style=discord.ButtonStyle.green)
    async def next(self, interaction: discord.Interaction, button: discord.ui.Button):
        if self.pagenumber == (self.listlength - 1):
            self.pagenumber = 0
        else:
            self.pagenumber = self.pagenumber + 1

        embed = self.setembed(self.pagenumber)
        await interaction.response.edit_message(embed=embed, view=self)

    @discord.ui.button(label="Update", style=discord.ButtonStyle.green)
    async def update_button(self, interaction: discord.Interaction, button: discord.ui.Button):
        await self.update(self.pagenumber)
        embed = self.setembed(self.pagenumber)
        await interaction.response.edit_message(embed=embed, view=self)
``` Snipped of my code.
Why am I getting an error? It's confusing to me ;-;
naive briar
#

You can use InteractionResponse only once

drifting arrow
#

But the previous/next buttons work as intended tho

naive briar
#

Eh, I probably misread something

#

What's self.update

#

And can you send the full traceback

drifting arrow
#

A function I run to update the data I have that then gets passed to the embed and suppose to update

drifting arrow
cinder tulip
#

i would just like to know to make you select a discord user like this, im learning app_commands and im trying to make an avatar command

drifting arrow
# naive briar And can you send the full traceback
Traceback (most recent call last):
  File "C:\Users\Declan\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 425, in _scheduled_task
    await item.callback(interaction)
  File "C:\Users\Declan\Desktop\discordbots2\adminmaster\cogs\alts.py", line 324, in update_button
    await interaction.response.edit_message(embed=embed, view=self)
  File "C:\Users\Declan\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 874, in edit_message
    await adapter.create_interaction_response(
  File "C:\Users\Declan\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 218, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
naive briar
#

You might have taken too long to respond

#

You can try deferring then edit it later

drifting arrow
naive briar
drifting arrow
cinder tulip
#

Oh

#

thanks alot

naive briar
#

Did you try

drifting arrow
# naive briar Did you try

I am able to actively and freely use the previous/next buttons but once I try and do Update it errors. so i know it's not a timeout issue

cinder tulip
#

man I tried to use discord_slash before, i tried updating, uninstalling it and reinstalling it again

#

but it doesnt work sadge

glad cradle
drifting arrow
cinder tulip
#

yeah

rose thistle
#

somone help meeee

slate swan
#

Can anyone explain me these thinks like

"Import ..."
Because i dont know what it does

rose thistle
slate swan
#

Iam new so...

glad cradle
rose thistle
drifting arrow
#

and add a comma

cinder tulip
drifting arrow
#

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

cinder tulip
rose thistle
#

like this?

cinder tulip
drifting arrow
rose thistle
cinder tulip
drifting arrow
cinder tulip
#

also do intents=discord.Intents.all()

rose thistle
slate swan
drifting arrow
#

Probably. I use the cogs method

cinder tulip
slate swan
cinder tulip
slate swan
#

yup

drifting arrow
#

no no.

rose thistle
drifting arrow
#

You dont understand.

slate swan
#

1 sec pls

cinder tulip
#

bro everyone is now looking down on me because i dont find myself comfy on cogs

slate swan
drifting arrow
#

main.py is just loader. it loads shit.
you have a cogs folder, in there, you put your classes for various commands/categories for commands.

naive briar
rose thistle
#

we love umava

drifting arrow
rose thistle
#

we love u mava

cinder tulip
# rose thistle

dude, you need to do "client = commands.Bot(command_prefix=".", intents = discord.Intents.all())"

rose thistle
#
client = commands.Bot(command_prefix=".", intents = discord.Intents.all())```
cinder tulip
cinder tulip
#

Oh alright

rose thistle
#

TYSM IT WORK MAVA

slate swan
#

before its too late

cinder tulip
#

No problem

slate swan
#

๐Ÿ˜ญ

drifting arrow
#

I got 2 files. one to connect to my apis and 1 to handle the database. both over a thousand lol

cinder tulip
drifting arrow
#

and thats not even the commands xD

slate swan
ionic edge
#
                button = discord.ui.Button(label="Create Ticket", style=discord.ButtonStyle.green)
                view = discord.ui.View()
                view.add_item(button)
                view.timeout = None
                await message.author.send("You don't have a ticket yet. Click the button below to create one.", view=view)```
#

how to check if user clicked the button

naive briar
#

Set the callback

rose thistle
cinder tulip
rose thistle
#

there is another errorr ig

naive briar
#

And consider subclassing the view instead

slate swan
rose thistle
slate swan
#

show us more of ur code please

rose thistle
rose thistle
slate swan
drifting arrow
# rose thistle

main.py

import discord, os, json
from discord.ext import commands

class MyBot(commands.Bot):
    def __init__(self):
        with open("./json/config.json", "r") as f:
            config = json.load(f)
        super().__init__(
            command_prefix=f"{config['prefix']}",
            intents=discord.Intents.all(),
            application_id = config['application_id']
        )
        
    async def setup_hook(self):
        for filename in os.listdir("./cogs"):
            if filename.endswith(".py"):
                await self.load_extension(f"cogs.{filename[:-3]}")
        await bot.tree.sync()
        
    async def on_ready(self):
        print('Logged in!')
        
bot = MyBot()
with open("./json/config.json", "r") as f:
    config = json.load(f)
bot.run(config['discord_token'])

config.json

{
    "discord_token": "",
    "application_id": 123,
    "prefix": "!"
}
rose thistle
drifting arrow
#

lol

rose thistle
#

i remove the help

slate swan
cinder tulip
#

man I feel so dumb lol

rose thistle
#

trust me im the dumbest guy here

drifting arrow
slate swan
rose thistle
#

SEE I CANT EVEN SPELL RIGHT

rose thistle
slate swan
drifting arrow
glad cradle
drifting arrow
rose thistle
#
my code
drifting arrow
#

I could update it but it's not relevant lol

unkempt canyonBOT
#

Hey @rose thistle!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

rose thistle
#

bruh

drifting arrow
#

use their pastebin!

glad cradle
slate swan
drifting arrow
#

This is why you use a separate file to hold your important shit

cinder tulip
drifting arrow
#

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

drifting arrow
#

I still need to fix my issue

cinder tulip
glad cradle
cinder tulip
slate swan
cinder tulip
#

Before having my issue I was like: "before sending let me search if I can see something bout this" but then I didn't understand lol

drifting arrow
cinder tulip
#

Tho I'm making huge improvements lately with discord.py

cinder tulip
glad cradle
glad cradle
#

you may want to defer at the start of your callback

drifting arrow
#

someone said that before. i disregarded it as fancy talk

naive briar
#

Told them. Didn't trust me ducky_sus

#

!d discord.InteractionResponse.defer

unkempt canyonBOT
#

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

Defers the interaction response.

This is typically used when the interaction is acknowledged and a secondary action will be done later.

This is only supported with the following interaction types...
naive briar
#

!d discord.Interaction.followup then respond with this

unkempt canyonBOT
cinder tulip
#

Can't you make that 3s longer?

glad cradle
drifting arrow
cinder tulip
#

I think 15 minutes is the max?

cinder tulip
glad cradle
#

you can't choose how many minutes/seconds the interaction will lasts

drifting arrow
#

So I change await interaction.response.edit_message(embed=embed, view=self) to await defer()?

cinder tulip
#

Didn't know

glad cradle
cinder tulip
#

Oh interesting

#

Man you're typing alot

#

I bet it's stuff that I won't understand

glad cradle
naive briar
cinder tulip
#

So wait, what he's trying to do is update an embed with a button to edit it?

glad cradle
#

ig yes?

drifting arrow
#

This is my solution:

@discord.ui.button(label="Update", style=discord.ButtonStyle.green)
async def update_button(self, interaction: discord.Interaction, button: discord.ui.Button):
    await interaction.response.defer()
    await self.update(self.pagenumber)
    embed = self.setembed(self.pagenumber)
    message = interaction.message
    await message.edit(embed=embed, view=self)
glad cradle
#

yeah

#

if I'm not mistaken in a library that implements interactions subclasses you could've done something else

#

(e.g disnake)

rose thistle
#

does anyone know anything about discord whitelist bot with github and replit?

slate swan
#

Does anyone know how to add buttons to your bot message?

vale wing
vale wing
slate swan
#

?

vale wing
slate swan
vale wing
quick gust
#

beat me to it

slate swan
#

Thanks!

rose thistle
vale wing
#

Replit + discord bot = hell

slate swan
#

im using replit

#
  • i have an active bot on my freinds server
#

will that cause issues?

glad cradle
#

the problem is that it'll hit 429 regularly

slate swan
#

oh ok no worries

#

the server insnt very active

white citrus
#
cmd = self.bot.get_application_command_from_signature(name=module, cmd_type=nextcord.SlashApplicationSubcommand, guild_id=interaction.guild.id)
``` this is always none
#

No Error

slate swan
#

anyone can help me out

#

for some reason it gives my big text a white color and the other text a orange colour

thin raft
#

?

#

you didn't format anything of that logo

slate swan
#

so how do i do that

thin raft
#

send the code

#

have you written the code?

slate swan
thin raft
#

don't dm it to me

#

send it here pls

slate swan
#

i want like the big text

smoky sinew
rose thistle
vocal snow
uneven hearth
#

can someone help me?
i have a system that creates a command access according to a user's role in the server.
the issue that the bot doesn't accept commands that contains arguments, it's related to the require_access function for sure, but I don't know how can I add the option of adding arguments (str/int/bool/float)

# Define a decorator function that checks if the user has the required access id before executing the command โœ…
def requires_access(required_access):
    def decorator(func):
            async def wrapper(interaction: discord.Interaction):
                user_roles = [{"role_id": role.id, "access_id": next((item["access_id"] for item in role_access_map if item["role_id"] == role.id), 0)} for role in interaction.user.roles]

                if has_access(user_roles, required_access):
                 await func(interaction, user_roles=user_roles)
                else:
                 await interaction.response.send_message("You are not eligible to use this command.")
               
            return wrapper
    return decorator


#code with an argument for example
# Command for getting product information ๐Ÿ“ฆ
@bot.tree.command(name="product")
@requires_access(ADMIN_ACCESS_ID)
async def product(interaction: discord, category : str, users_roles=None):
minor totem
left dew
#

hi, im using pycord and ive installed pycord and when im import discord, it says discord is undefined, ive imported discord tho

minor totem
#

If you don't necessarily know how decorators, I'll happily go into that more deeply

minor totem
left dew
minor totem
#

Okay, and how do you run your code? Can you try running python3 -c "import discord"?

left dew
#

got a type error

uneven hearth
minor totem
#

Oh- that would a discord.py or Pycord issue. Since that is different from an import error, I'm assuming the specific issue you're running into is that you're installing pycord to a version other than the one you're runnig

left dew
#

how do i fix that?

uneven hearth
minor totem
left dew
#

i press the run button

#

and i get an error

minor totem
# uneven hearth But that also because I'm quite new in coding discord bot.

Right, so there's more than one issue you have here and I think if I explain decorators from the start you'll realize why. To start of, decorators are just for wrapping functions as you've shown, but they're based on being able to create functions inside of a function. We can for example create a simple printer function like this:

def printer(message: str) -> Callable[[], None]:
    def inner() -> None:
        # We can access variables in the function this was defined in
        print(message)
    return inner  # Return the function created

hello = printer('Hello world')

hello()  # Hello world
hello()  # Hello world

Whenever we call hello(), we'll call the function that was created inside of printer(). Note that these variables are not shared, so we can have multiple printers at the same time:

hello = printer('Hello world')
goodbye = printer('Goodbye')

hello()  # Hello world
goodbye()  # Goodbye

If the variables were shared between calls, these would've both printed out Goodbye. Accidentally sent this, so I'll continue in another message

uneven hearth
#

yeah, i can see what you mean

minor totem
#

Decorators take advantage of this to wrap functions, so we create a new function which calls the previous function inside of it. This function prints the elapsed time: ```python
import time

def timefunc(func: Callable[[], None]) -> Callable[[], None]:
def inner() -> None:
start = time.perf_counter()
func()
print(time.perf_counter() - start)
return inner

def sleeping():
time.sleep(2)

timed_sleep = timefunc(sleeping)
timed_sleep() # 2

We can run code before and after the function we wrap. However, we'll run into issues like you have if we try to give it arguments and you'll see why if you print and compare the functions: ```python
print(timefunc, sleeping, timed_sleep)
<function timefunc at 0x...> <function sleeping at 0x...> <function timefunc.<locals>.inner at 0x...>

We have created a new function for timed_sleep which is not the same as sleeping. This is hidden when we use the decorator syntax: ```python
@timefunc
def sleeping():
time.sleep(2)

Same as the following

def sleeping():
time.sleep(2)
sleeping = timefunc(sleeping)

Now, onto fixing the problem...
tribal shell
#

I keep getting this error when running my bot: py 'module' object is not callable File "C:\Users\Clicx\OneDrive\Documents\HeXit\latexbot.py", line 64, in LatexBot @asyncio.coroutines ^^^^^^^^^^^^^^^^^^ File "C:\Users\Clicx\OneDrive\Documents\HeXit\latexbot.py", line 29, in <module> class LatexBot(discord.Client): TypeError: 'module' object is not callable

#

This is the target of the error: py @asyncio.coroutines def on_ready(self): print('------') print('Logged in as') print(self.user.name) print(self.user.id) print('------')

#

This is line 29: ```py
class LatexBot(discord.Client):

thin raft
#

on_ready should be async

#

and with @bot.event decorator

tribal shell
thin raft
#

or @commands.Cog.listener() if inside cog

minor totem
#

For us to be able to give a function arguments when it is wrapped by a decorator, we need to match the syntax of that function perfectly. Think about which def is the one being returned, in this case it is inner() I don't want to confuse you with the typehints, so I've stopped using them here:

def timefunc(func):
    def inner(*args, **kwargs) -> None:
        start = time.perf_counter()
        func(*args, **kwargs)
        print(time.perf_counter() - start)
    return inner

def sleeping(duration):
    time.sleep(duration)

timed_sleep = timefunc(sleeping)
timed_sleep(3)  # 3

Your code uses three functions though, and that's because if you notice I didn't have parenthesis in my decorator example before. You have a function, which creates a decorator, which creates a function to replace the function: ```python
def timewarn(duration):
def decorator(func):
def wrapper(*args, **kwargs):
start = time.perf_counter()
func(*args, **kwargs)
if time.perf_counter() - start > duration:
print('Warning! Function took too long')
return wrapper
return decorator

@timewarn(2)
def too_long():
time.sleep(3)

Equivalent to the following

decorator = timewarn(2)
def too_long():
time.sleep(3)
too_long = decorator(too_long)


As you'll see in this code, **you should add** `*args, **kwargs` **to** `wrapper()`. -but you'll run into another problem. Since we're replacing the function, when discord.py is reading the typehints it'll be reading *the returned function* (the same way, when we print it we get a different name):
```python
print(too_long)  # <function timewarn.<locals>.decorator.<locals>.wrapper at 0x...>

To fix this, we need to copy over this information - which functools will help you with: https://docs.python.org/3/library/functools.html#functools.wraps

Our timewarn function, should therefore look like this:

import functools

def timewarn(duration):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            start = time.perf_counter()
            func(*args, **kwargs)
            if time.perf_counter() - start > duration:
                print('Warning! Function took too long')
        return wrapper
    return decorator
minor totem
#

@uneven hearth, in the end... you want to add *args, **kwargs to your wrapper() and decorator wrapper() with @functools.wraps(func)

minor totem
left dew
minor totem
# left dew in vsc

In the bottom right, it'll say which Python version it is using. You can also open the Command Pallete with Ctrl + Shift + P and find "Select Interpreter". Make sure this is the same version as the one you get when you run python3 -V

left dew
#

hey that worked

#

wooooo

minor totem
# tribal shell Can I get help here?

@asyncio.coroutines is a file inside of the asyncio module: https://github.com/python/cpython/blob/main/Lib/asyncio/coroutines.py

The error here is correct, because you're trying to call a file which is considered a module. To fix the error, either remove the s at the end to make it @asyncio.coroutine which I assume it is you're looking for.

That is very old though, and you should be using async def instead. Change def on_ready(self): to async def on_ready(self): and remove the @asyncio.coroutines line

GitHub

The Python programming language. Contribute to python/cpython development by creating an account on GitHub.

tribal shell
#

Or just remove the S?

minor totem
#

Depends on which solution you're looking for, I recommend removing the entire line as I stated in the second solution (third paragraph)

tribal shell
# minor totem Depends on which solution you're looking for, I recommend removing the entire li...

I just decided to remove entire line, now I get: py Client.__init__() missing 1 required keyword-only argument: 'intents' File "C:\Users\Clicx\OneDrive\Documents\HeXit\latexbot.py", line 31, in __init__ super().__init__() File "C:\Users\Clicx\OneDrive\Documents\HeXit\latexbot.py", line 147, in <module> LatexBot() TypeError: Client.__init__() missing 1 required keyword-only argument: 'intents'

slate swan
#

@client.command()
async def test(ctx):
with open("kurac.json") as f:
guild = json.load(f)
if int(ctx.guild.id) in guild:
await ctx.send("kurac")

Traceback (most recent call last):
  File "/home/miricmatija2/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 179, in wrapped
    ret = await coro(*args, **kwargs)
  File "/home/miricmatija2/institut/as.py", line 15, in clear
    if int(ctx.guild.id) in guild:
TypeError: argument of type 'int' is not iterable

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

Traceback (most recent call last):
  File "/home/miricmatija2/.local/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 335, in invoke
    await ctx.command.invoke(ctx)
  File "/home/miricmatija2/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 916, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/home/miricmatija2/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 188, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: argument of type 'int' is not iterable```
#

any who can help?

left dew
# minor totem In the bottom right, it'll say which Python version it is using. You can also op...

do you know what this means?

  File "/Users/emlynphoenix/clothing.py", line 1, in <module>
    import discord
  File "/opt/homebrew/lib/python3.11/site-packages/discord/__init__.py", line 22, in <module>
    from ._version import *
  File "/opt/homebrew/lib/python3.11/site-packages/discord/_version.py", line 30, in <module>
    from importlib.metadata import PackageNotFoundError, version
  File "/opt/homebrew/Cellar/python@3.11/3.11.2_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/importlib/metadata/__init__.py", line 17, in <module>
    from . import _adapters, _meta
  File "/opt/homebrew/Cellar/python@3.11/3.11.2_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/importlib/metadata/_adapters.py", line 3, in <module>
    import email.message
  File "/opt/homebrew/Cellar/python@3.11/3.11.2_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/email/message.py", line 15, in <module>
    from email import utils
  File "/opt/homebrew/Cellar/python@3.11/3.11.2_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/email/utils.py", line 28, in <module>
    import random
  File "/Users/emlynphoenix/random.py", line 6, in <module>
    print(''.join(letters))
          ^^^^^^^^^^^^^^^^
TypeError: sequence item 0: expected str instance, int found```
uneven hearth
slate swan
minor totem
# left dew do you know what this means? ```Traceback (most recent call last): File "/User...

Ah- this would be your code's issue then. Let me simplify the traceback and we can look at it together: ```python
Traceback (most recent call last):
"/opt/homebrew/Cellar/python@3.11/3.11.2_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/email/utils.py", line 28, in <module>
import random
File "/Users/emlynphoenix/random.py", line 6, in <module>
print(''.join(letters))
^^^^^^^^^^^^^^^^
TypeError: sequence item 0: expected str instance, int found

When you import Pycord, it ends up importing `random` and the issue is that instead of importing *the real random* it is importing *your file named* `random`. In this file, your code has an issue.

```python
sequence item 0: expected str instance, int found

Tells you that in the sequence (which is letters) at the item 0 (which is the first one) it wanted a string but you gave it an integer.

Something is wrong with your code, where letters is a list of integers when it should be strings

uneven hearth
#

now i understand that

#

thank you!

left dew
# minor totem Ah- this would be your code's issue then. Let me simplify the traceback and we c...

this is my code```py
import discord

TOKEN = ""

intents = discord.Intents.all()
intents.members = True
bot = discord.Bot(command_prefix = '$', intents=intents)
bot.remove_command('help')

@bot.event
async def on_ready():
print("Bot is online!")

@bot.command()
async def group(ctx):
embed = discord.Embed(description=f"Roblox Group: https://www.roblox.com/groups/7952306/Skylinee#!/about", colour=0xa3fdee)
await ctx.reply(embed=embed)

bot.runt(TOKEN)```

minor totem
# uneven hearth i saw it now

All of the messages I sent between I started answering you to the end is a response, so I recommend starting from the first one and reading down to me pinging you with the summary ๐Ÿ™‚

minor totem
tribal shell
minor totem
#

I was about to respond ๐Ÿ˜…

tribal shell
#

I added this super().__init__(discord.Intents)

#
class LatexBot(discord.Client):
    def __init__(self):
        super().__init__(discord.Intents)```
smoky sinew
minor totem
smoky sinew
#
def __init__(self):
    super().__init__(intents = discord.Intents.default())
#

it's also a keyword argument

#

so you have to specify intents = ...

minor totem
tribal shell
#

So: py class LatexBot(discord.Client): def __init__(self): super().__init__(discord.Intents.default())???

minor totem
uneven hearth
smoky sinew
tribal shell
#
        super().__init__(intents = discord.Intents.default())```
smoky sinew
#

yes

smoky sinew
tribal shell
#

Okay so, when running I get: py Traceback (most recent call last): File "C:\Users\Clicx\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 409, in _run_event await coro(*args, **kwargs) File "c:\Users\Clicx\OneDrive\Documents\HeXit\latexbot.py", line 72, in on_message if chanrestrict.check(message): ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "c:\Users\Clicx\OneDrive\Documents\HeXit\chanrestrict.py", line 19, in check if message.channel.is_private: ^^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'TextChannel' object has no attribute 'is_private'

#

Is that in intent I need?

smoky sinew
glad cradle
smoky sinew
#

@tribal shell the code you are using is very outdated

minor totem
# slate swan dont work

Okay, then that means that guild is an integer. See, when you do in guild Python will try to loop through guild which isn't possible when guild is an integer. Are you sure that the JSON file you're loading is correct?

tribal shell
minor totem
# tribal shell Is that in intent I need?

The error would be a bit different if that was the case. This error is a bit weird, but that is because the code you're using is very old and assumes it is running on another version of discord.py

I would recommend trying out a different project, unfortunate that this one didn't work out!

tribal shell
slate swan
minor totem