Beispiel #1
0
def on_new_message(message):
    current_message = message['data']

    #If it is a url, send data to the client
    if uri_validator(current_message) == True:
        socketio.emit('url received', {'data': current_message})
        info = models.Message(message['data'], name, image)
        models.db.session.add(info)
        models.db.session.commit()

    # if current_message == "!! food":
    #     yelp()
    #If the message the user writes starts with !!, then call the Chatbot class in chatbot.py
    elif current_message[:2] == '!!':
        called_class = chatbot.Chatbot()
        final_response = called_class.response(current_message)
        new_message = models.Message(final_response, name, image)
        models.db.session.add(new_message)
        models.db.session.commit()

    else:
        info = models.Message(message['data'], name, image)
        models.db.session.add(info)
        models.db.session.commit()
    return on_connect()
Beispiel #2
0
def sms_message(request):
    twilio_message = request.POST['Body']
    phone_number = request.POST['From']
    incoming_phone_number = request.POST['To']

    hashtag, body = _split_message(twilio_message, incoming_phone_number)
    print hashtag, body
    if hashtag is not None and body is not None:
        message = models.Message()
        message.message = body
        message.phone_number = phone_number
        message.wall = models.Wall.objects.get(hashtag=hashtag)
        message.save()
        print message

        pubnub = Pubnub(settings.PUBNUB_PUBLISH_KEY,
                        settings.PUBNUB_SUBSCRIBE_KEY, settings.PUBNUB_SECRET,
                        False)
        print pubnub.publish({
            'channel': hashtag,
            'message': {
                'message': body
            }
        })
        return HttpResponse("Success!")
    return HttpResponse("Error")
Beispiel #3
0
    def post(self, name):
        topic = models.Topic.get_topic(self.current_site, name)
        if not topic:
            raise tornado.web.HTTPError(404)

        if not self.current_user:
            if self.get_argument('skill_test', None) != '8':
                return self.reload(message='skill_test')

        reply_to = self.get_argument('reply_to', None)
        if reply_to:
            reply_to = models.Comment.get_by_id(int(reply_to))

        comment = models.Comment(author=self.current_user,
                                 topic=topic,
                                 reply_to=reply_to,
                                 text=self.get_argument('text'))
        comment.update_score()

        topic.n_comments += 1
        if self.current_user:
            self.current_user.n_comments += 1
            db.put([topic, comment, self.current_user])
        else:
            db.put([topic, comment])

        parent_author = reply_to.author if reply_to else topic.author
        if parent_author and parent_author != comment.author:
            message = models.Message(to=parent_author,
                                     type='comment_reply',
                                     comment=comment)
            parent_author.n_messages += 1
            db.put([message, parent_author])

        self.redirect(self.request.path + '#c' + str(comment.id))
Beispiel #4
0
 def test_message_database(self):
     test_msg = models.Message('test', 'test', 'test')
     models.db.session.add(test_msg)
     models.db.session.commit()
     models.db.session.delete(test_msg)
     models.db.session.commit()
     models.db.session.close()
Beispiel #5
0
    def getMessages(self, groupId='', userGId='', limit=10, index=0):
        cursor = self.connection.cursor()
        get_query = '''SELECT 
                            userGId,
                            author,
                            title,
                            groupId,
                            message,
                            date,
                            messageId
                        FROM messages
                        WHERE (groupId=%s OR userGId=%s)
                        LIMIT %s OFFSET %s 
                 '''
        cursor.execute(get_query, (groupId, userGId, limit, index))
        messages = cursor.fetchall()
        if not messages:
            cursor.close()
            return None

        m_list = []
        for message in messages:
            m = models.Message(userGId=message[0],
                               author=message[1],
                               title=message[2],
                               groupId=message[3],
                               message=message[4],
                               date=message[5],
                               messageId=message[6])
            m_list.append(m)
        cursor.close()
        return m_list
Beispiel #6
0
def deserialize_message(id, user_id, type, body, date, updated):
    if not updated:
        updated = date

    if type == models.MessageType.NORMAL.value:
        return models.Message(id, user_id, models.MessageType.NORMAL, date, updated, body=body)
    elif type == models.MessageType.CONVERSATION_CREATED.value:
        return models.Message(id, user_id, models.MessageType.CONVERSATION_CREATED, date, updated)
    elif type == models.MessageType.USER_INVITED.value:
        invited_user_id = int(body) if body.isdigit() else 0
        return models.Message(id, user_id, models.MessageType.USER_INVITED, date, updated,
                              invited_user_id=invited_user_id)
    elif type == models.MessageType.TITLE_CHANGED.value:
        return models.Message(id, user_id, models.MessageType.TITLE_CHANGED, date, updated, new_title=body)
    else:
        return models.Message(id, user_id, models.MessageType.NORMAL, date, updated)
