Пример #1
0
    def _queue_message(self, sender, body, request):
        # Find any existing messages and merge...
        messages = list(Message.Query.filter(sender=sender.objectId))
        if messages:
            message = messages[0]
        
            message.body += '\n--\n' + body
            message.save()
            
            message_sending.send_received_message(sender.phone)
            return ""
    
        # Otherwise, add a new
        palships = list(Palship.Query.filter(lhs=sender.objectId))
        if palships:
            recipient = User.Query.get(objectId=palships[0].rhs)
        else:
            palships = list(Palship.Query.filter(rhs=sender))
            if not palships:
                return None
            recipient = User.Query.get(objectId=palships[0].lhs)

        message = Message(
            body=body,
            sender=sender.objectId,
            recipient=recipient.objectId
        )
        
        message.save()
        message_sending.send_received_message(sender.phone)
        return ""
Пример #2
0
 def create_entry_from_params(self, params):
     new_msg = Message(content = params["content"],
                       created = params["created_date"],
                       author = params["author"],
                       event = params["event"])
     new_msg.put()
     return new_msg
Пример #3
0
    def post(self):
        if self.request.POST.get('Body') is None or self.request.POST.get('From') is None:
            logging.error('Body and From params required')
            return self.abort(400, 'Body and From params required')

        user_message = Message(
            text=self.request.POST.get('Body').strip(),
            receiver=self.request.POST.get('To'),
            sender=self.request.POST.get('From'),
            media_url=self.request.POST.get('MediaUrl0'),
        )

        from_phone = self.request.get('From')
        logging.info('Received text from %s with media: %s message:\n%s', from_phone, user_message.media_url, user_message.text)

        user = User.get_by_id(from_phone)
        if user:
            logging.info('Found existing user for %s', from_phone)
        else:
            logging.info('Creating new user for %s', from_phone)
            user = User(id=from_phone)

        message_type = determine_message_type(user_message.text)
        logging.info('Message of type: %s', message_type)
        group = user.group
        response_type, messages, user, group = perform_action(message_type, user_message, user, group)
        responses = [format_message(m, user, group) for m in messages]
        logging.info('Responding with: %s', responses)
        self.response.body = twiml_response(user, group, response_type, responses)
        self.response.headers['Content-Type'] = 'text/xml'
        logging.info('Responding: %s', self.response.body)

        user_message.story_uid = group.story_uid if group else None
        user_message.group_uid = group.uid if group else None
        user_message.put()

        ndb.put_multi([Message(receiver=from_phone,
                               sender=m.sender or None,
                               text=m.text,
                               media_url=m.media_url,
                               group_uid= group.uid if group else None,
                               story_uid=group.story_uid if group else None)
                       for m in responses])

        if group:
            group.put()
            user.group_uid = group.uid
        else:
            user.group_uid = None
        user.put()
def retrieveNextMessage(ws):
    '''
    Retrieve next non-trivial message. Raise an exception if socket ends
    '''
    message = None
    while not message:
        message = Message.from_str(ws.receive())
        if not message:
            ws.send("error " + InvalidInputError("Invalid format.").json())
    return message
    def testHandleStartQuit(self):
        ws = MockWebsocket.create()
        userId, sessionId = self.users[1]
        msg = self.constructAuth('join', userId, sessionId)
        self.chatMessageHandler.handleFirstMessage(msg, self.roomId, ws)

        with self.assertRaises(InvalidInputError) as cm: # member cannot start the game
            self.chatMessageHandler.handleOtherMessage(Message.create('start'), self.roomId, userId)
        self.assertIn('permission', cm.exception.json())

        # owner should be able to start the game
        self.chatMessageHandler.handleOtherMessage(Message.create('start'), self.roomId, self.roomOwner[0])

        # owner quits the game
        self.chatMessageHandler.handleOtherMessage(Message.create('quit'), self.roomId, self.roomOwner[0])
        self.assertNotEquals(self.roomOwner[0], self.restInterface.get_room(self.roomId)['creator']['userId'])

        self.chatMessageHandler.handleOtherMessage(Message.create('quit'), self.roomId, userId)
        with self.assertRaises(Exception) as cm:
            self.restInterface.get_room(self.roomId)
        self.assertIn('Not Found Room', str(cm.exception))
