File size: 5,859 Bytes
b13eb29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5487a42
 
b13eb29
5487a42
 
 
b13eb29
 
71a0008
5487a42
b13eb29
39bcecc
71a0008
 
 
 
 
 
 
 
 
 
 
39bcecc
 
 
 
b13eb29
 
 
 
 
 
71a0008
b13eb29
71a0008
b13eb29
39bcecc
71a0008
5487a42
39bcecc
 
 
5487a42
39bcecc
 
5487a42
39bcecc
b13eb29
71a0008
b13eb29
 
 
5487a42
b13eb29
 
 
71a0008
 
39bcecc
71a0008
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
# import asyncio
# import socketio
# import logging

# # Configure logging
# logging.basicConfig(level=logging.DEBUG)
# logger = logging.getLogger(__name__)

# class RasaSocketIOClient:
#     def __init__(self, uri):
#         self.sio = socketio.AsyncClient(logger=True, engineio_logger=True)  # Enable internal logging
#         self.uri = uri
#         self.response = None

#         @self.sio.on('bot_uttered')  # Adjust the event name as per your Rasa setup
#         async def on_message(data):
#             logger.info("Received response: %s", data)
#             self.response = data  # Store the latest response

#     async def connect(self):
#         try:
#             await self.sio.connect(self.uri)
#             logger.info("Successfully connected to the server.")
#         except Exception as e:
#             logger.error("Failed to connect to the server: %s", e)

#     async def send_message(self, message):
#         self.response = None  # Reset previous response
#         try:
#             await self.sio.emit('user_uttered', message)  # Adjust the event name as per your Rasa setup
#             logger.debug("Message sent: %s", message)
#             await asyncio.sleep(1)  # Wait for the response to be received
#         except Exception as e:
#             logger.error("Failed to send message: %s", e)
#         return self.response

#     async def disconnect(self):
#         try:
#             await self.sio.disconnect()
#             logger.info("Disconnected from the server.")
#         except Exception as e:
#             logger.error("Failed to disconnect: %s", e)


# import asyncio
# import socketio
# import logging
# from custom_logging import IMPORTANT_LEVEL_NUM 

# logger = logging.getLogger(__name__)

# class RasaSocketIOClient:
#     def __init__(self, uri):
#         self.sio = socketio.AsyncClient(logger=False, engineio_logger=False)
#         self.response_event = asyncio.Event()
#         self.uri = uri
#         self.response = None

#         @self.sio.on('bot_uttered')  # Adjust the event name as per your Rasa setup
#         async def on_message(data):
#             # Use the new logging level
#             logger.important("Socket ID: %s Received response: %s", self.sio.sid, data)
#             self.response = data  # Store the latest response

#     async def connect(self):
#         try:
#             await self.sio.connect(self.uri)
#             # Use the new logging level
#             logger.important("Successfully connected to the server.")
#         except Exception as e:
#             # Use the new logging level for errors too, for consistency
#             logger.important("Failed to connect to the server: %s", e)
#             return "Failed to connect to the server."

#     async def send_message(self, message):
#         self.response = None  # Reset previous response
#         try:
#             await self.sio.emit('user_uttered', message)  # Adjust the event name as per your Rasa setup
#             # Since this is more of a debug level, consider if you want to keep it under IMPORTANT or not
#             logger.important("Message sent: %s", message)
#             await asyncio.sleep(1)  # Wait for the response to be received
#         except Exception as e:
#             logger.important("Failed to send message: %s", e)
#         return self.response

#     async def disconnect(self):
#         try:
#             await self.sio.disconnect()
#             logger.important("Disconnected from the server.")
#         except Exception as e:
#             logger.important("Failed to disconnect: %s", e)


import asyncio
import socketio
import logging
import custom_logging


# Obtain a logger for this module
logger = logging.getLogger(__name__)

class RasaSocketIOClient:
    def __init__(self, uri, update_chat_history_callback=None):
        self.sio = socketio.AsyncClient(logger=False, engineio_logger=False)
        self.uri = uri
        self.message_queue = asyncio.Queue()
        self.register_event_handlers()

    def register_event_handlers(self):
        @self.sio.event
        async def connect():
            logger.important("Connected to the server.")

        @self.sio.event
        async def disconnect():
            logger.important("Disconnected from the server.")

        @self.sio.on('bot_uttered')
        async def on_message(data):
            logger.debug(f"Socket ID: {self.sio.sid} Received response: {data}")
            await self.message_queue.put(data)  # Put received message into the queue

    async def connect(self):
        try:
            await self.sio.connect(self.uri)
            logger.important("Successfully connected to the server.")
        except Exception as e:
            logger.error(f"Failed to connect to the server: {e}")

    async def send_message(self, user_message):
        try:
            await self.sio.emit('user_uttered', {'message': user_message})
            logger.important(f"Message sent: {user_message}")
            timeout = 5.0  # Timeout in seconds after the last message is received
            while True:
                try:
                    data = await asyncio.wait_for(self.message_queue.get(), timeout)
                    logger.important(f"Message in queue: {user_message}")
                    yield data
                except asyncio.TimeoutError:
                    logger.important(f"send_message function timed out")
                    break
        except Exception as e:
            logger.error(f"Failed to send message: {e}")

    async def disconnect(self):
        try:
            logger.important(f"Attempting to disconnect: {id(self.sio)}")
            await self.sio.disconnect()
            logger.important("Disconnected from the server.")
        except Exception as e:
            logger.error(f"Failed to disconnect: {e}")