def handle_my_custom_event(data):

    if request.sid in socket_ids:
        socketio.sleep(seconds=0.1)
        massage = models.Message(json.dumps(data, ensure_ascii=False))
        models.db.session.add(massage)
        models.db.session.commit()

        socketio.sleep(seconds=0.1)
        socketio.emit('send:message', data, broadcast=True, include_self=False)
        the_text = str(data['text'])
        if (the_text[0:2] == '!!'):
            response = bot(data)
            if (response == "mario"):
                response = mario
            elif (response == "softkitty"):
                response = softkitty
            elif (response == "yoshi"):
                response = yoshi
            elif (response == "kenny"):
                response = kenny
            elif (response == "minion"):
                response = minion
            elif (response == "obama"):
                response = obama
            socketio.emit('bot:message',
                          response,
                          broadcast=True,
                          include_self=True)
Beispiel #8
0
def send_message(recipent=Form(...),
                 header=Form(...),
                 body=Form(...),
                 user=Depends(manager),
                 db: database.Session = Depends(database.get_db)):
    if not user:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
                            detail='Not authenticated')
    elif len(header) >= 25:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail='Message header cannot be more than 100 characters')
    elif len(body) >= 1000:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detial='Message body cannot be more than 1000 characters')
    else:
        to = db.query(database.User).filter_by(username=recipent).first()
        if to == None:
            raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST,
                                detail='Recipent of message not found')
        else:
            db_message = database.Messages(sent_at=time.time(),
                                           sent_by=user.username,
                                           recipent=recipent,
                                           header=header,
                                           body=body)
            db.add(db_message)
            db.commit()
            return models.Message(sent_at=time.time(),
                                  sent_by=user.username,
                                  recipent=recipent,
                                  header=header,
                                  body=body)
Beispiel #9
0
def text(message):
    """
    Событие при приеме сообщения
    Call this api passing a language name and get back its features
    ---
    tags:
      - Awesomeness Language API
    responses:
      200:
        description: html страница
        parameters:
          - name: "id"
            in: "delete_news"
            description: "ID новости"
            required: true
            type: "integer"
            format: "int64"
        content:
            html страница

    """
    room = session.get('room')
    if not (message['msg'].strip() == ""):
        block = models.BlockUser.query.filter_by(id_user=current_user.id).first()
        if (block is None) or not(block.block_message):
            message_bd = models.Message(id_from=int(message['id_from']), id_to=int(message['id_to']), text=message['msg'])
            db.session.add(message_bd)
            db.session.commit()
            emit('message', {'msg': message['msg'], 'recipient_id': message['id_from'], 'timestamp': str(datetime.now().strftime("%d.%m.%Y %H:%M:%S"))}, room=room)
Beispiel #10
0
    def getMessage(self, messageId):
        cursor = self.connection.cursor()
        get_query = ''' SELECT 
                             userGId,
                             author,
                             title,
                             groupId,   
                             message,
                             date 
                        FROM messages
                        WHERE messageId = %s'''
        cursor.execute(get_query, (messageId, ))
        result = cursor.fetchone()
        if not result:
            cursor.close()
            return None

        message = models.Message(userGId=result[0],
                                 author=result[1],
                                 title=result[2],
                                 groupId=result[3],
                                 message=result[4],
                                 date=result[5])
        cursor.close()
        return message
Beispiel #11
0
    def post_message(self, cid):
        ''' Posts a message to an existing conversation.

        param: cid: Numeric Id for the conversation to which to add the message
        '''

        logging.debug('Posting new message to conversation {0}'.format(cid))
        conversation = models.Conversation.get_by_id(int(cid))
        if not conversation:
            self.error(404)

        data = json.loads(self.request.body)
        message = models.Message(sender=data['sender'],
                                 text=data['text'],
                                 conversation=conversation)
        message.put()
        message.send_notifications()

        self.response.set_status(201, 'Created')
        self.response.headers.add_header(
            "Location", '{0}/{1}/{2}'.format(API_PREFIX,
                                             conversation.key().id(),
                                             message.key().id()))
        self.response.out.write(json.dumps(conversation.to_json()))
        return