Пример #6
0
class MessageTest(TestCase):

    def setUp(self):
        self.pop = Populator()
        self.pop.run()

        self.message = Message()
        self.users = User.objects

    def tearDown(self):
        if self.message.id is not None:
            self.message.delete()
        self.pop.clear()

    def test_save(self):
        self.message.subject = "First message"
        self.message.text = "This is the first message ever in the system"
        self.message.receiver = self.users[1]
        self.message.sender = self.users[0]
        self.assertIsNone(self.message.id)
        self.message.save()
        self.assertIsNotNone(self.message.id)
Пример #7
0
 def post(self):
     dt = datetime.now()
     
     message = Message()
     message.uid = int(self.request.get('uid'))
     message.author = self.request.get('author')
     message.content = self.request.get('message')
     message.timestamp = int(mktime(dt.timetuple()) * 1000)
     message.put()
     
     self.response.headers['Content-Type'] = 'application/json'
     self.response.out.write(json.dumps({}))
Пример #8
0
 def post(self, room_name):
     form_data = self.request.get('message')
     message = crypto_helper.decrypt(self, form_data)
     m = Message()
     m.text = message
     m.sender_email = user_help.get_user_email()
     m.room_name = room_name
     m.put()
     clients.push_to_channels(room_name, m)
     self.response.write('Success')
Пример #9
0
def push_to_channels(room, message):
    client_set = get_clients(room)
    unencrypted_message = message
    for u in client_set:
        if u.connected:
            encrypted_message = Message()
            client_e = u.e
            client_n = u.n
            if client_e:
                client_e = float(client_e)
                client_n = float(client_n)
                encrypted_message.text = crypto_helper.encrypt(None, client_n, client_e, message.text)
            else:
                encrypted_message.text = message.text
            encrypted_message.sender_email = message.sender_email
            encrypted_message.room_name = message.room_name
            json = encrypted_message.to_json()
            channel.send_message(u.client_id, json)
Пример #10
0
    def post(self):
        """
        Send a new message to a user.
        """
        user = self.user

        if not user:
            return render_json(self, {
                'status': 'error',
                'error': 'User not logged in'
            })

        recipient_name = cgi.escape(self.request.get('recipient'))
        body = cgi.escape(self.request.get('body'))

        recipient = UserPrefs.all()\
                             .filter('name =', recipient_name)\
                             .get()

        if not recipient:
            return render_json(self, {
                'status': 'error',
                'error': 'Recipient %(recipient_name)s not found' % locals()
            })

        msg = Message()
        msg.user_from = user
        msg.user_to = recipient
        msg.body = body
        msg.put()

        # TODO: put this into a transaction
        recipient.unread_messages += 1
        recipient.put()

        self.render_json({
            'status': 'ok'
        })
Пример #11
0
 def create_chat(self, event):
     message_to_add = Message(content = self.request.get("content"),
                              author = self.get_prdict_user(),
                              event = event)
     message_to_add.put()
     return message_to_add
Пример #12
0
    user_obj = User()
    #
    # user_obj.username = '******'
    # user_obj.email = '*****@*****.**'
    # user_obj.set_password('blablaBle1', generate_salt())
    #
    # # user_obj.save_to_db(cursor)

    obj = user_obj.load_user_by_id(cursor, 2)
    print(obj.__dict__)

    obj = user_obj.load_all_users(cursor)
    print([ob.__dict__ for ob in obj])

    message_obj = Message()
    # message_obj.from_id = 3
    # message_obj.to_id = 1
    # message_obj.text = 'ta wiadmość jest od id 3 do id 1'
    #
    # a = message_obj.save_to_db(cursor)

    print('all user messages by user')
    a = message_obj.load_all_messages_for_user(cursor, 1, 2)
    for i in a:
        print(i.__dict__)

    print('\nall_messages')
    a = message_obj.load_all_messages(cursor)
    for i in a:
        print(i.__dict__)
 def setUp(self):
     self.message = Message()
Пример #14
0
 def clear(self):
     User.drop_collection()
     Message.drop_collection()
Пример #15
0
def message_view(request):
    ms = Message.all()
    return render_response("messages.html", messages=ms)
Пример #16
0
def read_all():
    u = current_user()
    Message.read_all(u.id)
    data = dict(message='all message has been read')
    return response(data=data, status=status.HTTP_200_OK)
