#discord-bots

1 messages ยท Page 125 of 1

loud junco
#

but there is only 4 kinds of exception

slate swan
#

why did u add sleep?

loud junco
#

i handled 2 of them that happens quite frequently

slate swan
#

and what do u mean ur not getting the roles?

slate swan
#

so i had to

#

no.

naive briar
#

Why

#

Just why

slate swan
#

the callback for the view not the command lol

#

idk man

#

my brain

loud junco
slate swan
slate swan
#

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

where do i add "defer"

#

top of the callback

#

thne all of ur response.send_message turn into edit_original_message

slate swan
#

mhm

slate swan
#

at the top

#

the beginning of the callback

#

before async?

#

no

#

defer_help_callback

#

?

abstract kindle
#

How come I'm not getting any traceback errors when an interaction fails?

#

I'm having to manually go through the command to find where my code is having issues, and it's a pain

vocal snow
#

That could easily be used maliciously

grand willow
#

!d discord.Guild.channels

unkempt canyonBOT
slate swan
abstract kindle
#

Small errors like a variable being miss spelled or an object not having an attribute are not caught

#

But when I run another command without an interaction (like a normal command with a prefix), I get tracebacks just fine when the command doesn't work

#

With interactions, the command just gets to a point and then stops running when it encounters an error, and I have to figure out what the error is

slate swan
abstract kindle
#

No, just a regular slash command interaction

slate swan
#

and whats the error you see on discord?

abstract kindle
#

Interaction failed to respond

slate swan
#

either you just aren't responding to the interaction or u have a error handler for slash commands

#

maybe you just made a faulty app command error handler?

abstract kindle
#

Would those be caught under commands.Error or something like app_command Error?

slate swan
#

i mean if u have any error handler then that's probably ur issue

slate swan
#

do you have any?

abstract kindle
#

nope

#
@commands.Cog.listener()
    async def on_command_error(self, ctx: commands.Context, error: commands.CommandError):
        if isinstance(error, commands.CommandNotFound):
            return
...

only this

slate swan
#

that'll do it

#

i think.

#

is this dpy?

abstract kindle
#

Yeah

slate swan
#
class support(Button):
  def __init__(self, label):
    super().__init__(label=label, style=discord.ButtonStyle.red)
  async def callback(self, interaction):
      c = await interaction.guild.create_text_channel(f"ticket-{interaction.user}")
      await c.send(f"{interaction.user.mention} Please wait for staff.")
      await interaction.response.send_message("Opened Ticket")
      self.cooldown = commands.CooldownMapping.from_cooldown(1.0, 60.0, commands.BucketType.user)

why wont this cooldown work?

#

i actually dont know if that applies to app cmds

hushed galleon
#

though perhaps hybrid commands would still invoke it

slate swan
#
class ButtonOnCooldown(commands.CommandError):
  def __init__(self, retry_after: float):
    self.retry_after = retry_after

# you can also use a lambda if it's simple enough
# this function works similarly to the `key` in functions `sorted` and `list.sort`
def key(interaction: discord.Interaction):
  return interaction.user

class View(discord.ui.View):
  def __init__(self, *, timeout: float = 180.0):
    super().__init__(timeout=timeout)
    self.value = 0
    # create a CooldownMapping with a rate of 1 token per 3 seconds using our key function
    self.cd = commands.CooldownMapping.from_cooldown(1.0, 3.0, key)

  async def interaction_check(self, interaction: discord.Interaction):
    retry_after = self.cd.update_rate_limit(interaction)
    if retry_after:
      # rate limited
      # we could raise `commands.CommandOnCooldown` instead, but we only need the `retry_after` value
      raise ButtonOnCooldown(retry_after)

    # not rate limited
    return True

  async def on_error(self, interaction: discord.Interaction, error: Exception, item: discord.ui.Item):
    if isinstance(error, ButtonOnCooldown):
      seconds = int(error.retry_after)
      unit = 'second' if seconds == 1 else 'seconds'
      await interaction.response.send_message(f"You're on cooldown for {seconds} {unit}!", ephemeral=True)
    else:
      # call the original on_error, which prints the traceback to stderr
      await super().on_error(interaction, error, item)

  @discord.ui.button(label='Count', style=discord.ButtonStyle.green)
  async def count(self, interaction: discord.Interaction, button: discord.ui.Button):
    self.value += 1
    await interaction.response.send_message(self.value, ephemeral=True)