Beispiel #12
0
def send_message():
    message = models.Message(text=request.json['message'],
                             sender=request.json['sender'],
                             receiver=request.json['receiver'])
    db.session.add(message)
    db.session.commit()
    return make_response(jsonify(response='OK'), 201)
def post_message(user):
    file = flask.request.files['image']

    # check that we think the file is an image file, granted a file exists
    if file:
        if not file.mimetype.startswith('image/'):
            # oops
            flask.abort(400)
    message = flask.request.form['post-text']

    message_content = Markup(markdown.markdown(message, output_format='html5'))

    new_message = models.Message()
    new_message.message = message_content
    new_message.sender = flask.g.user.login
    new_message.recipient = user
    new_message.time_stamp = db.func.now()
    new_message.photo_type = file.mimetype

    photo_data = io.BytesIO()
    file.save(photo_data)
    new_message.photo = photo_data.getvalue()

    # if photo_data is None then no photo
    # need to display just message
    print("sender:", new_message.sender)
    print("recipient:", new_message.recipient)

    db.session.add(new_message)
    db.session.commit()

    return flask.redirect(flask.url_for('view_user', user=user))
Beispiel #14
0
def _sendMessage(sender, recipient, content, application=False):
    success = False
    if content:
        # Message is valid, check if there is a conversation already started between 2 users
        conversationID = None
        conversations1 = models.Conversation.objects.filter(user1=sender,
                                                            user2=recipient)
        conversations2 = models.Conversation.objects.filter(user1=recipient,
                                                            user2=sender)
        if conversations1 or conversations2:
            if conversations1 and len(conversations1) == 1:
                conversationID = conversations1[0].conversationID
            elif conversations2 and len(conversations2) == 1:
                conversationID = conversations2[0].conversationID
        if not conversationID:
            conversationID = helpers.createUniqueID(
                destDatabase=models.Conversation, idKey="conversationID")
            conversation = models.Conversation(conversationID=conversationID,
                                               user1=sender,
                                               user2=recipient)
            conversation.save()

        if conversationID:
            messageID = helpers.createUniqueID(destDatabase=models.Message,
                                               idKey="messageID")
            message = models.Message(messageID=messageID,
                                     conversationID=conversationID,
                                     sender=sender,
                                     recipient=recipient,
                                     content=content,
                                     applicationMessage=application)
            message.save()
            success = True
        return success
Beispiel #15
0
def sendMessage(msg):
    # console log message
    #print msg
    #print msg['facebook_user_token']
    response = requests.get(
        'https://graph.facebook.com/v2.8/me?fields=id%2Cname%2Cpicture&access_token='
        + msg['facebook_user_token'])
    json = response.json()
    user = {'img': json['picture']['data']['url'], 'user': json['name']}
    print 'sent message', msg['message']['text'], user['img'], user['user']

    message = msg['message']['text']
    if re.match(botSignal, message.strip()[:2]):
        checkMessage = checkBotMessage(message)
        print checkMessage
        if len(checkMessage) > 1:
            socketio.emit(checkMessage[0], checkMessage[1])
        else:
            socketio.emit(checkMessage)

    else:
        # broadcast message to main chatroom

        socketio.emit('send:message', {
            'text': msg['message']['text'],
            'img': user['img'],
            'user': user['user']
        },
                      broadcast=True)
        # add message to database
        text = models.Message(user['img'], user['user'], message)
        models.db.session.add(text)
        models.db.session.commit()
        models.db.session.close()
Beispiel #16
0
def commitMessage(message):
    #Create a Message model object for the new message
    message = models.Message(message['text'], message['username'],
                             message['picture'], message['link'])
    #Add the new Message model object to the "session" (like git's working area?)
    models.db.session.add(message)
    #Commit the changes to the database
    models.db.session.commit()
Beispiel #17
0
 def recordMessage(self, email, msg, msg_type, dt):
     db_msg = models.Message(dt, email, msg, msg_type)
     try:
         db = self.sessionLocal()
         db.add(db_msg)
         db.commit()
         db.close()
     except:
         db.close()
