Esempio n. 1
0
def slack_bot():
    global state, context
    if not context:
        context = {}
    if request.json['type'] == 'url_verification':
        return request.json['challenge']

    # TODO: parse and filter and delegate responses
    event_type = request.json['event']['type']
    channel = request.json['event']['channel']

    # Check if it's the bot's message - ignore it
    # This does not work at all!
    username = request.json['event'].get('username', '')

    # print(request.json['event'])

    if get_bot_username() == username:
        return ''

    def reply(text):
        '''A reply is just a message back to the channel that messaged us.'''
        return send_message(text, event_type, channel)

    # TODO: what field is the message?
    handle_message(request.json['event']['text'], reply, state, context)

    return ''
Esempio n. 2
0
    def test_handle_message__valid_post(self):
        current_server = {
            'server_id':
            1,
            'infracted_at':
            datetime.datetime.now() - datetime.timedelta(minutes=30),
            'calledout_at':
            datetime.datetime.now() - datetime.timedelta(minutes=30),
            'awake':
            True
        }
        server_dao = Mock(
            **{
                'get_server.return_value': current_server,
                'insert_server.return_value': None
            })
        message = Mock(
            **{
                'server': Mock(**{'id': 1}),
                'content': "I am a good boy",
                'author': Mock(**{
                    'id': 2,
                    'mention': "@test"
                }),
            })
        message_to_send = bot.handle_message(server_dao, message, 1)

        self.assertFalse(message_to_send)
Esempio n. 3
0
    def test_handle_message__infringing_post_on_cooldown(self):
        current_server = {
            'server_id':
            1,
            'infracted_at':
            datetime.datetime.now() - datetime.timedelta(minutes=30),
            'calledout_at':
            datetime.datetime.now() - datetime.timedelta(minutes=20),
            'awake':
            True
        }
        server_dao = Mock(
            **{
                'get_server.return_value': current_server,
                'insert_server.return_value': None
            })
        message = Mock(
            **{
                'server': Mock(**{'id': 1}),
                'content': "vore",
                'author': Mock(**{
                    'id': 2,
                    'mention': "@test"
                }),
            })
        message_to_send = bot.handle_message(server_dao, message, 1)

        self.assertEqual(message_to_send, False)
Esempio n. 4
0
    def test_handle_message__infringing_post(self):
        current_server = {
            'server_id':
            1,
            'infracted_at':
            datetime.datetime.now() - datetime.timedelta(minutes=30),
            'calledout_at':
            datetime.datetime.now() - datetime.timedelta(minutes=30),
            'awake':
            True
        }
        server_dao = Mock(
            **{
                'get_server.return_value': current_server,
                'insert_server.return_value': None
            })
        message = Mock(
            **{
                'server': Mock(**{'id': 1}),
                'content': "vore",
                'author': Mock(**{
                    'id': 2,
                    'mention': "@test"
                }),
            })
        message_to_send = bot.handle_message(server_dao, message, 1)

        self.assertEqual(
            message_to_send,
            "@test referenced the forbidden word, setting the counter back to 0. I'll wait a half hour before warning you again.\n The server went 30 minutes and 0 seconds without mentioning it."
        )
Esempio n. 5
0
    def test_handle_message__infringing_post_unicode(self, sPostMock,
                                                     bPostMock, fetchMock):
        message1 = Mock(
            **{
                'server': Mock(**{'id': 1}),
                'content': "vÒrË",
                'author': Mock(**{
                    'id': 2,
                    'mention': "@test",
                    'bot': False
                }),
            })

        message2 = Mock(
            **{
                'server': Mock(**{'id': 1}),
                'content': "vᴑRè",
                'author': Mock(**{
                    'id': 2,
                    'mention': "@test",
                    'bot': False
                }),
            })

        message3 = Mock(
            **{
                'server': Mock(**{'id': 1}),
                'content': "vÓrËD",
                'author': Mock(**{
                    'id': 2,
                    'mention': "@test",
                    'bot': False
                }),
            })

        message_to_send1 = bot.handle_message(message1, self.current_time,
                                              None)
        self.assertEqual(message_to_send1, self.infringedString)
        message_to_send2 = bot.handle_message(message2, self.current_time,
                                              None)
        self.assertEqual(message_to_send1, self.infringedString)
        message_to_send3 = bot.handle_message(message3, self.current_time,
                                              None)
        self.assertEqual(message_to_send1, self.infringedString)