Пример #17
0
    def post(self):
        if self.request.POST.get('Body') is None or self.request.POST.get(
                'From') is None:
            logging.error('Body and From params required')
            return self.abort(400, 'Body and From params required')

        user_message = Message(
            text=self.request.POST.get('Body').strip(),
            receiver=self.request.POST.get('To'),
            sender=self.request.POST.get('From'),
            media_url=self.request.POST.get('MediaUrl0'),
        )

        from_phone = self.request.get('From')
        to_phone = self.request.get('To')
        logging.info('Received text from %s with media: %s message:\n%s',
                     from_phone, user_message.media_url, user_message.text)

        user = User.get_by_id(from_phone)
        if user:
            logging.info('Found existing user for %s', from_phone)
        else:
            logging.info('Creating new user for %s', from_phone)
            user = User(id=from_phone)

        message_type = determine_message_type(user_message.text)
        logging.info('Message of type: %s', message_type)
        group = user.group

        if group is not None:
            expiry_time = group.created_at + timedelta(hours=48)

            if datetime.now() > expiry_time:
                user.group_uid = None
                group.completed_at = expiry_time
                group.messaged_at = datetime.now()
                group.put()
                group = None

        response_type, messages, user, group = perform_action(
            message_type, user_message, user, group)
        responses = [format_message(m, user, group) for m in messages]
        logging.info('Responding with: %s', responses)

        if not user.stopped:
            self.response.body = twiml_response(user, group, response_type,
                                                responses)
            self.response.headers['Content-Type'] = 'text/xml'
            user_message.story_uid = group.story_uid if group else None
            user_message.group_uid = group.uid if group else None
            user_message.put()

            ndb.put_multi([
                Message(receiver=from_phone,
                        sender=to_phone,
                        text=m.text,
                        media_url=m.media_url,
                        group_uid=group.uid if group else None,
                        story_uid=group.story_uid if group else None)
                for m in responses
            ])
            logging.info('Responding: %s', self.response.body)
        else:
            logging.info('User stopped so no respones is sent')

        if group:
            group.messaged_at = datetime.now()
            group.put()
            user.group_uid = group.uid
        else:
            user.group_uid = None
        user.messaged_at = datetime.now()
        user.put()
Пример #18
0
def delete(message_id):
    m = Message.delete(message_id)
    return redirect(url_for('message.index'))
Пример #19
0
    async def saveoldall(self,
                         ctx: commands.Context,
                         guild_id: int,
                         count: int = 20):
        """Save old sur les channels connus en db"""
        tracking_cog = get_tracking_cog(self.bot)
        db = tracking_cog.tracked_guilds[guild_id]
        guild = self.bot.get_guild(guild_id)

        if guild is None:
            await ctx.send("Je ne trouve pas cette guild")
            return

        # Récupérer liste channels connus
        known_channels = await self._get_known_channels(db)
        if not known_channels:
            await ctx.send(
                "Aucun channel connu, d'abord utiliser saveall ou save")
            return
        await ctx.send(
            f"J'ai trouvé **{len(known_channels)}** channels connus en db...")

        # Parcours channels
        for channel in known_channels:
            msg_bot = await ctx.send(
                f"J'enregistre le channel **{channel.name}**...")
            # Récupérer le plus ancien message du channel
            with db:
                with db.bind_ctx([Message]):
                    try:
                        oldest = (Message.select().where(
                            Message.channel_id == channel.id).order_by(
                                Message.message_id).get())
                    except DoesNotExist:
                        print(
                            f"Pas de message en db pour le channel {channel}")
                        continue

            # discord.Message correspondant
            try:
                oldest_msg: discord.Message = await channel.fetch_message(
                    oldest)
            except discord.NotFound:
                print(
                    f"Le plus ancien message enregistré du channel {channel} n'existe plus"
                )
            except discord.Forbidden:
                print(f"Problème de droit pour le channel {channel}")

            # Enregistrement
            try:
                save_result = await self._save_from_channel(channel,
                                                            count,
                                                            before=oldest_msg)
                await msg_bot.edit(
                    content=
                    f"**{channel.name}**\n{save_result} ({oldest_msg.created_at})"
                )
            except discord.Forbidden as exc:
                await msg_bot.edit(content=f"**{channel.name}**\nErreur: {exc}"
                                   )

        await ctx.send("Fini !")
