#discord-bots
1 messages ยท Page 125 of 1
why did u add sleep?
i handled 2 of them that happens quite frequently
and what do u mean ur not getting the roles?
?
u need to defer in the callback
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...
where do i add "defer"
top of the callback
thne all of ur response.send_message turn into edit_original_message
uhh didnt understand where
at the top
the beginning of the callback
before async?
no
defer_help_callback
?
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
Maybe you just forgot to respond to the interaction
That could easily be used maliciously
!d discord.Guild.channels
property channels```
A list of channels that belongs to this guild.
this dude has fuck skid in his bio then ask for code to send a message in every channel lmfaoooo
Nope
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
is that an interaction related to views?
No, just a regular slash command interaction
and whats the error you see on discord?
Interaction failed to respond
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?
Would those be caught under commands.Error or something like app_command Error?
i mean if u have any error handler then that's probably ur issue
on_app_command_error event
do you have any?
nope
@commands.Cog.listener()
async def on_command_error(self, ctx: commands.Context, error: commands.CommandError):
if isinstance(error, commands.CommandNotFound):
return
...
only this
Yeah
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
it does not, d.py has a dedicated handler for that
though perhaps hybrid commands would still invoke it
because it's not correct
how would it be correct?
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())```
only other thing i could suggest is are you responding to the interactions themselves? properly
as in interaction.response.send_message(...) or something?
is there any other way to this
yeee
Yes, at the end of the command that is called
instead of having a huge code
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
not sure what u mean by that. i sent u the proper way to add a cooldown to the button
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
lmao]
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
can u show an example ?
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
overriding on_error event could also be the problem, if you did
what does @registered do ?
I took it out and still the same problem. It's just a check to see if the user is in my database
yes
i got it to work ๐
it might be taking more than 3 seconds causing the interaction to timeout
noice
And it won't send an error for that?
question
how can I do #code-of-conduct like that
how can I get the id?
yeah it should raise an error when you do interaction.response.create_message, that's the weird part
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
It would make sense if that was the error, because my university wifi has been a pain for interaction with the database
right click
interaction.response.send_message()? It's not even getting to that line if it's a database issue
or how can I do [#code-of-conduct](/guild/267624335836053506/channel/783829285227462697/) like that
just put a backslash in front of the channel
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
hm how about you add some print statments to see till what part does your code gets executed? or use icecream
\[#code-of-conduct](/guild/267624335836053506/channel/783829285227462697/)
Yeah, I've been doing that with print statements to debug my code up until this point. The problem is, even if it's not a database error, it still doesn't show anything
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
do you have custom logging setup?
I don't think so...
c.mention
when u create the channel it gets returned. and u assigned it to c. channels have a mention attr.
which would highlight the channel like so
#discord-bots
Is it normal to have the indent at the second @ here?
discord formatting
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?
i see can you just send all of your code if it doesn't have any data that can't go public or if its not too much
you would have to store the time in a database or a file or something, can't store it in the code if the bot goes offline
db
My bad I needed to turn my phone sideways ๐ forgot that happens
how would i make it compare the times?
it's quite a bit of code, mutliple files and stuff
pull the data and compare
i- ill try- thanks xD
Okay, on_command_error is not catching it, so that's not the problem
i would say between ur internet issues and ur db it's hanging up ur bot entirely. what db are you using?
postgresql on railway
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
@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
doesn't that have an async api?
yeah, it actually looks like the code is stopping on database.connect()
database = PostgresqlDatabase(database=data['postgreSQLparams']['PGDATABASE'],
**{'host': data['postgreSQLparams']['PGHOST'], 'port': data['postgreSQLparams']['PGPORT'],
'user': data['postgreSQLparams']['PGUSER'],
'password': data['postgreSQLparams']['PGPASSWORD']})
are the credentials correct or not?
they are
It's probably a timeout issue
but that wouldn't explain why nothing else gets caught
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
https://docs.peewee-orm.com/en/latest/peewee/database.html#async-with-gevent
peewee has async impl too but it doesn't look very promising
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 #
do other parts of code work?
like other events and commands
@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
when do you call database.connect()?
i mean i used sqlite3 all the way up to about 700 guilds without any issues lmao
in an started event or something?
dont ask how
anyone?
do you develop on one computer? I want to use sqlite 3 but its so hard to develop from 2 computers
wdym? like mulitple monitors?
Sooo it sounds like I'll be good for a while then 
In the RequestUser init. But even without that, nothing is getting caught
i use a discord message as my database
multiple computers
ehhh i wouldn't suggest that exactly lmfao. i just dk how i lasted so long
oh no. just one pc
Well I mean it's being run from localhost so I don't expect queries to take long at all..
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
yeee but when multiple run it at once.
ohhhhhhh. oracle cloud has a cracked host free tier
for hosting and stuff. it would prob solve alot of ur issues. also always free
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)
i would look into it
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
hmmm weird
why can't you just have a seperate db for development and another one for prod
which sounds like it could be my problem, but even with nothing related to a database at all, the interaction is still failing
wait am i actually stupid. that's a genius idea
well this fails because u don't respond to the interaction itself
its just a .db file anyways
just noticed that. trying it now
Ah I see. I'll have to look for one that I'll need to make minimal changes for
sqlite databases are cheap lol
@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
so you're saying have an sqlite3.db file on each computer and use one for testing and another to host everything?
Isn't this mitigated with connection pools?
yeah exactly
I think I tried that but I was trying to transfer over the sqlite3 file and it really wasn't liking it
the library might handle those connections in different threads, but if their API doesnt support async/await, your event loop's thread will still get blocked whenever you call a method that has to wait for a query to finish
!d discord.InteractionResponse.send_message - set ephemeral to true
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.
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
https://discordpy.readthedocs.io/en/stable/api.html#discord.Guild.create_text_channel
the documentation provides an example for this: ```py
overwrites = {
guild.default_role: discord.PermissionOverwrite(read_messages=False),
guild.me: discord.PermissionOverwrite(read_messages=True)
}
channel = await guild.create_text_channel('secret', overwrites=overwrites)```
how do u get someone's name from id
people also make them because they need them, its not always just a trend
i dont think it was ever a trend
is this for a command? or just in general
it's always been a thing imo
yeah you don't even get that shiny verified developer badge now
*shitty
i have the id in database and i wanna output the name based on that
ah ok
i do
they made it shitty by the way they got them lmao
after 6 months break :D
thats why they shitty lmfao
you could make an API request with Client.fetch_user() to get a user object from their ID, which includes their name
wonder where is those dudes that i met last time tho
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
can i do it without requesting?
like adding the <@> thing
i forgot how already
yeah that could work as well, depending where you use it
mention them also can
<@id> is the format
thanks thanks
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)
}
long += f'{n+1}) <@{userid}>\n'
```is this how u do it
no. u already have the role obj
ignore n+1 KEKW
thats fine
just make sure its part of the message content
n=0
long = ''
while n <= db[f'{id}matchplayers']:
userid = f'{id}player{n}'
long += f'{n+1}) <@{userid}>\n'
n += 1
this doesnt work any help?
i mean, you can put mentions inside an embed, but discord clients wont always resolve those mentions
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'
roles
interaction.guild.role doesn't exist.
s
apparently your userid has the text 'player1' at the end?
?
interaction.guild.role: discord.PermissionOverwrite(read_messages=True)
how can I fix this?
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
thats what I have?
oh right you defined userid right there
There's no such thing as guild.role
yes exactly. which i pointed out to him.
so how can I get a custom role in?
bud
u literally already defined the role
Use the role object
the 103 blahblah is the channel id btw
.
role = interaction.guild.get_role(1039176031422132224)
so id should be the one going inside the <@id> format, and not including player{n}
interaction.guild.role:
id = ctx.channel.id
does not exist
userid = db[f'{id}matchplayer{n}']
db[f'{id}player1'] = ctx.author.id
assuming that gives you the user's id sure
n = 1 in this case
key-value db for relational data must be horrendous to use
so how I make it exist?
oo i realised something
i forgot to add db[]
you already have your role object, just use it as the key in your overwrite dict
?
role = guild.get_role(...)
overwrites = {
role: discord.PermissionOverwrite(read_messages=True)
}```
!d discord.ext.commands.Context.message
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.
heh
i want to delete msg
await channel.id(overwrites=overwrites)
Then use that to delete it
can I do this?
It returns the message that triggers the command
so i do ctx.message.delete?
!d discord.Message.delete
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.
Yes
await ctx.message.delete?
ok thanks
np
question, is there a "filename".write() command for deleting stuff
You mean delete file?
no, a line containing a certain word
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
Does anything work at all or just this command not working
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?
could have the bot check each existing channel in the server and look for a specific channel name or something
Yeah I could, the ticket is named with the interaction users name and then ticket. Also all tickets are grouped under a certain category
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
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
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
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
channel topic?
this
but the database route that Blvck talked about might be a better way
up to you, good luck with the bot
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
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
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
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
I'll make sure to inform them
You should only make one connection
Otherwise they might crash the entire bot lol
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?
I make a connection for each action I perform
lets say I want to write to it I create a connection perform the action then close the connection
Sounds like you get rate limited?
That's not recommended
Really I was told that was preferred as sqlite cant peform two actions simulatenously
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
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
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
lol ight
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
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
how to make a shard?
uhm usually this doesn't happen with aiosqlite, which program did you use to open the database?
sqlite
i mean to open it manually
yes sqlite
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
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
I prefer mongo db
then it should work
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
because TextChannel.topic returns None if the topic is blank
Ohhh
can someone help with this?
how can I make it so only the member role cant talk
it just makes it so you cant see
the top one says read_messages not send_messages
ctx.guild.default_role: discord.PermissionOverwrite(read_messages=False)
This is what you have
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)
}
is that not your goal?
Are you trying to make some sort of ?lockdown command?
no
yea
only the members cant send messages
if I use .ticketmute
everyone in your server has the member role i presume?
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
@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
what
damn the more you know
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
is that not the member role?
that is
exactly
ro = ctx.guild.get_role(1038630407622635570) #member
you made it so members cant speak but everyone has the member role
therefore everyone cant speak
yea but it makes it so ppl can see it
Yes
Everyone can see it but nobody can speak in it
you need to define a staff role and give it permission to speak
What?
Why would you do that
i need help thats why
I think your not understanding what im saying
the part with the members is correct
im so confused
yes
They can't speak in a channel if they can't see it
and it still doesnt work
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
how can I do that?
Are you using slash commands>
Just double checking you want them only able to not speak in the ticket correct?
await channel.set_permissions(interaction.user, send_messages=False)
It would work like that
what no
You would change the permissions of the channel for the user
Channel = the ticket
well technically that code would make it so the person who executed it cant send messages
instead of interaction.user use the owner of the ticket
my bad
Yea whoever opened the ticket with the button would be interaction.user correct
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
So you'd have to specify who's ticket you're muting then. I see
Yeah
if he stores the ticket owner for each ticket somewhere he could design it to go .muteticket #ticket8378
Sorry I like to lurk on my free time
learning things lol
Kekw fair enough
I actually have an issue of my own
What you got going on I've got 30 mins lol
I'd love if you could try to help me with it
Out of curiosity, why do you want the ticket to become visible to everyone after muting the ticket?
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
@winged linden i have an idea
Otherwise it will check other peoples tickets who obviously dont have the same id and then it creates a new channel
Yeah?
get every user and then set the person who doesnt have helper or mod role to a var
then set that persons perms
Or you could just store the owner of the ticket
and then change the specific owners permissions
Instead of making an if true statement why not make an if false? Then it would have to check them all, if it's not there perform the action, else do something else
eh
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
Yeah
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
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
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
ohh that could work alright let me give it a try
Hi cereal ๐
Hello
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'
How could I check the user ID against the list without running into the same issue
@winged linden idk how to do what you where saying but this is my thought and error
If userid in channellist:
Do a thing
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)
Ok heres my idea: when creating the ticket you store to owners id somewhere.
then when you run mute ticket it grabs the owners id for the specific ticket
then it changes the channel permissions for the specific owner only
idk how to do that
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
if role not in user.roles or rol not in user.roles: what is rol?
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.")
The problem in question is that it performs this for every channel the user ID is not in and creates a new channel for every channel they aren't in. Why I suggested putting the channel IDs in a list to compare
np
I yeah I just noticed I could contribute with a tip ^^
Solid tip though it's a lot of extra nonsense lol
@winged linden could you help me acheive this?
Achieve what?
it still made a new ticket im going to cry
store it in the channels topic
and just make sure nobody changes the topic
Still made a new ticket if their id is in the channel topic?
You could also use a database
Yep.
I could just mute the user in the ticket...
using .mute @rich otter then override the permissions
Yes
that would work because since you pinged the user you can use it as a parameter to edit the channel permissions
Print your list and user ID to compare in console and see why it said it wasn't in the list
Yeah let me print it
Did you try reading the error you posted before this
You defined user as a list of user objects and you're trying to get the roles attribute from the list itself, not from each individual element of the list
@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
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
append adds an element to the end of a list
Yeah wait so it should be working
the list only contained one id
and I believe it was the last channels
question, is there a "filename".write() command for deleting stuff
well what was meant to happen
How did you write the for statement
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')
you're re-defining listchannel as an empty list each time the loop runs
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?
I could but then if two people have the same name it would cause issues
This was discussed earlier, 2 users could have the same username or tag which is why they're using IDs.
IDs are unique to the user.
yea so you could just do id in the ticket

