Django Websocket: Messages are all sent after loop is finished - python

I am trying to create a application, where i start the game with a countdown. For that I have a loop counting down. The problem is when i am awaiting my send loop, all messsages are sent after the loop is finished. When i am putting the function in a task it is sending instant but thats not what i want because I need to wait for the function to call another after.
Thats the the countdown function
async def init_starting(self):
if not self.lobby.status == "waiting":
print("Already Started")
return False
else:
print("Starting Countdown")
self.lobby.status = 'starting'
await self.save_lobby()
await self.send_status_message_with_status(status='starting', data={'has_started': self.lobby.has_started,
'host': self.host.username,
'players': self.players,
'lobby_code': self.lobby_code,
'countdown': 3})
countdown = 3
while countdown >= 0: # here are the messages not sent instant but after the loop is finished (with my current approach they are sent instant but i cant await it
countdown_data = {
'countdown': countdown
}
await self.send_status_message_with_status(status='starting', data=countdown_data)
countdown -= 1
await asyncio.sleep(1)
self.lobby.status = 'started'
await self.save_lobby()
await self.send_status_message_with_status(status='started', data={
'message': "Test"
})
return True
Here i am currently starting the task
if "command" in text_data_json:
command = text_data_json['command']
match command:
case 'start':
loop = asyncio.get_running_loop()
start_task1 = loop.create_task(self.init_starting()) # here i would like to await the task but when i do it they are not sent instant
case _:
print("Code not found")
Thanks for any help in advance!

Related

Issues with making a simple loading icon inside an async event loop

I'm making a bot for a discord server and have a function that takes a bit of time to run. I want to add a spinning loading icon next to the status message like this Doing something: <spinning icon>. It edits the original message to loop through these messages:
Doing something: \
Doing something: |
Doing something: /
Doing something: -
I tried using a separate thread to update the message like this:
async def loadingBar(ctx, message : discord.Message):
loadingMessage0 = "{0}: \\".format(message)
loadingMessage1 = "{0}: |".format(message)
loadingMessage2 = "{0}: /".format(message)
loadingMessage3 = "{0}: -".format(message)
index = 0
while True:
if(index == 0):
await message.edit(contents = loadingMessage0)
index = 1
elif(index == 1):
await message.edit(contents = loadingMessage1)
index = 2
elif(index == 2):
await message.edit(contents = loadingMessage2)
index = 3
elif(index == 1):
await message.edit(contents = loadingMessage1)
index = 0
farther down, the bot command that starts the process...
#bot.command()
async def downloadSong(ctx, url : str, songname : str):
#Other code that doesn't matter
message = await ctx.send("Downloading audio")
_thread = threading.Thread(target=asyncio.run, args=(loadingBar(ctx, message),))
_thread.start()
#Function that takes a while
#Some way to kill thread, never got this far
However, I get the error Task <Task pending coro=<loadingBar() running at bot.py:20> cb=[_run_until_complete_cb() at /Users/user/.pyenv/versions/3.7.3/lib/python3.7/asyncio/base_events.py:158]> got Future <Future pending> attached to a different loop. I'm new to async programming and the discord libraries; Is there a better way to do this and if not what am I doing wrong?
Firstly, you should add a delay between iterations inside the while loop, use asyncio.sleep for this.
Secondly - asyncio and threading doesn't really work together, there's also no point in using threading here since it defeats the whole purpose of asyncio, use asyncio.create_task to run the coroutine "in the background", you can asign it to a variable and then call the cancel method to stop the task.
import asyncio
async def loadingBar(ctx, message : discord.Message):
loadingMessage0 = "{0}: \\".format(message)
loadingMessage1 = "{0}: |".format(message)
loadingMessage2 = "{0}: /".format(message)
loadingMessage3 = "{0}: -".format(message)
index = 0
while True:
if(index == 0):
await message.edit(contents = loadingMessage0)
index = 1
elif(index == 1):
await message.edit(contents = loadingMessage1)
index = 2
elif(index == 2):
await message.edit(contents = loadingMessage2)
index = 3
elif(index == 1):
await message.edit(contents = loadingMessage1)
index = 0
await asyncio.sleep(1) # you can edit the message 5 times per 5 seconds
#bot.command()
async def downloadSong(ctx, url : str, songname : str):
message = await ctx.send("Downloading audio")
task = asyncio.create_task(loadingBar(ctx, message)) # starting the coroutine "in the background"
# Function that takes a while
task.cancel() # stopping the background task