Esempio n. 6
0
    def test_handle_message__infringing_post_formatting(
            self, sPostMock, bPostMock, fetchMock):
        message1 = Mock(
            **{
                'server': Mock(**{'id': 1}),
                'content': "-v-o-r-e-",
                'author': Mock(**{
                    'id': 2,
                    'mention': "@test",
                    'bot': False
                }),
            })

        message2 = Mock(
            **{
                'server': Mock(**{'id': 1}),
                'content': "**v**o**r**e**",
                'author': Mock(**{
                    'id': 2,
                    'mention': "@test",
                    'bot': False
                }),
            })

        message3 = Mock(
            **{
                'server': Mock(**{'id': 1}),
                'content': "|||v||||o||||r||e|||",
                'author': Mock(**{
                    'id': 2,
                    'mention': "@test",
                    'bot': False
                }),
            })

        message_to_send1 = bot.handle_message(message1, self.current_time,
                                              None)
        self.assertEqual(message_to_send1, self.infringedString)
        message_to_send2 = bot.handle_message(message2, self.current_time,
                                              None)
        self.assertEqual(message_to_send1, self.infringedString)
        message_to_send3 = bot.handle_message(message3, self.current_time,
                                              None)
        self.assertEqual(message_to_send1, self.infringedString)
Esempio n. 7
0
    def test_handle_message__help_backup(self, helpMock, sMock):
        message = Mock(
            **{
                'server': Mock(**{'id': 1}),
                'content': "!vthelp",
                'author': self.admin,
            })

        message_to_send = bot.handle_message(message, self.current_time, None)
        self.assertTrue(helpMock.called)
Esempio n. 8
0
    def test_handle_message__VT_delay_nonadmin(self, timeMock, sMock):
        message = Mock(
            **{
                'server': Mock(**{'id': 1}),
                'content': "!baddelay 1",
                'author': self.nonadmin,
            })

        message_to_send = bot.handle_message(message, self.current_time, None)
        self.assertFalse(timeMock.called)
Esempio n. 9
0
    def test_handle_message__VT_extra(self, vtMock, sMock):
        message = Mock(
            **{
                'server': Mock(**{'id': 1}),
                'content': "!bad test",
                'author': self.nonadmin,
            })

        message_to_send = bot.handle_message(message, self.current_time, None)
        self.assertTrue(vtMock.called)
Esempio n. 10
0
    def test_handle_message__bad_prefix(self, noMock, sMock):
        message = Mock(
            **{
                'server': Mock(**{'id': 1}),
                'content': "!vt",
                'author': self.nonadmin,
            })

        message_to_send = bot.handle_message(message, self.current_time, None)
        self.assertTrue(noMock.called)
Esempio n. 11
0
    def test_handle_message__VT_silence(self, silenceMock, sMock):
        message = Mock(
            **{
                'server': Mock(**{'id': 1}),
                'content': "!badsilence",
                'author': self.admin,
            })

        message_to_send = bot.handle_message(message, self.current_time, None)
        self.assertTrue(silenceMock.called)
Esempio n. 12
0
    def test_handle_message__valid_post(self, sPostMock, bPostMock, fetchMock):
        message = Mock(
            **{
                'server': Mock(**{'id': 1}),
                'content': "I am a good boy",
                'author': Mock(**{
                    'id': 2,
                    'mention': "@test",
                    'bot': False
                }),
            })

        message_to_send = bot.handle_message(message, self.current_time, None)
        self.assertFalse(message_to_send)
Esempio n. 13
0
    def test_handle_message__infringing_post_embedded_hyphen(
            self, sPostMock, bPostMock, fetchMock):
        message = Mock(
            **{
                'server': Mock(**{'id': 1}),
                'content': "asdf-vore-is the worst ",
                'author': Mock(**{
                    'id': 2,
                    'mention': "@test",
                    'bot': False
                }),
            })

        message_to_send = bot.handle_message(message, self.current_time, None)
        self.assertEqual(message_to_send, self.infringedString)
Esempio n. 14
0
    def test_handle_message__infringing_post(self, sPostMock, bPostMock,
                                             fetchMock):
        message = Mock(
            **{
                'server': Mock(**{'id': 1}),
                'content': "vore",
                'author': Mock(**{
                    'id': 2,
                    'mention': "@test",
                    'bot': False
                }),
            })
        message_to_send = bot.handle_message(message, self.current_time, None)

        self.assertEqual(message_to_send, '')
Esempio n. 15
0
    def test_handle_message__valid_post(self):
        message = Mock(**{
            'server': Mock(**{
                'id': 1
            }),
            'content': "I am a good boy",
            'author': Mock(**{
                'id': 2,
                'mention': "@test",
                'bot': False
            }),
        })

        message_to_send = bot.handle_message(self.server_dao, message, 1, self.current_time)
        self.assertFalse(message_to_send)
Esempio n. 16
0
    def test_handle_message__infringing_post_from_bot(self):
        message = Mock(**{
            'server': Mock(**{
                'id': 1
            }),
            'content': "asdf vore is the worst ",
            'author': Mock(**{
                'id': 2,
                'mention': "@test",
                'bot': True
            }),
        })

        message_to_send = bot.handle_message(self.server_dao, message, 1, self.current_time)
        self.assertFalse(message_to_send)