Пример #20
0
def send_message():
    data = request.get_json()

    if (not data['room_id'] and not data['to_id']) or data['to_id'] == g.user['id']:
        return jsonify({'message': "Bad Request"}), 400

    if data['room_id']:
        room_id = data['room_id']
        room = Room.find(room_id)
        room_member = RoomMember.where('room_id', room_id).where('user_id', g.user['id']).first()
        if not room or not room_member:
            return jsonify({'message': "Unknown Room"}), 400
    else:
        user = User.find(data['to_id'])
        if not user:
            return jsonify({'message': "Unknown User"}), 400
        room = Room.where('is_group', 0) \
            .select('rooms.id') \
            .join('room_members as rm', 'rm.room_id', '=', 'rooms.id') \
            .where('rm.user_id', g.user['id']) \
            .where_has(
            'members',
            lambda q: q.where('user_id', data['to_id']).where_raw('room_id = rooms.id')
        ) \
            .distinct() \
            .first()

        if not room:
            room = Room()
            room.save()

            member1 = RoomMember()
            member1.room_id = room.id
            member1.user_id = data['to_id']
            member1.save()

            member2 = RoomMember()
            member2.room_id = room.id
            member2.user_id = g.user['id']
            member2.save()

            #connect exist socket to room
            clients = _.where(connected_users,{'id':data['to_id']})
            my_clients = _.where(connected_users,{'id':g.user['id']})

            clients = _.compact(_.union(clients, my_clients))
            for item in clients:
                join_room('room-%s' % room.id, sid=item['sid'], namespace='/')




        room_id = room.id

    message = Message()
    message.sender_id = g.user['id']
    message.room_id = room_id
    message.message = data['message'] if data['message'] else '...'
    message.save()

    RoomMember.where('room_id', room_id).where('user_id', g.user['id']).update(last_read_message=message.id)

    message_response = message.serialize()
    message_response['first_name'] = g.user['first_name']
    message_response['last_name'] = g.user['last_name']
    message_response['avatar'] = g.user['avatar']

    return jsonify(message_response), 200
Пример #21
0
class ExtenderTest(unittest.TestCase):
    oid = 1
    messages = [
        (1, Message(1, MessageType.NEW_ORDER, oid, 123, 10, 1)),
        (2, Message(2, MessageType.EXECUTE, oid, 20, 10, 1)),
        (3, Message(3, MessageType.MODIFY, oid, 50, 10, 1)),
        (4, Message(4, MessageType.EXECUTE, oid, 33, 10, 1)),
        (5, Message(5, MessageType.DELETE, oid, 20, 10, 1)),
    ]

    def test_weekdays(self):

        ts = _datetime_ts(2019, 10, 24, 0, 0, 0, 1, tzinfo=TZ)
        w = weekdays(ts, 4)

        self.assertEqual(ts - 10**3, next(w))
        friday = _datetime_ts(2019, 10, 25, tzinfo=TZ)
        self.assertEqual(friday, next(w))
        monday = _datetime_ts(2019, 10, 28, tzinfo=TZ)
        self.assertEqual(monday, next(w))
        tuesday = _datetime_ts(2019, 10, 29, tzinfo=TZ)
        self.assertEqual(tuesday, next(w))
        with self.assertRaises(StopIteration):
            next(w)
            self.fail()

    def test_mix_by_index(self):
        base = [1, 2, 3, 4, 5]
        mix = [Placement(0, 6), Placement(1, 7), Placement(3, 8)]
        self.assertListEqual(
            [6, 1, 7, 2, 3, 8, 4, 5],
            list(_mix_by_index(base, mix))
        )

    def test_initial_qty_new(self):
        self.assertEqual(123, _initial_qty_for_messages(self.messages))

    def test_initial_qty_no_new(self):
        messages = self.messages[1:]  # Drop new
        self.assertEqual(123, _initial_qty_for_messages(messages))

        m_lower = messages[1:]  # Drop an execute
        self.assertEqual(103, _initial_qty_for_messages(m_lower))

    def test_unfilled_qty_delete(self):
        self.assertEqual(0, _unfilled_qty_for_messages(self.messages))

    def test_unfilled_qty_no_delete(self):
        messages = self.messages[:-1]  # Drop delete
        self.assertEqual(20, _unfilled_qty_for_messages(messages))

        m_lower = messages[:-1]  # Drop an execute
        self.assertEqual(53, _unfilled_qty_for_messages(m_lower))

    def test_messages_no_new_or_delete(self):
        messages = self.messages[1:-1]
        self.assertEqual(206, _initial_qty_for_messages(messages))
        self.assertEqual(103, _unfilled_qty_for_messages(messages))

    def test_backfill(self):
        """Run with `-b` to silence prints generated in Extender"""
        start = _datetime_ts(2019, 10, 21)
        sample = []
        extended = []
        with open('tests/messages_sample.fixture', 'r') as f:
            e = Extender(f, start, 1, (1356500, 1356300))

            sample_count = 9
            extended_count = (9 + 4) * 2

            ob = OrderBook("SPY")
            for m in e.extend_sample(0, ob):
                if len(sample) < sample_count:
                    sample.append(m)
                elif len(extended) < extended_count:
                    extended.append(m)
                else:
                    break
                ob.send(m)

        new_orders = [m for m in extended
                      if m.message_type == MessageType.NEW_ORDER]
        self.assertEqual(11, len(new_orders))

        id_map = defaultdict(list)
        sample_ids = set(m.id for m in sample if m.id > 0)
        extended_ids = set(m.id for m in extended if m.id > 0)

        for m in sample:
            id_map[m.id].append(m)

        for m in extended:
            id_map[m.id].append(m)

        for id_ in extended_ids.difference(sample_ids):
            # All ids generated in the extended set have a NEW
            self.assertTrue(
                any(m.message_type ==
                    MessageType.NEW_ORDER for m in id_map[id_])
            )

        for id_ in sample_ids.intersection(extended_ids):
            # All ids from the sample set have a DELETE
            self.assertTrue(
                any(m.message_type == MessageType.DELETE for m in id_map[id_])
            )
