Created
March 24, 2022 10:53
-
-
Save DanyF-github/e7c080e78700859ca4a438e4d9e51e65 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
json | |
from channels.generic.websocket import WebsocketConsumer | |
from asgiref.sync import async_to_sync | |
from django.contrib.contenttypes.models import ContentType | |
from .models import Message | |
from .views import send_outbound | |
from lead_manager.models import Lead, Agent | |
def create_conversation_group(convo_id): | |
return "conversation_%s" % convo_id | |
class ConversationConsumer(WebsocketConsumer): | |
def connect(self): | |
self.lead_id = self.scope['url_route']['kwargs']['lead_id'] | |
self.conversation = create_conversation_group(self.lead_id) | |
self.agent = getattr(self.scope['user'], 'agent', None) | |
try: | |
self.lead = Lead.objects.get(id=self.lead_id) | |
except Lead.DoesNotExist: | |
self.lead = None | |
# join conversation | |
async_to_sync(self.channel_layer.group_add)( | |
self.conversation, | |
self.channel_name | |
) | |
self.accept() | |
def disconnect(self, exit_code): | |
# leave conversation | |
async_to_sync(self.channel_layer.group_discard)( | |
self.conversation, | |
self.channel_name | |
) | |
def save_message(self, message_data): | |
if self.agent: | |
sender_type = ContentType.objects.get_for_model(self.agent) | |
message_data['sender_type'] = sender_type | |
message_data['sender_id'] = self.agent.id | |
if self.lead: | |
receiver_type = ContentType.objects.get_for_model(self.lead) | |
message_data['receiver_type'] = receiver_type | |
message_data['receiver_id'] = self.lead.id | |
message = Message.objects.create(**message_data) | |
return message | |
def receive(self, text_data): | |
data = json.loads(text_data) | |
message = data['message'] | |
saved_message = self.save_message({'body': message}) | |
if self.lead: | |
# send message to Lead on social media (Facebook) | |
response = send_outbound(message, self.lead.facebook_id) | |
if response and response.ok: | |
response_data = response.json() | |
saved_message.is_delivered = True | |
saved_message.message_key = response_data["message_uuid"] | |
saved_message.save() | |
# send message to everyone connected to the conversation | |
async_to_sync(self.channel_layer.group_send)( | |
self.conversation, | |
{ | |
'type': 'send_to_conversation', | |
'message': message, | |
'from_agent': True | |
} | |
) | |
def send_to_conversation(self, event): | |
# send message to Websocket | |
self.send( | |
json.dumps( | |
{ | |
"message": event['message'], | |
"from_agent": event['from_agent'], | |
} | |
) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment