#discord-bots
1 messages · Page 965 of 1
I replaced it with my on_message
cool, recheck if you really did that.
Lol
- listen is only be used with commands.Bot
- you can have multiple listeners but only one event ( of same kind)
- there are multiple ways to do an listener
never used on_message before tbh 🤷
Oh
Never?
I've used on_message_delete
I’ve never used that
🏃♂️ i use MessageCreateEvent
it's used for making a snipe command
I’ve never new what a snipe command is?
What does a snipe command do?
how can i make a command only to be used in a particular guild?
basically when a user deletes a message it retrieves the deleted message
So they been sniped
just use an if statement and return if its not the server you want py if ctx.guild.id != your_server_id: return
@client.command()
async def example(self, ctx):
if ctx.guild.id is not 1234564789: #This is the wanted guild id
return
#code here
k ty
Ok so I've added the following:
@bot.command()
async def ping(ctx):
await ctx.send(f'The bot\'s latency is {round(bot.latency * 1000)}ms')
but the bot won't reply, any idea why?
is the latency super high?
can I see all of the code.
make sure its above bot.run()
import discord
from discord.ext import commands
import requests
import json
token = 'token'
intents = discord.Intents(messages=True, guilds=True)
bot = commands.Bot(command_prefix='.', intents=intents)
@bot.event
async def on_ready():
print('The {0.user} bot has logged in!'.format(bot))
@bot.command()
async def ping(ctx):
await ctx.send(f'The bot\'s latency is {round(bot.latency * 1000)}ms')
bot.run(token)
ye i just removed that to see if that was the problem but it still has the problem even with parenthesis
I suggest using time btw
I still can’t figure this out
bot.time?
@client.command(pass_context=True)
async def ping(ctx):
"""**Pong!**"""
before = time.monotonic()
message = await ctx.send("Pong!")
ping = (time.monotonic() - before) * 1000
await message.edit(content=f"Pong! `{int(ping)}ms`")
print(f'Ping {int(ping)}ms')
@blissful sparrow using time package you can do this for ping.
What is bot.time?
just make sure to add import time to the very top of your code @blissful sparrow
You new to discord.py?
Yup
Oh ok
@blissful sparrow try this out
did you try this?
yup
let me see all of your code again
import discord
from discord.ext import commands
import time
import requests
import json
token = 'token'
intents = discord.Intents(messages=True, guilds=True)
bot = commands.Bot(command_prefix='.', intents=intents)
@bot.event
async def on_ready():
print('The {0.user} bot has logged in!'.format(bot))
@bot.command(pass_context=True)
async def ping(ctx):
"""**Pong!**"""
before = time.monotonic()
message = await ctx.send("Pong!")
ping = (time.monotonic() - before) * 1000
await message.edit(content=f"Pong! `{int(ping)}ms`")
print(f'Ping {int(ping)}ms')
)
bot.run(token)
ok remove what I told you to add
done
@bot.command()
async def ping(ctx):
await ctx.send(f'Pong {bot.latency}!')
try this instead,
Still refuses to reply :/
where are you hosting the bot?
is there a documentation for buttons on d.py docs?
if yes may i have the link?
local as of rn
it's apart of the
https://discord.com/developers/docs/interactions/message-components
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
@client.command()
async def ping(ctx):
await ctx.send(f"**__Pong! {round(client.latency * 1000)}ms__**", delete_after=5)
isnt this better?
well his bot isn't replying so as of now no
ive been at it for a while and idk why its not replying
um not this
im asking about discord.py/readthedocs one
it has admin perms and message intents
!d discord.ui.Button
class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.
New in version 2.0.
@bot.command()
@commands.has_permissions(manage_roles=True)
async def welcome_setup(ctx, channel: discord.TextChannel, *, message):
with open('welcome.json') as f: data = json.load(f)
data[str(ctx.guild.id)] = {}
data[str(ctx.guild.id)]['channel_name'] = channel.name
data[str(ctx.guild.id)]['channel_id'] = channel.id
data[str(ctx.guild.id)]['message'] = message
with open('welcome.json', 'w') as f:
json.dump(data, f)
await ctx.send("welcome channel setup")
async def on_member_join(member):
with open('welcome.json') as welcome_file:
data = json.load(welcome_file)
channel = data[str(member.guild.id)]["channel_id"]
channel = member.guild.get_channel(channel)
message = data[str(member.guild.id)]["message"]
await channel.send(f"{message}")
Guys why isn’t this working
I’ve dumped the message into the json file
@blissful sparrow
@bot.command()
async def exx(ctx):
await ctx.send("Sent message!")
try this for testing purposes
just do your command prefix then exx
what editor are you using, or ide?
VSC
are you sure you installed discord.py
yup
what python version do you have?
isnt dpy discontinued
erm sec
no
i thought they stopped working on it
It is recontinued
OH
No documentation found for the requested symbol.
YES
what the
oh thank the lord
3.10.2
@bot.command()
@commands.has_permissions(manage_roles=True)
async def welcome_setup(ctx, channel: discord.TextChannel, *, message):
with open('welcome.json') as f: data = json.load(f)
data[str(ctx.guild.id)] = {}
data[str(ctx.guild.id)]['channel_name'] = channel.name
data[str(ctx.guild.id)]['channel_id'] = channel.id
data[str(ctx.guild.id)]['message'] = message
with open('welcome.json', 'w') as f:
json.dump(data, f)
await ctx.send("welcome channel setup")
async def on_member_join(member):
with open('welcome.json') as welcome_file:
data = json.load(welcome_file)
channel = data[str(member.guild.id)]["channel_id"]
channel = member.guild.get_channel(channel)
message = data[str(member.guild.id)]["message"]
await channel.send(f"{message}")
Guys why isn’t this working
I’ve dumped the message into the json file
Oh heck json again
im looking for some $20 optiplex i can host my bots on
The message won’t send
Show your JSON file and tell me if you are getting any errors
Also do you have error handlers
{"channel_name": "testing", "channel_id": 946000818891526144, "879646357940473866": {"channel_name": "discord-server-bot", "channel_id": 879658500312170496, "message": " joined the server"}, "942442967174623322": {"channel_name": "testing", "channel_id": 946000818891526144}, "856209570384707635": {"channel_name": "welcome", "channel_id": 868148492638490664}, "919206575841869865": {"channel_name": "general", "channel_id": 919206575841869868}}
@blissful sparrow try using a different editor, I recommend Thonny
do yall prefer dpy over djs
Yes
Do you have
else:
raise error``` at them?
On what?
Handlers
That’s exactly what I have
For my error handle
Do you mean how much
else:
raise error
Or other types
It should be at every error handler I think
Wdym?
You can have only one "else" per if construction this makes no sense
No I have only 1
1 handler?
No
Ig you get no errors because of improper error handlers
This is what I mean
All the inner bodies should look like this
if isinstance(error, ErrorClass1):
...
elif isintance(error, ErrorClass2):
...
...
else:
raise error```
Including locals
What’s a global handler
Idk about locals much but you should try to raise the error in them
I’m using both
Also you have 2 functions named the same
True
I’m going to change that
Ok done
@formal basin try adding simple raise error in those local error handlers
Why?
I’ve never used raise error on a local
What do I do?
You can remove it later
@client.command()
async def test1(ctx):
button1 = Button(label="click me", style=discord.ButtonStyle.green, emoji="😀")
button2 = Button(label="Hello!", style=discord.ButtonStyle.green, emoji="😀")
button3 = Button(label="Hi", style=discord.ButtonStyle.green, emoji="😀")
button4 = Button(label="test", style=discord.ButtonStyle.green, emoji="😀")
view = View()
view.add_item(button1)
view.add_item(button2)
view.add_item(button3)
view.add_item(button4)
await ctx.send(f"Hello!", view=view)
i used this code and started the bot
no errors were there in console but the command is unresponsive
You may also comment them out
Your current objective is to find where the program stops working
Oh heck that construction
Why not subclass the view
So
@command.error
async def command_error(ctx, error):
raise error
await ctx.send*(“message”)
I don't see anything wrong with that anyways
@formal basin forget it just comment out the local handlers
Wdym comment out
Select them and CTRL + /
I’m not on computer
Understandable
So how can I do it
Then go with raising
So
@command.error
async def command_error(ctx, error):
raise error
await ctx.send*(“message”)
Why is ctx.send outside
Remove it at all
Cause none of code gets executed after error is raised
Should I just remove the error then paste it back when were done?
All of the local errors
Should I just remove the error then paste it back when were done?
Eh wait we are working with event sorry for that
Wdym
In on_member_join print channel
print(channel)
Yes
What did you get
You want me to run test it?
Yeah
Ok 1 sec
class MyView(View):
@discord.ui.button(label="click here", style=discord.ButtonStyle.green, emoji=":emark:")
async def button_callback(self, button, interaction):
await interaction.response.send_message("hello")
@client.command()
async def test1(ctx):
view = MyView()
await ctx.send("Hi!", view=view)
still no errors and command unresponsive
@vale wing it printed nothing
what did you invoke
wait
@vale wing I fixed it
do you have message_content intents?
nope
The problem was I didn’t have @bot.event
Why does my bot doesn't respond to commands in v2.0? / Why is message.content not there.
Discord.py v2.0 has migrated to api v10, and with this has come the introduction of Intents.message_content, which is disabled by default.
This means that you will need to __explicitly enable it in code and in the panel, at https://discord.com/developers/applications
intents = discord.Intents.default() # All but the THREE privileged ones
intents.message_content = True # Subscribe to the Message Content intent
bot = commands.Bot(command_prefix='-', intents=intents) # Pass the intents into your commands.Bot or discord.Client
``` NOTE: Still not responding to commands? see `?faq on_message` in #playground
k
@vale wing I have a new problem
I want to do like ?welcome_setup #welcome {member.mention} joined the server
did you update to 2.0
pip install git+https://github.com/Rapptz/discord.py
But it doesn’t mention the user
this error pops up
is there a way to read a text file in a specified format?
like this:
user#0001 5 10 30
so it would read user#0001 as the author, 5 as test1, 10 as test2, 30 as test3, and then i could do a if statement like this:
if test1 >= 6
is it possible to leave a blank field in an embed. for example the description or the name of the field?
I recommend using a json file (if the data isnt edited often) or a proper database, you can in that way, bind values to certain keys/columns
use an invis char
Full Invisible Character: \u2800
Zero Width Character: \u200b & \uFEFF
its never edited, but idk json lol
It's to skip a line in fact
itll be added there once andthen itl be there
\n
alrdy tried
Yes
I'll try with use an invis char
\u2800
Nvm idk actually
@heavy folio
u need to have dpy 2.0 to use view
so pip install git+https://github.com/Rapptz/discord.py to install it
What does this error mean?
ur json is empty?
{
"author": "user#0001",
"test1":5
}
json will help you to do this
then you can do
data['author']
in your code easy peasy, json is easy to learn, wont be a big issue
Nope
that errpr poped up when im used this
no wait ur missing a comma @formal basin
what error?>
.
Where?
in ur json
once i do data['author'] does it automatically read everything assigned to the author? (test1, test2, test3)
no no xD, if you want that, you could use their own keys
check out the full logs, as the errors suggests
Oh
data['test1']
like that
you can of course, use lists in place of a single value
or a whole new dictionary
i don wanna do a dictionary
well, I'll try to help with what you have right now, can you show me your txt file
havent done anything yet, i was asking so i could start on it
wait i do have pycord 2.0
learn json, thats recommended (for data that is not edited much and is small in size)
you may have to refer to this - https://www.w3schools.com/python/python_json.asp
if ur sure that u have pycord 2.0 installed, check out the docs to see how views word for pycord and make changes
{
"user#0001": {
"test1": "5",
"test2": "10",
"test3": "30",
},
"user2#0001": {
"test1": "10",
"test2": "15",
"test3": "20"
}
}
could i not store like this?
you can, for sure
so uh how can i read it
id need to search for the ctx.authors data
so if the ctx.author is user2#0001 then it reads all the data for user2#0001
import json
def read_data("filename.json") as f:
data = json.load(f)
read this @slate swan
something like this?
import json
def read_data("filename.json") as f:
data = json.load(f)
data[f'{ctx.author}']
if test1 >= 5:
...
for voice-text channel linking, would changing channel permissions each join be bad on ratelimits?
Uhh, Guys is it on_member_join or on_member_joined...?
join
How does it work really-
whatchu need help with
When a member joins, Send a message
async def on_member_join(member):
channel = bot.get_channel(welcomechannelid)
await channel.send("welcome")
No ctx?
oh yea
xd
think u cant use ctx lol
Btw thank you
that shold work, i edited it
you also need to enable member intents in the code, dev portal and also import intents
@client.event
async def on_member_join(member):
channel = (channe_id)
await channel.send("hemlo")
What about dis?
no, that wont work
oh
ook
.
pretty sure this wont work if ur bot is public cause people join other servers and you cant welcome other server members in ur server xd
uhhh
ik?
if ur bot is for your server only then youre good to go with that
Ye its only my server
hmm?
!d intents
Hey, i have an error in my giveaway command but i dont know how to fix it ```py
@bot.command(name="giveaway")
@commands.has_permissions(administrator=True)
async def giveaway(ctx, mins : int, , prize: str):
user=ctx.author
end = datetime.datetime.utcnow() + datetime.timedelta(seconds= mins60)
embed = discord.Embed( title = "Giveaway", description = f"Host: {user}\nPrize: {prize}", color=discord.Color.gold())
embed.add_field(name= "Ends at:", value=f"{end} (in {mins}min)")
gwmsg = await ctx.send(embed = embed)
await gwmsg.add_reaction("🎉")
await asyncio.sleep(mins)
gwmsg1 = await ctx.channel.fetch_message(gwmsg.id)
users = await gwmsg1.reactions[0].users().flatten()
users.pop(users.index(bot.user))
winner = random.choice(users)
await ctx.send(f"{winner.mention} hat {prize} gewonnen!")```
Thats the error: ```Ignoring exception in command giveaway:
Traceback (most recent call last):
File "C:\Users\tim10\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\tim10\OneDrive\Desktop\Testbebo\bot - Kopie.py", line 88, in giveaway
winner = random.choice(users)
File "C:\Users\tim10\AppData\Local\Programs\Python\Python39\lib\random.py", line 347, in choice
return seq[self._randbelow(len(seq))]
IndexError: list index out of range
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\tim10\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\tim10\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\tim10\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: list index out of range```
The message does NOT have anuy reaction
@slate swan
Okay how can i convert sec in min?
elaborate
divide it by 60....
bc this py end = datetime.datetime.utcnow() + datetime.timedelta(seconds= mins*60) dont working
when you join a VC, you set access to a text channel. Should this be done with giving a role or changing channel perms
a role would be better
but is the permission changing bad?
I mean, changing permissions again and again....?
I'd choose a role tbh
Hey how can i convert the time mins? ```py
@bot.command(name="giveaway")
@commands.has_permissions(administrator=True)
async def giveaway(ctx, mins : int, , prize: str):
user=ctx.author
end = datetime.datetime.utcnow() + datetime.timedelta(seconds= mins60)
embed = discord.Embed( title = "Giveaway", description = f"Host: {user}\nPrize: {prize}", color=discord.Color.gold())
embed.add_field(name= "Ends at:", value=f"{end} (in {mins} min)")
gwmsg = await ctx.send(embed = embed)
await gwmsg.add_reaction("🎉")
await asyncio.sleep(mins)
gwmsg1 = await ctx.channel.fetch_message(gwmsg.id)
users = await gwmsg1.reactions[0].users().flatten()
users.pop(users.index(ctx.guild.me))
winner = random.choice(users)
await ctx.send(f"{winner.mention} hat {prize} gewonnen!")
who can add to my bot that every message gets logged, can pay
I dont know how can i set the timestamp to the end of the giveaway
hello, how do you do during an embed to make a footer with the time that the command took to execute. if it is a command that takes time for example put a footer saying 30s
I know how to make a timestamp but not this
And how can i do that?
yes a footer to say how long the command took to get a response from the bot
time the time it took to execute the command, and make a new embed and send that time
I'm not english so i dont understand everything u said
Not a New embed
property latency```
Measures latency between a HEARTBEAT and a HEARTBEAT\_ACK in seconds.
This could be referred to as the Discord WebSocket protocol latency.
Just as a footer
nah i think they want to time a command, not bot
Yes
time.perf_counter() → float```
Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. The reference point of the returned value is undefined, so that only the difference between the results of two calls is valid.
Use [`perf_counter_ns()`](https://docs.python.org/3/library/time.html#time.perf_counter_ns "time.perf_counter_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.10: On Windows, the function is now system-wide.
ok im gonna write some rough code but u can do this
async def func(...):
start = time.perf_counter()
...
embed = discord.Embed(...)
end = time.perf_counter
embed.set_footer(text=end-start)
await ctx.send(embed=embed)
u can change the position of end, if u want to it to include the time took to create embed to put it above embed = discord...
Okay i'll try
or use use a contextmanager-time function, if u know how they work
await is a keyword which waits for a coroutine to finish its execution
now what are you trying to do?
does await wait for a task to complete then runs another
or does it do all at the same itme
await foo()
this will only wait for foo to finish its task
what if
do
await foo()
await foo2()
@paper sluice would that do both at once or will it wait for foo to finish then do foo2
first it will wait for foo then it will wait for foo2
hello
im trying to make a fivem bot. i secess all exept the discord tag.
look at the code
await lets you run the rest of the code while in case if one function takes time to execute
your other code still works perfectly fine
thats what awaiting is
!e
from asyncio import run, sleep
async def foo():
print('entered foo')
await sleep(1)
print('still in foo')
return 1
async def bar():
print('entered bar')
await sleep(1)
print('still in bar')
return 1
async def main():
print('entered')
await foo()
await bar()
print('left')
run(main())
this is what i mean
@paper sluice :white_check_mark: Your eval job has completed with return code 0.
001 | entered
002 | entered foo
003 | still in foo
004 | entered bar
005 | still in bar
006 | left
it first waits for foo to finish, even when foo is sleeping, it still waits for it
if len(resp) > 25:
for i in range(round(len(resp) / 25)):
embed = discord.Embed(title='FiveMBot Bot', description='Server Players', color=discord.Color.blurple())
embed.set_footer(text=f'Total Players : {total_players} | FiveMBot | {timenow}')
count = 0
for player in resp:
embed.add_field(name=f"{player['name']}ID : {str(player['id'])}{str(player['discord'])} ",value="----------", inline=False)
resp.remove(player)
count += 1
if count == 25:
break
else:
continue
#await channel.send(embed=embed)
message= await channel.fetch_message(962264818520297512)
await message.edit(embed=embed)
else:
embed = discord.Embed(title='FiveMBot Bot', description='Server Players', color=discord.Color.blurple())
embed.set_footer(text=f'Players : {total_players} | {timenow}')
for player in resp:
embed.add_field(name=f"{player['name']} ID : {str(player['id'])} {str(player['discord'])}",value="----------", inline=False)
if i used something like gather the output would be
entered
entered foo
entered bar
still in foo
still in bar
left
@sterile talon explain your problem
i made this code
at the json its look like this (the discord)
@client.group(invoke_without_command=True)
async def help(ctx):
start = time.perf_counter()
end = time.perf_counter
em=discord.Embed(title = "**📂 | __Commands List__**\n\u2800", color=0x2F54C7)
em.add_field(name = "📒 | Acc Related Command", value = "**>randomkc** ➛ Generate a random KeyChain\n>**lockedacc** ➛ Get a Locked Account ( No-Bot )\n>**creation** ➛ Get estimated creation date of a tag\n>**acc** ➛ Get Account’s Infos\n>**clan** ➛ Get Clan’s Infos\n>**appledevs** ➛ Get Apple Devices for a specific year\n**samsungdevs** ➛ Get Apple Devices for a specific year\n**device** ➛ Get help to find device's account ( mention Local + Year )\n\u2800", inline = False)
em.add_field(name = "#️⃣ | Tag Related Command", value = "**>3gen** ➛ Generate a random 3 digit tag\n>**4gen** ➛ Generate a random 4 digit tag\n>**7gen** ➛ Generate a random 7 digit tag\n>**taggen** ➛ Generate a random 6 digit tag\n>**clangen** ➛ Generate a random 4/5/6 digit clan tag", inline = False)
em.set_footer(text= f"command successfully completed !" (end-start))
await ctx.send(embed = em)
end = time.perf_counter
forgot to call this
bt i have this error Command raised an exception: TypeError: unsupported operand type(s) for -: 'builtin_function_or_method' and 'float'
it should be end = time.perf_counter()
"discord:739178267361148950"
and the others like the name look like this
"name":"Broxax"
@paper sluice
em.set_footer(text= f"command successfully completed !" + str(end-start))
and this
what are you expecting @sterile talon
to take like the others and put it on the embed for eatch player
There's an unclosed bracket in former lines
Adding a ) at the required place
u forgot + between end-start and the string
It's good, there's no more error
and btw, ur timing nothing right now
these are not supposed to be together
@client.group(invoke_without_command=True)
async def help(ctx):
start = time.perf_counter()
em = discord.Embed(title="**📂 | __Commands List__**\n\u2800", color=0x2F54C7)
em.add_field(name="📒 | Acc Related Command", value="**>randomkc** ➛ Generate a random KeyChain\n>**lockedacc** ➛ Get a Locked Account ( No-Bot )\n>**creation** ➛ Get estimated creation date of a tag\n>**acc** ➛ Get Account’s Infos\n>**clan** ➛ Get Clan’s Infos\n>**appledevs** ➛ Get Apple Devices for a specific year\n**samsungdevs** ➛ Get Apple Devices for a specific year\n**device** ➛ Get help to find device's account ( mention Local + Year )\n\u2800", inline=False)
em.add_field(name="#️⃣ | Tag Related Command", value="**>3gen** ➛ Generate a random 3 digit tag\n>**4gen** ➛ Generate a random 4 digit tag\n>**7gen** ➛ Generate a random 7 digit tag\n>**taggen** ➛ Generate a random 6 digit tag\n>**clangen** ➛ Generate a random 4/5/6 digit clan tag", inline=False)
end = time.perf_counter()
em.set_footer(text=f"command successfully completed !" + str(end - start))
await ctx.send(embed=em)
this will time the amount of time it took to create embed
'AttributeError: 'Client' object has no attribute 'load_extension'' I'm trying to load a cog but I get this
The channel’s topic. None if it doesn’t exist.
!hosting
||
||
wojtazon do you know how to add a footer to my embed to tell how long the command took to run. The time between the >help and the response of the bot
use the datetime module and subtract datetime.datetime.now() from ctx.message.created_at
!d discord.TextChannel.topic
None
var http = require('http'); http.createServer(function (req, res) { res.write("I'm alive"); res.end(); }).listen(8080);
I guess you need to add another timezone
At worst it doesn't matter I leave it like that for now
I'm stuck on a command
Can i tell u what i want to do and if u know Can u help me?
sure
you don't need to pass an argument
I would like to make a command that gives the approximate date of creation of an account. The creation date depends on the tag (#) of the player and it is with the help of this list that the bot will give the creation date. The creation date depends on the number of letters in the tag and the first letter.
The list is this: ```6 digit tag = august-october 2012
#UXXXXX = august 2012
#UXXXXXX/#2XXXXXX/#LXXXXXX = december 2012
#XXXXXXX = 2013
#Qxxxxxxx = end 2013
#Gxxxxxxx = start/early 2013
#Rxxxxxxx = summer 2013
#Vxxxxxxx = 2014
#Pxxxxxxx = start-early 2014
#9xxxxxxx = early 2014
#2xxxxxxxx = early-end 2015
#8xxxxxxxx = start-early 2015
#9xxxxxxxx = 2016
#Pxxxxxxxx = end 2016
#Yxxxxxxxx = end 2017
#Lxxxxxxxx = end 2018
#Qxxxxxxx = end 2020
and the person will make the command >creation #TAGPLAYER and the bot will adapt its answer to the number of letters in the tag and its first letter
fun fact theres a discord function that lets you get the exact creation date of an account
and u could use strftime to format it nicely
then why tf r u asking here
because i'll do the command with my bot lmao
wtf u said for a game
damn u dont understand
um
nvm
I just need the main idea and then I make the script
but in the ss you passed an argument and the error still got raised

oh no i didnt restart the bot after
its just that self is not defined when i input it
Hey why is this doesnt working ```py
embed = discord.Embed( title = "Giveaway", timestamp = datetime.datetime.utcnow() + datetime.timedelta(time), color=discord.Color.gold())
start it in the class's initializer
how?
which part isn't working?
I try to set the time when the giveaway is ending
put the verification_loop.start in the class's initializer
timestamp
how to unban member by using both id and username
then the loop isnt defined
?
class A:
def foo(*args, **kwargs):
...
def bar():
self.foo(...)
``` you access it by using `self`
how to unban member by using both id and username
??
Hey why is this doesnt working ```py
embed = discord.Embed( title = "Giveaway", timestamp = datetime.datetime.utcnow() + datetime.timedelta(time), color=discord.Color.gold())
I dont know how to set the Timestamp to the time when the Giveaway ends
the code earlier was already correct, you just had to access it using self
so this was correct?
yes
how to unban member by using both id and username
id: ```py
member = discord.Object(id=...)
await guild.unban(member)
username: ```py
member = await commands.MemberConverter().convert(ctx, "sift#0410")
await guild.unban(member)
you don't need to keep sending the same thing mate
no one replied
Hey I dont know how to set the Timestamp to the time when the Giveaway ends ```py
embed = discord.Embed( title = "Giveaway", timestamp = datetime.datetime.utcnow() + datetime.timedelta(time), color=discord.Color.gold())
anyone can help me?
put the second start method inside the class's initializer and remove the first one
what's time
still, have a little patience
@bot.command(name="giveaway")
@commands.has_permissions(administrator=True)
async def giveaway(ctx, time: str, *, prize: str):
time = convert(time)
user=ctx.author
endtime = datetime.datetime.utcnow() + datetime.timedelta(time)
if not prize or time == 0:
return
embed = discord.Embed( title = "**Giveaway**", timestamp = datetime.datetime.utcnow() + datetime.timedelta(time), color=discord.Color.gold())
embed.add_field(name= "Host:", value=f"{user}")
embed.add_field(name='** **', value='** **', inline=True)
embed.add_field(name='** **', value='** **', inline=True)
embed.add_field(name="Prize:", value=f"{prize}")
gwmsg = await ctx.send(embed = embed)
await gwmsg.add_reaction("🎉")
await asyncio.sleep(int(time))
gwmsg1 = await ctx.channel.fetch_message(gwmsg.id)
users = await gwmsg1.reactions[0].users().flatten()
users.pop(users.index(ctx.guild.me))
winner = random.choice(users)
await ctx.send(f"{winner.mention} hat {prize} gewonnen!")
try timedelta(seconds=time)
oo lemme try
how to use it in same command
like sometime id and sometime username
Use a try-except ig
i couldnt make it async
and also the only reason it has to be async is cause im using dpy 2.0
self.verification_loop.start()
👍
Anyone know how to do it
how do i access the member object with only the id any idea?
Use get_member/fetch_member
discord.utils.get(self.client.guild.members, id=id)?
?
no
I'm working with API and i need json. How to pip install json?
you don't need to install json it's a standard library
you don't
*module
Hey, how can i set an error if an argument is missing in a command?
make an error handler using async def on_command_error and if isinstance
*on_command_error
and it ain't even a deco
thanks for correction
The Movie Database (TMDB) is a popular, user editable database for movies and TV shows.
and don't make the argument optional
https://github.com/AnthonyBloomer/tmdbv3api this may be helpful
just use run_in_executor while using the library
!d asyncio.loop.run_in_executor
awaitable loop.run_in_executor(executor, func, *args)```
Arrange for *func* to be called in the specified executor.
The *executor* argument should be an [`concurrent.futures.Executor`](https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor "concurrent.futures.Executor") instance. The default executor is used if *executor* is `None`.
Example:
basically, use a blocking function, without the function blocking your code
loop = asyncio.get_event_loop()
loop.run_in_executor(None, bot.run, token)
can someone tell me how to do this command?
didnt understand what you meant
I want to do a command >creation + #PLAYERTAG which will give the date of creation of the # according to the length of the tag and its first letter.
Let's say I do >creation #UVGP22 then the bot will print "account created between August and October" because according to the list above the tag has a length of 6 letters and begins with the letter U
use conditionals
if / else?
tag = member_tag
if len(tag) == 6 and tag.startswith("#U"):
'''created between whatever month'''
smth like this
yeah
async def creation(ctx: commands.Context, tag: str):
...
''' USAGE '''
>creation #UFFFF667
here in the function, tag will be set to #UFFFF667```
@client.command()
async def creation(ctx: commands.Context, tag: str):
tag = int(input())
if len(tag) == 6 and tag.startswith("#U","#V","#C","#P","#2","#8","#9","#0","#O"):
await ctx.send("created between whatever month")
nothing happen
you're using input() in your command which is halting the bot's execution to wait for an integer from the console
!d str.startswith < also it only takes a single string or tuple of strings, not 9 strings
str.startswith(prefix[, start[, end]])```
Return `True` if string starts with the *prefix*, otherwise return `False`. *prefix* can also be a tuple of prefixes to look for. With optional *start*, test string beginning at that position. With optional *end*, stop comparing string at that position.
But in fact I want a guy to do >creation in the discord discord server
How to make the bot take into account the answer of the guy in discord when he does >creation #UVVVVV
you already did so by writing a tag parameter
dpy will try to match the user's message to the parameters of your function
@client.command()
async def creation(ctx: commands.Context, tag: str):
tag = #depend the guy entered
if len(tag) == 6 and tag.startswith("#U"):
await ctx.send("created between august-october")
how to take the information that the guy entered?
when the command is run, it will substituted to the tag parameter in the function initiator, that is what the information will be that the "guy" entered
hi, slash is work?
there are plenty of libraries that can offer slash commands for you
e.g. discord.py 2.0 (master branch) or forks of that project like disnake
@slash.slash(name="test")
async def _test(ctx: SlashContext):
embed = discord.Embed(title="embed test")
await ctx.send(content="test", embeds=[embed])
Its now work, why?
this is my first slash
Why you use embeds when you have just one embed 
What if, for example, not everyone teased? I found this shit on a page.
It's not teasing
It's pointing out flaws that can be fixed
No? this person at any time I wrote bound to me, even if there was a point of error
I don’t know where many people think of themselves, but there will be no one more than the other.
Use the embed kwarg and why are you using the content kwarg when the text gets passed to the content kwarg automaticcaly
Why is your name pep 9001
Are you using Google translate or smth?

I think so
?
Hello ashley
teasing 😔 you're the school bully who bullies people and tell them that they are filled with flaws
hi skev
Me?
Hungarian lang have a lot of word for this
yeah, I was kidding btw
Ugratas wow they compressed all those words to one word
google translate majik
one word but i translate this, ugratás, te vagy az iskola zaklatója, aki mindenkibe csak beleköt (yeah its not english)
What should I change in the code then?
how weird
Hey
await ctx.send("test", embed=embed)
Already said it
happy for u
I don't think he likes when his flaws get pointed out
and yeah, he translated it correctly by himself
but what we pointed out doesn't fix anything
how about you first ask him what version of dpy or what lib he uses
He's asking us why it now works
oh I saw a t
winners = random.sample([user for user in users if not user.bot], k=1)
print(winners)
>>> [<Member id=757311230582063275 name='The Owl' discriminator='6390' bot=False nick=None guild=<Guild id=945023980681723924 name='LegendBot' shard_id=None chunked=True member_count=4>>]
how i can access to member id
now -> not
Yeah
that's unfortunate
winners[0].id
!d random.sample
random.sample(population, k, *, counts=None)```
Return a *k* length list of unique elements chosen from the population sequence or set. Used for random sampling without replacement.
Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples. This allows raffle winners (the sample) to be partitioned into grand prize and second place winners (the subslices).
Members of the population need not be [hashable](https://docs.python.org/3/glossary.html#term-hashable) or unique. If the population contains repeats, then each occurrence is a possible selection in the sample.
yeah it returns a list
its ok but if i write / in the slash menu nothing from my bot
maybe your command isn't registered yet
@client.command()
async def creation(ctx: commands.Context, tag: str):
tag = #depend the guy entered
if len(tag) == 6 and tag.startswith("#U"):
await ctx.send("created between august-october")
What should I change in the code then?
Are you trying to get account creation?
You’re aware you can get the exact date and time easily by reverse engineering their ID?
user for user in users huh
??
Yes but not for discord
For clash of clans
What are u trying to do
Do coc have an api?
the player will do >creation+ his tag and the bot will answer depend the tag
yes but i dont Need atm
I would like to make a command that gives the approximate date of creation of an account. The creation date depends on the tag (#) of the player and it is with the help of this list that the bot will give the creation date. The creation date depends on the number of letters in the tag and the first letter.
The list is this: 6 digit tag = august-october 2012
#UXXXXX = august 2012
#UXXXXXX/#2XXXXXX/#LXXXXXX = december 2012
#XXXXXXX = 2013
#Qxxxxxxx = end 2013
#Gxxxxxxx = start/early 2013
#Rxxxxxxx = summer 2013
#Vxxxxxxx = 2014
#Pxxxxxxx = start-early 2014
#9xxxxxxx = early 2014
#2xxxxxxxx = early-end 2015
#8xxxxxxxx = start-early 2015
#9xxxxxxxx = 2016
#Pxxxxxxxx = end 2016
#Yxxxxxxxx = end 2017
#Lxxxxxxxx = end 2018
#Qxxxxxxx = end 2020
and the person will make the command >creation #TAGPLAYER and the bot will adapt its answer to the number of letters in the tag and its first letter
Its what i want to do
y do u change tag
I said that three times with an explanation every single time, still didnt get to it
sorry?
Nah i tried But I didn't succeed I'm not strong so I don't understand everything
wdym button is invalid?
Ig he mean interaction failed
well, use a command to set a make a button turn off and turn on
i can’t remember what it’s called
button.disabled = True
yes that
I just feel like you gonna call a mod and get me banned from the server someday 😔
sad
can i use a command to toggle when a button is disabled then?
you never know 😳
nice
uhhh.. maybe, make a command, when its called disable that button, but why use commands...?
your question doesn't make sense
i don’t know how to explain it
Open paint
Draw
Send here
Thats what i use when i cant explain
you're like, whenever you go offline, the buttons get disabled, so that people cant create a ticket, whenever you're back online, the buttons are re-enabled, so that people can create a ticket, am I getting it right?
yes
lmao wtf
save your view, change its buttons on_member_update
He just said yes
!d disnake.on_presence_update exists in discord.py 2 too
ahh nevermind
disnake.on_presence_update(before, after)```
Called when a [`Member`](https://docs.disnake.dev/en/latest/api.html#disnake.Member "disnake.Member") updates their presence.
This is called when one or more of the following things change:
• status
• activity
This requires [`Intents.presences`](https://docs.disnake.dev/en/latest/api.html#disnake.Intents.presences "disnake.Intents.presences") and [`Intents.members`](https://docs.disnake.dev/en/latest/api.html#disnake.Intents.members "disnake.Intents.members") to be enabled...
How does he not mean it
wth
it’s fine, it’s doesn’t matter anymore
I mean it's kinda useful
@slate swan do u want a command like !ticket disable so ppl cant create ticket
i know
yeah
text_channel_list = []
for guild in client.guilds:
for channel in guild.text_channels:
text_channel_list.append(channel)
async for channel in text_channel_list:
async for message in history:
if message.author == client.user:
return
print(f"{username} Posted {message.content}")
history_list.append(message.content)
i += 1
if i< 5:
await message.channel.send("Less Than 5 Messages In Current History... Returning All Time History")
await message.channel.send(history_list)
does something like this work to get all the messages in all the text channels? (sry for bad formatting)
See
are you creating buttons using a subclass of the View class?
and which library?
async for message in channel.history():
you mean?
that's gonna be a lot
..
@cold sonnet how did you disable all buttons in a View class using the children attribute? 😔 me forgot
ive defined history as
history = message.channel.history()
nah I didn't use no attribute like that
im tryna make a bot that completely merges servers into backups
cap
Messages too?
yeah
Thats a lot of process
Legends
yeah.. i saw a similar thing in java and alot of my friends liked it so im tryna remake it in py
[<Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='a1' emoji=None row=0>, <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='a2' emoji=None row=0>, <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='a3' emoji=None row=0>, <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='b1' emoji=None row=1>, <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='b2' emoji=None row=1>, <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='b3' emoji=None row=1>, <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='c1' emoji=None row=2>, <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='c2' emoji=None row=2>, <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='c3' emoji=None row=2>]
so the children of my view only returned buttons
?
so Ig
for button in view.children:
button.disabled = True
..
..
Ok
i’ve found out how to do it: create a new class, then get the button message i want to edit and then edit that message with the disabled button
for text_channel in text_channel_list:
print(text_channel.name)
why does this return the text channel names twice?
ahmm
👀
this chat is cursed
no
time to report to modmail
uhhh sifttt
appropriate
When is it not
no you don't?
wdym
I'm on mobile rn, just waiting for dinner
oh wow
ok
for child in self.children:
child.disabled = True
Why it don't work?
https://pastebin.com/b0nC8SXa
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.
I should use that
That was actually mu assumption
r is still a file object, you haven't read it. But I guess this isn't related to discord bots anywhere?
this is me creating bad words in the bot
i tested this on my own PC and it works fine 
I'm not entirely sure why it doesn't work, but in the case of understanding what this does and asking for help I'd recommend trying to give the variables more useful names. If I just read ar, i, n I don't have a clue what they mean, but if they're lines, line, etc. they're far easier to make sense of
the role 962287817071927346 doesn't exist in that guild, so it returns None and then the call to add the role can't get the ID of the object because it's not a Role object
then the role isnt in the bot's cache?
are you positive you copied the role id not a message id, guild id, channel id, etc.?
as long as you haven't messed with intents I'd be surprised if the cache was out of date for that
how do i make an error handler for MemberNotFound?
I’ve tried if user == NotFound:
you'd have to use try/except:
try:
do_something_with_user()
except MemberNotFound as e:
handle_error(e)
membernotfound? where are you getting that error
maske a file cfalled cenz.txt
i’m adding a user to a ticket and if the user isn’t in the server, it says MemberNotFound and i want it to reply with something like, This user isn’t in this server!
if i get all the channels in a guild, how do i get all the messages attched to that channel?
use the on_command_error event and use the isinstance function to check if the error is an instance of MemberNotFound error
okay thanks
His hat is a duck :3
:3
||you too||
|| u more :3||
<str>.endswith('.jpg') ig? idk 💀 just guessing
i mean if you're passing it thorugh command or something can be checked liek that
embed.set_thumbnail(url="https://m.media-amazon.com/images/M/MV5BMzhiYzRlNDctY2Y0My00ZTkwLTk0ODgtODg5ZTcxMWY5MjczXkEyXkFqcGdeQXRoaXJkLXBhcnR5LXZpZGVvLXVwZGF0ZXI@._V1_QL75_UX500_CR0,47,500,281_.jpg")
url=...
oh it's a url kwarg
+1
i'm feeling more dumb for what u asked & what i understood
lol
like akinator? :3
wut that? oh that geine game??
Best would be to use mimetype
yeah :3
haven't heard of that in ages, imma go play that now
😂 woah nice
lol
💀 i was assuming that he gonna put the url .. so url is string.. so... I hope u getting my point
and thought he wanna check if the image in url has .jpg extension.. so.. :'/
are u not planning to use some movie related api..? like the api will itself have the movie name, images nd stuff...
💀 just asking
bot.event
async def on_message(message):
if {i.lower ().translate(str.maketrans('','', string.punctuation)) for i in message.content.split(' ')}\
.intersection(set(json.load(open('cenz.json')))) != set():
await message.channel.send(f' {message.author.mention}, не матерись')
await message.delete()
await bot.process_commands(message)
why not work?
everything is well written
ok so ngl.. i'm using https://www.themoviedb.org/documentation/api for movie command in my bot & trust me it provides all the info with "images"...
The Movie Database (TMDB) is a popular, user editable database for movies and TV shows.
owo
eh... idk what u want as a reply.. but using aiohttp.. and u need api key to use their api
:3
obviously, since discord.py is an async lib
:'/
using requests is a bad practice to use in async flow :'/
results in "blocking"
i can send u good docs about using it
yes sir
and if you've used requests, then switching to aiohttp won't be hard for u
since they've few things in common
:")
who help me?
aah.. idr sowwy
its not hard, you make a request with a method, a path an endpoint, headers and parameters
headers would be api keys
^ +1
💀 it says indenation error
!d aiohttp.ClientSession.get
coroutine async-with get(url, *, allow_redirects=True, **kwargs)```
Perform a `GET` request.
In order to modify inner `request` parameters, provide kwargs.
Hosted API documentation for every OAS (Swagger) and RAML spec out there. Powered by Stoplight.io. Document, mock, test, and more, with the StopLight API Designer.
^ +1
and just suggesting.. in case you've used requests at other places for other commands.. try to replace it with aiohttp if possible :'/
that's okay :")
but their aiohttp docs is good
haha that's okay :3
ic Yerl with an anime pfp 👀
💀 depends on lib that you're using
disnake
:'/ if it's pycord then i can help
ah.. sowwy, i'm useless here :/
u shifted to dpy from disnake?
owo dpy has slash? 😳 sowwy dude.. i'm currently familiar with py-cord.. i've no idea about the changes made in dpy since danny continued the thing
I do 4 spaces, it writes the same to me again
😭 idk bro.. maybe your python is blind
but it says indentation error :'/
can this be fixed somehow?
💀 can ya send ss of your code? screenshot
ig i'm not able to guess your indenattion properly with that code block
1st line will be
@bot.event
and
that 3rd line looks like space of only 3 :'/ it hsould be 4 spaces
do you mean an argument with multiple choices? This could help: https://gist.github.com/Rapptz/c4324f17a80c94776832430007ad40e6#choices
Thanks
:>
Sorry for ping. I cant read
it's not hard using aiohttp, pretty much the same as requests with some extra steps
Choices are defined once in the code and then stay the same. For autocomplete on the other hand you write a function which gets called every time the user writes something and you return the options.
So for an argument which should either be either ON or OFF you'd use choices, and for searching a movie db you'd probably use autocomplete
has no support.
Yeah it does…?
I'm pretty sure it has been discontinued by the author.
Nah its development has started again
?
Read the gist
I don’t have the link on hand atm
I’m sure someone’s searching for it right now
I don't even know what that is.
apparentally danny resumed development
it now support everything latest
how to get lost, discord.py edition...
Indeed haha
But wait, there is nothing about slash commands in the docs.
what is that...
I went to docs listed in this server: https://discordpy.readthedocs.io/en/stable/ext/commands/index.html
Code: https://mystb.in/DisabilitiesApplicantShort.python
Error: https://mystb.in/YogaTendAssume.sql
Any idea when I add this in it gives me this error
Without that my code works perfectly
Basically donator is a top level command, balance is a sub command and details is a sub sub command.
omg @boreal ravine yk I was just searching up something related to mongodb to find out something that someone had helped me here and it was you loll
most new features are probably not documented or have examples so you should try to find if the feature has docs or examples on repo or you can just read src code
import asyncio
from aiohttp import ClientSession
from client import Dispy
from constants import config
client = Dispy()
async def main() -> None:
async with ClientSession() as session:
async with client:
client.https_session = session
await client.start(config.bot.token)
asyncio.run(main())
``` what do you guys think about the new way to run the bot?
Using app commands
what library?
also that isn't a new way

start has existed for a while
"new way"
aka danny is most likely going to force this at some point.
i would just subclass Dispy() so i can just put the session in the context manager where the bot starts and closes
Ah, I won't understand anything, then.
I don't understand other people's code.
¯\_(ツ)_/¯
Is there any documented lib then?
If anyone could help
been struggling with this for over an hour
it's not a new way?
disnake has everything documented and is up to date
most forks are lol
!pypi disnake
Finally lmao
cogs are also going async
It kind of made no real sense to have a sync entry point E.g run
Should've just forced from day one to use start
The only problem I can see although is the asyncio.run part, as that creates a whole new event loop
Therefor maybe problems such as futures on a different event loop may occur
Esp with discord.py's use of wait_for
Yeah that's annoying.. you need to put in intents now in 2.0.0
Not to mention on_ready also depends on a bunch of Futures
To ensure cache is populated
people from dpy server are surely toxic

Figuring out now where the best place is to put await tree.sync() since this can only be run after on_ready() has been called.
from discord import Client, Intents
client = Client(intents=Intents())
Why can it only be called after ready has been dispatched?
it's still not a new way 🤷♂️
Since the application id has to be defined.
Even setup_hook doesn't work.
Just manually request application info
Anyone know how I can fetch all the objects from an array motor mongo
And set it yourself
Plus, application ID should just be your client's ID
"fetch all objects"?
Hmm could try
I have an array like this, need to be able to get the Value, Date and proof for each of them and post them in an embed
just intents=Intents() lol
async def setup_hook(self) -> None:
data = await self.application_info()
self.app_id = data.id
``` I'd assume
Lemme see what i can do
Really might just start working on Rin again
bro comeon do it already
Asyncio is a built in module
I know, this was just a example
Did I summon you
Look
async is a keyword so that’s why
Look what I send
Yeah weird
Sill sync takes no kwarg or arg might need to modify it lol
If you explain a bit to me what exactly sync does I'll be able to help
Can someone help me? my self is coming as None on command and i have no idea how to solve this
I haven't even taken a look at discord.py's new stuff
How do I fix it tho?
try ctx.bot
Not sure
It gives a error on every pip command I run
Traceback (most recent call last):
File "C:\Users\eboss\Downloads\dpy\__main__.py", line 14, in <module>
asyncio.run(main())
File "C:\Users\eboss\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\eboss\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
return future.result()
File "C:\Users\eboss\Downloads\dpy\__main__.py", line 12, in main
await client.start(config.bot.token)
File "C:\Users\eboss\Downloads\dpy\venv\lib\site-packages\discord\client.py", line 681, in start
await self.login(token)
File "C:\Users\eboss\Downloads\dpy\venv\lib\site-packages\discord\client.py", line 544, in login
await self.setup_hook()
File "C:\Users\eboss\Downloads\dpy\client.py", line 22, in setup_hook
await self.tree.sync()
File "C:\Users\eboss\Downloads\dpy\venv\lib\site-packages\discord\app_commands\tree.py", line 869, in sync
raise ClientException(APP_ID_NOT_FOUND)
discord.errors.ClientException: Client does not have an application_id set. Either the function was called before on_ready was called or application_id was not passed to the Client constructor.
``` when doing it inside the setup hook
Does it maybe have to do anything with this
That is supposed to only be called once before on_ready but it does work in on ready lol
Set self.application_id inside of setup_hook?
What constructor lol
I have no idea
client = discord.Client(…)

it worked, thanks
Ig then lemme hard code it
If u want the bots member object use ctx.me
i get summoned everytime you mention that you're going resume to rin
Maybe I shouldn't then
ill help you!
not in core tho!
maybe just suggestions!
Did it take over 3 seconds before it tried to responded
!d discord.InteractionResponse.defer
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...
Try deferring
from ext.cmd import slash
from constants import config
from log import log
from datetime import datetime
from aiohttp import ClientSession
import discord
from discord import Client, Intents
from discord.app_commands import CommandTree
class Dispy(Client):
tree: CommandTree[Client]
https_session: ClientSession
def __init__(self) -> None:
super().__init__(intents=Intents(), application_id=config.bot.app_id)
self.launch_time = datetime.now()
async def setup_hook(self) -> None:
self.https_session = ClientSession()
self.tree = CommandTree(self)
self.tree.add_command(slash, guild=discord.Object(id=config.debug.guild))
await self.tree.sync()
async def close(self) -> None:
await super().close()
await self.https_session.close()
async def run(self) -> None:
async with self:
await self.start(config.bot.token)
@staticmethod
async def on_ready() -> None:
log.info("Ready")
``` got this rn
Ah
Defer then send
why not overwrite the context managers of the client and you add the session there?
wdym?
You mean ctx?
self.__exit__ & self.__enter__
async with self: the context manager of the client class why not overwrite it and you add your client session their?
await interaction.response.defer() somewhere else await interaction.followup.send(…)
andy gets what i mean
so it would be a backended session inside of the context manager so you wont have 2 context managers over eachother
Never really worked with context managers. Will do.
well the context managers use dunders as any keyword in py so just overwrite the one in the class
!e ```py
class Foo:
async def aenter(self) -> "Foo":
# Do stuff
return self
async def __aexit__(self, *_: "Any") -> None:
...
@pliant gulch :warning: Your eval job has completed with return code 0.
[No output]
^
__aenter__ called via async with
yup
Then __aexit__ is called after leaving the context
andy showed me all about them!
ahh
The parameters being passed to __aexit__ are for if any exceptions occur while in the context manager
I "omitted" them cause I'm lazy, but those are important
Depending on how you do it, you would accidentally suppress all errors
!d discord.Client.wait_for
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
Gonna eat now idk what's cleaner tough.
A few examples in the docs
the single context manager is better than 2 over eachother!
!d discord.app_commands.describe
@discord.app_commands.describe(**parameters)```
Describes the given parameters by their name using the key of the keyword argument as the name.
Example:
```py
@app_commands.command()
@app_commands.describe(member='the member to ban')
async def ban(interaction: discord.Interaction, member: discord.Member):
await interaction.response.send_message(f'Banned {member}')
yes
Why not use f strings?
await message.delete and remove ctx from the event and you didnt define msg
Also on message doesn’t provide ctx
Yep
Also you’re checking if it’s in a dm and deleting it
Which is impossible
You can’t delete other peoples messages in a dm
Show error
Ohh can u show the code again
Hello,
I am using an on_member_update event to get user's status and voice channel.
Does anyone know why I get None as before.voice and after.voice just after I get the right infos ? I got them 2 times when I change my status
and I am in a voice channel btw
Why 2 message arguments
U only need 1 arg which is message (u already have it)
its await message.delete() not await ctx.message.delete() (its bc you are using on_message event and the event needs only 1 arg which is message)
You can type / on discord and see the slash command?
show the codes
yes
Also that is not going to work since the bot cannot delete msgs in DM's(ppl's msgs)
hmm im not sure
It will check if the msg sent in a guild (if the msg sent in the dm's it will return False)
Ye.
U forgot the other and
and message.content =="ur msg idk"
Ye 
await message.author.send()
if the user's dms are closed then the bot cannot dm them
then add try except
try:
await message.author.send("uwu")
except discord.Forbidden:
await message.channel.send("rip")
uwu :|😭😭😭😭😭😭😭😭
Nun. My bad
Ye but await client.process_commands(message) should be outside the try: 
if the bot couldnt dm them then it will send the msg to that channel and it wont delete the msg anyway
😧
Wait
that code is cursed
Where is if

Btw use !paste cuz im on phone😭
Hi, i asked this yesterday but didn't get a clear answer.
the bot worked for like a year, but for some reason it stopped working properly. I do have a channel where i only put 20 images (png). When i use this function he only reads like 11 images or less. Does someone has any idea how to fix this?
@bot.command()
async def updb(ctx):
collection.drop() # Drops database collection
channel = bot.get_channel(962354717307068426) # Gets channel that's need to be readed
async for message in channel.history(limit=20): # Reads history of channel limitation is 20
url = message.attachments[0].url # Checks per message for url (png)
urlArray.append(url) # Adds url to array
print(url)
await bot.et_channel(id=818813967198978078).send("There are " + str(len(urlArray)) + " images posted in #visitcard_database!")
for url in urlArray:
collection.insert_one({"url": url})
```
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.
@client.event
async def on_message(message):
if message.guild is None and not message.author.bot and message.content == "fdp":
await message.delete()
print(f"Message was deleted !")
try:
await message.author.send(f"Insult :
{message}")
print(f"Private Message was sent !")
except Exception:
#get the channel here and send the error etc
await client.process_commands(message)
@slate swan take a ss of this
I wanna see the indents