Пример #22
0
 def get(self, nickname=None):
     message = Message.query().order(Message.created)
     return self.render_template("home_page.html",
                                 params={"message": message})
 def from_madrill_payload(cls, payload):
     return Message(**cls.convert_mandrill_payload(payload))
Пример #24
0
 def post(self):
     form_data = self.request.get('message')
     m = Message()
     m.text = form_data
     m.put()
Пример #25
0
    def post(self):
        content = self.request.body
        logger.info(content)
        message = Message(content)
        # 初始化
        wechat_service.init_user(message.to_user_name, message.from_user_name)
        wechat_service.init_handler(self)
        if message.msg_type == 'event':
            if message.event == 'subscribe':
                user_service.insert_or_update(message.from_user_name)
                wechat_service.reply_text(
                    '真好呀,你没有错过我。这个地球上有几十亿人口,两个人相遇的概率只有千万分之一。\n\n'
                    '歌曲下载,请直接回复链接即可。目前支持:咪哒、唱吧、友唱M-bar、全民K歌、哇屋wow。'
                    '如有疑问或建议,直接加小扎微信,微信号:fhm911')
            return
        else:
            req_msg = message.content
            keywords = [
                '咪哒', '下载', '帮助', '歌曲', 'authorize', 'record/index.html',
                'help'
            ]
            need_help = False
            for kw in keywords:
                if req_msg.find(kw) != -1:
                    need_help = True
                    break
            if need_help:
                wechat_service.reply_text("直接在聊天框中回复要下载的歌曲链接即可")
                # wechat_service.reply_help()
                return

            if req_msg.startswith("keyc"):
                pay_code = pay_code_service.get(req_msg)
                if pay_code is None or pay_code['status'] == '1':
                    wechat_service.reply_text("无效的编码")
                    return
                else:
                    left_count = user_service.inc_count(
                        message.from_user_name, pay_code['count'])
                    if left_count == -1:  # 找不到用户
                        wechat_service.reply_text("请先取消关注公众号,再重新关注,然后再回复密码")
                        return
                    pay_code_service.disable(req_msg)
                    wechat_service.reply_text("恭喜你,增加下载次数成功,剩余次数为:%s" %
                                              left_count)
                    return

            # 下载
            if req_msg.startswith("http"):
                if not user_service.is_can_download(message.from_user_name):
                    song = converter_service.convert(req_msg)
                    song_tip = ""
                    if song is not None:
                        song_tip = "你要下的歌曲为:%s\n\n" % song.name
                    text = song_tip + "如需继续下载,请加小扎微信(微信号:fhm911)以红包或转账形式赞助带宽费用,谢谢支持。\n赞助标准:\n10元3首。最低10元起。"
                    wechat_service.reply_text(text)
                else:
                    logger.info("download url: %s" % req_msg)
                    song = converter_service.convert(req_msg)
                    logger.info("converted song: %s" % song)
                    if song is not None:
                        user_service.reduce_count(message.from_user_name)
                        text = '注:苹果手机需要用电脑版微信下载\n\n<a href="{0}">{1}(点击直接下载)</a>'
                        #song_url = urllib.parse.quote(song.url)
                        song_url = song.url
                        download_url = "http://converter.wezhake.com/download/?name={0}&url={1}".format(
                            song.name, song_url)
                        text = text.format(download_url, song.name)
                        wechat_service.reply_text(text)
                    else:
                        wechat_service.reply_text(
                            "歌曲不存在,请检查输入的歌曲链接。如有问题,请联系人工客服,请加小扎微信,微信号:fhm911")
            else:
                wechat_service.reply_text("人工客服,请加小扎微信,微信号:fhm911")
