예제 #1
0
 def test_create_message(self):
     message_obj = message.Message()
     assert message_obj.channel == ""
     assert message_obj.text == ("Category\n"
                                 ">%s\n"
                                 "Summarized article sent to Google NLP\n"
                                 ">>>%s")
예제 #2
0
 def test_update_message(self):
     message_obj = message.Message()
     message_obj.update_text_categorized("test/category",
                                         "Test Original Text")
     assert message_obj.text == ("Category\n"
                                 ">test/category\n"
                                 "Summarized article sent to Google NLP\n"
                                 ">>>Test Original Text")
예제 #3
0
    def categorized_message(self, category, thread_id, channel,
                            summarized_text):
        """
        Respond to a message containing an article with the
        category and summarized text of that article.

        Responds in the same channel, and if possible starts a thread to reply in

        Parameters
        ----------
        category : str
            The category that the article belongs to
        thread_id : str
            The thread ID of the parent that originally sent the article
        channel : str
            The channel that the message was sent in
            This bot must have correct permissions in slack for this channel
                channels:write
                channels:read
                channels:history
                chat:write:bot 
                incoming-webhook 
                links:read 
        original_text : str
            The summarized text of the article returned from sumy
        """

        # We've imported a Message class from `message.py` that we can use
        # to create message objects for each message we send to thread.

        # First, we'll check to see if there's already messages our bot knows
        # of for the thread.
        if self.messages.get(thread_id):
            # If we've already replied to this thread - return without re-sending a message
            return
        else:
            # If there aren't any message for that thread, we'll add a dictionary
            # of messages for that thread on our Bot's messages attribute
            self.messages[thread_id] = message.Message()

        # Alias for easier accessing
        message_obj = self.messages[thread_id]

        # Update the channel
        message_obj.channel = channel

        # Update the text with the category and summarized text
        message_obj.update_text_categorized(category=category,
                                            summarized_text=summarized_text)

        # Send the message with the bots new text
        post_message = self.client.api_call("chat.postMessage",
                                            channel=message_obj.channel,
                                            username=self.name,
                                            icon_emoji=self.emoji,
                                            text=message_obj.text,
                                            thread_ts=thread_id)
예제 #4
0
async def test_sending_previous_messages(state):
    # GIVEN
    database_mock = mocked_database.MockedDatabase()
    m1 = message.Message(1, 'sender', 'message1', 'room1', 123)
    m2 = message.Message(2, 'sender', 'message2', 'room1', 123)
    m3 = message.Message(3, 'sender', 'message3', 'room1', 123)
    database_mock.set_return_value('fetch_last_messages', [m1, m2, m3])
    state.server_obj.chatbox_database = database_mock
    await state.client.connect()
    asyncio.create_task(state.client.start_receiving())

    # WHEN
    await state.client.request_last_messages()
    await asyncio.sleep(1)

    # THEN
    assert state.client.received_messages == [
        m1.message, m2.message, m3.message
    ]
예제 #5
0
 def update_and_save_message(self, mes, chat_name, login,
                             websocket) -> message.Message:
     date_time = datetime.now(timezone.utc)
     time_millis = helper_functions.date_time_to_millis(date_time)
     if self.chatbox_database:
         updated_message = self.chatbox_database.add_message(
             login, chat_name, mes[JsonFields.MESSAGE_VALUE], date_time)
         self.log.info(
             f'{websocket} - message {updated_message} added to db, room {chat_name}'
         )
         updated_message.timestamp = time_millis
         return updated_message
     return message.Message(Constants.DEFAULT_NO_DATABASE_MESSAGE_ID, login,
                            mes[JsonFields.MESSAGE_VALUE], chat_name,
                            time_millis)
예제 #6
0
 def add_message(self, login, chat, mes, date_time) -> message.Message:
     if self.connection:
         messages = self.metadata.tables['messages']
         stm = messages.insert().values(sender_login=login,
                                        chat_name=chat,
                                        message=mes,
                                        date_time=date_time)
         entry = self.connection.execute(stm)
         self.log.debug(
             f'adding message "{mes}" to the database, sent by {login} in chat {chat}'
         )
         entry_id = entry.inserted_primary_key[0]
         return message.Message(entry_id, login, mes, chat, date_time)
     else:
         self.log.error('cannot add message to database')
예제 #7
0
 def fetch_last_messages(self,
                         chat_name,
                         n=10,
                         start_from_id=-1) -> [message.Message]:
     message_table = self.metadata.tables['messages']
     if start_from_id == -1:
         inner_query = (select([
             message_table
         ]).where(message_table.c.chat_name == chat_name).order_by(
             message_table.c.id.desc()).limit(n).alias('inner_query'))
     else:
         inner_query = (select([
             message_table
         ]).where(message_table.c.id < start_from_id).where(
             message_table.c.chat_name == chat_name).order_by(
                 message_table.c.id.desc()).limit(n).alias('inner_query'))
     n_entries: ResultProxy = self.connection.execute(
         select([inner_query]).order_by(inner_query.c.id))
     return [
         message.Message(
             entry.id, entry.sender_login, entry.message, entry.chat_name,
             helper_functions.date_time_to_millis(entry.date_time))
         for entry in n_entries
     ]