I was so confused
{interaction.user}-{interaction.user.id}
I've stored their id in the channel topic
and im checking the channel topic to see if it matches with their id

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 ๐
What you're trying to get at here is what is happening right now. The problem was it was inside a for loop making a new ticket open for every channel not containing their ID
I forgot since the list starts from 0 I have to do +1
this is why you have to make sure you name your variable correctly so they're relevent. Don't name listchannel a list of topics you'll get confused ^^
ok sensei ๐
Or like 30 different embeds with the name embed
Lmao I try to specify between them throughout my code to avoid my own confusion
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 ^^
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 
That's the user ID not the channel id?
because you are comparing a string to an int
Yes its meant to be the user ID
OFBIPFOC]#]
user id is int
maybe it's time to take a little break and come back later before you lose your motivation being stuck
I took a 2 day break already ๐ญ
Yes but TextChannel.topic returns a string
I hadn't even thought of that tbh
you need to convert the topic string to an int
@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?
Did you get any errors
Nice make sure to test it thoroughly under all possible scenarios to be sure it works
Yes, apparently the people in the server im making the bot for will attempt to break it
I lost my motivation months ago hahaha
Nice. Now wouldn't it break in the event that the channel topic contains alphabetic characters?
Discord bots do get a bit dull after a while
Seems like it'd be safer to convert ID to string instead of topic to int
It wont
the channel topic is just the owners id
...until it does
just asking questions
I'm guessing that will never happen if all other channels in the category are just other tickets, but it is a valid point
but just to be on the safe side
no errors
Ill do it anyway
.
?
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
can somebody help me out rq
Thats going to cause issues
how?
If two people have the same username
What exactly isn't it doing? That's a good place to start
no?
What's your question
it doesnt stop the user from making a 2nd channel
your checking if cname is in channel
so if their name is in the channel
it going to print that
your checking their name not their id therefore interaction.user.id has no purpose
wat
Guild.channels returns a list of channel objects
You're searching for a string inside a list of channel objects
my elif doesnt work for some reason
Send the applicable code and any errors you're getting
ephemeral means disappearing right
Means only the person involved in the interaction can see it
Great thats what i need
Moreso hidden than disappearing
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:
if i change the if to elif it doesnt work
no errors but this doesnt work
@winged linden
^^
syntax error, mb
In one statement you use == and the other you use in
anyone pls
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
Text channels on Discord have a name attribute
I gotta go though, back to jury duty 
Cya
wait so what do i do
There's other people that can help
๐ฆ
Unindent with to the same place as elif for a start
Don't be looking at me, I'm a noob + I'm about to go cook 
so what should I do
can embed.set_image accept gifs?
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
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
Read the error
What does it say
its been responded to before
what does that mean
and it doesnt stop it from making a new ticket
so idk what to do
!d discord.Interaction.response
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.
Is there a way to check for a pinned message?
im reading and idk how to read docs
!d discord.TextChannel.pins
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.
so what should I do?
i read the docs the other guy gave me and idk what im doing
on error?
??
What does it say
and it makes 2 channels
oh my fault
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
U can't respond 2 times to one interaction

