Example #1
0
def handle_new_message(data):
    db.session.add(
        models.Messages(
            data["username"],
            data["messageText"][0:256],
            datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            models.Users.query.filter_by(username=data["username"]).first().imageUrl,
        )
    )
    if data["messageText"][0:2] == "!!":
        db.session.add(
            models.Messages(
                "butler-bot",
                chatbot.respond(data["messageText"]),
                datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                "https://i.imgur.com/m9mlpmh.png",
            )
        )
    db.session.commit()
    update_messages()
    return models.Messages(
        data["username"],
        data["messageText"][0:256],
        datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        models.Users.query.filter_by(username=data["username"]).first().imageUrl,
    )
Example #2
0
def user(username):
    user = User.query.filter_by(username=username).first()
    token = False
    if user == None:
        flash('User %s not found.' % username)
        return redirect(url_for('index'))
    messages = Messages.query.filter_by(username=username)
    form = MessageForm()
    if form.validate_on_submit():
      m = models.Messages(username = user.username, author=current_user.username, content = form.content.data)
      db.session.add(m)
      db.session.commit()
    if request.method == "POST" and request.values.get("delete"):
      delete = models.Messages.query.filter_by(id=request.form['id_message']).first()
      db.session.delete(delete)
      db.session.commit()
    if request.method == "POST" and request.values.get("edit"):
      token = True
    if request.method == "POST" and request.values.get("repost"):
      m = models.Messages.query.filter_by(id=request.form['id_message']).first()
      m.content = form.content.data
      db.session.commit()
      token = False
    return render_template('user.html',
                           user=user,
                           messages=messages,
                           form=form,
                           token=token)
 def send_message(from_user, to_user, text, date=datetime.now()):
     from_id = from_user.get_id
     to_id = to_user.get_id
     message = models.Messages(from_id, to_id, text)
     message.set_date(date)
     message.save_to_db(cursor)
     connection.commit()
     return f"Message send to user: {to_user.username}"
Example #4
0
def on_new_message(data):
    print("Got an event for new message input with data:", data)
    user = {}
    user["sid"] = flask.request.sid
    user["room"] = get_room(flask.request.sid)  # TODO: get room_id from the sender request.sid
    user_id = models.DB.session.query(models.CurrentConnections.user).filter_by(sid=flask.request.sid).first()[0]
    user["username"] = models.DB.session.query(models.AuthUser.username).filter_by(id=user_id).first()[0] 
    models.DB.session.add(models.Messages(user, user['username'] + ": " + data['message']))
    models.DB.session.commit()
    emit_all_messages(get_room(flask.request.sid))
Example #5
0
def on_new_message(data):
    print("Got an event for new message input with data:", data)
    output = bot.switch(data["message"])
    print(output)
    # output = parseInput(data)
    try:
        db.session.add(
            models.Messages(
                connected[request.sid] + ": " + data["message"],
                db.session.query(models.user_info.id)
                .filter(models.user_info.user == connected[request.sid])
                .first()
                .id,
            )
        )
        db.session.commit()
        if (output[KEY_IS_BOT] == True):
            db.session.add(
                models.Messages(
                    "Awesome Bot: " + output[KEY_MESSAGE],
                    db.session.query(models.user_info.id)
                    .filter(models.user_info.user == "Awesome Bot")
                    .first()
                    .id,
                )
            )
            db.session.commit()
    except Exception as error:
        db.session.rollback()
        db.session.add(
            models.Messages(
                "ERROR: User "
                + connected[request.sid]
                + "'s message has failed to send! Please try again!",
                db.session.query(models.user_info.id)
                .filter(models.user_info.user == connected[request.sid])
                .first()
                .id,
            )
        )
        db.session.commit()
    emit_all_messages(MESSAGES_RECEIVED_CHANNEL)
Example #6
0
def handle_message(data):
    db.session.add(
        models.Messages(data['newUserMessage'], data['userId'],
                        data['groupId']))
    db.session.commit()
    server_socket.emit("broadcast", {
        "newMessage": data['newUserMessage'],
        "groupName": "another group"
    },
                       broadcast=True,
                       include_self=False)
Example #7
0
def on_send_message(data):
    """recieve message, parse, add to db, and update messages"""
    date = datetime.now(TIME_ZONE)
    msg = msg_parser.parse_pictures_and_links(data['message'])

    #add message to db
    db.session.add(
        models.Messages(clients[data['id']]['name'], msg,
                        date.strftime("%H:%M %m/%d/%y")))
    db.session.commit()

    #add message to this instance's data storage
    messages.append({
        'user': clients[data['id']]['name'],
        'message': msg,
        'timestamp': date.strftime("%H:%M %m/%d/%y")
    })

    #Check if message is a command
    if data['message'][:2] == '!!':
        #respond with bot
        data['user'] = '******'
        data['message'] = bot(data['message'])
        #add bot message to db
        db.session.add(
            models.Messages(data['user'], data['message'],
                            date.strftime("%H:%M %m/%d/%y")))
        db.session.commit()
        #add bot message to this instance's data storage
        messages.append({
            'user': data['user'],
            'message': data['message'],
            'timestamp': date.strftime("%H:%M %m/%d/%y")
        })

    #send all messages in storage to all users
    return socketio.emit('messages updated', {'messages': messages},
                         broadcast=True)
Example #8
0
def on_new_message(data):
    print("Got an event for new message input")
    curr_conn_row = models.DB.session.query(
        models.CurrentConnections).filter_by(sid=flask.request.sid).first()
    if curr_conn_row:
        user_id = curr_conn_row.user
    else:
        print("\tmessage not added due to unconnected sender")
        return
    user_row = models.DB.session.query(
        models.AuthUser).filter_by(id=user_id).first()
    if user_row:
        user = {}
        user["sid"] = flask.request.sid
        user["username"] = user_row.username
        user["picUrl"] = user_row.picUrl
        user["room"] = get_room(flask.request.sid)
        models.DB.session.add(
            models.Messages(user, user["username"] + ": " + data["message"]))
        models.DB.session.commit()
        print("\tmessage added to message history")
        emit_all_messages(flask.request.sid)
    else:
        print("\tmessage not sent due to unidentified sender")
 def messages(self):
     return m.Messages(self.user)
Example #10
0
KEY_INPUT = "input"
KEY_EXPECTED = "expected"
KEY_EMIT = "emit"
KEY_CHANNEL = "channel"
KEY_ID = 0
freezer = freeze_time("2020-10-27 21:24:00")
freezer.start()

dotenv_path = join(dirname(__file__), 'sql.env')
load_dotenv(dotenv_path)

database_uri = os.environ['DATABASE_URL']

botty = bot.Bot()
db = app.db
mess = models.Messages("hi there", 1)
user = models.user_info("*****@*****.**", "bot", "pic")


class MockedDateResponse:
    def __init__(self, date):
        self.date = date


class MockedJokeResponse:
    def __init__(self, joke):
        self.joke = joke


class MockedTranslateResponse:
    def __init__(self, text):
Example #11
0
def send_message(username, password, to, send):
    if check_pass(username, password) == 0:
        u1 = m.User.load_user_by_name(cursor, username)
        u2 = m.User.load_user_by_name(cursor, to)
        mess = m.Messages(u1.id, u2.id, send)
        mess.safe_to_db(cursor)