#discord-bots
1 messages · Page 214 of 1
what are you trying to do?
if a channl is called chat in a specifc category them after an hour it gets deleted and remade
ooohh tyy
it will return the chat channel
^ but getting channel with id is much safer
i cant
Why
because the channel is deleted and re-created
Hmmm
Instead, I think one way that is safer, unless any of ur staff edits the spacing of the channel, is to iterate through all channels and check to see if the name u give us the same as the category name. But without the emoji. That way, if u edit emoji but u keep the channel called chat, u will still be able to retrieve the channel.
ohh
I can write you a code example if u need
i think it should be alr for now, if not ill let u know
trying to get the last 10 messages in a channel but i'm getting an error
ur trying to flatten that method
instead flatten m2
async def on_message(message: discord.Message):
chan = message.channel #finds channel of message
print(chan)
chann = chan.id
print(chann)
m = discord.utils.get(message.guild.text_channels, name=chan)
m2 = await m.history(limit=10)
m3 = m2.flatten()
print (m3)```
well ur m variable isnt getting assigned
r u sure theres a channl with taht name
and ur bot has perms
From the print (chan) and print (chann). so It knows what the channel name is
I gave my bot admin acess
but print m
says m is None for some reason
there isnt a channel with the as the var chan
in the list of channels u provided
and chan is general
when I test it
I gtg but let me know if u know how to fix it
what are you even trying to do? if you want to read the history of the channel use message.channel.history directly....
Which would you say is currently better?
Discord.py or Pycord or Nextcord?
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
there are even more
I getting a headache
just use whatever you're fine with
i personally would recommend Disnake or discord.py
||i personally would recommend nextcord 🤫 ||
That isn’t specifically a bot question, but more for a general python question. U may get more help in gen or help channel.
But seems that u don’t have an empty list
everybody asks for non-discord bot stuff all the time in here
the list is returned it's just empty
I know. Which is why I said they may get better help in general or text channel.
Is u try accessing an element from a list, u will get that error
yes, but you said a list isn't being returned which is not true
Could any of you help me figure out why my /viewcard command isn't working? The bot says that the card is not recognized. Here's the relevant code: https://pastebin.com/u0Waa9qG
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
For example, if I do "/viewcard Jhett [Standard]", it responds with "Card not found: Jhett [standard]"
can you use prefix and slash commands in 1 bot
Here's the /openpack command for reference on how they are added to the db:
if so how
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Yes u can!
For my code, I separate it into cogs.
I have cogs that are dedicated to slash commands and cogs that are dedicated to prefix commands
The difference is ```py
@app_commands.command()
vs
@bot.command()```
just use both
im getting sh AttributeError: 'str' object has no attribute 'send'
@commands.Cog.listener()
async def on_member_join(self, member):
with open("welcome.json", "r") as e:
fr = json.load(e)
message = fr[str(member.guild.id)]["message"]
channel = fr[str(member.guild.id)]["channel"]
if "{user.mention}" in message:
message.replace("{user.mention}", member.mention)
await channel.send(str(message))```
and what is channel
what do you mean by channel? the channel its trying to send to?
or?
ur channel variable
await channel.send()
the channel variable is getting the channel id from a json file it saved to to get the channel ID and send it but its not working
Well, u cant send an id, its returning a string object. U need to use the client to get the channel from the id.
channel = client.get_channel(channel_id)
ah yeah i forgot about that
get_channel isn't a coroutine
!d discord.Client.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
I didnt even know u could pass it in as a kwarg before 
@commands.Cog.listener()
async def on_member_join(self, member):
with open("welcome.json", "r") as e:
fr = json.load(e)
message = fr[str(member.guild.id)]["message"]
channel = fr[str(member.guild.id)]["channel"]
frr = int(channel)
channelf = await self.bot.get_channel(frr)
if "{user.mention}" in message:
message.replace("{user.mention}", member.mention)
await channelf.send(str(message))``` so this would work

no
it's not a coroutine like i said remove the await]
what do u need help with
U shld be using prefix commands
the bot is not answering me
capital P
oh nvm
U never used capital P
print out and see if on_message even runs
@slate swan you should migrate into prefix commands, it will be much better than running in events
how can i process ?
print hi in the on_message function to see if it is actually being called
Maybe u dont have intents enabled/passed in
wait
huh
he is calling discord.Client() without anything
wdym
not two
client = discord.Client is being called and he didnt pass intents in
@client.event
async def on_message(message):
print("Called")
if message.content == "Ping":
await message.channel.send("Pong")```
2 sec
u need to enable intents @slate swan
how ?
intents = discord.Intents.all()
client = discord.Client(intents=intents)```
I think thats correct.
just migrate to:
client = commands.Bot(command_prefix = "", intents=discord.Intents.all())```
commands is not defined
how can i define it ?
from discord.ext import commands```
good ?
you should hide your token, as someone could generate and check the other 4 digits
Delete the two on_messages and do py @client.command() async def ping(ctx): await ctx.send("Pong")
yeah i know
yes. but test with the command
ik
see if that worked
how so
when i started the script, the window were closed instantly
@slate swan could you help me ?
Reset your token and have you installed discord.py?
sure
Pardon?
Can you hover over the yellow underlined text? And may i ask, do you have several python versions?
whats not working
And do you have all of your intents enabled in dev portal?
worked because i just activated this presence intent
look at my username
Oh 2 days ago
@young dagger :x: Your 3.11 eval job has completed with return code 1.
001 | File "/home/main.py", line 2
002 | existing_tier_rank = Gold 3
003 | ^
004 | SyntaxError: invalid syntax
@young dagger need help?
How is return outside function?
return isn't in a function...
!e
tier_and_rank = None
existing_tier_rank = 'Unranked'
if tier_and_rank is None:
tier_and_rank = existing_tier_rank
if tier_and_rank != "Unranked":
tier, rank, lp = tier_and_rank.split()
tier_and_rank = f"{tier} {rank}"
print(tier_and_rank)```
@young dagger :white_check_mark: Your 3.11 eval job has completed with return code 0.
Unranked
!e
tier_and_rank = None
existing_tier_rank = 'Gold 3'
if tier_and_rank is None:
tier_and_rank = existing_tier_rank
if tier_and_rank != "Unranked":
tier, rank, lp = tier_and_rank.split()
tier_and_rank = f"{tier} {rank}"
print(tier_and_rank)```
@young dagger :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 7, in <module>
003 | tier, rank, lp = tier_and_rank.split()
004 | ^^^^^^^^^^^^^^
005 | ValueError: not enough values to unpack (expected 3, got 2)
!e
tier_and_rank = None
existing_tier_rank = 'Gold 3'
if tier_and_rank is None:
tier_and_rank = existing_tier_rank
elif tier_and_rank != "Unranked":
tier, rank, lp = tier_and_rank.split()
tier_and_rank = f"{tier} {rank}"
print(tier_and_rank)```
@young dagger :white_check_mark: Your 3.11 eval job has completed with return code 0.
Gold 3
intents = intents
can i get a help for bot devlopment here??
yes
hi, I am using app_commands.Group for another file how would i put a task.loop into that file?
same as a regular cog?
can anyone tell how to set up discord.py cuz i am not able to download pip
Does anyone know of a way in xml.etree to get specific fields of a POST response? I’m trying to get that information to post as a message to my discord bot
you mean groupcog??
you can't download it without pip
i guess download the wheel manually or something
Yea i figured it out though
Mhm I knew XML is used as data transmission format in web but never encountered it
hello, I am using slash commands but i want to use a commands.GroupCog but i can't get it to load the extenstion because client doesn't have an attribute load_extension How do i make this load a cog without a prefix?
extensions and cogs are different things
cogs can be in extensions but you can also have an extension without a cog
clients dont have extensions
only bots
ok so how do i load a commands.GroupCog
u use bot
Did you read
i did read
await load_extension(name, *, package=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Loads an extension.
An extension is a python module that contains commands, cogs, or listeners.
An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.
Changed in version 2.0: This method is now a [coroutine](https://docs.python.org/3/glossary.html#term-coroutine "(in Python v3.11)").
but
They just said client doesn't support extensions
so how do i redo this because the other way involves a prefix
I used bot but it said that the tree command was already being used but then when i removed the statement it said it was undefinded
property tree```
The command tree responsible for handling the application commands in this bot.
New in version 2.0.
It's already there
now's it says tree is not defined
.
it's all slash commands
And?
so it's just sitting there collecting dust ok
how do I specify a tasks start and end without the def init at the top?
def cog_load:
?
set the prefix to commands.when_mentioned and remove help command
hi i am hosting my discord bot locally currently.. and i wanted to host it 24/7 is there any good services to host it? btw, it is a discord play "currency" and multipurpose bot
you can check pinned messages in this thread
oh ok
!pypi discord.py
Try downloading it from here maybe
is there any discordpy readthedocs alternative?
What
ummm whats my problem ?://
Can you check if a user is in a guild if member intents are disabled?
You're using parenthesis () instead of curly braces {} for a dict
Even if there is why would you ever use it
Discordpy's docs are one of the best I've seen tbh
No
bruhhhh whats the problem ://
You are trying to send something outside of a function
aha
@shrewd fjord :x: Your 3.11 eval job has completed with return code 1.
001 | File "/home/main.py", line 2
002 | await hello
003 | ^^^^^^^^^^^
004 | SyntaxError: 'await' outside function
the search feature didn't work
This is how the error occurs
You will always need to await something under async func
And?
If he removes await it isn't gonna help
Who said him to remove tho,
He need to await it anyway
Just saying him how the error occurs and what to do 
What do you think what you told him tells him?
That await shouldn't be outside an async func
Ye
You told him what to do?
What you told is to put it in a async func right?
This is simple just add "async" behind the def 🗿
What's so hard about that fr
Do you not see that it's not even in a function
Fr it doesn't work for some browser, but it does work on chrome tho
I can see a space tho
I use R Danny search instead
Maybe idk, i didnt use that IDE so lol
What?
This is simply indentation
Ikr, i saw a space between line numbers so i thought there is a space mb
how do i use but respond only if message content greater than 80? idk how to explain it
if '80' in message.content
len(message.content)
if len(message.content)>80:
#do stuff
I told ya i didnt use that IDE 🗿, also i was only focusing to the error 
So ig forgive me 
How does the ide matter
Bro gone crazy mode
GUI?
does it count the number of words or compare the numbers?
Same way of showing indentation? Spaces? Or use an ide that use something different to show indentation? Colors?
I'm trying to create register form
The len(...) Just returns how many "chars" on the string and the > 80 compares it
?
I mean all IDE's workspace layout isnt same 🗿
Actually leave the topic fr, lets not argue 💀
Hm cool
!e
chars="Tyrion"
print(len(chars), type(chars))
@shrewd fjord :white_check_mark: Your 3.11 eval job has completed with return code 0.
6 <class 'str'>
!d len
len(s)```
Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).
**CPython implementation detail:** `len` raises [`OverflowError`](https://docs.python.org/3/library/exceptions.html#OverflowError "OverflowError") on lengths larger than [`sys.maxsize`](https://docs.python.org/3/library/sys.html#sys.maxsize "sys.maxsize"), such as [`range(2 ** 100)`](https://docs.python.org/3/library/stdtypes.html#range "range").
So I just changed my python version but now
import discord says - import “discord” could not be resolved
install discord.py on your current python version
how?
Tried pip install
Try specifying your python version first

pythonx - m pip
or on windows maybe
pyx - m pip
I think that's the windows one i'm not sure
Tried python-3.8 -m pip install discord
But it says CommandNotFoundException
its discord.py
Still the same
What do I do now?
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Guild' object has no attribute 'icon_url'
duds whats problem ?
The error just told you
If I treat the error in the error handler and also treat it in a specific command, who then accesses it?
No documentation found for the requested symbol.
property icon```
Returns the guild’s icon asset, if available.
It's Asset.url eh i forgor
Both actually i think
discord-py-slash-commands isn't being recognised
I pip installed it and it's in the same environment and I am running it correctly but it just wont accept the fact it's there
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.utils' raised an error: ModuleNotFoundError: No module named 'discord_slash'
discord-py-slash-command 4.2.1
can someone help?
use discord.py 2.0
ok
!d discord
In order to work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
..
pip install discord.py
the bot’s ping depends upon what factors?
your internet and discord's servers
you can't do much about the latter
and distance between ur host and discord server
altho that dosent matter as much as ur internet speed
mhm
I believe you can host your bot on the specific AWS region that Discord is also hosted it - it'll give your bot practically 0 ping
Not sure if it's exactly AWS but I do remember hearing something about that
how can i fetch a category
!d discord.Client.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
shouldnt this return a CategoryChannel too?
that is apparently how discord structures their category payloads (parent_id being the source of *Channel.category_id)
https://discord.com/developers/docs/resources/channel#channel-object-example-channel-category
though its weird that GuildChannel.category_id isnt documented despite it being declared as an attribute, i guess their sphinx configuration considers it undocumented?
https://github.com/Rapptz/discord.py/blob/v2.2.2/discord/abc.py#L360
discord/abc.py line 360
category_id: Optional[int]```
wait rlly?
yea look at infernum's screenshot, its not listed there
?
nothing
Well, if I treat the error in the error handler and also treat it in a specific command, who then accesses it?
me
Lmao
?
the command
the lib checks for more specific error handlers first
you mean like
@bot.command()
async def command(ctx):
pass
@command.error
async def command_error(ctx, error):
pass
@bot.event
async def on_command_error(ctx, error):
pass
command_error treats the errors of command
How can I make the task to run once at the time?
async def calculate_mmr_async(summoner_id, RIOT_API_KEY):
elo_rating = await calculate_mmr(summoner_id, RIOT_API_KEY)
return elo_rating
@client.command(name='checkmmr')
@commands.guild_only()
async def checkmmr(ctx, summoner_id):
task = asyncio.create_task(calculate_mmr_async(summoner_id, RIOT_API_KEY))
elo_rating = await task
embed = discord.Embed(title='',
description=f'Your elo: {elo_rating}',
color=discord.Color.blue())
await ctx.send(embed=embed)```
To allow multiple users to run !checkmmr at the same time, but only one instance of calculate_mmr will be executed at a time?
so you want to wait?
what do i have to do ?
pls help me
in dm so ?
no...
lol
ik lemme just send the pfp
Why am I getting Unexpected argument when I use @tasks.loop(days=4) and not @tasks.loop(hours=96)
the screen
i already do that how create own bot cmds
like a generator of accounts
i just copy cat
tasks.loop doesn't have a days argument
also, tasks.loop is unreliable because if your bot restarts it will reset the loop
So I just have to 24 x 4 then?
or 96
just don't use tasks.loop for that long of a time
im done with prefix
save it to a database
How can I use it with a database? Can you give me an example?
hmm sure
slash commands?
ty the boss of the boss
simple as that
Hi im making a discord bot for keyauth basically i have the keyauth.py file in the same directory but there is a variable there i want to called
"failed_register"
ive tried doing from keyauth import * but its no use can anyone help
you don't have to pass it
it's optional
it's just for command metadata
Metadata
extras (dict) – A dictionary that can be used to store extraneous data. The library will not touch any values or keys within this dictionary.
.
What metadata diserve
Ok
anything you want
@client.command()
@commands.is_owner()
async def nuke(ctx, user: discord.User = None):
for i in range(5):
await ctx.send(user.mention)
await ctx.message.delete()
hmmm how do i ping everyone?
by typing in @ everyone
do you have allowedmentions?
try f"<@&{ctx.guild.id}>
interesting
can anyone help i want to make it so I can call a "def" in a discord bot function e.g
def sendmsg(ctx):
await ctx.send("HI")
@bot.command()
async def sayhello(ctx):
sendmsg(ctx)```
there are a couple things wrong
- sendmsg needs to be
async defand needs to be awaited because it uses a coroutine (context.send) inside - the inside of the sendmsg function needs to be indented
- you need to pass the ctx argument to sendmsg
alr thanks
so like this??
def sendmsg(ctx):
await ctx.send("HI")
@bot.command()
async def sayhello(ctx):
await async def sendmsg(ctx)```
no
async def is for a function definition
await is for calling the function
so move the async to before def
so u mean??
async def sendmsg(ctx):
await ctx.send("HI")
@bot.command()
async def sayhello(ctx):
await sendmsg(ctx)```
yeah
can u help me with something in dms i can pay if u want
discord.py related
should be pretty simple for u
We can help here!
We don’t do stuff for pay.
can we go dms its abit lengthy
and I want to attach a file if thats okay
Let’s keep it here 🙂
what are you having trouble with?
U csn make a help channel if u need
basically, I have two files
my main.py (my discord bot)
and keyauth.py (basically an api not sure how to describe it)
now keyauth.py has a function register, i want to call that from the discord bot it all works well it registers an account with the details provided however it prints "Sucessfully registered" to console I want it to display it as a message on a discord bot I cant find a way to do it.
I can attach files if needed ❤️
ive tried even that wont work lol
Why not?
literally just copy and pasted the code from keyauth.py into main.py and tried editing the function etc to send a message in a discord bot instead of printing it
U can import the module.
And error?
no error just dosent send
Did u try printing to see if it is called
def register(self, user, password, license, hwid=None):
self.checkinit()
if hwid is None:
hwid = others.get_hwid()
init_iv = SHA256.new(str(uuid4())[:8].encode()).hexdigest()
post_data = {
"type": binascii.hexlify("register".encode()),
"username": encryption.encrypt(user, self.enckey, init_iv),
"pass": encryption.encrypt(password, self.enckey, init_iv),
"key": encryption.encrypt(license, self.enckey, init_iv),
"hwid": encryption.encrypt(hwid, self.enckey, init_iv),
"sessionid": binascii.hexlify(self.sessionid.encode()),
"name": binascii.hexlify(self.name.encode()),
"ownerid": binascii.hexlify(self.ownerid.encode()),
"init_iv": init_iv
}
response = self.__do_request(post_data)
response = encryption.decrypt(response, self.enckey, init_iv)
json = jsond.loads(response)
if json["success"]:
print("successfully registered")
self.__load_user_data(json["info"])
else:
print(json["message"])```
keyauth.py file ^
Let me see bot code
And ur bot is online? And u have all intents?
you aren't sending a discord message in that code though
He said that isn’t the file with the bot code
@bot.command()
async def register(ctx, arg1, arg2, arg3):
user = arg1
password = arg2
license = arg3
result = keyauthapp.register(user, password, license)
if result == "success":
await ctx.send("Registered")
else:
await ctx.send(result)
the "if else" statement dosent work lol just found that out
register isn't returning anything
what should I return?
Or returning the wrong thing
no it's not returning anything
U said u want it to return success
why make it return "success" and send a message based off that? return the "Registered" and just send whatever it returns via the bot
im new to all this
in the keyauth.py file they do "if json["succes"]:
so I thought i would try the same
Where do I start with all this discord bot with python stuff. I’m kinda past that beginner point of python
Where do u return it tho
Are you experienced with python
What counts experienced?
do you have any knowledge of async programming and async patterns?
No💀
or object oriented programming / classes?
i dont believe i do
I heard of it before but I’m not 100% sure
but result is none
then you will probably find it hard
I think u shld learn that first.
So what things should I learn to make learning a discord bot easier?
Yes. U return success if it is successful or whatever the other option is. But I do not suggest that method, instead, I would return a boolean
Learning OOP, getting a general idea of how the event loop and coroutines work, and type hinting.
It is for converters/transformers.
i was thinking of a boolean however when theres an error
else:
print(json["message"])``` it returns the error message e.g "username already used" or "key not found"
Ah ok then
i wouldn't call converters type hinting
nevermind
No, the hint is what uses the converter.
If u hint, Optional, it will be optional in discord.
So yes, type hinting is required.
lol
What?
at the top of my code I did
success = None
if json["success"]:
print("successfully registered")
return success
self.__load_user_data(json["info"])
@bot.command()
async def register(ctx, arg1, arg2, arg3):
user = arg1
password = arg2
license = arg3
result = register(user, password, license)
if result == "success":
await ctx.send("Registered")
else:
await ctx.send(result)
this would work right? I slimmed down the register func
to the main part of code
I think a lot of this shld be worked out.
Why do u have json["success"]
no because success is still none
just do return True instead
def register(self, user, password, license, hwid=None):
self.checkinit()
if hwid is None:
hwid = others.get_hwid()
init_iv = SHA256.new(str(uuid4())[:8].encode()).hexdigest()
post_data = {
"type": binascii.hexlify("register".encode()),
"username": encryption.encrypt(user, self.enckey, init_iv),
"pass": encryption.encrypt(password, self.enckey, init_iv),
"key": encryption.encrypt(license, self.enckey, init_iv),
"hwid": encryption.encrypt(hwid, self.enckey, init_iv),
"sessionid": binascii.hexlify(self.sessionid.encode()),
"name": binascii.hexlify(self.name.encode()),
"ownerid": binascii.hexlify(self.ownerid.encode()),
"init_iv": init_iv
}
response = self.__do_request(post_data)
response = encryption.decrypt(response, self.enckey, init_iv)
json = jsond.loads(response)
if json["success"]:
print("successfully registered")
return True
self.__load_user_data(json["info"])
else:
print(json["message"])```
i really appreciate you guys doing this I spent 1-2 hours going through forums etc I didnt wanna ask here and sound like an idiot since im new to all this
Np! Why do u overwrite response tho?
that will work
i didnt write def register its included in the keyauth.py they send u to include in your dir and import it to use the api
There are things we need to fix.
https://github.com/KeyAuth/KeyAuth-Python-Example this is for console based application im just trynna intergrate register function to discord bot
U wouldn't be overwriting response, so change that.
what one?
u overwrite response
oh.
why not
alr thank you so much btw may I ask how did u learn all this im still learning im 14 and I find this really interesting
Why do that?
because you're using response while overwriting it
Its pointless. Just add another var.
i'm also 14
Still, it should be in a separate variable.
No reason to use the same name.
thats great man how long have u been coding for?
there are more things to nitpick than just that
about 6 years
damn
Delete both response lines, and do this ```py
response = encryption.decrypt(self.__do_request(post_data), self.enckey, init_iv)
In practice, it's is less prefferd to use to one variable name like that. Assigning two varaibles makes it more modular. But since that is the only use, it is better to just pass that directly into the function.
Unless u wanna make a temp.
at least split it up into multiple lines
response = encryption.decrypt(
self.__do_request(post_data),
self.enckey, init_iv
)
temp = self.__do_request(post_data)
response = encryption.decrypt(temp, self.enckey, init_iv)```
temp is not a very descriptive variable name either
That is readability purposes. Doesn't have any general purpose.
what is the purpose of not overwriting response though
readability is one of the most important things in python
It is descriptive, because it is saying its a temp variable. There is no point in arguing on the specifics.
temp variable of what though
Usability. That way U can use that value if u want. If u dont wanan use it, u might as well pass the function in directly.
It's common practice 
@bot.command()
async def register(ctx, arg1, arg2, arg3):
user = arg1
password = arg2
license = arg3
result = register(user, password, license)
if result == "success":
await ctx.send("Registered")
else:
await ctx.send(result)
``` do i need to change result == "succes": to result == True or something or success == True
not really
have it return a boolean and just do py if result: ...
Erm... yes. A lot of people use temp variables.
im guessing thats saying if its true so I can use an else statement to see if its false
if you're not using it, there's no point in storing it as a variable and calling it temp does not help other people that are reading the code
Exactly
💀 thats why my first example was passing in the function directly.
This argument is pointless.
Less move on.
your example stretched too long, that's why i recommended to split it up
but you insisted on the temp variable name
ok though
I didnt
I said its a good alternative.
Ur response after I sent the message was that, it isn't a good name.
it should send the else statement on the second command as the username and key have already been used
wait I think I know why I didnt return false
Did u have register return false?
nope just fixed
Perfect!
U aren't awaiting a method.
nah the issue is from discord.py (probably)
something is async that shouldn't be i guess
U sure?
Is register a coroutine?
Actually, it must not be.
why would it be Command.__call__ if it's with register
Cause the message was getting sent.
True, but a lot of times, errors like those can produce via user errors.
Maybe not this time, but it is good to check.
thanks for the help guys i guess ill wait till tmrw for a keyauth admin to assist he knows discord.py aswell and he said he could assist me tmrw I think it would be easier for all of us!
it is a user error
the error is happening while discord.py is trying to call some coroutine without await
are you sure you mean to be recursively calling your command and not some other function?
huh
if you have a function named register() but also want a command named register, you can use the command(name=) parameter to set that name without shadowing your first function, i.e. py @bot.command(name="register") async def register_command(ctx, user, password, ...): ... or you can rename your other function instead
oh YEAH
whats the best i can use to use apis in my bot? isnt it aiohttp.ClientSession()?
Wdym?
like
ima start on a lastfm command right
and it uses an api
whats the best i can do that with
is it aiohttp.ClientSession()?
aiohttp as a library yes
alright
aiohttp supports more than just that
i never worked with apis before rly so
it even has server support
so whats the best i should use to work with lastfm api?
wdym
Wait nvm I misread what u said
Im not saying it is an api, im saying im going to use the lastfm api and im wondering what the best thing is i can use haha
allg nw
Yes aiohttp is good.
alright 👍
It will help prevent blocking.
I'm a beginner, I would like to know which library you use to make slash commands
If u want to make slash commands in python.

There’s something I wanna solve an issue to my modmail but I have very low knowledge with coding. I asked about 3 times here and all 3 times, it was a different answer. May someone help me to literally rewrite my code to help me solve my issue?
Hey, im trying to figure out a way to import slash commands in discord.py, most of them requires guild ids and only works in the server im testing it in. plz help 🙏
What question do u have?
Importing slash commands? R u talking abt the module.
from discord import app_commands
Hi! When a user types in the bot’s dm, this text appear. From there, they can choose if they want to create a ticket or cancel the interaction. Although, we found a glitch that if you send 2 messages, the text will sent twice and then, you will be able to create 2 tickets at once. Can someone help me to code so that the embed stops resending everytime they type in? My script is: https://paste.pythondiscord.com/yidukekala
I don't believe any of them require guild IDs
If you just leave it off entirely they become global commands
@gusty flax
What do you want the bot to do when you said "H" in that screenshot?
Send me the embed
But only once.
Like it wont send it a second time if I resend another text
But in the screenshot, it already sent it once?
Nope! Did it twice
The embed sent once
So when you said "H" it shouldn't have said anything, is that correct?
Got it. Just trying to figure out what the intended behaviour was.
How I'd go about doing it is having somewhere where you would store all the created tickets, and if a user tries to create another one, it'd just deny them saying "You already have a ticket open" or something similar
This external source would probably be a database
That’s not it
They can send multiple messages when there’s no opened ticket
And then, spam accept on every embeds and create tons of tickets
And I dont want the embed to send more than once
Yes. So the first time they click "accept", it would create an entry in the database for them
Next time they click "accept", your bot would check the database to see if there's already an entry
There is, so the bot just wouldn't do anything
That works
But I still don’t want the embed to send more than once anyways
Like this
That's going to be a quite a bit more difficult
Yeah but that’s really important
Is there something wrong with just sending a message saying the user already has a ticket open?
Why is it imperative that that the embed doesn't show at all?
Yes, the embed is big and its aesthetically not beautiful lol
You could just set a timeout on it
Wdym
Once the view times out (say 30 seconds), the embed is deleted along with the view
You could do that
You could also just delete the embed entirely
Up to you
You'd just remove the view by passing view=None into the edit method
What would that do
Removes the view without touching anything else
What is view
A "view" is conceptually a container that holds all of the components in a message - I believe that's only buttons and select menu as of now
Each message can have at most 1 view
Right.
The exact time-out behaviour is up to you
Either way you'd use the on_timeout method of discord.ui.View
alright
Any website to help me? Im new at coding lol
Or maybe you could help me out
That’s up to you
All of this is quite complex, I'd say 🤔
These examples may be able to help you out: https://github.com/Rapptz/discord.py/tree/master/examples/views
There's also the Interactions API documentation: https://discordpy.readthedocs.io/en/stable/interactions/api.html
Is it something like this @sick birch ?
async def ask(ctx: commands.Context):
"""Asks the user a question to confirm something."""
# We create the view and assign it to a variable so we can wait for it later.
view = Confirm()
await ctx.send('Do you want to continue?', view=view)
# Wait for the View to stop listening for input...
await view.wait()
if view.value is None:
print('Timed out...')
elif view.value:
print('Confirmed...')
else:
print('Cancelled...')```
This will create a basic confirmation view sure but not really what you want
Do you have an underlying database?
I have one database that contains closed ticket and member id I tuink
Update your schema so it includes a relation between user IDs and their opened tickets
I*
How
Perform database migrations if you need to (alembic is quite nice)
Depends on the database, but you can just run SQL queries to directly update it
I much prefer working with ORMs so I can't be of much use in that area
My script is here btw https://paste.pythondiscord.com/yidukekala
For some reason my buttons of my VoiceMaster stop working after a while, is there any way i can fix that?
@dense jackal whats ur question? Sry I had dinner
@gusty flax
Do you have your timeout set to None?
We’ll create a list of users called is applying, and before u send it, check to see if the user is in that list.
How??
It automatically timesout unless u say otherwise
As said yeah im not really experienced
Well, the problem is that I need it to be always useable, so how would I fix that?
Create a list in ur class that will be the overarching class, and pass that list reference to where u send the view. Then add that user to that list the users who applied.
In the init of the view, do py super().__init__(timeout=None)
I would recommend appending that to a database.
So it persists.
^^
hey this is kinda not discord.py related but Idk where else it should go im using it as part of my discord bot can I just send here its about requests
Imma need more assistance than this lol
Do u have a specific question about what I described? That will help me help you the best I can 🙂
i just need help stripping a few things from requests content
Like what?
it returns this I just wanna strip the b'' part but keep the KOTH-JOB-F60
Can we just do what you said step by step? Like
- find the class in your script,
- add this script to the class :
Etc
That would be better
Where do u send the view?
response = requests.get('url')
key = response.content``` my code
Ah, well u wanna do data.text
so change response to data and do data.txt?
text*
Leave the name. The name can be whatever u want
class TicketButtons(discord.ui.view) right above my buttons @gusty flax
Wat
So it can be py response.text
ahh
Whatever is being assigned to the response.
perfect thanks
Where is that view sent tho?
Why is it subclassing ui.view
It should be ui.View
def __init__(self):
super().__init__()
self.author_name = None
self.author_id = 0
self.avatar = None
self.content = None
self.message = None
# If they click reject do this
@discord.ui.button(label="Reject", style=discord.ButtonStyle.red)
async def reject(
self, interaction: discord.Interaction, button: discord.ui.Button
):
await interaction.response.send_message("No new ticket has been submitted. Thank you :)")
await self.message.delete()
# if they press accept do this
@discord.ui.button(label="Accept", style=discord.ButtonStyle.green)
async def accept(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message("A new ticket has been created! Please wait for a staff member to respond.")
guild = bot.get_guild(1081721180123320413)
category = bot.get_channel(1081726505496887327)
admin_role = discord.utils.get(guild.roles, name="Reports")
overwrites = {
guild.default_role: discord.PermissionOverwrite(read_messages=False),
admin_role: discord.PermissionOverwrite(read_messages=True)
}
modmail_channel = await guild.create_text_channel(f"{self.author_name}-modmail", overwrites=overwrites, category=category)
await add_user(discord_user=self.author_id, channel_id=modmail_channel.id)
embed = discord.Embed(
title="New Modmail Ticket",
color=discord.colour.Color.brand_green(),
timestamp=datetime.now(),
description=self.content
)
embed.set_footer(icon_url=self.avatar, text='\
Sent by {}'.format(self.author_name))
embed.set_author(name=self.author_name,
icon_url=self.avatar)
await modmail_channel.send(embed=embed)
await self.message.delete()```
It is,
This is your view thing ig
!code
class TicketButtons(discord.ui.View):
def __init__(self):
super().__init__()
self.author_name = None
self.author_id = 0
self.avatar = None
self.content = None
self.message = None
# If they click reject do this
@discord.ui.button(label="Reject", style=discord.ButtonStyle.red)
async def reject(
self, interaction: discord.Interaction, button: discord.ui.Button
):
await interaction.response.send_message("No new ticket has been submitted. Thank you :)")
await self.message.delete()
# if they press accept do this
@discord.ui.button(label="Accept", style=discord.ButtonStyle.green)
async def accept(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message("A new ticket has been created! Please wait for a staff member to respond.")
guild = bot.get_guild(1081721180123320413)
category = bot.get_channel(1081726505496887327)
admin_role = discord.utils.get(guild.roles, name="Reports")
overwrites = {
guild.default_role: discord.PermissionOverwrite(read_messages=False),
admin_role: discord.PermissionOverwrite(read_messages=True)
}
modmail_channel = await guild.create_text_channel(f"{self.author_name}-modmail", overwrites=overwrites, category=category)
await add_user(discord_user=self.author_id, channel_id=modmail_channel.id)
embed = discord.Embed(
title="New Modmail Ticket",
color=discord.colour.Color.brand_green(),
timestamp=datetime.now(),
description=self.content
)
embed.set_footer(icon_url=self.avatar, text='\
Sent by {}'.format(self.author_name))
embed.set_author(name=self.author_name,
icon_url=self.avatar)
await modmail_channel.send(embed=embed)
await self.message.delete()```
…
Doesnt make a difference
@gusty flax https://paste.pythondiscord.com/yidukekala.py its at the end
It shld be discord.ui.View
Or ui.View
That’s what they have…
^^
Kk let me see

I’m on mobile so give me a sec
Alright
Where do you actually send the view?
Idk, am I supposed to send it somewhere
That’s how the view shows up. U send it.
Mhm then idk where I send it, a friend did this code lol mmmhhh
I can’t do control f rn. Check where u instantiate TicketButtobs
The class TicketButtons thing?
Damn alright lemme try to find
What should I try looking for?
A certain keyword?
Found it I tuink
ticketbuttons = TicketButtons()
ticketbuttons.author_id = ctx.author.id
ticketbuttons.author_name = ctx.author.name
ticketbuttons.avatar = ctx.author.avatar.url
ticketbuttons.content = ctx.content
confirm_message = await ctx.reply(embed=embed, view=ticketbuttons)
# This is so the confirm embed is deleted. Don't want errors in our database
ticketbuttons.message = confirm_message```
@gusty flax
You can just take those as arguments
So that’s not it?
can someone help me with datetime? im working on adding a 'deleted amount of seconds to a snipe command idk how to count the time since the time stored in the db'
Do i have to add something else anywhere else? like at the buttons ui or?
what library are you using @slate swan ?
will that just be enough
datetime
Yes that’s where. Here u wanna append to the list.
^
What do you mean
It encompasses the whole view.
ok
Talk in beginner terms
for your database
so i dont need to add timeout=... anywhere else in my code, but just there?
Per view
huh
oh i use mongodb with the motor library
now im confused
what's your code? are you passing a datetime object
Make a list for now, for the ppl who are in the process. So where u send the view, u want to know that user is storing it. So u add to a list and in that list will be a list of ppl in the ticket or whatever. That means u can’t do it if u are already in the process.
For every view, if u never want it to timeout, u gotta put that in each init.
ooh
How do I do that?
this my code and this is the error im getting ValueError: time data '21:18:43.319858' does not match format '%I:%M:%S.%f'
you should just write the datetime object to the database, don't bother with strptime
motor will convert it automatically
Do you know how to make a list?
this is what it is posted to the db when a message is deleted what should i change this too then?
Just set it as timestamp at this point
Well I think its like list() or sum
!d datetime.datetime.timestamp
datetime.timestamp()```
Return POSIX timestamp corresponding to the [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") instance. The return value is a [`float`](https://docs.python.org/3/library/functions.html#float "float") similar to that returned by [`time.time()`](https://docs.python.org/3/library/time.html#time.time "time.time").
Naive [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") instances are assumed to represent local time and this method relies on the platform C `mktime()` function to perform the conversion. Since [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") supports wider range of values than `mktime()` on many platforms, this method may raise [`OverflowError`](https://docs.python.org/3/library/exceptions.html#OverflowError "OverflowError") for times far in the past or far in the future.
For aware [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") instances, the return value is computed as:
```py
(dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()
``` New in version 3.3.
Changed in version 3.6: The [`timestamp()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.timestamp "datetime.datetime.timestamp") method uses the [`fold`](https://docs.python.org/3/library/datetime.html#datetime.datetime.fold "datetime.datetime.fold") attribute to disambiguate the times during a repeated interval.
Not rlly tbh
🫠
@dense jackal are you making the modmail bot?
Yes!
wow
I only have 2-3 more things and I’m done with it
Alot of people helped me tbh, I needed a quick made modmail bot. I’ll learn coding more deeply later
ok it posted this to the db. do you know how i could get how many seconds since the current time? i want to add a 'deleted 5 seconds ago' or however many seconds to the bottom of my snipe command
I think reviewing the basics of python would be beneficial before finishing it. A list/array is a required data type for any type of programming.
Cant we just get it done in like 10 mins
Though a list is:
my list = []
That’s like one of the last things I need
Do you know what a list is?
Like store multiple stuff
Make a var called is_applied in the init of ur class.
In one variable
It will be a list
I resell think u shld just go over basics first. A list is one of the first things u learn
This is the init of my class?
I’m not trying to be mean, but I am just hurting ur learning rn 😦
why not just use a formatted discord timestamp
Yeah ik but-
<t:1678930560:R>
No.
how can i do that? i've tried using the time in the db on the footer it just never works and doesn't return an error
I really think u shld just go over basics quickly first.
!d discord.utils.format_dt you can't use it on the footer
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.11)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
Rushing it without knowing what u are doing will cause more problems.
Or get Unix TS themselves
/j
Can you just resume what I need to do and I’ll try to understand with this?
Cause I dont want to have to ask again here any sooner
For the same thing again
It's hard for me to describe what you need. Do you have your code, where you instantiate the view, within a class?
That’s what I sent earlier
ticketbuttons = TicketButtons()
ticketbuttons.author_id = ctx.author.id
ticketbuttons.author_name = ctx.author.name
ticketbuttons.avatar = ctx.author.avatar.url
ticketbuttons.content = ctx.content
confirm_message = await ctx.reply(embed=embed, view=ticketbuttons)
# This is so the confirm embed is deleted. Don't want errors in our database
ticketbuttons.message = confirm_message```
Nah not that. I just checked ur script. It isn't in a class.
Then idk
So at the top of ur file, underneath py bot = commands.Bot(command_prefix="=", intents=discord.Intents.all()) do ticketer_list = []
On the line under?
So before u do ```py
confirm_message = await ctx.reply(embed=embed, view=ticketbuttons)
Hm?

Ticket_list or ticketer_list?
name doesnt matter.
I mean you put ticketer_list earlier so does it have to be the same thing the second time?
yes its the same thing. i just messed up the names
Then in the first line of the on_message function, do py if ctx.author.id in ticketer_list: return
But that wont persist even if bot goes down.
That will require a db. But as long as bot is online, this is good.
But pls, check out the basics.
Lmao alright
If the bot goes down the embed wont be sent anyways
why not just save the tickets to the database
Okay, can I hug you now, your my life saver
Wdym by that
❤️
Theres a problem @gusty flax
They can't do that yet, they need to learn basics.
Well then, where they interact, remove them from list.
They can, just not easily
Wait how
hey, i have a general question, if i wanted to make custom boost messages when a person boosts the server, how should i do it? is their any event for the boost request for guild updates?
I mean if you can help me, why now /shrung
Check to see if the booster role is assigned to someone.
If they press reject, or the modmail ticket is closed, remove them from ticket.
so i make a role event, and check to see if the member got assaigned the booster role?
Ofc there are more factors to consider, but this is simplist.
No, if they click on closed, the procedure of opening one is closed
well u determine where u want it to go.
just giving them the code won't help
What’s the command tho, to remove them
I said ill learn after
Basically and yes it does help a bit
I've told them many times to review the basics. But they will ask for help anyway, I might as well help and explain it as I go.
Cause im understanding at the same time
^
Lol
You can keep telling that to yourself but there's no way to understand code if you don't know the syntax and fundamental concepts behind it
ticketer_list.remove(userid)
hi zefo
^^^
Good morning mudkip, how's your pyweek going
It will be easier for me to understand afterwards then
that seems easy, all your doing is after the close class if they close it, it will go to another class that gets the channel ID and save all the messages that are in the chat, or they could just potentially scrape HTML, but thats against discord's ToS
wdym the theme isn't announced for like another week
Ohh
Thats how i would have done it tbh
scrape html
I do not think that is the right way to go 
bots do not have access to html
its not but alot of ticket bots do that with beautiful soup & redirects with access headers 
It wouldn't be hard to get 
get the html of what though
Either way, the person doesn't have programming experience, so this is way out of their league.
I assume the discord page.
from the bot owner's account
Which is kinda a rlly weird thing to do.
Keeps saying userid isn’t defined. Ive tried with ctx.author.id and same thing (ctx isnt defined)
That was a placeholder 
Alot of verified ticket bots do this 
This is why u need to review basics.
This isn't a verified bot 
Scrape HTML to save messages?
I doubt that; I'm pretty sure they generate html and add the messages via the channel history endpoint, with some css to mock the look of discord's UI
^ I also bet that is against TOS.
It bypasses message content intent.
We don't do that here 😄
Hey, how do you close/delete a dropdown after interacting with that said interaction?
How would that be formatted at the end of the callback?
actually just do self.clear_items()
if you're deleting the whole view
@idle surge what does your code look like
class Inviter(discord.ui.Select):
def __init__(self):
options=[
RANDOM OPTIONS
]
async def callback(self, interaction: discord.Interaction):
rant = random.randint(0, 0xffffff)
value=rant
channel = vini.get_channel(1085711629775294516)
userss = len(interaction.user.voice.channel.members)
usersize = await interaction.user.voice.channel.create_invite()
embed = discord.Embed(title=f"Need More People!",colour=value, description=f'To invite others to your voice channel simply go to [#1085711668622921988](/guild/267624335836053506/channel/1085711668622921988/)`. \n \n :point_right: [Click this link to join this parties voice channel.]({usersize}) :point_left: \n \n')
embed.set_author(name=f"{self.values[0]} LFG", icon_url=vini.user.avatar.url)
embed.add_field(name=":loud_sound: Voice Channel",value=interaction.user.voice.channel.name, inline=True)
embed.add_field(name=":map: Game",value=f'{self.values[0]}', inline=True)
embed.add_field(name=":family_mwgb: VC Size",value=f'{userss}/10', inline=True)
embed.set_footer(text=f'Requested by {interaction.user} | {interaction.message.guild.name}', icon_url=interaction.user.avatar.url)
await interaction.response.send_message(f"Your invite has been created at [#1085711629775294516](/guild/267624335836053506/channel/1085711629775294516/)", ephemeral=True, delete_after=3)
await channel.send(embed=embed, view=Close(interaction.user))
what does your view look like though
So this is basically grabbing the information for the class but the actual view I want to delete is this:
@discord.ui.button(label="Create Invite", style=discord.ButtonStyle.blurple, emoji="🎮")
async def blurple_button(self, interaction:discord.Interaction, button:discord.ui.Button):
channel = vini.get_channel(1085711668622921988)
embed1 = discord.Embed(colour=0x25F8F8)
embed1.description ='Click the dropdown and choose the game you are wanting to play.'
embed1.set_footer(text = 'PC Gaming')
if not interaction.user.voice:
await interaction.response.send_message(f"Please join a voice channel. {interaction.user.mention}", delete_after = 3, ephemeral=True)
await interaction.response.send_message(embed=embed1, view=InviterView(), ephemeral=True)
class InviterView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
self.add_item(Inviter())
i don't know if this will work but maybe do
self.inviter = Inviter()
self.add_item(self.inviter)
...
self.remove_item(self.inviter)
Okay, ill try it. Thanks.
Got this:
AttributeError: 'Inviter' object has no attribute 'remove_item'
nah, still doesnt work. Just nothing happens. No error.
how do i create a list with 100-199, 200-299, 300-399, 400-499 ?
besides doing only every single one
!e
print(list(range(100, 501)))
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
[100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299,
... (truncated - too long)
Full output: https://paste.pythondiscord.com/epiyurupum.txt?noredirect
thanks i forget the basics some times
!d discord.utils.format_dt
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.11)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
x == y Checks if two embeds are equal.
New in version 2.0...
How do I make slash commands inside a cog
!d discord.app_commands.command
@discord.app_commands.command(*, name=..., description=..., nsfw=False, auto_locale_strings=True, extras=...)```
Creates an application command from a regular function.
I have this in my cog but I still don’t see the command And I use await bot.tree.sync()
Send the code
of?




