I use Scheduled Celery workers to perform a loop of sending WebSocket events, but it doesn't seem to work inside tasks.py.
I tested inside views.py and that seems to work, but I need to send them in tasks.py, does anyone has any fix for this?
consumers.py
class RouletteConsumer(WebsocketConsumer):
def connect(self):
self.room_group_name = 'roulette'
async_to_sync(self.channel_layer.group_add)(
self.room_group_name,
self.channel_name
)
self.accept()
self.send(text_data=json.dumps({
'type':'connection_established',
'message': "Working"
}))
def receive(self, text_data):
text_data_json = json.loads(text_data)
bet_data = text_data_json['bet_data']
async_to_sync(self.channel_layer.group_send)(
self.room_group_name,
{
'type':'send_bet',
'bet_data': bet_data,
}
)
def send_bet(self, event):
print("EVENT TRIGGERED")
bet_data = event['bet_data']
self.send(text_data=json.dumps({
'type':'bet',
'bet_data': bet_data
}))
def current_state(self, event, type='current_state'):
print("EVENT TRIGGERED")
message = event['message']
self.send(text_data=json.dumps({
'type':'state',
'current_state': message
}))
tasks.py
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
@app.task
def change_state(*args, **kwargs):
channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)(
'roulette',
{
'type': 'current_state',
'message': "EVENT TRIGGERED"
}
)