예제 #8
0
#! /usr/bin/env python
# encoding:utf-8

import time
import sys

sys.path.append("../")

import src.message as msg
import src.serial_bridge as pb

vect1 = msg.Message("./vector3.yml")
vect2 = msg.Message("./vector3.yml")
dev = pb.SerialBridge("TestVect3", 16, "ttyS")

dev.add_frame(vect2)

while (True):
    vect1.set(x=0.321, y=0.654, z=0.123)  # 適当なデータ
    dev.send(0, vect1)
    if dev.recv() == 0:
        print(vect2.data.x)
        print(vect2.data.y)
        print(vect2.data.z)
        print(" ")
    time.sleep(0.020)
예제 #9
0
 def add_message(self, login, chat_name, msg, date_time):
     self.messages.append(msg)
     return message.Message(Constants.DEFAULT_NO_DATABASE_MESSAGE_ID, login,
                            msg, chat_name,
                            helper_functions.date_time_to_millis(date_time))
예제 #10
0
    def run(self):
        request_count = 0
        waiting_for_key = []
        waiting_for_users = {}  # expected response id : (group, message)
        message_queue = queue.Queue()
        inputs = [self.sock, sys.stdin]
        while self.running:
            inputs_ready, _, _ = select.select(inputs, [], [])
            for s in inputs_ready:
                if s == sys.stdin:  # TODO: break down into functions
                    user_input = sys.stdin.readline()
                    if user_input.startswith('/'):
                        if user_input.lower().startswith(
                                '/msg') or user_input.lower().startswith(
                                    '/gmsg'):
                            split_user_input = user_input.split(' ')
                            to = split_user_input[1]
                            text = " ".join(split_user_input[2:]).strip('\n')
                            if split_user_input[0].startswith('/gmsg'):
                                json_message = {
                                    'type': 'group-message',
                                    'group': to,
                                    'message': text,
                                    'from': self.client_name
                                }
                            else:
                                json_message = message.Message(
                                    to, text, self.client_name).data
                            message_queue.put(json_message)
                        elif user_input.lower().startswith('/register'):
                            split_user_input = user_input.strip().split(' ')
                            usn = split_user_input[1]
                            self.client_name = usn
                            pswhash = hash_password(split_user_input[2])
                            pswhash = crypto.encrypt_message(
                                pswhash, self.server_key)

                            request = message.Request(message.REGISTER_REQUEST,
                                                      [usn, pswhash]).data
                            message_queue.put(request)
                        elif user_input.lower().startswith('/login'):
                            split_user_input = user_input.strip().split(' ')
                            try:
                                usn, psw = split_user_input[1:]
                            except ValueError:
                                print(
                                    "Invalid command! /login <username> <password>"
                                )
                            passhash = hash_password(psw)
                            passhash = crypto.encrypt_message(
                                passhash, self.server_key)
                            psw = None
                            rq = message.Request(message.AUTH_REQUEST,
                                                 [usn, passhash])
                            passhash = None
                            self.client_name = usn
                            #  print(rq.to_json())
                            message_queue.put(rq.data)
                        elif user_input.lower() == '/exit\n':
                            self.stop()
                            sys.exit(0)

                if s == self.sock:
                    received = s.recv(4096).decode('utf-8')
                    if len(received) > 0:
                        results = Helper.clean_json(received)
                        for r in results:  # received multiple json strings in one buffer, clean_json strips them into
                            # a list of json strings
                            self.handle_sock(r, message_queue, waiting_for_key,
                                             waiting_for_users)

            while not message_queue.empty():
                msg = message_queue.get_nowait()
                if msg['type'] == 'group-message' and msg.get('to') is None:
                    group = msg['group']
                    # request user list
                    waiting_for_users[request_count] = (group, msg)
                    msg = {
                        'type': 'request',
                        'request': 'group-list',
                        'group': group,
                        'id': request_count,
                        'from': self.client_name
                    }
                    request_count += 1
                elif msg['type'] == 'message' or msg['type'] == 'group-message':
                    if msg['to'] not in self.user_keys.keys():
                        waiting_for_key.append(
                            msg)  # put it in the waiting pile
                        # send a request for public key
                        # print('Don\'t have the public key, sending a request for it.')
                        msg = message.Request('pubkey', [
                            msg['to'],
                        ]).data
                    else:
                        msg['message'] = crypto.encrypt_message(
                            msg['message'].encode('utf-8'),
                            self.user_keys[msg['to']])
                if isinstance(msg, dict):
                    data = json.dumps(msg)
                else:
                    data = msg
                data = data.encode('utf-8')
                # print(json.dumps(msg))
                self.sock.send(data)