Beispiel #18
0
async def chat(id: str, page: Optional[int] = 0):
    if not user.is_connected():
        await user.connect()
    if not await user.is_user_authorized():
        return templates.get_template("auth/not_authorized.html").render()
    try:
        try:
            id = int(id)
        except:
            pass
        chat = await user.get_entity(id)
        await user.conversation(chat).mark_read()
        messages = await user.get_messages(id, limit=10, add_offset=10 * page)
        msgs = []
        for m in messages:
            m: types.Message
            r = await m.get_reply_message()
            reply = None
            if r:
                name = r.sender.title if hasattr(
                    r.sender, 'title') else r.sender.first_name
                if r.file:
                    rfile = models.MessageMedia(
                        type=r.file.mime_type,
                        typ=r.file.mime_type.split("/")[0],
                        size=utils.humanize(r.file.size),
                        filename=r.file.name)
                else:
                    rfile = None
                reply = models.ReplyMessage(
                    name=name,
                    id=r.id,
                    file=rfile,
                    text=utils.replacing_text(r.text) if r.text else None)
            if m.file:
                file = models.MessageMedia(type=m.file.mime_type,
                                           typ=m.file.mime_type.split("/")[0],
                                           size=utils.humanize(m.file.size),
                                           filename=m.file.name)
            else:
                file = None
            msgs.append(
                models.Message(
                    id=m.id,
                    sender=m.sender,
                    text=utils.replacing_text(m.text) if m.text else None,
                    file=file,
                    reply=reply,
                    mentioned=m.mentioned,
                    date=m.date.strftime("%Y-%m-%d %H:%M:%S"),
                    out=m.out))
        return templates.get_template("chat.jinja2").render(messages=msgs,
                                                            chat=chat,
                                                            page=page)
    except Exception as ex:
        return templates.get_template('error.jinja2').render(
            error='<br>'.join(ex.args))
Beispiel #19
0
async def add_message(message: MessageCreate):
    message_obj = models.Message(
        name=message.name,
        body=message.body
    )
    session.add(message_obj)
    session.commit()
    session.refresh(message_obj)
    return Response200(data=message_obj)
Beispiel #20
0
def on_send_friend_request(data):
    to_user = data['user1']
    from_user = data['user2']

    if not friend_request_exists(to_user, from_user):
        db.session.add(
            models.Message(from_user=from_user,
                           to_user=to_user,
                           msg_type=models.MessageType.FriendRequest))
        db.session.commit()
def add_message():
    if flask.request.method == 'POST':
        message = models.Message()
        message.title = flask.request.form['title']
        message.content = flask.request.form['content']
        database.db_session.add(message)
        database.db_session.commit()
        return flask.render_template('add_message_ok.html')
    else:
        return flask.render_template('add_message.html')
Beispiel #22
0
def handleMessage(data):
    username = data['Username']
    current_message = data['Message']

    def is_url(url):
        try:
            result = urlparse(url)
            return all([result.scheme, result.netloc])
        except ValueError:
            return False

    if current_message[:2] == '!!':
        username = "******"
        called_class = chatbot.Chatbot()
        final_response = called_class.response(current_message)
        new_message = models.Message("{}: \n {}".format(
            username, final_response))
        models.db.session.add(new_message)
        models.db.session.commit()
    #joy working with database table
    elif current_message[:2] == '!! PR-Music':
        username = "******"
        class_call = chatbot.Chatbot()
        final_response = class_call.response(current_message)
        new_message = models.Genius("{}: \n {}".format(username,
                                                       final_response))
        models.db.session.add(new_message)
        models.db.session.commit()

    elif is_url(current_message) is True:
        hyperlink_format = '<a href="{link}">{text}</a>'  #doesn't work now
        hyperlink_format.format(link=current_message, text='foo bar')
        link_text = hyperlink_format.format
        message_now = models.Message(link_text)
        models.db.session.add(message_now)
        models.db.session.commit()

    else:
        info = models.Message("{}: \n {}".format(username, data['Message']))
        models.db.session.add(info)
        models.db.session.commit()

    return on_connect()
Beispiel #23
0
def on_new_number(data):
    print(("Got an event for new number with data:"), data)
    new_message = models.Message(data['message'])
    models.db.session.add(new_message)
    models.db.session.commit()
    if data['message'] == '!! help' or data['message'] == '!! chat' or data[
            'message'] == '!! about':
        chat_bot_response(data['message'])

    query()