Пример #26
0
    def run(self):

        MONGO_URL = os.environ.get('MONGOHQ_URL')
        if MONGO_URL:
            client = MongoClient(MONGO_URL)
        else:
            client = MongoClient()
        db = client.demo
        db.users.drop()
        db.messages.drop()

        u1 = User(firstName="John", lastName="Doe", userName="******",
                  password=bcrypt.hashpw("1234password", bcrypt.gensalt()))
        u1.created = datetime.now()

        u2 = User(firstName="Jane", lastName="Doe", userName="******",
                  password=bcrypt.hashpw("mypassw0rd", bcrypt.gensalt()))
        u2.created = datetime.now()

        u3 = User(firstName="Kristel", lastName="Nielsen", userName="******",
                  password=bcrypt.hashpw("asdfda3", bcrypt.gensalt()))
        u3.created = datetime.now()

        u4 = User(firstName="Erik", lastName="Johannesen", userName="******",
                  password=bcrypt.hashpw("kjasdfj8i32", bcrypt.gensalt()))
        u4.created = datetime.now()

        u1.save()
        u2.save()
        u3.save()
        u4.save()

        m1 = Message(
            sender=u1.id, subject="First message",
            message="This is the first ever message in the system?!",
            receiver=u4.id,
            sent=datetime.now()
        )

        m2 = Message(
            sender=u4.id, subject="RE: First message",
            message="It's awesome isn't it?",
            receiver=u1.id,
            sent=datetime.now()
        )

        m3 = Message(
            sender=u2.id, subject="Remember, remember",
            message="Remember to buy milk!!!!!!",
            receiver=u2.id,
            sent=datetime.now()
        )

        m4 = Message(
            sender=u3.id, subject="New project",
            message="We need an extra developer for a new ruby project, are you in?",
            receiver=u2.id,
            sent=datetime.now()
        )

        m5 = Message(
            sender=u2.id, subject="RE: New project",
            message="Sure why not, could we have a look at sinatra in that case?",
            receiver=u4.id,
            sent=datetime.now()
        )

        m1.save()
        m2.save()
        m3.save()
        m4.save()
        m5.save()
Пример #27
0
 def get(self):
     deleted_messages = Message.query(Message.deleted == True, Message.updated <
                                      datetime.datetime.now() - datetime.timedelta(days=10)).fetch()
     for message in deleted_messages:
         message.key.delete()
Пример #28
0
def add():
    form = request.form
    m = Message(form)
    Message.add(m)
    return redirect(url_for('message.index'))
          'r') as headlines, open(curr_dir + '/posts.csv',
                                  'a+') as headlines_csv:
    data = json.load(headlines)
    writer = csv.DictWriter(headlines_csv,
                            delimiter=',',
                            lineterminator='\n',
                            fieldnames=row_headers)
    writer.writeheader()
    today = date.today()
    for idx in data:
        headline = data[idx]

        total_sentiment = 0
        for e in headline['info']:
            sentiment_score = e['sentiment_score']
            total_sentiment += float(sentiment_score)

        avg_sentiment = total_sentiment / len(headline['info'])
        breaking_point = 0.05
        if (abs(avg_sentiment) < breaking_point):
            avg_sentiment = Sentiment.UNCERTAIN
        elif avg_sentiment >= breaking_point:
            avg_sentiment = Sentiment.BULLISH
        else:
            avg_sentiment = Sentiment.BEARISH

        message = Message(uuid.uuid4(), headline['sentence'], uuid.uuid4(),
                          today, "FIQA", avg_sentiment)

        writer.writerow(to_dict(message))
Пример #30
0
def unread_num():
    u = current_user()
    num = Message.get_unread_num(u.id)
    data = dict(unread=num)
    return response(data=data, status=status.HTTP_200_OK)
