Browse Source

Upload files to 'chatbot/actions'

SadhulaSaiKumar 2 years ago
parent
commit
c08ae8f073
2 changed files with 170 additions and 0 deletions
  1. BIN
      chatbot/actions/__init__.py
  2. 170
    0
      chatbot/actions/actions.py

BIN
chatbot/actions/__init__.py View File


+ 170
- 0
chatbot/actions/actions.py View File

@@ -0,0 +1,170 @@
1
+# This files contains your custom actions which can be used to run
2
+# custom Python code.
3
+#
4
+# See this guide on how to implement these action:
5
+# https://rasa.com/docs/rasa/custom-actions
6
+
7
+
8
+# This is a simple example for a custom action which utters "Hello World!"
9
+
10
+from typing import Any, Text, Dict, List
11
+
12
+from rasa_sdk import Action, Tracker
13
+from rasa_sdk.executor import CollectingDispatcher
14
+from flask import request
15
+import json
16
+
17
+
18
+class ActionService(Action):
19
+
20
+    def name(self) -> Text:
21
+        return "action_service"
22
+
23
+    def run(self, dispatcher: CollectingDispatcher,
24
+            tracker: Tracker,
25
+            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
26
+    	buttons=[
27
+    		{"payload":'/docs{"content_type":"blogs"}',"title":"yes"},
28
+    		{"payload":'/video{"content_type":"video"}',"title":"no"},
29
+
30
+    	]
31
+    	dispatcher.utter_message(text="Are you satisfied with above solution",buttons=buttons)
32
+    	return []
33
+
34
+
35
+
36
+
37
+
38
+class ActionService(Action):
39
+
40
+    def name(self) -> Text:
41
+        return "action_suport_service"
42
+
43
+    def run(self, dispatcher: CollectingDispatcher,
44
+            tracker: Tracker,
45
+            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
46
+        buttons=[
47
+            {"payload":'/connect_support{"content_type":"text"}',"title":"yes"},
48
+            {"payload":'/noconnect_support{"content_type":"text"}',"title":"no"},
49
+
50
+        ]
51
+        dispatcher.utter_message(text="do you want me to connect to support team",buttons=buttons)
52
+        return []
53
+
54
+question=[]
55
+answer=[]
56
+class ActionSaveConversation(Action):
57
+    def name(self) -> Text:
58
+        return "action_save_conersation"
59
+
60
+    def run(self,
61
+            dispatcher: CollectingDispatcher,
62
+            tracker: Tracker,
63
+            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
64
+
65
+        
66
+        sender_id = tracker.sender_id
67
+        #print(tracker.events)
68
+        conversation=tracker.events
69
+        import os
70
+        if not os. path.isfile('chats.txt'):
71
+            with open('chats.txt ','w') as file:
72
+                file.write("user_input $$$$ bot_reply\n")
73
+        chat_data=''
74
+        for i in conversation:
75
+            if i['event'] == 'user':
76
+                chat_data+=i['parse_data']['intent']['name']
77
+                print('user: {}'.format(i['text']))
78
+                a='user{}: {}'.format(sender_id,i['text'])
79
+                question.append(a)
80
+                if len(i['parse_data']['entities']) > 0:
81
+                    chat_data+=i['parse_data']['entities'][0]['entity']+', '+i['parse_data']['entities' ][0]['value']+','
82
+                    print('extra data:', i['parse_data']['entities'][0]['entity'], '=',
83
+                            i['parse_data']['entities'][0]['value'])
84
+            elif i['event'] == 'bot':
85
+                print('{}'.format(i['text']))
86
+                b='Bot{}: {}'.format(sender_id,i['text'])
87
+                question.append(b)
88
+                # try:
89
+                #     chat_data+=i['metadata']['utter_action']+','+i['text']+'\n'
90
+                # except KeyError:
91
+                #     pass 
92
+                chat_data+=i['text']+'\n'
93
+
94
+        else:
95
+            with open('chats.txt','a') as file:
96
+                file.write(chat_data)
97
+        #print(question)
98
+        import pandas as pd
99
+        df=pd.DataFrame(question)
100
+        print(df)
101
+        conversation=None
102
+        question.clear()
103
+        print(conversation)
104
+        print(question)
105
+
106
+        print(sender_id)
107
+
108
+     #   print(answer)
109
+        # a=question
110
+        # b=answer
111
+        # import numpy as np
112
+        # import pandas as pd
113
+        # if len(a) > len(b):
114
+        #     b = np.pad(b, (0, len(a) - len(b)), 'constant')
115
+        # else:
116
+        #     a = np.pad(a, (0, len(b) - len(a)), 'constant')
117
+        # df=pd.DataFrame({'question':a,"answer":b})
118
+        # print(df)
119
+        dispatcher.utter_message(text="All Chats saved")
120
+
121
+        return []
122
+
123
+
124
+
125
+class ActionSaveConversation(Action):
126
+    def name(self) -> Text:
127
+        return "action_save_conersation"
128
+
129
+    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
130
+        # Get sender_id
131
+        sender_id = tracker.sender_id
132
+
133
+        conversation = tracker.events
134
+        chat_data = []
135
+        for i in conversation:
136
+            if i['event'] == 'user':
137
+                text = i['text'].replace('/connect_support{"content_type":"text"}', 'yes').replace('/noconnect_support{"content_type":"text"}','No').replace('/docs{"content_type":"blogs"}','yes').replace('/video{"content_type":"video"}','No')
138
+                chat_data.append({'sender': f'user_{sender_id}', 'message': text})
139
+                print(f'user_{sender_id}: {i["text"]}')
140
+                if len(i['parse_data']['entities']) > 0:
141
+                    print('extra data:', i['parse_data']['entities'][0]['entity'], '=',
142
+                          i['parse_data']['entities'][0]['value'])
143
+            elif i['event'] == 'bot':
144
+                print(f'bot_{sender_id}: {i["text"]}')
145
+                chat_data.append({'sender': f'bot_{sender_id}', 'message': i['text']})
146
+
147
+        with open('chats.json', 'w') as file:
148
+            json.dump({'conversation': chat_data, 'sender_id': sender_id}, file)
149
+            file.write('\n')
150
+            file.close()
151
+        print(json.dumps({'conversation': chat_data, 'sender_id': sender_id}, indent=4))
152
+        conversation = None
153
+
154
+        return []
155
+
156
+
157
+class ActionClearConversation(Action):
158
+    def name(self) -> Text:
159
+        return "action_clear_conversation"
160
+
161
+    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
162
+
163
+        sender_id = tracker.sender_id
164
+        tracker.events = []
165
+
166
+        return []
167
+
168
+
169
+
170
+

Loading…
Cancel
Save