How to make a certain function stop executing when a certain condition is met

I am designing a discord bot that loops certain text when a certain conditions are met, which then triggers this function to run.
async def inform(self,message):
while flag==1:
await message.channel.send("text")
await asyncio.sleep(5)
await message.channel.send("text2")
await asyncio.sleep(5)
await message.channel.send("text3")
await asyncio.sleep(5)
Now the problem is when the conditions are not met anymore the function completes the entire cycle before haulting. I want it to stop the moment the condition is not satisfied anymore.
I thought of adding an
if flag==0:
return
After every line but that is not the elegant solution I am looking for.
I don't want the entire code to stop running, but just this function.
I am a beginner to python and any insights are welcome :)
Thank You!
A while loop, before each iteration will look if the condition is True, if it is, it will continue, if not it will stop.
while flag == 1:
if 'some condition met':
flag = 0
# And the loop will stop
The loop will stop by itself, nothing more. Also it's better to use booleans.
Here's your code a bit improved
# Defining variables
flag = True
iteration = 0
while flag:
# Adding `1` each iteration
iteration += 1
# Sending the message
await message.channel.send(f'text{iteration}')
# Sleeping
await asyncio.sleep(5)
If I got it right, You want to check if a condition is met. Here is an infinite loop until some criteria is met. If this is not what you wanted please explain it again.
import random
msgs = ['msg1','msg2','msg3']
condition_met = False
while True:
if condition_met:
break
# also return works here
else:
await message.channel.send(random.choise(msgs))
await asyncio.sleep(5)
if something == 'Condition met here':
condition_met = True
Each iteration of the loop should only send one message, to keep track of the order of messages sent, I used the variable i which is incremented every time a message is sent.
async def inform(self,message):
i = 0
while flag==1:
if i == 0:
await message.channel.send("text")
await asyncio.sleep(5)
elif i == 1:
await message.channel.send("text2")
await asyncio.sleep(5)
elif i == 2:
await message.channel.send("text3")
await asyncio.sleep(5)
i = (i + 1) % 3

How to set a background timer, and stop a function when it finishes while still waiting for reactions

So I'm making some minigame using discord.py, and this is what I got:
asyncio.create_task(self.stream_message_timer(ctx, correct, total), name=f"stream message timer {ctx.author.id}")
while bad_count > 0:
done, pending = await asyncio.wait([
self.client.wait_for('reaction_add', check=lambda reaction, user: str(reaction.emoji) in number_emojis and reaction.message.id == discord_message.id and user == ctx.author),
self.client.wait_for('message', check=lambda m: m.author == self.client.user and m.content == f"Times up!\n{correct}/{total} tasks successful.")
], return_when=asyncio.FIRST_COMPLETED)
try:
result = done.pop().result()
except Exception as e:
raise e
for future in done:
future.exception()
for future in pending:
future.cancel()
if type(result) == discord.Message:
return False
else:
reaction = result
# process the reaction, edit a message
await ctx.send(f"You deleted all the bad messages!\n{correct+1}/{total} tasks successful.")
for task in asyncio.all_tasks():
if task.get_name() == f"stream message timer {ctx.author.id}":
task.cancel()
break
return True
async def stream_message_timer(self, ctx, correct, total):
await asyncio.sleep(5)
await ctx.send(f"Times up!\n{correct}/{total} tasks successful.") # message linked to delete_chat, change there if this is changed
return False
Basically, I'm trying to make some kind of 5 second background timer as I wait for reactions at the same time.
No, I am not looking for timeout=5
The code that I have here works, but its very hacky. I'm either waiting for a reaction from the user, or just waiting for the bot to message "Times up".
Is there a cleaner way to do this? I would like to have the timer start right before the while loop, and forcefully stop anything inside the loop and make the function return False right when the timer finishes
Also, if the function does stop, I still want some way to cancel the timer, and that timer only.
I've been using this method for quite some time and it's making my code very unorganized. Thanks.
Here’s some sort of example that is independent from discord.py:
import asyncio
import random
async def main():
asyncio.create_task(timer(), name="some task name")
# simulates waiting for user input
await asyncio.sleep(random.uniform(2, 5))
return True
async def timer():
await asyncio.sleep(5)
# somehow make this return statement stop the main() function
return False
asyncio.run(main())
wait(return_when=FIRST_COMPLETED) is the correct way to do it, but you can simplify the invocation (and subsequent cancellation) by using the return value of create_task:
async def main():
timer_task = asyncio.create_task(timer())
user_input_task = asyncio.create_task(asyncio.sleep(random.uniform(2, 5)))
await asyncio.wait([timer_task, user_input_task], return_when=asyncio.FIRST_COMPLETED)
if not timer_task.done():
timer_task.cancel()
if user_input_task.done():
# we've finished the user input
result = await user_input_task
...
else:
# we've timed out
await timer_task # to propagate exceptions, if any
...
If this pattern repeats a lot in your code base, you can easily abstract it into a utility function.