# send the view
await ctx.send('Start counting!', view=View())```
slate swan
# abstract kindle Yeah

only other thing i could suggest is are you responding to the interactions themselves? properly

abstract kindle
#

as in interaction.response.send_message(...) or something?

slate swan
#

yeee

abstract kindle
#

Yes, at the end of the command that is called

slate swan
#

instead of having a huge code

abstract kindle
#

The reason it isn't getting to that line however is because there's an error in the code before it that's going uncaught

slate swan
#

like to have it more organized

#

cause what you sent is confusing

#

not really. first u need to initialize the cooldownmapping then use interaction_check to see if the user is on cooldown.

#

so I have to use every bit of that?

#

then you need a way to let the user no they are on cooldown

turbid heart
#

lmao]

slate swan
#

no but if you dont understand the basic parts of what u need then you should prob take a step back before trying to use custom cooldowns

#

i mean i sent u the entire code from dpy discord of how to do it

abstract kindle
#

Yeah

#
@registered()
    @app_commands.guilds(856915776345866240, 977351545966432306)
    @app_commands.command(name="beg", description="Beg for some money! Must have less than 10000 bits.")
    async def beg(self, interaction: discord.Interaction):
        user = RequestUser(interaction.user.id, interaction=interaction)  # Initialize user object upon request
        titles = ["Begging is for poor people...", "You're already rich!", "Really?"]  # Possible embed titles
        max_balance = 10000
        user_total_balance = user.instance.money + user.instance.bank
        if user_total_balance >= max_balance:  # If user has 10000 bits or more in their purse or bank

            embed = discord.Embed(
                title=random.choice(titles),
                description=f"You cannot beg if you have more than 10,000 bits\n"
                            f"You have **{'{:,}'.format(user_total_balance)}** bits",
                color=discord.Color.red()
            )

            embed.set_footer(text=f"User: {interaction.user.name}")
            await interaction.response.send_message(embed=embed)
        else:
            beg_amount = randint(100, 500)  # Randomly generate how many bits they will get
            await user.update_balance(beg_amount)

            embed = discord.Embed(
                title=f"Someone kind dropped {beg_amount} bits in your cup.",
                description=f"You now have {'{:,}'.format(user_total_balance + beg_amount)} bits.",
                color=discord.Color.green()
            )

            embed.set_footer(text=f"User: {interaction.user.name}")
            await interaction.response.send_message(embed=embed)

Here is a command

slate swan
#

overriding on_error event could also be the problem, if you did

abstract kindle
slate swan
#

what does @registered do ?

abstract kindle
#

I took it out and still the same problem. It's just a check to see if the user is in my database

slate swan
#

are those db functions?

#

whats RequestUser? has some database operatione?

abstract kindle
#

yes

slate swan
#

i got it to work ๐Ÿ‘

#

it might be taking more than 3 seconds causing the interaction to timeout

slate swan
abstract kindle
#

And it won't send an error for that?

slate swan
#

how can I get the id?

slate swan
#

it should say interaction took to long to respond but if the db is erroring or getting hung up idk what the cause would be there

abstract kindle
#

It would make sense if that was the error, because my university wifi has been a pain for interaction with the database

alpine cove
abstract kindle
alpine cove
#

or how can I do [#code-of-conduct](/guild/267624335836053506/channel/783829285227462697/) like that

#

just put a backslash in front of the channel

slate swan
#

c = await interaction.guild.create_text_channel(f"ticket-{interaction.user}")
await c.send(f"{interaction.user.mention} Please wait for staff.")
await interaction.response.send_message(f"Opened Ticket <#{c}>")

#

what about this

slate swan
alpine cove
#

\[#code-of-conduct](/guild/267624335836053506/channel/783829285227462697/)

abstract kindle
#

For example, let's say I tried to call user.balance when .balance is not an attribute of user. It wouldn't catch it as an error, but the code would stop there until I changed it

slate swan
#

do you have custom logging setup?

abstract kindle
#

I don't think so...

slate swan
#

when u create the channel it gets returned. and u assigned it to c. channels have a mention attr.

mighty pilot
abstract kindle
wanton pebble
#

if i wanted a remind command or something similar, is there a way to keep track of the remind times and the current time even if the bot goes offline and back online?

slate swan
abstract kindle
mighty pilot
wanton pebble
#

how would i make it compare the times?

abstract kindle
slate swan
wanton pebble
abstract kindle
#

Okay, on_command_error is not catching it, so that's not the problem

slate swan
#

i would say between ur internet issues and ur db it's hanging up ur bot entirely. what db are you using?

abstract kindle
#

postgresql on railway

slate swan
#

with an async driver?

#

yeeee what pgsql lib u usin

#

i don't think so cause you're not using awaits related to db anywhere

#

unless you use create_task or something

#

oh true

abstract kindle
#

Ah that might be it

#

I'm using peewee as my orm

slate swan
#

  @discord.ui.button(label='Open', style=discord.ButtonStyle.green)
  async def count(self, interaction: discord.Interaction, button: discord.ui.Button):
      with open("ticket.txt", "r") as f:
        client.ticket += 1
        f.read()
      with open("ticket.txt", "w") as f:
        f.write(f"{client.ticket}")
      c = await interaction.guild.create_text_channel(f"ticket-{interaction.user}")
      await c.send(f"{interaction.user.mention} Please wait for staff. ({client.ticket})")
      await interaction.response.send_message(f"Opened Ticket {c.mention}")

but it just keeps resetting client.ticket at the top i have client.ticket = 0

slate swan
abstract kindle
#
database = PostgresqlDatabase(database=data['postgreSQLparams']['PGDATABASE'],
                              **{'host': data['postgreSQLparams']['PGHOST'], 'port': data['postgreSQLparams']['PGPORT'],
                                 'user': data['postgreSQLparams']['PGUSER'],
                                 'password': data['postgreSQLparams']['PGPASSWORD']})
slate swan
abstract kindle
#

they are

#

It's probably a timeout issue

#

but that wouldn't explain why nothing else gets caught

slate swan
#

well if ur using non-async then ur code is just getting blocked

#

I'll suggest using an async implementation like asyncpg or Sqlalchemy if you want an orm

mighty pilot
#

When does not having an async driver for database really start causing issues? I'm just using mariadb library right now and have no issues but further down the road I expect to have the bot grow in size and server #

slate swan
#

like other events and commands

abstract kindle
#
@app_commands.guilds(856915776345866240, 977351545966432306)
    @app_commands.command(name="beg", description="Beg for some money! Must have less than 10000 bits.")
    async def beg(self, interaction: discord.Interaction):
        number = random.ball
        print(number)

This is the command now. It fails and doesn't give an error

#

I put in an obvious error and nothing is caught

slate swan
slate swan
#

in an started event or something?

abstract kindle
slate swan
#

wdym? like mulitple monitors?

mighty pilot
abstract kindle
slate swan
#

i use a discord message as my database

abstract kindle
slate swan
slate swan
mighty pilot
abstract kindle
# slate swan oh no. just one pc

darn. using sqlite3 would be so simple, but I develop from my laptop and host the code on my PC in my dorm, so I can't use sqlite3

slate swan
#

yeee but when multiple run it at once.

slate swan
#

for hosting and stuff. it would prob solve alot of ur issues. also always free

hushed galleon
# mighty pilot When does not having an async driver for database really start causing issues? I...

every query you make with a non-async driver will block the event loop, but the impact depends on how long those queries take overall
if its for short periods, users might notice a bit of lag
if it blocks for a few seconds, you might encounter issues like interactions failing to respond
and if it blocks even longer you might prevent dpy from sending heartbeat commands, forcing the gateway connection to restart (and resulting in missed events)

slate swan
#

i would look into it

abstract kindle
#

Oracle also just has a free tier that you can use, but the M1 chip on my mac is causing lots of issues with oracle

slate swan
#

why can't you just have a seperate db for development and another one for prod

abstract kindle
abstract kindle
slate swan
slate swan
abstract kindle
mighty pilot
slate swan
#

sqlite databases are cheap lol

abstract kindle
# slate swan well this fails because u don't respond to the interaction itself
@app_commands.guilds(856915776345866240, 977351545966432306)
    @app_commands.command(name="beg", description="Beg for some money! Must have less than 10000 bits.")
    async def beg(self, interaction: discord.Interaction):
        number = random.ball
        await interaction.response.send_message(number)

Still no error and application fails to respond

abstract kindle
mighty pilot
abstract kindle
# slate swan yeah exactly

I think I tried that but I was trying to transfer over the sqlite3 file and it really wasn't liking it

hushed galleon
slate swan
#

any way to hide this to only the clicker?

naive briar
#

!d discord.InteractionResponse.send_message - set ephemeral to true

unkempt canyonBOT
#

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

Responds to this interaction by sending a message.
slate swan
#

i got it

#

how can I overwrite the channel to only the clicker can view it and send messages

#

using overwrites

#

Do people still create discord bots?

#

yea?

#

I thought trend of creating bots died.

#

no?

#

ok ok

hushed galleon
loud junco
#

how do u get someone's name from id

slate swan
#

ok

#

ill try thank you

slate swan
#

i dont think it was ever a trend

hushed galleon
slate swan
#

it's always been a thing imo

#

yeah you don't even get that shiny verified developer badge now

#

*shitty

loud junco
hushed galleon
#

ah ok

loud junco
slate swan
loud junco
#

after 6 months break :D

slate swan
hushed galleon
loud junco
#

wonder where is those dudes that i met last time tho

slate swan
#

omg thanks so much!

#

they shoulda made them harder to obtain rather than just spitting some shit out and praying it reached 75 guilds lol

loud junco
#

like adding the <@> thing

#

i forgot how already

hushed galleon
#

yeah that could work as well, depending where you use it

loud junco
#

mention them also can

hushed galleon
#

<@id> is the format

loud junco
slate swan
#

although if ur tryna get the user/member object. member.mention or user.mention works

#
      role = interaction.guild.get_role(1039176031422132224)
      overwrites = {
        interaction.guild.default_role: discord.PermissionOverwrite(read_messages=False),
        interaction.guild.me: discord.PermissionOverwrite(read_messages=True),
        interaction.guild.role: discord.PermissionOverwrite(read_messages=True)
      }
loud junco
#
long += f'{n+1}) <@{userid}>\n'
```is this how u do it
slate swan
#

no. u already have the role obj

loud junco
#

ignore n+1 KEKW

hushed galleon
#

just make sure its part of the message content

loud junco
#
n=0
long = ''
while n <= db[f'{id}matchplayers']:
  userid = f'{id}player{n}'
  long += f'{n+1}) <@{userid}>\n'
  n += 1
slate swan
hushed galleon
slate swan
#
Traceback (most recent call last):
  File "/home/runner/zio-bot/venv/lib/python3.8/site-packages/discord/ui/view.py", line 425, in _scheduled_task
    await item.callback(interaction)
  File "main.py", line 381, in count
    interaction.guild.rol: discord.PermissionOverwrite(read_messages=True)
AttributeError: 'Guild' object has no attribute 'rol'
zealous jay
#

roles

slate swan
#

interaction.guild.role doesn't exist.

loud junco
#

s

slate swan
#

how can i do a custom role?

#

u already defined the role

hushed galleon
# loud junco

apparently your userid has the text 'player1' at the end?

slate swan
slate swan
#

interaction.guild.role: discord.PermissionOverwrite(read_messages=True)

#

how can I fix this?

loud junco
#
db[f'{id}matchcreated'] = True
        db[f'{id}matchplayers'] = 1
        db[f'{id}player1'] = ctx.author.id
        await ctx.send(f'Successfully created a room by {ctx.author.name}')
        ############################################
        ############################################
        ############################################
        n=0
        long = ''
        while n <= db[f'{id}matchplayers']:
          userid = f'{id}player{n}'
          long += f'{n+1}) <@{userid}>\n'
          n += 1
hushed galleon
#

oh right you defined userid right there

slate swan
#

yeah that isn't correct

#

how would it be correct?

naive briar
slate swan
#

yes exactly. which i pointed out to him.

#

so how can I get a custom role in?

#

bud

#

u literally already defined the role

naive briar
loud junco
slate swan
#

he already did it lmao

#

what

slate swan
#

role = interaction.guild.get_role(1039176031422132224)

hushed galleon
slate swan
#

interaction.guild.role:

slate swan
loud junco
#
db[f'{id}player1'] = ctx.author.id
hushed galleon
#

assuming that gives you the user's id sure

loud junco
#

n = 1 in this case

hushed galleon
#

key-value db for relational data must be horrendous to use

slate swan
loud junco
#

i forgot to add db[]

slate swan
#

@hushed galleon can you help me

#

how do I overwrite a channels perms with roles

hushed galleon
#

you already have your role object, just use it as the key in your overwrite dict

slate swan
#

?

