def setUp(self): self.factory = APIRequestFactory() self.start_state = 'hillary' self.bot = Bot(self.start_state) self.user = User.objects.create_user(username='******', password='******', email='*****@*****.**') self.client = Client.objects.first()
class BotTest(TestCase): def setUp(self): self.factory = APIRequestFactory() self.start_state = 'hillary' self.bot = Bot(self.start_state) self.user = User.objects.create_user(username='******', password='******', email='*****@*****.**') self.client = Client.objects.first() def test_start_test(self): json_data = { "questions": [{ "text": "hillary", "quick_replies": "yes, no" }, { "text": "billiard", "quick_replies": "1, 2" }], "answers": [{ "name": "maddy", "type": "A", "text": "catty", "description": "physics" }, { "name": "patty", "type": "A", "text": "sreadily", "description": "open source" }], "transitions": [{ "current_state": "hillary", "answer": "maddy", "next_state": "billiard" }, { "current_state": "billiard", "answer": "patty", "next_state": "" }], "tree": [{ "trigger": "assscssary", "root_state": "hillary", "completion_text": "Thanks man ..!!" }] } request = self.factory.post( '/chat/tree/', format='json', data=json_data, HTTP_CHATBOT_CLIENT_KEY=self.client.key, HTTP_CHATBOT_CLIENT_SECRET=self.client.secret) response = TreeViewSet.as_view()(request) self.assertEqual(response.status_code, status.HTTP_201_CREATED) current_state = Tree.objects.first().root_state user_input = 'catty' state = self.bot.get_next_state(current_state, user_input) self.assertEqual(state.name, 'billiard')
def api_bot_task(request, task_id): messages = [] try: task = Task.objects.get(pk=task_id) task.status = Task.TASK_STATUS_PROCESS task.save() task_command = task.task args = json.loads(task.args) # For REMIND command we need additional argument: timestamp when task created if task_command == 'REMIND': args.append(time.mktime(task.created_at.timetuple())) result = Bot.run_command(task_command, args) task.status = Task.TASK_STATUS_COMPLETE task.result = json.dumps(result) task.save() cur_date = datetime.datetime.now().strftime('%d.%m.%Y %H:%M:%S') # Message for send to client bot_message = { 'time': cur_date, 'nick': 'Bot', 'text': 'Результат выполнения команды {0}: {1}'.format(task_command, result) } if task_command == 'REMIND': bot_message['text'] = 'Напоминаю: {0}'.format(result) messages.append(bot_message) if result != -1: # Store messages ... Message.from_messages(messages) return JsonResponse({'result': result, 'messages': messages}) except Task.DoesNotExist: return JsonResponse({'result': 0, 'error': 'Incorrect task_id'})
def api_bot_command(request): command_str = request.GET.get('command', False) res = Bot.parse_command_string(command_str) # res = Bot.parse_command_string("Бот, дай мне заголовок сайта http://ya.ru") # res = Bot.parse_command_string("Бот, напомни мне ололо через 5") cur_date = datetime.datetime.now().strftime('%d.%m.%Y %H:%M:%S') messages = [] # If command not recognized if res is False: # Messages for send to client user_message = {'time': cur_date, 'nick': request.session['nick'], 'text': command_str} bot_message = {'time': cur_date, 'nick': 'Bot', 'text': 'Команда не распознана'} messages.append(user_message) messages.append(bot_message) # Store messages ... Message.from_messages(messages) return JsonResponse({'task_id': 0, 'error': 'Incorrect command', 'messages': messages}) else: # Right command task_str = getattr(Task, 'TASK_{0}'.format(res['command'])) task = Task() task.task = task_str task.args = json.dumps(res['args']) task.save() # Messages for send to client user_message = {'time': cur_date, 'nick': request.session['nick'], 'text': command_str} bot_message = {'time': cur_date, 'nick': 'Bot', 'text': 'Команда {0} успешно добавлена'.format(res['command'])} messages.append(user_message) messages.append(bot_message) # Store messages ... Message.from_messages(messages) return JsonResponse({'task_id': task.pk, 'task': res['command'], 'messages': messages})
def connect(self): # TODO: Find a more sensible authentication strategy using twitch 'sub' id perhaps # Ensure user has valid session decoded = verify_and_decode_jwt(self.scope['cookies']['token']) if decoded['preferred_username'] == self.scope['url_route']['kwargs'][ 'room_name']: # Accept connection self.accept() # Get user self.user_id = decoded['sub'] self.twitch_user = Twitch_User.objects.get(pk=self.user_id) self.chat_responses = ChatResponse.objects.filter( twitch_user=self.twitch_user) # Get channel name from route self.channel = self.scope['url_route']['kwargs']['room_name'] # Instantiate chat bot self.bot = Bot(self.chat_responses) # Start a Twitch Chat listener on user's channel self.twitch_chat = TwitchIrc(self.channel) self.twitch_chat.listen(lambda msg: self.message(msg))
def update_responses(self): self.chat_responses = ChatResponse.objects.filter( twitch_user=self.twitch_user) self.bot = Bot(self.chat_responses)
class ChatConsumer(WebsocketConsumer): def connect(self): # TODO: Find a more sensible authentication strategy using twitch 'sub' id perhaps # Ensure user has valid session decoded = verify_and_decode_jwt(self.scope['cookies']['token']) if decoded['preferred_username'] == self.scope['url_route']['kwargs'][ 'room_name']: # Accept connection self.accept() # Get user self.user_id = decoded['sub'] self.twitch_user = Twitch_User.objects.get(pk=self.user_id) self.chat_responses = ChatResponse.objects.filter( twitch_user=self.twitch_user) # Get channel name from route self.channel = self.scope['url_route']['kwargs']['room_name'] # Instantiate chat bot self.bot = Bot(self.chat_responses) # Start a Twitch Chat listener on user's channel self.twitch_chat = TwitchIrc(self.channel) self.twitch_chat.listen(lambda msg: self.message(msg)) def disconnect(self, close_code): self.close() pass # Called by Twitch chat listener on new message def message(self, msg): if msg: # Messages beginning with '#' are bot responses and should be ignored if msg[0] == '#': return # Relay message from Twitch chat to dashboard chat self.send(text_data=json.dumps({'message': msg})) # Send message to bot and get response response = self.bot.get_response(msg) # Send response to Twitch chat listener to send to Twitch chat if response: self.twitch_chat.send(response) # Receive messages from socket connection with user client def receive(self, text_data): data = json.loads(text_data) # Chat responses need to be updated # (There were changed via the API) if data.get('update'): self.update_responses() # elif data.get('message'): # message = text_data_json['message'] # self.send(text_data=json.dumps({ # 'message': message # })) # Create new bot with updated chat responses def update_responses(self): self.chat_responses = ChatResponse.objects.filter( twitch_user=self.twitch_user) self.bot = Bot(self.chat_responses)