Esempio n. 17
0
    def test_handle_message__infringing_post_embedded(self):
        message = Mock(**{
            'server': Mock(**{
                'id': 1
            }),
            'content': "asdf vore is the worst ",
            'author': Mock(**{
                'id': 2,
                'mention': "@test",
                'bot': False
            }),
        })

        message_to_send = bot.handle_message(self.server_dao, message, 1, self.current_time)
        self.assertEqual(message_to_send, self.infringedString)
Esempio n. 18
0
    def test_handle_message__different_word(self):
        message = Mock(**{
            'server': Mock(**{
                'id': 1
            }),
            'content': "bepis is good",
            'author': Mock(**{
                'id': 2,
                'mention': "@test",
                'bot': False
            }),
        })

        message_to_send = bot.handle_message(self.server_dao, message, 1, self.current_time)

        infringedString = "@test referenced a forbidden word, setting its counter back to 0.\n"
        infringedString += "I'll wait 30 minutes and 0 seconds before warning you for this word again.\n"
        infringedString += "The server went 30 minutes and 0 seconds without mentioning the forbidden word 'bepis'."
        self.assertEqual(message_to_send, infringedString)
Esempio n. 19
0
    def test_handle_message__different_word(self, sPostMock, bPostMock,
                                            fetchMock):
        message = Mock(
            **{
                'server': Mock(**{'id': 1}),
                'content': "bepis is good",
                'author': Mock(**{
                    'id': 2,
                    'mention': "@test",
                    'bot': False
                }),
            })

        message_to_send = bot.handle_message(message, self.current_time, None)

        infringedString = "@test referenced the forbidden word 'bepis', breaking a streak of 30 minutes and 0 seconds.\n"
        infringedString += "I'll wait 30 minutes and 0 seconds before warning you for this word again."

        self.assertEqual(message_to_send, infringedString)
Esempio n. 20
0
def webhook_callback():
    ###
    logger.info("MESSAGING EVENT RECEIVED.")
    ###

    data = request.json

    # ensure that callback came from a "page" object
    if data["object"] == "page":
        # go through each entry
        for entry in data["entry"]:
            # only if messaging
            if "messaging" in entry:
                # go through each messaging event
                for event in entry["messaging"]:
                    # check if we have a new message
                    if "message" in event:

                        ###
                        logger.info("MESSAGE RECEIVED.")
                        ###

                        # get sender
                        sender = event["sender"]["id"]
                        # get session token
                        token = session_manager.get_session_token(sender)
                        # try and find session
                        existing_session = session_manager.get_session(token)
                        # get message
                        message = event["message"]
                        # check to see if this is a new user/session
                        if existing_session is None:
                            ###
                            logger.info("New session: {}".format(sender))
                            ###

                            # mark seen
                            send_mark_seen(sender)

                            session_manager.create_session(sender, **{
                                "context": {},
                                "lang": 0
                            })
                        # check to see if it is a message or attachment
                        elif "attachments" in message:

                            ###
                            logger.info("Attachment received from: {}".format(sender))
                            ###

                            # typing...
                            send_typing(sender)
                            # cannot process attachments
                            send_message(sender, "I can't do much with that, but if you send me a name of a country, I can tell you the travel advisory for it.")
                        elif "text" in message:

                            ###
                            logger.info("Text received from: {}".format(sender))
                            ###

                            # typing...
                            send_typing(sender)
                            # get session ID
                            session_id = session_manager.get_session_token(sender)
                            # converse
                            response = wit.message(msg=message["text"], context={"session_id": session_id})
                            # respond
                            handle_message(response, session_id)
                    # check if we have a message delivered
                    elif "delivery" in event:
                        ###
                        logger.info("MESSAGE DELIVERED.")
                        ###
                    # check if a message was read
                    elif "read" in event:
                        ###
                        logger.info("MESSAGE READ.")
                        ###
                    # check if we have a postback
                    elif "postback" in event:
                        ###
                        logger.info("POSTBACK RECEIVED.")
                        ###

                        # get sender
                        sender = event["sender"]["id"]
                        # get postback data
                        postback = event["postback"]
                        payload = postback["payload"]
                        # what do I do?
                        if payload == "WHAT_DO_I_DO":
                            # typing...
                            send_typing(sender)
                            # cannot process attachments
                            send_message(sender, "I want you to help you stay informed when travelling abroad. Ask me something like \"What is the current travel advisory for the Brazil?\".")
                    else:

                        ###
                        logger.error("UKNOWN MESSAGING EVENT.")
                        ###

    return make_response(jsonify({}), 200)
Esempio n. 21
0
 def user_message(self, message, author=create_discord_user()):
     """Use @bot for mentions"""
     coroutine = handle_message(
         self._create_fake_discord_message(
             self._preprocess_test_discord_message(message), author=author))
     asyncio.get_event_loop().run_until_complete(coroutine)