hushed galleon
#
role = guild.get_role(...)
overwrites = {
    role: discord.PermissionOverwrite(read_messages=True)
}```
slate swan
#

ohhhhh

#

that makes a lot more sense now

loud junco
#

how to delete the command message

#

await ctx.delete?

naive briar
#

!d discord.ext.commands.Context.message

unkempt canyonBOT
#

The message that triggered the command being executed.

Note

In the case of an interaction based context, this message is โ€œsyntheticโ€ and does not actually exist. Therefore, the ID on it is invalid similar to ephemeral messages.

loud junco
#

heh

loud junco
slate swan
naive briar
#

Then use that to delete it

slate swan
#

can I do this?

loud junco
#

what is ctx.message

naive briar
#

It returns the message that triggers the command

loud junco
#

so i do ctx.message.delete?

naive briar
#

!d discord.Message.delete

unkempt canyonBOT
#

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

Deletes the message.

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

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

Yes

loud junco
#

await ctx.message.delete?

slate swan
#

dont forget ()

#

await ctx.message.delete()

loud junco
#

ok thanks

slate swan
#

np

spring summit
#

question, is there a "filename".write() command for deleting stuff

spring summit
abstract kindle
#

Still need some help with this.
Slash commands aren't throwing tracebacks

#
@app_commands.guilds(977351545966432306)
@app_commands.command(name="test", description="test")
    async def test(self, interaction: discord.Interaction):
        number = random.ball
        await interaction.response.send_message(number)

I put in an obvious error, and it's not getting caught. The application fails to respond in discord
Please note, I know it's not working because of random.ball, I just put that in there to try and get an error and I'm getting nothing, the terminal is still empty

mighty pilot
#

Does anything work at all or just this command not working

winged linden
#

Im making a ticket system and I want to make it so if the user already has a ticket open. The button will not create a new one. How would I do this?

slate swan
winged linden
#

I was originally thinking to have like a for loop which checks the names of all channels in a category to see if they contain the users name however

#

If two users have the same name it will prevent the other from creating a ticket

placid skiff
#

In those case you should use user ids
Do never use usernames, not only because two user can have the same name, but also because they can change their username and you would have to handle it

#

even use their discriminator or username+discriminator would not work

slate swan
#

I would add the user's ID in the channel topic when a ticket is created (having each ticket just named '730793398600073317' or whatever would just look messy) then when a user clicks the button, have the bot look through each existing ticket to see if the topic is equal to interaction.user.id

#
     overwrites = {
        ctx.guild.default_role: discord.PermissionOverwrite(read_messages=False),
        ctx.guild.me: discord.PermissionOverwrite(send_messages=True),
        role: discord.PermissionOverwrite(send_messages=False)
      }
#

how can I make it so just the member role cant send messages?

#

it just makes it so the users cant see the channel

placid skiff
#

You can name the channel however you want, it will not be a problem even if two user have the same name, you can handle it without any trouble, you just have to associate in a database that channel with the user id, but the files, just name them with user id

#

I would create a ticket table in the database and there save a ticket id, the ticket file name if exists, the user id which created the ticket and the channel id related to the ticket

#

also with the database it will be easy to check if a user has already a ticket opened

slate swan
winged linden
#

OHHHH

#

THATS SMART!!!!

slate swan
#

but the database route that Blvck talked about might be a better way

#

up to you, good luck with the bot

winged linden
#

I feel like your idea would be easier to implement

#

I had so many errors just reading and writing to a databas

#

Plus the channel topic doesn't really matter in a ticket

placid skiff
#

I can share you an easy database configuration if you want

#

you would just need to change it from sqlite to aiosqlite, but it will not be a problem

winged linden
#

no I know how to configure a database

#

im already using aiosqlite

#

It was a hassle just getting it to write records into the database

#

I feel like for tickets there isn't much need for a whole database

#

Storing it in the channel description would make it easy to move around and stuff as it would just be channel.description or whatever the syntax is

#

but with a database I have to make a whole connection everytime I want to perform an action

placid skiff
#

well just remember to handle if someone of the staff member change the channel topic, they could do it if they don't know how the bot works xD

winged linden
#

I'll make sure to inform them

sick birch
winged linden
#

Otherwise they might crash the entire bot lol

ripe blaze
#

when playing music through the bot, I sometimes get "HTTP error 403 Forbidden"
I read that it can be fixed by just clearing the cache but is there a way to avoid this error completely or do I just have to clear the cache each time it happens?

winged linden
#

lets say I want to write to it I create a connection perform the action then close the connection

winged linden
sick birch
winged linden
sick birch
#

Sure but making a new connection on every command is bad practice and resource intensive

#

Rather, store a global connector and use that as necessary

winged linden
#

the bot is like 20 kilobytes

#

But I get what your saying

placid skiff
#

usually you create one connection and close it when you stop the program or the bot

#

and do all of your stuff with that connection

winged linden
#

Issue with that is the bot would have to be stopped to manually edit the database

#

But doing it this way the database can be manually edited whilst the bot is running

#

so long as nobody happens to run a command at the exact same time

placid skiff
#

bruh no

#

wait i'm playing rainbow i'll answer asap

winged linden
#

lol ight

placid skiff
#

the bot doesn't need to be stopped while editing the database, using asyncio while the db operation are done the bot will continue to work as usual

winged linden
#

but if the connection isnt closed until the bot stops running

#

wont i get locked out if the bot has a connection already

#

I had the issue previously where I edited something with the bot and didnt close the connection and it resulted in me not being able to edit the database manually

#

because it only allows one connection at a time

jovial tide
#

how to make a shard?

placid skiff
#

uhm usually this doesn't happen with aiosqlite, which program did you use to open the database?

winged linden
#

sqlite

placid skiff
#

i mean to open it manually

winged linden
#

yes sqlite

placid skiff
#

ah wait sqlite? lmao yeah

#

you can't have more than one connection with sqlite

winged linden
#

yeah

#

so that was my issue

#

So I decided to just create a new connection each time and close it once im done with writing

placid skiff
#

if you have to make some changes manually then you could be able to do it while there is no current operation in the database made by your program

#

when you have done your changes you have to save

slate swan
#

I prefer mongo db

placid skiff
#

then it should work

winged linden
#

I've already written all the code now and got it working so I don't see much value in changing it

#

If the bot ends up having performance issues or something then ill know what to change ๐Ÿ˜„

#

thanks for the help guys ๐Ÿ™‚

#

I've already hit an error ๐Ÿ˜ญ

#
category1 = interaction.guild.get_channel(bot.ticketcategory)

        print (len(category1.channels))

        for i in range (len(category1.channels)):
            if interaction.user.id in category1.channels[i].topic:
                await interaction.response.send_message("Sorry you already have a ticket open!")
            else:
                channel = await interaction.guild.create_text_channel('New Ticket')

                await channel.edit(name=f'โ”โ”ƒ{interaction.user.name}-ticket', category = category1, topic = interaction.user.id)

mt current code

#

sometimes it also says textchannel is not iterable if I remove .topic

slate swan
#

because TextChannel.topic returns None if the topic is blank

winged linden
#

Ohhh

slate swan
#

how can I make it so only the member role cant talk

#

it just makes it so you cant see

winged linden
#
ctx.guild.default_role: discord.PermissionOverwrite(read_messages=False)
#

This is what you have

slate swan
#

oh ok thanks lol

#

im tesing

#

just makes every member be able to see

#
ro = ctx.guild.get_role(1038630407622635570) #member
      overwrites = {
        ro: discord.PermissionOverwrite(send_messages=False, read_messages=True)
      }
winged linden
slate swan
#

Are you trying to make some sort of ?lockdown command?

#

no

#

yea

#

only the members cant send messages

#

if I use .ticketmute

winged linden
#

everyone in your server has the member role i presume?

slate swan
#

yea

#

i tried doing a list

#

ro = ctx.channel.members

winged linden
#

If everyone has the member role you will have to specify what roles you want to be able to speak. And they need to be above the member role in terms of hierarchy

hushed galleon
# placid skiff you can't have more than one connection with sqlite

@winged linden SQLite does support multiple, simultaneous read/writing connections* when you configure the database file to use write-ahead logging, i.e. by running PRAGMA journal_mode = wal; once
https://sqlite.org/wal.html
(and technically they also support infinite readers in the default rollback journal mode, but having one writer can cause lock timeouts)
*correction: as per the above doc, 1 writer can coexist with other connections, any more will have to be queued

winged linden
# slate swan what

Ok look so every single person in your server has the member role right

#

And you made the member role unable to speak

#

But you didn't specify what roles you want to be able to speak

#

Therefore everyone is unable to speak unless they have administrator

slate swan
#

I did

#

ro = ctx.guild.get_role

winged linden
#

is that not the member role?

slate swan
#

that is

winged linden
#

exactly

slate swan
#

ro = ctx.guild.get_role(1038630407622635570) #member

winged linden
#

you made it so members cant speak but everyone has the member role

#

therefore everyone cant speak

slate swan
#

yea but it makes it so ppl can see it

winged linden
#

Yes

#

Everyone can see it but nobody can speak in it

#

you need to define a staff role and give it permission to speak

slate swan
#

wait wait

#

can I just get a list

winged linden
#

What?

slate swan
#

of members and then make them not be able to speak

#

if they have a role

winged linden
#

Why would you do that

slate swan
#

i need help thats why

winged linden
#

I think your not understanding what im saying

#

the part with the members is correct

slate swan
#

im so confused

winged linden
#

but your staff also have the member role right

#

therefore your staff cannot speak

slate swan
#

no wait

#

i want it so members cant speak

winged linden
#

yes

slate swan
#

but it just makes it so all members can see

#

i dont want all members to see

winged linden
#

what

#

You set read_message to true

slate swan
#

yea

#

I removed that

winged linden
#

They can't speak in a channel if they can't see it

slate swan
#

and it still doesnt work

winged linden
#

Ok wait

#

Clarify to me what is your goal

slate swan
#

u open a ticket

#

channel is made and then only staff and helpers + u can see it

#

when I do .muteticket I want it so only that one user with the member role cant speak

#

but it makes all users see it

winged linden
#

Then you need to change the specific users permissions

#

not the roles

slate swan
#

how can I do that?

winged linden
#

Are you using slash commands>

slate swan
#

no

#

buttons to open ticket

winged linden
#

Just double checking you want them only able to not speak in the ticket correct?

slate swan
#

yea

#

they can read the msgs just not speak

winged linden
#
await channel.set_permissions(interaction.user, send_messages=False)
#

It would work like that

slate swan
#

what no

winged linden
#

You would change the permissions of the channel for the user

slate swan
#

wait

#

I can use that actually

winged linden
#

Channel = the ticket

#

well technically that code would make it so the person who executed it cant send messages

winged linden
#

my bad

mighty pilot
#

Yea whoever opened the ticket with the button would be interaction.user correct

winged linden
#

Well no because he wants it so that when he says .muteticket it stops the ticket owner from speaking in it

#

So the technically the user/author would be him

mighty pilot
#

So you'd have to specify who's ticket you're muting then. I see

winged linden
#

Yeah

#

if he stores the ticket owner for each ticket somewhere he could design it to go .muteticket #ticket8378

mighty pilot
#

Sorry I like to lurk on my free time LurkMimi learning things lol

winged linden
#

Kekw fair enough

winged linden
mighty pilot
#

What you got going on I've got 30 mins lol

winged linden
#

I'd love if you could try to help me with it

slate swan
winged linden
#

alright so im trying to make a ticket system and im storing the users id in the topic of the channel and then when someone tries to make a ticket it checks the topic of the channel and compares it to their id

#
for i in range (len(category1.channels)):
            if str(interaction.user.id) in category1.channels[i].topic:
                await interaction.response.send_message("Sorry you already have a ticket open!")
                break
            else:
                channel = await interaction.guild.create_text_channel('New Ticket')
                await channel.edit(name=f'โ”โ”ƒ{interaction.user.name}-ticket', category = category1, topic = interaction.user.id)
#

I've got this right now but becaause its a loop whats happening is its checking all the tickets

#

I need it to check all the tickets and then only perform the else statement at the end of checking all the tickets

slate swan
#

@winged linden i have an idea

winged linden
#

Otherwise it will check other peoples tickets who obviously dont have the same id and then it creates a new channel

#

Yeah?

slate swan
#

get every user and then set the person who doesnt have helper or mod role to a var

#

then set that persons perms

winged linden
#

Or you could just store the owner of the ticket

#

and then change the specific owners permissions

mighty pilot
slate swan
#

eh

winged linden
#

Hmmm

#

what like

if str(interaction.user.id) not in category1.channels[i].topic:
mighty pilot
#

Well no that probably wouldn't help actually. Because this is all inside of your for loop so it would perform this action for every channel inside your loop

#

I think you need to move the for loop inside your if statement

winged linden
#

Yeah

cerulean folio
#

I wonder why this little trick doesn't work:

async def is_id(bot: Bot, id: int) -> User | None:
    if not (user:= await search_id(bot, id)):
        if not (guild:= search_guild(bot, id)):
            return None
        return guild
    return user

if looks so intuitive lol

winged linden
#

But then how would it check the channels if its inside the if statement

#

is there a way to detect if the above loop is ongoing

mighty pilot
#

Instead of performing everything inside the for loop, turn your results from the for loop into a list and check the user ID against that list

winged linden
#

ohh that could work alright let me give it a try

slate swan
#

Hi cereal ๐Ÿ‘€

mighty pilot
#

Hello

slate swan
#
      if role not in user.roles or rol not in user.roles:
       await ctx.channel.set_permissions(member, send_messages=False)
       await ctx.send(f"Muted {ctx.channel.mention}")
      else:
        await ctx.send(f"Cant mute {ctx.channel.mention} as everyone is a helper/mod.")
    else:
      await ctx.send(f"Cannot mute channel {ctx.channel.mention} as it is not a ticket.")
#
Traceback (most recent call last):
  File "/home/runner/zio-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 190, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 400, in muteticket
    if role not in user.roles or rol not in user.roles:
AttributeError: 'list' object has no attribute 'roles'

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

Traceback (most recent call last):
  File "/home/runner/zio-bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 1347, in invoke
    await ctx.command.invoke(ctx)
  File "/home/runner/zio-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 986, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "/home/runner/zio-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 199, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'list' object has no attribute 'roles'
winged linden
slate swan
mighty pilot
cerulean folio
# winged linden ```py for i in range (len(category1.channels)): if str(interaction.u...

You don't need to bother yourself with for i in range(len(category.channels)):
You could do things directly this way:

for channel in category1.channels:
        if str(interaction.user.id) in channel.topic:
            await interaction.response.send_message("Sorry you already have a ticket open!")
            break
        else:
            new_channel = await interaction.guild.create_text_channel('New Ticket')
            await new_channel.edit(name=f'โ”โ”ƒ{interaction.user.name}-ticket', category = category1, topic = interaction.user.id)
winged linden
slate swan
#

idk how to do that

winged linden
#

I'd reccomending doing what im doing and storing their user id in the channel topic

#

then when you run the mute command you can just check the channel topic, take its contents and use it to change the permissions of the user

cerulean folio
slate swan
#
  role = ctx.guild.get_role(1038630402723680356)
  rol = ctx.guild.get_role(1039176031422132224)
  if role in ctx.author.roles:
    if c in ctx.channel.name:
      user = ctx.channel.members
      ro = ctx.guild.get_role(1038630407622635570) #member
      if role not in user.roles or rol not in user.roles:
       await ctx.channel.set_permissions(member, send_messages=False)
       await ctx.send(f"Muted {ctx.channel.mention}")
      else:
        await ctx.send(f"Cant mute {ctx.channel.mention} as everyone is a helper/mod.")
cerulean folio
#

Try add a e to rol and see if it workd?

#

Ohhhhh I apologize

mighty pilot
slate swan
#

np

cerulean folio
mighty pilot
#

Solid tip though it's a lot of extra nonsense lol

winged linden
#

Yeah it was actually very helpful

#

Its good to have good readability

slate swan
#

@winged linden could you help me acheive this?

winged linden
#

Achieve what?

slate swan
#

storing the id

#

ik with open

#

idk how to make it not reset tho

winged linden
winged linden
#

and just make sure nobody changes the topic

mighty pilot
#

Still made a new ticket if their id is in the channel topic?

winged linden
#

You could also use a database

slate swan
#

I could just mute the user in the ticket...

#

using .mute @rich otter then override the permissions

winged linden
#

Yes

#

that would work because since you pinged the user you can use it as a parameter to edit the channel permissions

mighty pilot
# winged linden Yep.

Print your list and user ID to compare in console and see why it said it wasn't in the list

winged linden
#

Yeah let me print it

slate swan
#
@client.command()
async def muteticket(ctx, member: discord.User):
  await ctx.message.delete()
  c = 'ticket-'
  role = ctx.guild.get_role(1038630402723680356)
  rol = ctx.guild.get_role(1039176031422132224)
  if role in ctx.author.roles:
    if c in ctx.channel.name:
       await ctx.channel.set_permissions(member, send_messages=False)
       await ctx.send(f"Muted {user} from {ctx.channel.mention}.")
    else:
      await ctx.send(f"Cannot mute channel {ctx.channel.mention} as it is not a ticket.")
  else:
    await ctx.send("You cannot run this action as you are not mod.")
#

this is what im thinking

winged linden
#

wait i used list.append()

#

That doesn't add to the list does it

#

that changes an value it already has

#

i need to use insert

#

im an idiot

slate swan
#

append adds an element to the end of a list

mighty pilot
#

Append should add to the list

#

Specifically to the end of it

winged linden
#

Yeah wait so it should be working

#

the list only contained one id

#

and I believe it was the last channels

spring summit
#

question, is there a "filename".write() command for deleting stuff

slate swan
#

well what was meant to happen

mighty pilot
#

How did you write the for statement

slate swan
#

works i think

winged linden
#

        for i in range (len(category1.channels)):
            listchannel = []
            listchannel.append(category1.channels[i].topic)

        print(listchannel)

        if interaction.user.id in listchannel:
            await interaction.response.send_message("Sorry you already have a ticket open!")
        else:
            channel = await interaction.guild.create_text_channel('New Ticket')
slate swan
#

you're re-defining listchannel as an empty list each time the loop runs

winged linden
#

OH IM AN IDIOT

#

lordy lord

slate swan
#

wait couldnt you just get all channels then if the channel name is equal to like f"ticket-{interaction.user}" you can say you cant open a ticket?

#

bc if theres a channel with ticket-your name it wont open

#

right?

winged linden
#

I could but then if two people have the same name it would cause issues

slate swan
#

IDs are unique to the user.

winged linden
slate swan
#

yea so you could just do id in the ticket

winged linden
#

I HAVE THE BOT OPEN TWICE NVM

#

i forgor to close it

mighty pilot
winged linden
#

I was so confused

slate swan
winged linden
#

and im checking the channel topic to see if it matches with their id

slate swan
cerulean folio
# winged linden I was so confused
topics_list = list()
for channel in category1.channels:
    listchannel.append(channel.topic)

This might be cleaner and less confusing for you to read whenever you're looking at your code ๐Ÿ˜Š

winged linden
#

kekw

#

thx โค๏ธ

#

my code always ends up being messy by default

mighty pilot
winged linden
#

I forgot since the list starts from 0 I have to do +1

cerulean folio
winged linden
#

ok sensei ๐Ÿ™

mighty pilot
#

Or like 30 different embeds with the name embed

winged linden
#

im guilty of that

#

every single one of my embeddeds is named embed

mighty pilot
#

Lmao I try to specify between them throughout my code to avoid my own confusion

cerulean folio
# winged linden ok sensei ๐Ÿ™

You can also use something called "type hinting", that give you hints about what types of data you're manipulating:

topics_list : list[str] = list()
for channel in category1.channels:
    listchannel.append(channel.topic)

so next time you read this code you can understand that this list contains strings with a single eye glance :D

#

it's good to spend much time organizing your code, because you spend 90% of your time reading vs 10% of coding ^^

mighty pilot
#

That's why I want to seperate my code into cogs. Tired of scrolling through it to find some command that was 4 lines long Norow

winged linden
#

it made another channel even with the id in it

#

im actually ab to break something

mighty pilot
#

That's the user ID not the channel id?

slate swan
#

because you are comparing a string to an int

winged linden
#

Yes its meant to be the user ID

winged linden
#

user id is int

cerulean folio
winged linden
slate swan
mighty pilot
slate swan
#

you need to convert the topic string to an int

winged linden
#

Or do that

slate swan
#
 @discord.ui.button(label='Open', style=discord.ButtonStyle.green)
  async def count(self, interaction: discord.Interaction, button: discord.ui.Button):
    channel = interaction.guild.channels
    cname = f"ticket-{interaction.user}-{interaction.user.id}"
    if cname in channel:
      await interaction.response.send_message("You already have a ticket open.", ephemeral=True)
    else:
      with open("ticket.txt", "r") as f:
        f.read()
      with open("ticket.txt", "w") as f:
        client.ticket += 1
        f.write(f"{client.ticket}")
      role = interaction.guild.get_role(1039176031422132224) #helper
      rol = interaction.guild.get_role(1038630402723680356) #mod
      overwrites = {
        interaction.guild.default_role: discord.PermissionOverwrite(read_messages=False),
        interaction.guild.me: discord.PermissionOverwrite(read_messages=True),
        role: discord.PermissionOverwrite(read_messages=True),
        rol: discord.PermissionOverwrite(read_messages=True)
      }
      c = await interaction.guild.create_text_channel(f"ticket-{interaction.user}-{interaction.user.id}", overwrites=overwrites)
      await c.send(f"{interaction.user.mention} Please wait for staff. ({client.ticket})")
      await interaction.response.send_message(f"Opened Ticket {c.mention}", ephemeral=True)
#

why doesnt this work?

winged linden
#

I did it.

#

I achieved a ticket system

slate swan
#

Nice make sure to test it thoroughly under all possible scenarios to be sure it works

winged linden
#

Yes, apparently the people in the server im making the bot for will attempt to break it

sick birch
mighty pilot
#

Nice. Now wouldn't it break in the event that the channel topic contains alphabetic characters?

sick birch
#

Discord bots do get a bit dull after a while

mighty pilot
#

Seems like it'd be safer to convert ID to string instead of topic to int

winged linden
#

the channel topic is just the owners id

mighty pilot
slate swan
winged linden
#

but just to be on the safe side

slate swan
#

no errors

winged linden
#

Ill do it anyway

slate swan
winged linden
#

ill look at it in a second

slate swan
#

?

winged linden
#

cs joke

#

logic errors are by far the worst kind of errors

slate swan
#
  channel = interaction.guild.channels
    cname = f"ticket-{interaction.user}-{interaction.user.id}"
    if cname in channel:
      await interaction.response.send_message("You already have a ticket open.", ephemeral=True)
    else:
#

but this is ok right?

#

channel is same indent btw

spring summit
#

can somebody help me out rq

winged linden
#

Thats going to cause issues

slate swan
#

how?

winged linden
#

If two people have the same username

mighty pilot
slate swan
#

no?

mighty pilot
slate swan
slate swan
winged linden
#

so if their name is in the channel

#

it going to print that

slate swan
#

cname = ""

winged linden
#

wat

slate swan
spring summit
slate swan
#

for channel is list:

#

?

mighty pilot
winged linden
#

ephemeral means disappearing right

mighty pilot
winged linden
#

Great thats what i need

mighty pilot
#

Moreso hidden than disappearing

slate swan
#
   channel = list(interaction.guild.channels)
    cname = f"ticket-{interaction.user}-{interaction.user.id}"
    if cname in channel:
        await interaction.response.send_message("You already have a ticket open.", ephemeral=True)
    else:
spring summit
slate swan
spring summit
slate swan
slate swan
#

so how would I do this?

spring summit
#

syntax error, mb

mighty pilot
slate swan
mighty pilot
# spring summit

Now your with is indented so it's being executed in the code block above it. So you can't assign keys if that code block isn't executed

slate swan
mighty pilot
#

I gotta go though, back to jury duty PikaF

slate swan
#

Cya

mighty pilot
#

There's other people that can help

spring summit
#

๐Ÿ˜ฆ

mighty pilot
#

Unindent with to the same place as elif for a start

slate swan
slate swan
winged linden
slate swan
#

u need the link

#

waiting

#
    channel = str(interaction.guild.text_channels)
    cname = f"ticket-{interaction.user}-{interaction.user.id}"
    if cname in channel:
#

this doesnt work ether

slate swan
# slate swan waiting

Do something like:

channel_list = []
for channel in interaction.guild.channels:
  channel_list.append(channel.name)

That should create a list containing each channel's name, you can then compare that list to your target channel.

Also, please don't be impatient.

#

im not trying to be lol

#

I have adhd and it kinda messes with it

#
    channel_list = []
    for channel in interaction.guild.channels:
      channel_list.append(channel.name)
      cname = f"ticket-{interaction.user}-{interaction.user.id}"
      if cname in channel_list:
          await interaction.response.send_message("You already have a ticket open.", ephemeral=True)
      else:
Traceback (most recent call last):
  File "/home/runner/zio-bot/venv/lib/python3.8/site-packages/discord/ui/view.py", line 425, in _scheduled_task
    await item.callback(interaction)
  File "main.py", line 394, in count
    await interaction.response.send_message(f"Opened Ticket {c.mention}", ephemeral=True)
  File "/home/runner/zio-bot/venv/lib/python3.8/site-packages/discord/interactions.py", line 692, in send_message
    raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before
naive briar
#

Read the error

slate swan
#

i did

#

i dont understand it

naive briar
#

What does it say

slate swan
#

its been responded to before

#

what does that mean

#

and it doesnt stop it from making a new ticket

#

so idk what to do

naive briar
#

!d discord.Interaction.response

unkempt canyonBOT
#

Returns an object responsible for handling responding to the interaction.

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

slate swan
#

IDK

hushed coral
#

Is there a way to check for a pinned message?

slate swan
naive briar
unkempt canyonBOT
#

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

Retrieves all messages that are currently pinned in the channel.

Note

Due to a limitation with the Discord API, the [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") objects returned by this method do not contain complete [`Message.reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message.reactions "discord.Message.reactions") data.
slate swan
#

i read the docs the other guy gave me and idk what im doing

#

on error?

spring summit
naive briar
#

What does it say

spring summit
#

unused

#

LOL

slate swan
#

and it makes 2 channels

spring summit
#

oh my fault

slate swan
#
2022-11-07 18:37:57 ERROR    discord.ui.view Ignoring exception in view <View timeout=180.0 children=1> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Open' emoji=None row=None>
Traceback (most recent call last):
  File "/home/runner/zio-bot/venv/lib/python3.8/site-packages/discord/ui/view.py", line 425, in _scheduled_task
    await item.callback(interaction)
  File "main.py", line 394, in count
    await interaction.response.send_message(f"Opened Ticket {c.mention}", ephemeral=True)
  File "/home/runner/zio-bot/venv/lib/python3.8/site-packages/discord/interactions.py", line 692, in send_message
    raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before
silent portal
slate swan
slate swan
#

Your if else statement is inside your for loop

spring summit
slate swan
spring summit
#

prolly

slate swan
#

alr im testing now

#

still opens more than one

spring summit
#

@slate swan mind helping me out G?

slate swan
#
   channel_list = []
    for channel in interaction.guild.channels:
      channel_list.append(channel.name)
      cname = f"ticket-{interaction.user}-{interaction.user.id}"
    if cname in channel_list:
          await interaction.response.send_message("You already have a ticket open.", ephemeral=True)
    else:
slate swan
spring summit
#

the line above works

#

dyk why?

slate swan
# spring summit the line above works

Because in this example, your with open(... line is inside the previous if/elif statement (by the looks of it at least, I can only see what's in the image).

spring summit
slate swan
# spring summit what

In this example you have stuff going on between an if and an elif statement, a bit like this:

spring summit
#

its the exact same i think

#

and the other line works kaokdoaskdoaksd ๐Ÿ˜ญ

#
@client.command(pass_context=True)
async def redeem(ctx, code='xxx-xxxx-xxx'):
    with open('key_codes_bronze', 'r') as key_codes_bronze:
        keyb = key_codes_bronze.read()
        with open('key_codes_silver', 'r') as key_codes_silver:
            keys = key_codes_silver.read()
            with open('key_codes_gold', 'r') as key_codes_gold:
                keyg = key_codes_gold.read()

    if code == keyb:
        await ctx.author.add_roles(discord.utils.get(ctx.guild.roles, name='Bronze'))
        embed = discord.Embed(title=f"{key_emoji} BRONZE KEY ", description=f'KEY REDEEMED SUCCESSFULLY.',
                              color=0x2F3136)
        embed.set_image(url="")
        await ctx.author.send(embed=embed)
        await ctx.message.add_reaction(f"{done_emoji}")
        chars = string.ascii_letters + string.digits
        keybr = ('PX' + '-' + 'BRONZE' + '-' + ''.join(random.choice(chars) for i in range(6))  + '-' +''.join(random.choice(chars) for i in range(6)) + '-' + ''.join(random.choice(chars) for i in range(6)) + '-' + ''.join(random.choice(chars) for i in range(6)))
        with open('key_codes_bronze', 'w') as key_codes:
            key_codes.write(keybr)
            with open('bronze', 'w') as f:
                f.write(f"{str(ctx.author.id)}\n")
                f.close()

        with open('key_codes_silver', 'r') as key_codes_silver:
         keys = key_codes_silver.read()
    elif code == keys:
            await ctx.author.add_roles(discord.utils.get(ctx.guild.roles, name='Silver'))
            embed = discord.Embed(title=f"{key_emoji} SILVER KEY ", description=f'KEY REDEEMED SUCCESSFULLY.',
                                  color=0x2F3136)
            await ctx.author.send(embed=embed)
            await ctx.message.add_reaction(f"{done_emoji}")
            chars = string.ascii_letters + string.digits
            keys = ('PX' + '-' + 'SILVER' + '-' + ''.join(random.choice(chars) for i in range(6)) + '-' + ''.join(random.choice(chars) for i in range(6)) + '-' + ''.join(random.choice(chars) for i in range(6)) + '-' + ''.join(random.choice(chars) for i in range(6)))
    with open('key_codes_silver', 'w') as key_codes_silver:
            key_codes_silver.write(keys)
            with open('silver', 'w') as g:
                g.write(f"{str(ctx.author.id)}\n")

    elif code == keyg:
            await ctx.author.add_roles(discord.utils.get(ctx.guild.roles, name='Silver'))
            embed = discord.Embed(title=f"{key_emoji} SILVER KEY ", description=f'KEY REDEEMED SUCCESSFULLY.',
                                  color=0x2F3136)
            await ctx.author.send(embed=embed)
            await ctx.message.add_reaction(f"{done_emoji}")
            chars = string.ascii_letters + string.digits
            keys = ('PX' + '-' + 'SILVER' + '-' + ''.join(random.choice(chars) for i in range(6)) + '-' + ''.join(random.choice(chars) for i in range(6)) + '-' + ''.join(random.choice(chars) for i in range(6)) + '-' + ''.join(random.choice(chars) for i in range(6)))
    with open('key_codes_silver', 'w') as key_codes_silver:
            key_codes_silver.write(keys)
            with open('silver', 'w') as g:
                g.write(f"{str(ctx.author.id)}\n")
#

this is the code in case it helps

slate swan
spring summit
#

like this?

#

im sorry for making it hard for you lmao

slate swan
#

BlobPain The with open(...) line in the 2nd image is not indented correctly. You need to indent it properly for it to actually be inside your if/elif statement.

Indentation refers to the spaces at the beginning of a code line. Python uses indentation to indicate a block of code.

spring summit
#

dude im lost

viscid wren
#

sorry, what version of python requires the latest version of dpy?

abstract kindle
white citrus
#

Can me someone help with this?

Traceback (most recent call last):
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 502, in _run_event
    await coro(*args, **kwargs)
  File "c:\Discord\Maja Projekt\MajaSystem_Test\bot.py", line 202, in on_message
    global_chat_check = await bot.settings.find_many_by_custom(global_chat_filter)
  File "c:\Discord\Maja Projekt\MajaSystem_Test\utils\mongo.py", line 43, in find_many_by_custom
    self.__ensure_dict(filter_dict)
  File "c:\Discord\Maja Projekt\MajaSystem_Test\utils\mongo.py", line 126, in __ensure_dict
    assert isinstance(data, collections.abc.Mapping)
AssertionError```
silent portal
#

Hey, I'm trying to make a Voice Level System Discord Bot and I want to add a 2 minute timer individually for every user joining a voice channel. When the timer is done, it checks if the user is still in the Voice Channel. If so, the 2 minutes resets and it repeats. If not, the timer will stop.

@bot.event
async def on_voice_state_update(member, before, after):
    if after.channel != None and before.channel == None:
        await start_timer(member)

async def start_timer(member):
    await asyncio.sleep(120)
    if member.voice:
        # Add XP and Level Up and stuff..
        await start_timer(member)```
Should the main-concept work? And is it bad if there are like hundreds of users in a Channel so the same function runs like 100x times at the same time?
shrewd apex
#

add xp at the end or evaluate that dict in a tasks loop

#

!d time.monotonic

unkempt canyonBOT
#

time.monotonic() โ†’ float```
Return the value (in fractional seconds) of a monotonic clock, i.e. a clock that cannot go backwards. The clock is not affected by system clock updates. The reference point of the returned value is undefined, so that only the difference between the results of two calls is valid.

Use [`monotonic_ns()`](https://docs.python.org/3/library/time.html#time.monotonic_ns "time.monotonic_ns") to avoid the precision loss caused by the [`float`](https://docs.python.org/3/library/functions.html#float "float") type.

New in version 3.3.

Changed in version 3.5: The function is now always available and always system-wide.

Changed in version 3.10: On macOS, the function is now system-wide.
silent portal
shrewd apex
silent portal
shrewd apex
tulip oracle
#

has anyone worked with reactions with unicode emojis before

#

i got a few questions

shrewd apex
tulip oracle
#

i been here long enough

shrewd apex
#

u never edited the message

#

last pic i dont see any (edited) tag

#

edit the message duh

tulip oracle
#

does on_raw_reaction_add support unicode emojis

mighty pilot
#

You need to have the message object then message.edit with the new embed

silent portal
mighty pilot
#

I'm saying you need to have the message that your trying to edit, whatever that's assigned to, with the original embed and view, then edit that message with your new embed

#

Not too familiar with editing messages yet tbh

winged linden
#

whats the easiest way for me to check if a user has a role during a slash command

winged linden
#

I need to do it inside the command

#

I'm trying to make it so either the owner of the ticket or someone with a certain role can delete the message

mighty pilot
#

Ohh. If I remember correctly the way I did that, use get() to get the role object then if xyz in user.roles: been a min since I've looked at that though

winged linden
#

what would it be get(roleid)

winged linden
#

ahhh thanks

shrewd apex
#

having a function on wait for every member

spring summit
#

i need help

#
@client.command(pass_context=True)
async def redeem(ctx, code='xxx-xxxx-xxx'):
    with open('key_codes_bronze', 'r') as key_codes_bronze:
        keyb = key_codes_bronze.read()
        with open('key_codes_silver', 'r') as key_codes_silver:
            keys = key_codes_silver.read()
            with open('key_codes_gold', 'r') as key_codes_gold:
                keyg = key_codes_gold.read()

    if code == keyb:
        await ctx.author.add_roles(discord.utils.get(ctx.guild.roles, name='Bronze'))
        embed = discord.Embed(title=f"{key_emoji} BRONZE KEY ", description=f'KEY REDEEMED SUCCESSFULLY.',
                              color=0x2F3136)
        embed.set_image(url="https://share.creavite.co/j8SFDfVpVXysYI5Z.gif")
        await ctx.author.send(embed=embed)
        await ctx.message.add_reaction(f"{done_emoji}")
        chars = string.ascii_letters + string.digits
        keybr = ('PX' + '-' + 'BRONZE' + '-' + ''.join(random.choice(chars) for i in range(6)) + '-' + ''.join(
            random.choice(chars) for i in range(6)) + '-' + ''.join(
            random.choice(chars) for i in range(6)) + '-' + ''.join(random.choice(chars) for i in range(6)))
        with open('key_codes_bronze', 'w') as key_codes:
            key_codes.write(keybr)
            with open('bronze', 'w') as f:
                f.write(f"{str(ctx.author.id)}\n")
                f.close()
                await asyncio.sleep(1)

        with open('key_codes_silver', 'r') as key_codes_silver:
            keys = key_codes_silver.read()
    elif code == keys:
        await ctx.author.add_roles(discord.utils.get(ctx.guild.roles, name='Silver'))
        embed = discord.Embed(title=f"{key_emoji} SILVER KEY ", description=f'KEY REDEEMED SUCCESSFULLY.',
                              color=0x2F3136)
        await ctx.author.send(embed=embed)
        await ctx.message.add_reaction(f"{done_emoji}")
        chars = string.ascii_letters + string.digits
        keys = ('PX' + '-' + 'SILVER' + '-' + ''.join(random.choice(chars) for i in range(6)) + '-' + ''.join(
            random.choice(chars) for i in range(6)) + '-' + ''.join(
            random.choice(chars) for i in range(6)) + '-' + ''.join(random.choice(chars) for i in range(6)))
    with open('key_codes_silver', 'w') as key_codes_silver:
        key_codes_silver.write(keys)
        with open('silver', 'w') as g:
            g.write(f"{str(ctx.author.id)}\n")
            g.close()
    if code == keyg:
        await ctx.author.add_roles(discord.utils.get(ctx.guild.roles, name='Gold'))
        embed = discord.Embed(title=f"{key_emoji} GOLD KEY ", description=f'KEY REDEEMED SUCCESSFULLY.',
                              color=0x2F3136)
        embed.set_image(url="https://share.creavite.co/j8SFDfVpVXysYI5Z.gif")
        await ctx.author.send(embed=embed)
        await ctx.message.add_reaction(f"{done_emoji}")
        chars = string.ascii_letters + string.digits
        keg = ('PX' + '-' + 'GOLD' + '-' + ''.join(random.choice(chars) for i in range(6)) + '-' + ''.join(
            random.choice(chars) for i in range(6)) + '-' + ''.join(
            random.choice(chars) for i in range(6)) + '-' + ''.join(random.choice(chars) for i in range(6)))
    with open('key_codes_gold', 'w') as key_codes_gold:
        key_codes_gold.write(keg)
    with open('gold', 'w') as h:
        h.write(f"{str(ctx.author.id)}\n")
        h.close()
#

this is supposed to be a redeem command, every time you redeem, the bot writes your id in 3 different files

#

the thing is, every time you redeem like bronze for example, it writes your id in every file

#

do you guys know how to fix that

silent portal
#

idk man I'm kinda 'scared' to use for loops for maybe 5k+ keys

shrewd apex
#

lmao

quaint epoch
#

This code is ancient

shrewd apex
#

if u dont even have confidence in the language and its capacities idk what to say

quaint epoch
#

Just iterate over a list of strings, open the file and write your name there

shrewd apex
quaint epoch
unkempt canyonBOT
spring summit
#

i got aired

quaint epoch
#

No u

shrewd apex
shrewd apex
quaint epoch
quaint epoch
#

Depends on case tho

shrewd apex
shrewd apex
#

txt and json files are not made for asynchronous purposes and is likely to cause corruption if made writes to concurrently

slate swan
#

thats why you should use csv files

nova mauve
#

Hey, how would I allow for my bot to support commands with no the correct capitalisation

#

For example, if the command was !hi and the user tried Hi, how would I allow for this

#

not all too sure where i would put .lower() or if i would use it at all

winged coral
#

Set this kwarg in the bot constructor

#

To True

quaint epoch
nova mauve
#

thanks bro

winged coral
#

Anytime kirby

mighty pilot
#

Wow has it really been more than an hour with no new questions?

#

Is there a default help command with slash commands similar to the one for text commands?

#

Or do I need to make my own help command

hushed galleon
#

there is not

#

though its a bit unusual to make such a help command when your discord app can already list all the slash commands your bot has

mighty pilot
#

I agree. It isn't something that's normally needed but I'd like some way to expound upon the subcommands of a couple of my commands in case there's any confusion. Because I have 10 variables that need to be set in order for one of the functions of my bot to work

#

If I do it inside a command on discord I can use screenshots and links to give examples on how to set it up

hushed galleon
#

hm that sounds fine

#

would be nice if discord.py had a .mention attribute for app command objects

#

oh wait a minute, how did i not notice it exists

mighty pilot
#

You can mention an app command object? Does that mean like in the command when you click on it or a subcommand

hushed galleon
#

ah wait, app_commands.AppCommand given by the discord API has the mention attribute, but app_commands.Command as given by the command decorator doesnt

#

yeah you can mention them using </cmd name:cmd_id>

mighty pilot
#

Wild

slate swan
#

yea the API has the ability to but I dont think and lib as implemented an actual way to .mention them yet

#

other than what you've just provided

mighty pilot
#

I'm just going to make a help command with the names of my commands as subcommands

slate swan
#

dark just use an option with those commands as choices

mighty pilot
#

Default value = None

slate swan
#

an optional option i.e. ig

mighty pilot
#

Is there a way to make my own list like this?

hushed galleon
#

truly the most inconvenient way to mention them ๐Ÿ˜”

mighty pilot
# hushed galleon

I just did that and I agree it's inconvenient but it'll be helpful in explaining how to set stuff up with slash commands lol

slate swan
winged linden
#

I do not know what I have done wrong but I get the error

class SelectionList(discord.ui.View):



    @discord.ui.Select(placeholder = "Please Select the type of ValCarry You Would Like", options = [
                        discord.SelectOption(label="Floor 1", value="F1", description='ValCarry for Floor 1', emoji='โ”'),
                        discord.SelectOption(label="Floor 2", value="F2", description='ValCarry for Floor 2', emoji='๐Ÿ”ง'),
                        discord.SelectOption(label="Floor 3", value="F3", description='ValCarry for Floor 3', emoji='๐Ÿšซ')
                        ])


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

        channel = interaction.channel

        # Dungeons, CataCombs

        if value == "F1":
            await channel.edit(name = f"F1โ”ƒ{interaction.user.name}")

        if value == "F2":
            await channel.edit(name = f"F2โ”ƒ{interaction.user.name}")

        if value == "F3":
            await channel.edit(name = f"F3โ”ƒ{interaction.user.name}")

Heres the error:

 File "C:\Users\Fiery\OneDrive\Desktop\AtomProjects\HyperionFund\verification.py", line 159, in <module>
    class SelectionList(discord.ui.View):
  File "C:\Users\FIery\OneDrive\Desktop\AtomProjects\HyperionFund\verification.py", line 199, in SelectionList
    async def specify(self, interaction: discord.Interaction):
TypeError: 'Select' object is not callable
mighty pilot
#

So I can set my own strings as command choices?

slate swan
#

!d discord.app_commands.choices

unkempt canyonBOT
#

@discord.app_commands.choices(**parameters)```
Instructs the given parameters by their name to use the given choices for their choices.

Example...
mighty pilot
#

Thanks

slate swan
upbeat gust
#

or just use typing.Literal

slate swan
#

yeah that works too if you don't want the name and value of the optionchoice to be different

hushed galleon
#

oops wrong message reply

slate swan
#

if you have more than 25 commands you can go for an autocomplete, else both of them can work ig

#

the good thing about choices would be that the user wont be able to enter any invalid command

hushed galleon
#

yup ๐Ÿ˜”

slate swan
#

nvm

#

its @discord.ui.select, not @discord.ui.Select

winged linden
#

breh

mighty pilot
hushed galleon
#

its not limited by the number of commands, its just per argument

mighty pilot
#

Regardless

#

In the context of a help menu

slate swan
mighty pilot
#

Well I only know of one other that does what mine does and it's paid and "stupid" text commands. Not very user friendly

#

So hopefully not lol

slate swan
#

ow what is the bot about?

mighty pilot
#

Split tree leveling

#

Assigning roles based on what path you choose

slate swan
#

i see, that sounds interesting

mighty pilot
#

I've got a good start on it. Works pretty well now it's just a matter of adding any extras I want to the base

#

Like the ability to adjust the exponential growth in level xp

#

Or choosing what levels the role path buttons appear at

slate swan
#

roleplay servers* are gonna use that bot a lot

mighty pilot
#

That's my goal

#

There's a lot of them out there

#

?

winged linden
#

Anyone know anything about this error.

[2022-11-07 23:04:27] [ERROR   ] discord.ui.view: Ignoring exception in view <ButtonTest timeout=180.0 children=1> for item <Button style=<ButtonStyle.danger: 4> url=None disabled=False label='Create Ticket' emoji=None row=None>
Traceback (most recent call last):
  File "C:\Users\Fiery\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 425, in _scheduled_task
    await item.callback(interaction)
  File "C:\Users\Fiery\OneDrive\Desktop\AtomProjects\HyperionFund\verification.py", line 367, in new
    await channel.send(embed=embed, view=SelectionList())
  File "C:\Users\Fiery\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\abc.py", line 1536, in send
    data = await state.http.send_message(channel.id, params=params)
  File "C:\Users\Fiery\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 744, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In components.0.components.0.options: Must be between 1 and 25 in length. ```
#

I would send me code but I can't really pinpoint what to send as I have no clue where to error is originating from

#
await channel.send(embed=embed, view=SelectionList())
``` I believe this is somehow the line that is erroring
sick birch
winged linden
#

sure

#

its extremelly long though

#

whats the site I can send it vi

#

via

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

winged linden
mighty pilot
#

You can only have 25 options is what it's saying

winged linden
#

Fuck

mighty pilot
winged linden
#
return self.callback(self.view, interaction, self.item)
TypeError: SelectionList.specify() takes 2 positional arguments but 3 were given
async def specify(self, interaction: discord.Interaction):
#

why was self.item given aswell

sick birch
slate swan
#

i dont think callbacks for views take the select as well. i believe it's just (self, interaction: discord.Interaction)

slate swan
#

?

sick birch
slate swan
#

but why are u passing the select itself into the callback?

cerulean folio
versed comet
#

pls help

#

someone help me? I have a problem with my bot script, the /help dropdown I'm trying to create is syncing with the ticket dropdown I created, I need help to solve this

slate swan
versed comet
#

ok

indigo pilot
#

Anyone got any ideas how to access my passed in var, test?

#

from the form questions

#

Since its gey and you gotta define the questions like that i wont be able to access it so idk what to do

pliant gulch
#

Class method probably instead of constructing it regularlly

hushed galleon
#

you dont actually have to specify the text input as a class attribute, but regardless dpy allows you to modify the text input after instantiation

#

e.g. ```py
class MyModal(discord.ui.Modal):
my_input = discord.ui.TextInput(label='')

def __init__(self, my_title: str, my_label: str):
    super().__init__(title=my_title)
    self.my_input.label = my_label```
winged linden
#
result2 = await db.execute("SELECT Amount From Database1 Where UUID = ?", [value])
        result3 = await result2.fetchall()
        print(result3)
        TotalAmount = sum(result3)
        print (TotalAmount)

This is my code and its aim is to fetch data from a database if the UUID matches to a variable and then it would add the Amount value of each record to get the total Amount. However fetchall() returns a tuple and to use sum I need the list to contain integers.

#

How can I convert this lists values from a tuple to an integer or even get the result from fetchall to be integers

hushed galleon
winged linden
#

Sorry about that, I never really know where to ask so I just go here because I'm making a discord bot

mighty pilot
#

Boy I did that very different in my code

winged linden
pliant gulch
mighty pilot
#

I took the long route personally

        results = cur.fetchall()
        res1 = results[0]
        res11 = res1[1]
        roleid1 = int(res11)
        res2 = results[1]
        res22 = res2[1]
        roleid2 = int(res22)
        res3 = results[2]
        res33 = res3[1]
        roleid3 = int(res33)
winged linden
#

๐Ÿ˜ญ

viral stump
#

Hello there, i got victim user id (victim_user_id) i want to show it for username on chat but when i try like that {id(victim_user_id).name or username} i got this error {id(victim_user_id).name}") AttributeError: 'int' object has no attribute 'name', what should i do? Bascally i want to convert id to username

hushed galleon
unkempt canyonBOT
#

discord/ui/modal.py lines 115 to 117

for name, item in self.__modal_children_items__.items():
    item = deepcopy(item)
    setattr(self, name, item)```
winged linden
#

this is so cursed

hushed galleon
#

it would be nice for this behavior to have been documented, but at least its there

hushed galleon
#

!d discord.Client.fetch_user

unkempt canyonBOT
#

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

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

Note

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

Changed in version 2.0: `user_id` parameter is now positional-only.
viral stump
#

i am rookie sorry about that question's stupidity

hushed galleon
#

fetch_user() returns a User object, and that has the .name attribute containing the name of whoever's ID you fetched

viral stump
#

ohh wait

hushed galleon
#

kind of, but fetch_user is a method of your Client/Bot instance

pliant gulch
#

I didn't know that kek

slate swan
#

typing <@user_id> in the message works too if you're only looking to mention them
but if you wanna do other stuff with the User object then use fetch_user()

pliant gulch
#

Well, that's good at least they thought about that

slate swan
mossy jacinth
#

Any way to fix that it says "None" If you write it in russian or any other language that contains special characters?
used
from translate import Translator

viral stump
#

What did o do wrong? target1 = client.fetch_user(victim_user_id)

    hedef = client.fetch_user(victim_user_id)
NameError: name 'client' is not defined```
sick birch
hushed galleon
viral stump
# sick birch The error says it all, `client` is not defined. Perhaps you meant `bot`?

okay, it is like that right now except: for victim_user_id, percentage in targeted_victims: target1 = bot.fetch_user(victim_user_id) await message.channel.send(f"Oda boลŸ olduฤŸundan ya da hedef oda da olmadฤฑฤŸฤฑndan dolayฤฑ bot gelmiyor.") await message.channel.send(f"Hedefler ลŸuydu (id, oran) {id(target1).name}")
And i got this error, target1 was never awaited

if i try await target1 == bot.fetch_user(victim_user_id) i got this error what is "target1" how can i fix that?

hushed galleon
#

its more likely that you saw a message like this in your first attempt py RuntimeWarning: coroutine 'fetch_user' was never awaited the warning means that you didnt await the asynchronous method fetch_user()

#

its correctly written as await bot.fetch_user(...), where await is in front of your method call

#

also you should not have id() around target1 when you're getting their name attribute

viral stump
#

ty

upbeat gust
#

what are you looking for-

elfin plume
#

bruh

upbeat gust
unkempt canyonBOT
elfin plume
#

iโ€™m stupid

upbeat gust
#

!d discord.Client.guilds

unkempt canyonBOT
versed comet
#

what is the command to update pip?

rustic crater
vale wing
versed comet
#

thanks ๐Ÿ™‚

slate swan
#

How do i do that?

alpine cove
#

hyperlinks?

#

(text)[link]

#

or the other way around

#

its the same for markdowb

half oxide
#

Hey guys, in making a chatbot and using

elif 'time' in message.content:
    await message.channel.send(now)```
, the reply i get is `Tue Nov  8 12:43:46 2022`
Any way to make it more presentable?
like keep it in an embed and Date: the date Day: the day like so?
loud junco
#

anyone know any website for online database?

#

i mean this works right?

slate swan
slate swan
slate swan
loud junco
loud junco