How to restart a loop in discord.py?

I am making a discord bot using discord.py. I want to make a command to purge all messages inside a channel every 100 seconds. Here is my code:
autodeletetime = -100
autodeletelasttime = 1
#client.command()
#commands.has_permissions(manage_messages=True)
async def autodelete(ctx):
global autodeleterunning
if autodeleterunning == False:
autodeleterunning = True
asgas = True
while asgas:
message = await ctx.send(f'All messages gonna be deleted in 100 seconds')
await message.pin()
for c in range(autodeletetime,autodeletelasttime):
okfe = abs(c)
await message.edit(content=f"All messages gonna be deleted in {okfe} seconds" )
await asyncio.sleep(1)
if c == 0:
await ctx.channel.purge(limit=9999999999999999999999999999999999999999999999999999999999999999999)
await time.sleep(1)
autodeleterunning = False
else:
await ctx.send(f'The autodelete command is already running in this server')
I want the loop to restart every 100 seconds after the purge is complete.
You should use tasks instead of commands for these kind of commands.
import discord
from discord.ext import commands, tasks
import asyncio
#tasks.loop(seconds=100)
async def autopurge(channel):
message = await channel.send(f'All messages gonna be deleted in 100 seconds')
await message.pin()
try:
await channel.purge(limit=1000)
except:
await channel.send("I could not purge messages!")
#client.group(invoke_without_command=True)
#commands.has_permissions(manage_messages=True)
async def autopurge(ctx):
await ctx.send("Please use `autopurge start` to start the loop.")
# Start the loop
#autopurge.command()
async def start(ctx):
task = autopurge.get_task()
if task and not task.done():
await ctx.send("Already running")
return
autopurge.start(ctx.channel)
# Stop the loop
#autopurge.command()
async def stop(ctx):
task = autopurge.get_task()
if task and not task.done():
autopurge.stop()
return
await ctx.send("Loop was not running")

Discordpy, praw, blocking

So i'm writing discord bot on python, and i want to make background task which would check subreddit for new submissions and post it if there's certain flair. But when i'm trying to start my bot, which worked perfect before, it just wait for something and doesn't start. What should i do?
async def reddit_task():
await bot.wait_until_ready()
start_time = time.time()
reddit = praw.Reddit(different keys)
subreddit = reddit.subreddit('certain subreddit')
for submission in subreddit.stream.submissions():
if submission.created_utc > start_time:
if submission.link_flair_text == 'certain flair':
em = discord.Embed(title=submission.title+'\n'+submission.shortlink)
if len(submission.preview) > 1:
em.set_image(url=submission.preview['images'][0]['source']['url'])
await bot.send_message(discord.Object(id='my channel id'), embed=em)
else:
pass
if __name__ == "__main__":
for extension in startup_extensions:
try:
bot.load_extension(extension)
except Exception as e:
exc = '{}: {}'.format(type(e).__name__, e)
print('Failed to load extension {}\n{}'.format(extension, exc))
bot.loop.create_task(reddit_task())
bot.run(config.bot_beta_token)
I ran into this problem as well since subreddit.stream.submissions() is blocking the for loop. So I solved it by using an infinite loop and subreddit.stream.submissions(pause_after=0) so it returns None if there are no new posts then waits 60 seconds before checking again.
async def reddit_task():
await client.wait_until_ready()
start_time = time.time()
reddit = praw.Reddit("<client_stuff>")
subreddit = reddit.subreddit("<some_subreddit>")
submissions = subreddit.stream.submissions(pause_after=0)
while not client.is_closed:
submission = next(submissions)
if submission is None:
# Wait 60 seconds for a new submission
await asyncio.sleep(60)
elif submission.created_utc > start_time:
<do_stuff_with_submission>

Categories

Resources