from models.message import Message
from models.comment import Comment
from models.content import Content

messages = Message.select().order_by(Message.id)

comments = Comment.select().order_by(Comment.id)

contents = Content.select().order_by(Content.id)

for message in messages:
    print(str(message))

for comment in comments:
    print(str(comment))

for content in contents:
    print(str(content))
class TestMessage(unittest.TestCase):
    def setUp(self):
        self.message = Message()

    @parameterized.expand([
        ['Origem 1'],
        ['Origem 2'],
        ['Origem 3'],
    ])
    def test_set_source(self, source):
        self.message.set_source(source)
        self.assertEqual(self.message.get_source(), source)

    @parameterized.expand([
        ['Destino 1'],
        ['Destino 2'],
        ['Destino 3'],
    ])
    def test_set_target(self, target):
        self.message.set_target(target)
        self.assertEqual(self.message.get_target(), target)

    @parameterized.expand([
        [1.0],
        [0.0],
        [0.5],
    ])
    def test_set_prob(self, prob):
        self.message.set_prob(prob)
        self.assertEqual(self.message.get_prob(), prob)
    
    @parameterized.expand([
        ['Sync'],
        ['Async'],
        ['Reply'],
    ])
    def test_set_message_type(self, message_type):
        self.message.set_message_type(message_type)
        self.assertEqual(self.message.get_message_type(), message_type)
Пример #33
0
class MessagesResource(Resource):
    @marshal_with(Message.format())
    # def get(self, user_id):
    def get(self):
        return list(Message.objects.all())
Пример #34
0
def message_seen(data):
    db = get_db()
    user = User(db).get_user_by_username(session['username'])
    room = Room(db).get_users_room(user['user_id'], data)
    Message(app.config['messages_location'],
            room['room_name']).mark_as_seen(data)
Пример #35
0
            mainPlayer.hp = commData['plHp']
            enPl = commData['enemyObj']
            enemyPlayer.posX = enPl['x']
            enemyPlayer.posY = enPl['y']
            enemyPlayer.hp = enPl['hp']
            enemyPlayer.username = enPl['username']
            # TODO: think of a better way to propagate enemy bullets
            # so the screen wont flicker.
            enemyPlayer.clear_bullets()
            if enPl['bullets']:
                for bullet in enPl['bullets']:
                    enemyPlayer.add_bullet(definitions.RED_LASER_SPRITE,
                                           bullet['x'], (bullet['y'] - 50))
        elif commData is not None and commData['isGameOver'] is not None:
            glVars.messages.append(
                Message(commData['message'], definitions.INFO_MESSAGE))
            if commData['isWinner']:
                enemyPlayer.hp = 0
            else:
                mainPlayer.hp = 0

            isGameOver = True

    # Update all visual  objects
    screen.blit(background, ballrect, ballrect)
    # Loops through the messages (if any) and displays them.
    drawUtils.draw_existing_messages(screen, glVars.messages)

    drawUtils.draw_health_ui(screen, mainPlayer.hp, enemyPlayer.hp)
    drawUtils.draw_username_ui(screen, mainPlayer.get_username(),
                               enemyPlayer.get_username())
Пример #36
0
    def run(self):

        User.drop_collection()
        Message.drop_collection()

        user1 = User()
        user2 = User()
        user3 = User()
        user4 = User()

        user1.firstName = "John"
        user1.lastName = "Doe"
        user1.birthDate = datetime.now()
        user1.userName = "******"
        user1.passHash = user1.userName

        user2.firstName = "Jane"
        user2.lastName = "Doe"
        user2.birthDate = datetime.now()
        user2.userName = "******"
        user2.passHash = user2.userName

        user3.firstName = "Michelle"
        user3.lastName = "Nielsen"
        user3.birthDate = datetime.now()
        user3.userName = "******"
        user3.passHash = user3.userName

        user4.firstName = "Leif"
        user4.lastName = "Paulsen"
        user4.birthDate = datetime.now()
        user4.userName = "******"
        user4.passHash = user4.userName

        user1.save()
        user2.save()
        user3.save()
        user4.save()

        message1 = Message()
        message1.subject = "First message"
        message1.text = "This is the first message ever in the system. Hello Jane this is John, how are you?"
        message1.sender = user1
        message1.receiver = user2
        message1.save()

        message2 = Message()
        message2.subject = "Second message"
        message2.text = "This is the second message ever in the system. Hello Jane this is Åge, how are you?"
        message2.sender = user4
        message2.receiver = user2
        message2.save()

        message3 = Message()
        message3.subject = "Second message"
        message3.text = "This is the Third message ever in the system. Hello Jane this is Åge, how are you?"
        message3.sender = user4
        message3.receiver = user1
        message3.save()