Beispiel #24
0
def message(user_name):
    form = MessageForm()
    username = session['username']
    username_obj = models.User.query.get(user_name)
    user_obj = models.User.query.get(username)
    if not username_obj:
        redirect('/user')
    if not user_obj:
        redirect('/user')
    if user_name == username:
        redirect('/user')

    relation = models.Friend.query.filter_by(first_username=username,
                                             second_username=user_name).first() \
                   or models.Friend.query.filter_by(first_username=user_name,
                                            second_username=username).first()

    msg_obj1 = models.Message.query.filter_by(first_username=username,
                                              second_username=user_name)
    msg_obj2 = models.Message.query.filter_by(first_username=user_name,
                                              second_username=username)
    msg_all = msg_obj1.union(msg_obj2).order_by(
        models.Message.timestamp).limit(10)

    frndlist1 = user_obj.friends_f
    frndlist2 = user_obj.friends_s
    frnd_all = frndlist1.union(frndlist2).order_by(models.Friend.timestamp)

    #message_id = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(30))
    message_id = random.randint(1000000, 9999999)
    if form.validate_on_submit() and request.method == 'POST':
        msg = models.Message(id=message_id,
                             first_username=username,
                             second_username=user_name,
                             chat=form.message.data,
                             timestamp=datetime.datetime.utcnow(),
                             chat_by=username)
        db.session.add(msg)
        db.session.commit()

        return render_template(
            'message.html',
            username_obj=username_obj,
            username=username,
            msg_all=msg_all,
            relation=relation,
            form=form,
        )

    return render_template('message.html',
                           username_obj=username_obj,
                           username=username,
                           msg_all=msg_all,
                           relation=relation,
                           form=form)
Beispiel #25
0
def handleMessage(data):
    u_message = data['Message']
    u2_message = models.Message(data['Message'])
    #If statement for chatbot here

    current_message = data['Message']

    #If it is a url, send data to the client
    if current_message[:2] == '!!':
        called_class = chatbot.Chatbot()
        final_response = called_class.response(current_message)
        new_message = models.Message(final_response)
        models.db.session.add(new_message)
        models.db.session.commit()

    else:
        info = models.Message(data['Message'])
        models.db.session.add(info)
        models.db.session.commit()
    return on_connect()
Beispiel #26
0
    def sync(self):

        self.data = []

        r = get('topics', self.topic.id, 'messages')
        for _message in deserialize(r.content)['messages']:

            message = models.Message()
            message.import_from_api(_message)
            message.topic = self.topic
            self.data.append(message)
Beispiel #27
0
def chat_bot_response(message):
    if message == '!! help':
        chatbot_message = 'try typing \"!! about\" or \"!! chat\" for me to respond'
    if message == '!! about':
        chatbot_message = 'Welcome to Deandra\'s chatbot where you can talk to anyone on here including me'
    if message == '!! chat':
        chatbot_message = 'I love talking to you chat anytime'

    new_message = models.Message(chatbot_message)
    models.db.session.add(new_message)
    models.db.session.commit()
Beispiel #28
0
def random_record(timestamp=time.time()):
    """Generate a random record with the given time

    Args:
        timestamp (optional[float]) - the timestamp for the record. Default is
            the current time.
    Returns:
        models.Message with random data and the specified timestamp.
    """
    return models.Message(username=random_string(),
                          text=random_string(50),
                          timestamp=datetime.datetime.fromtimestamp(timestamp))
Beispiel #29
0
def on_new_message(data):
    print('Data Recieved: ', data)
    new_message = models.Message(data['message'])
    models.db.session.add(new_message)
    models.db.session.commit()

    if data['message'][:2] == '!!':
        chat_message = data['message']
        bot_response = chatbot.Chatbot()
        print("Chatbot message: " + chat_message)
        response = bot_response.get_response(chat_message[2:])
    query()
Beispiel #30
0
    def post_message(self, cid):
        ''' adds a new message to the thread, and sends notifications '''
        logging.info('Posting new message to conversation {0}'.format(cid))
        conversation = models.Conversation.get_by_id(int(cid))
        logging.info(self.request.get('sender'))
        msg = models.Message(sender=self.request.get('sender'),
                             text=self.request.get('text'),
                             conversation=conversation)
        notifications = msg.set_notifications()
        msg.put()

        return