That title made no sense but I'll clarify here. I have this command where it'll send an embed and get data from a JSON and then send it back inside of the embed and I want to make it so that after 5 seconds, it deletes and sends another JSON.
Here's the code:
@client.command()
async def test(ctx):
with open('test.json', 'r') as homeworkfile:
homework = json.loads(homeworkfile.read())
embed=discord.Embed(title='Test', description=f"Here's the saved contents for test: {homework}", color=0x9932CC)
deletewarn=discord.Embed(title='Answer ticket expired.', description="Oops, looks like this ticket expired. Try saying !ss again?", color=0x9932CC)
await ctx.send(embed=embed, delete_after=5)
time.sleep(5)
await ctx.send(embed=deletewarn)
When I use the command, it does send the other embed after 5 seconds have passed, but the other embed doesn't delete until a few seconds later.
How do I fix this?
CodePudding user response:
time.sleep is blocking, meaning that all code execution is stopped until the 5 seconds pass. Instead, use asyncio.sleep:
from asyncio import sleep
def my_func():
# code blah blah...
await sleep(5)
# code...
CodePudding user response:
await ctx.send(embed=embed, delete_after=5) use asyncio.sleep function to wait before deleting the message.
You use blocking call: time.sleep(5). It blocks all your code and also blocks await ctx.send(embed=embed, delete_after=5) timer execution.
You should use asyncio.sleep:
import asyncio
@client.command()
async def test(ctx):
with open('test.json', 'r') as homeworkfile:
homework = json.loads(homeworkfile.read())
embed=discord.Embed(title='Test', description=f"Here's the saved contents for test: {homework}", color=0x9932CC)
deletewarn=discord.Embed(title='Answer ticket expired.', description="Oops, looks like this ticket expired. Try saying !ss again?", color=0x9932CC)
await ctx.send(embed=embed, delete_after=5)
await asyncio.sleep(5)
await ctx.send(embed=deletewarn)
CodePudding user response:
Change time.sleep(5) to await asyncio.sleep(5) instead. While using time.sleep your entire code is frozen.
Your code works like this:
- Sends your first message
- Immediately "sleeps" for 5 seconds (because of
time.sleep(5)) - After 5 seconds code resumes:
- sends your second message
- starts 5 second counter you used in
delete_after=5
That's why it waits 10 seconds before deleting the message instead of the 5 you wanted. It just starts counter execution for delete_after=5 later, because your time.sleep froze the whole code.
Remember to import asyncio to use asyncio.sleep.