what
Your if else statement is inside your for loop
what
is that for me
prolly
@slate swan mind helping me out G?
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:
Probably because you're doing stuff between an if and elif statement
the line above works
dyk why?
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).
want me to send you the entire code?
In this example you have stuff going on between an if and an elif statement, a bit like this:
what does that mean lol
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
No, they're indented differently in the 2 images you sent.
like this?
im sorry for making it hard for you lmao
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.
i know, but i literally copied the block above and it doesnt work
dude im lost
sorry, what version of python requires the latest version of dpy?
lots of things work, i'm just having trouble when they don't work and I get no error
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```
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?
i suggest u store time stamps or something similar in a dict and check
add xp at the end or evaluate that dict in a tasks loop
!d time.monotonic
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.
won't asyncio.sleep(120) work?
inefficient also if u were to scale up the bot u can store the dict so it works on restart of the bot the sleep i dont think so
Using DB should work aswell, right? I have a code rn that stores datetimes but idk how to start a timer with that
look here is the thing u store user key and a timestamp run a taskloop fetch time subtract from current time find diff based on this diff give xp
u would be better of asking the questions instead of asking for ppl
i been here long enough
u never edited the message
last pic i dont see any (edited) tag
edit the message duh
does on_raw_reaction_add support unicode emojis
yes
You need to have the message object then message.edit with the new embed
Using for-loop to loop through all the keys? Isn't that inefficient aswell?
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
This may be what you're looking for https://discordpy.readthedocs.io/en/stable/interactions/api.html?highlight=edit_original#discord.Interaction.edit_original_response
Not too familiar with editing messages yet tbh
whats the easiest way for me to check if a user has a role during a slash command
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
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
what would it be get(roleid)
ahhh thanks
much better than using asyncio.sleep
having a function on wait for every member
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
u think so?
idk man I'm kinda 'scared' to use for loops for maybe 5k+ keys
lmao
This code is ancient
if u dont even have confidence in the language and its capacities idk what to say
Just iterate over a list of strings, open the file and write your name there
plz dont do anything with files in a discord bot ;-;
!pypi aiofiles
i got aired
No u
this is all blocking code and will misbehave and cause bugs in file and bot alike
better to use a db
Yes
right so what should i do
Depends on case tho
use a sql (postgresql) or no sql (mongodb) db
even if its info needed in runtime its better to have only static data never edit data and just load it before loading bot
txt and json files are not made for asynchronous purposes and is likely to cause corruption if made writes to concurrently
thats why you should use csv files
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
aiosqlite 
Anytime kirby
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
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
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
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

You can mention an app command object? Does that mean like in the command when you click on it or a subcommand
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>
Wild
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
I'm just going to make a help command with the names of my commands as subcommands
just use an option with those commands as choices
Yea that's what I meant
Default value = None
an optional option i.e. ig
Is there a way to make my own list like this?
truly the most inconvenient way to mention them ๐
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
they are command choices
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
So I can set my own strings as command choices?
yep
!d discord.app_commands.choices
@discord.app_commands.choices(**parameters)```
Instructs the given parameters by their name to use the given choices for their choices.
Example...
Thanks
i knew it would be some weird deco like that, that was a random guess 
or just use typing.Literal
yeah that works too if you don't want the name and value of the optionchoice to be different
as a note, choices are pre-defined and limited to 25 max (per argument), but the alternative is "autocomplete" options where you define a callback that can return up to 25 choices based on what the user's currently typed
oops wrong message reply
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
yup ๐
anyone?
send full exception please
nvm
its @discord.ui.select, not @discord.ui.Select
breh
Oh God i hope I don't make it up to 25 commands on this bot
but that's good info to know
its not limited by the number of commands, its just per argument
if you make a bot that already doesn't exist you won't end up making these many commands
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
ow what is the bot about?
i see, that sounds interesting
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
roleplay servers* are gonna use that bot a lot
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
Could I see the SelectionList class?
!paste
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.
You can only have 25 options is what it's saying
Fuck
There's also autocomplete as mentioned above
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
async def specify(self, interaction: discord.Interaction, select: discord.ui.Select):
i dont think callbacks for views take the select as well. i believe it's just (self, interaction: discord.Interaction)
it worked thanks
nah
?
it takes self interaction and the select
but why are u passing the select itself into the callback?
Hi Robin? you fancy allow me have a tiny conversation in DMs please? It's regarding my new job that I'll soon start I kinda have some insecurities and I don't want to talk about it publically ^^
Sure!
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
Send code, explain what you expect it to do vs what it actually is doing as well as any error codes you get
ok
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
Class method probably instead of constructing it regularlly
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```
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
this more of a #databases question, but the most preferable answer would be performing this calculation within your SQL query directly using the SUM() aggregate function, i.e. py cursor = conn.execute('SELECT SUM(column) FROM table') total: int = cursor.fetchone()
Sorry about that, I never really know where to ask so I just go here because I'm making a discord bot
Boy I did that very different in my code
result2 = await db.execute("SELECT SUM(Amount) From Database1 Where UUID = ?", [value])
``` ?
Wouldn't this cause issues later on? Granted you're working with discord.py so expect multiple tasks per command callback which doesn't do to well with singletons
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)
๐ญ
sure, something like that
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
guess what, dpy never told you this but modals make deep copies of their items so they cant interfere with other concurrent callbacks
https://github.com/Rapptz/discord.py/blob/master/discord/ui/modal.py#L115-L117
discord/ui/modal.py lines 115 to 117
for name, item in self.__modal_children_items__.items():
item = deepcopy(item)
setattr(self, name, item)```
this is so cursed
it would be nice for this behavior to have been documented, but at least its there
is this with discord.py? to get a username from an ID, you need to fetch the user object from the discord API using your client
!d discord.Client.fetch_user
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.
yes, this is with .py so i will use this command and after that?
i am rookie sorry about that question's stupidity
fetch_user() returns a User object, and that has the .name attribute containing the name of whoever's ID you fetched
like that one? await fetch_user(victim_user_id)
ohh wait
kind of, but fetch_user is a method of your Client/Bot instance
This is my first time seeing this
I didn't know that kek
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()
Well, that's good at least they thought about that
can also use guild.get_member if the member is in that guild to avoid making api calls.
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
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```
The error says it all, client is not defined. Perhaps you meant bot?
this seems more of an issue with the translate package you're using, but looking at their source code you dont seem to have written anything wrong with it
id ask in your own help channel about it though (#โ๏ฝhow-to-get-help), and also consider using an asynchronous library for translation instead
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?
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
ty
what are you looking for-
bruh
The guildโs ID.
iโm stupid
!d discord.Client.guilds
property guilds```
The guilds that the connected client is a member of.
what is the command to update pip?
would anyone be able to look in #help-pancakes, its related to a bot
python3 -m pip install -U pip
thanks ๐
How do i do that?
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?
Oh thanks!
like hosting the database?
garbage
yeye
LOL