Пример #37
0
        Delete a message.
        """
        message_json = cgi.escape(self.request.get('message'))

        # Parse the JSON into Python objects
        try:
            message_data = json.loads(message_json)
        except Exception, e:
            render_json(self, {
                'status': 'error',
                'error': str(e),
                'input': message_json
            })
            return

        msg = Message.get_by_id(message_data['id'])

        if not msg:
            return render_json(self, {
                'status': 'error',
                'error': 'Message %(id)s not found' % message_data
            })

        # Update unread message cache if needed
        if not msg.read:
            recipient = msg.user_to
            recipient.unread_messages -= 1
            recipient.put()

        # Delete this message from the data store
        msg.delete()
Пример #38
0
 def _create_message(self, content, author, event):
     message = Message(content = content, author = author, event = event)
     message_key = str(message.put())
     return message
Пример #39
0
 def clear(self):
     connect("demo")
     User.drop_collection()
     Message.drop_collection()
 def constructAuth(self, command, userId, sessionId):
     ts = int(time.time() * 1000)
     return Message.create(command,{
                 "userId":userId,
                 "ts":ts,
                 "auth":hashlib.sha256("{}:{}:{}".format(sessionId, userId, ts))})
Пример #41
0
def add():
    form = request.form
    Message.new(form)
    return redirect(url_for('.index'))
Пример #42
0
 def validate_params(self, params):
     return Message.validate_params(params)
Пример #43
0
from models.message import Message

message_data = [Message()]
Пример #44
0
def delete(id):
    Message.delete(id)
    return '删除成功'
Пример #45
0
def get_my_chats():
    my_chats = Message.get_user_chats(g.current_user.id)
    return jsonify(chats=my_chats)
Пример #46
0
    def setUp(self):
        self.pop = Populator()
        self.pop.run()

        self.message = Message()
        self.users = User.objects
Пример #47
0
        user_to_remove.remove_user(cursor)
        print(f'{user_to_remove} was removed')
    else:
        print(
            'It\'s impossible to remove this user. Please check your credentials'
        )

if args.command == 'list_users':
    users = User.load_all_users(cursor)
    for user in users:
        print(user)

if args.command == 'create_message':
    user = User()
    if user.verify_user(cursor, args.username, args.password):
        new_message = Message()
        new_message.from_user_id = args.from_user
        new_message.to_user_id = args.to_user
        new_message.text = args.text
        Message.set_creation_date()
        new_message.save_message_to_db(cursor)
        print(f'message for user{args.to_user} was created')
    else:
        print('Your credentials don\'t work. Please check them.')

if args.command == 'view_message':
    user = User()
    if user.verify_user(cursor, args.username, args.password):
        Message().load_message_by_id(cursor, args.id)
    else:
        print('Your credentials don\'t work. Please check them.')
Пример #48
0
def message_view(request):
    ms = Message.all()
    return html_response('messages.html', messages=ms)
Пример #49
0
 def create(self, db: Session, *, obj_in: MessageCreate) -> Message:
     db_obj = Message(text=obj_in.text, room_id=obj_in.room_id)
     db.add(db_obj)
     db.commit()
     db.refresh(db_obj)
     return db_obj
Пример #50
0
#!/usr/bin/env python3
import cgi
import csv
import hashlib
import base64
import sys, os
from models.session import Session
from models.message import Message
from views.chat_view import chat_view

if os.environ["REQUEST_METHOD"] == "POST":
    form = cgi.FieldStorage()
    nickname = form.getvalue('nickname')

    session = Session(nickname)
    session.last_msg = Message.get_last_msg_id()
    session.save()

    print("Status: 200 OK")
    print("Content-type: text/html")
    print(session.cookie.output())
    print()
    print(chat_view(nickname))

elif os.environ["REQUEST_METHOD"] == "GET":

    print("Location: /login.html")
    print()
Пример #51
0
 def _handle_conflicts(self, conflicts, msg):
     return [
         Message(msg.time, MessageType.DELETE, order.id, order.qty,
                 order.price, order.direction)
         for order in conflicts
     ]