I am creating a battle game for telegram groups as my beginner's project, one player challenges the other, and then a battle happens in the chat. Now I want to implement a "timeout" function for it. I've managed to make it work using _thread:
import _thread
class Battle:
def __init__(self, chat_id):
self.chat = chat
print('Instance of battle started on chat %s' % self.chat)
self.pcount = 0
self.p1score = 0
self.p2score = 0
def reset(self):
self.pcount = 0
self.p1score = 0
self.p2score = 0
def timeout(chat_id):
time.sleep(90)
battle = battledic[chat_id]
if battledic[chat_id].timer == 1:
sendmessage(chat_id, 'no one accepted') # first parameter is the chat address and the second one is the message
battle.reset()
else:
return
battle = Battle(chat_id)
if message == "challenge":
if battle.pcount == 0:
_thread.start_new_thread(timeout, (chat_id,))
...
So basically what I'm doing is calling the timeout function, that is going to sleep in a different thread for 90 seconds, and then it checks if the battle still with only one player (pcount == 1), if it is the case, it sends the chat a message telling them the fight did not start, and then resets the battle instance.
The problem here is that I'm raising exceptions very often, even though it works fine most of the time, also sometimes it doesn't have the desired effect, closing ongoing battles. Researching I've found out that this is not the desired way of doing this butI could not find better solution, and maybe I want to run other battles from other chats in parallel too. What should be used in this case? cooperative multitasking? multiprocessing? the trheading module? thanks for any tips on this task!