Skip to content

Commit

Permalink
Merge branch 'development'
Browse files Browse the repository at this point in the history
  • Loading branch information
Ahmad Faizal B H committed Aug 22, 2020
2 parents c373cc2 + a81204f commit cff5348
Show file tree
Hide file tree
Showing 5 changed files with 142 additions and 28 deletions.
24 changes: 23 additions & 1 deletion README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ in settings.py add the following::
START_MESSAGE = "Welcome to ChatBotAI"



in urls.py add the following::

from django.chatbot.views import web_hook
Expand All @@ -42,9 +43,30 @@ in urls.py add the following::
...
]

For Microsoft Bot Framework Webhook
-----------------------------------

in addition to the above in settings.py add
::

APP_CLIENT_ID = "<Microsoft App ID>"
APP_CLIENT_SECRET = "<Microsoft App Secret>"


in urls.py add the following::

from django.chatbot.views import botframework

urlpatterns = [
...
path("botframework-webhook/",
botframework.web_hook,
name="botframework-webhook"),
...
]

Web Hook API (should authenticate before API request)
============
=====================================================
::

URL: /webhook/
Expand Down
44 changes: 23 additions & 21 deletions django_chatbot/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,18 @@ def __init__(self, sender_id, *args, **kwargs):

def __getitem__(self, key):
try:
return Memory.objects.get(sender__messengerSenderID=self.sender_id,
return Memory.objects.get(sender__sender_id=self.sender_id,
key__iexact=key).value
except Memory.DoesNotExist:
raise KeyError(key)

def __setitem__(self, key, val):
try:
memory = Memory.objects.get(sender__messengerSenderID=self.sender_id, key__iexact=key)
memory = Memory.objects.get(sender__sender_id=self.sender_id, key__iexact=key)
memory.value = val
Memory.save()
memory.save()
except Memory.DoesNotExist:
sender = Sender.objects.get(messengerSenderID=self.sender_id)
sender = Sender.objects.get(sender_id=self.sender_id)
Memory.objects.create(sender=sender, key=key.lower(), value=val)

def update(self, *args, **kwargs):
Expand All @@ -32,12 +32,12 @@ def update(self, *args, **kwargs):

def __delitem__(self, key):
try:
return Memory.objects.get(sender__messengerSenderID=self.sender_id, key=key).delete()
return Memory.objects.get(sender__sender_id=self.sender_id, key=key).delete()
except Memory.DoesNotExist:
raise KeyError(key)

def __contains__(self, key):
return Memory.objects.filter(sender__messengerSenderID=self.sender_id, key=key)
return Memory.objects.filter(sender__sender_id=self.sender_id, key=key)


class UserConversation:
Expand All @@ -47,11 +47,11 @@ def __init__(self, sender_id, *args):
self.extend(list(*args))

def get_sender(self):
return Sender.objects.get(messengerSenderID=self.sender_id)
return Sender.objects.get(sender_id=self.sender_id)

def get_conversation(self, index):
try:
conversations = Conversation.objects.filter(sender__messengerSenderID=self.sender_id)
conversations = Conversation.objects.filter(sender__sender_id=self.sender_id)
if index < 0:
index = -index - 1
conversations = conversations.order_by('-id')
Expand All @@ -78,7 +78,8 @@ def append_bot(self, message):
Conversation.objects.create(sender=self.get_sender(),message=message,bot=True)

def append_user(self, message):
Conversation.objects.create(sender=self.get_sender(),message=message,bot=False)
Conversation.objects.create(sender=self.get_sender(), message=message,
bot=False)

def __delitem__(self, index):
self.get_conversation(index).delete()
Expand All @@ -93,7 +94,7 @@ def pop(self):
raise IndexError("pop from empty list")

def __contains__(self, message):
return Conversation.objects.filter(sender__messengerSenderID=self.sender_id,
return Conversation.objects.filter(sender__sender_id=self.sender_id,
message=message)


Expand All @@ -104,31 +105,31 @@ def __init__(self, *args, **kwargs):

def __getitem__(self, sender_id):
try:
sender = Sender.objects.get(messengerSenderID=sender_id)
sender = Sender.objects.get(sender_id=sender_id)
except Sender.DoesNotExist:
raise KeyError(sender_id)
return sender.topic

def __setitem__(self, sender_id, topic):
try:
sender = Sender.objects.get(messengerSenderID=sender_id)
sender = Sender.objects.get(sender_id=sender_id)
sender.topic = topic
sender.save()
except Sender.DoesNotExist:
Sender.objects.create(messengerSenderID=sender_id, topic=topic)
Sender.objects.create(sender_id=sender_id, topic=topic)

def update(self, *args, **kwargs):
for k, v in dict(*args, **kwargs).items():
self[k] = v

def __delitem__(self, sender_id):
try:
return Sender.objects.get(messengerSenderID=sender_id).delete()
return Sender.objects.get(sender_id=sender_id).delete()
except Sender.DoesNotExist:
raise KeyError(sender_id)

def __contains__(self, sender_id):
return Sender.objects.filter(messengerSenderID=sender_id).count() > 0
return Sender.objects.filter(sender_id=sender_id).count() > 0


class UserSession:
Expand All @@ -139,11 +140,12 @@ def __init__(self, object_class, *args, **kwargs):

def __getitem__(self, sender_id):
try:
return self.objClass(Sender.objects.get(messengerSenderID=sender_id).messengerSenderID)

return self.objClass(Sender.objects.get(sender_id=sender_id).sender_id)
except:raise KeyError(sender_id)

def __setitem__(self, sender_id, val):
Sender.objects.get_or_create(messengerSenderID=sender_id)
Sender.objects.get_or_create(sender_id=sender_id)
self.objClass(sender_id, val)

def update(self, *args, **kwargs):
Expand All @@ -152,12 +154,12 @@ def update(self, *args, **kwargs):

def __delitem__(self, sender_id):
try:
return Sender.objects.get(messengerSenderID=sender_id).delete()
return Sender.objects.get(sender_id=sender_id).delete()
except:
raise KeyError(sender_id)

def __contains__(self, sender_id):
return Sender.objects.filter(messengerSenderID=sender_id).count() > 0
return Sender.objects.filter(sender_id=sender_id).count() > 0


class MyChat(Chat):
Expand All @@ -176,8 +178,8 @@ def respond(self, message, session_id):
'substitute': True
}
self.conversation[session_id].append_user(message)
message = message.rstrip(".! \n\t")
response = super().respond(message, session_id=session_id)
response = super().respond(message.rstrip(".! \n\t"),
session_id=session_id)
self.conversation[session_id].append_bot(response)
del self.attr[session_id]
return response
Expand Down
4 changes: 1 addition & 3 deletions django_chatbot/models.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
from django.db import models

# Create your models here.


class Sender(models.Model):
messengerSenderID = models.TextField()
sender_id = models.TextField()
topic = models.TextField()


Expand Down
6 changes: 3 additions & 3 deletions django_chatbot/views.py → django_chatbot/views/__init__.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from .chatbot import chat
from .models import Conversation
from ..chatbot import chat
from ..models import Conversation


@csrf_exempt
Expand All @@ -17,7 +17,7 @@ def web_hook(request):
last_message_id = request.POST.get("last_message_id")
if message:
chat.respond(message, session_id=sender_id)
msgs = Conversation.objects.filter(sender__messengerSenderID=sender_id)
msgs = Conversation.objects.filter(sender__sender_id=sender_id)
if last_message_id:
msgs = msgs.filter(id__gt=last_message_id)
count = msgs.count()
Expand Down
92 changes: 92 additions & 0 deletions django_chatbot/views/botframework.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from background_task import background
from django.conf import settings
from ..chatbot import chat
import requests
import datetime
import json


def respond(service_url, reply_to_id, from_data,
recipient_data, message, message_type, conversation):
if settings.APP_CLIENT_ID != "<Microsoft App ID>":
url = "https://login.microsoftonline.com/common/oauth2/v2.0/token"
data = {
"grant_type": "client_credentials",
"client_id": settings.APP_CLIENT_ID,
"client_secret": settings.APP_CLIENT_SECRET,
"scope": "https://api.botframework.com/.default"
}
response = requests.post(url, data)
response_data = response.json()
headers = {
"Authorization": "%s %s" % (response_data["token_type"], response_data["access_token"])
}
else:
headers = {}
if service_url[-1] != "/":
service_url += "/"
response_url = service_url + "v3/conversations/%s/activities/%s" % (conversation["id"], reply_to_id)
requests.post(
response_url,
json={
"type": message_type,
"timestamp": datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S.%f%zZ"),
"from": from_data,
"conversation": conversation,
"recipient": recipient_data,
"text": message,
"replyToId": reply_to_id
},
headers=headers
)


@background(schedule=1)
def initiate_conversation(data):
conversation_id = data["id"]
sender_id = data["conversation"]["id"]
message = chat.start_new_session(sender_id)
respond(data["serviceUrl"],
conversation_id,
data["recipient"],
{"id": sender_id},
message,
"message",
data["conversation"])


@background(schedule=1)
def respond_to_client(data):
conversation_id = data["id"]
message = data["text"]
sender_id = data["conversation"]["id"]
result = chat.respond(message, session_id=sender_id)
respond(
data["serviceUrl"],
conversation_id,
data["recipient"],
data["from"],
result,
"message",
data["conversation"]
)
del chat.attr[sender_id]


def conversation_handler(request):
data = json.loads(request.body)
# Send text message
if data["type"] == "conversationUpdate":
initiate_conversation(data)
if data["type"] == "message":
respond_to_client(data)
return HttpResponse("It's working")


@csrf_exempt
def web_hook(request):
if request.method == "POST":
return conversation_handler(request)
return HttpResponse("Invalid request method")

0 comments on commit cff5348

Please sign in to comment.