예제 #1
0
def test_friend_system(new_user, new_user1):
    """
    Tests if two users can add each other correctly.
    """
    friend1 = Friend(author=new_user, friend_username=new_user1.username)
    friend2 = Friend(author=new_user1, friend_username=new_user.username)
    assert friend1.friend_username == new_user1.username and friend2.friend_username == new_user.username
예제 #2
0
def best_friend2(current_monkey_id, new_best_friend_name):
    """ Select best friend for a given monkey """
    monkeys = Monkey.query.all()
    monkeynames = [(monkey.name, monkey.name) for monkey in monkeys]
    monkeynames.sort()
    current_monkey = Monkey.query.get(current_monkey_id)
    #form = SelectOneMonkeyForm()
    #form.example.label='Select Best Friend for '+current_monkey.name
    #form.example.choices=monkeynames

    if True:
        friend1 = Friend.\
                 query.filter(Friend.name==new_best_friend_name,
                              Friend.monkey_id==current_monkey_id).first()
        current_monkey.best_friend_name = new_best_friend_name
        if not (friend1):
            #best friend was not in friends, we must add it there
            friend = Friend(name=new_best_friend_name, monkey=current_monkey)
            db.session.add(friend)
            #also the other way round
            if (new_best_friend_name != current_monkey.name):
                friend_monkey = \
                    Monkey.query.filter_by(name=friend.name).first()
                friend = Friend(name=current_monkey.name, monkey=friend_monkey)
                db.session.add(friend)
            #update number of friends
            monkeys = Monkey.query.all()
            for monkey in monkeys:
                monkey.lenfriends = len(monkey.friends)
        db.session.commit()
    return
예제 #3
0
 def test_count_friends(self):
     u1_name = 'john'
     u1_email = '*****@*****.**'
     u2_name = 'alex'
     u2_email = '*****@*****.**'
     u3_name = 'cat'
     u3_email = '*****@*****.**'
     u1 = User(username=u1_name, email=u1_email, password='******')
     u2 = User(username=u2_name, email=u2_email, password='******')
     u3 = User(username=u3_name, email=u3_email, password='******')
     db.session.add(u1)
     db.session.add(u2)
     db.session.add(u3)
     db.session.commit()
     status = 'Accepted'
     time = datetime.datetime.utcnow()
     f1 = Friend(first_username=u1_name,
                 second_username=u2_name,
                 status=status,
                 timestamp=time,
                 action_username=u1_name)
     f2 = Friend(first_username=u1_name,
                 second_username=u3_name,
                 status=status,
                 timestamp=time,
                 action_username=u3_name)
     db.session.add(f1)
     db.session.add(f2)
     db.session.commit()
     self.assertEqual(Friend.count_friends(u1_name), 2)
예제 #4
0
def friends(username):
    if username != current_user.username:
        return redirect(current_user.username)

    form = FriendsForm()
    
    user = User.query.filter_by(username = username).first()
    if username == current_user.username and form.is_submitted():
        friends = db.session.query(Friend).filter(user.id == Friend.u_id).filter(user.id != Friend.f_id).all()
        
        friend = User.query.filter_by(username = form.username.data).first()
        allrd = False
        for f in friends:
           if friend is not None:
              if f.f_id == friend.id:
                  allrd = True
                
        if friend is None:
            flash('User does not exist')
        elif friend.id == user.id:
            flash('You cant add yourself')
        elif allrd == True:
            flash("User is already added")
        else:
            friend = Friend(u_id = user.id, f_id = friend.id)
            db.session.add(friend)
            db.session.commit()
    
   
    friends = db.session.query(User, Friend).join(Friend, User.id == Friend.u_id).filter(user.id == Friend.u_id).filter(user.id != Friend.f_id).all()
    all_friends = []
    for friend in friends: 
        all_friends.append(User.query.filter(User.id == friend[1].f_id).first())
    return render_template('friends.html', title='Friends', username=username,form=form, friends=all_friends)
예제 #5
0
 def test_are_friends(self):
     u1_name = 'john'
     u1_email = '*****@*****.**'
     u2_name = 'alex'
     u2_email = '*****@*****.**'
     u1 = User(username=u1_name, email=u1_email, password='******')
     u2 = User(username=u2_name, email=u2_email, password='******')
     db.session.add(u1)
     db.session.add(u2)
     db.session.commit()
     f = Friend(first_username=u1_name,
                second_username=u2_name,
                status='Accepted',
                timestamp=datetime.datetime.utcnow(),
                action_username=u1_name)
     db.session.add(f)
     db.session.commit()
     self.assertTrue(Friend.are_friends(u1_name, u2_name))
예제 #6
0
def add_friend():
    try:
        data = request.json
        newFriend = Friend(user_id=data['user_id'],
                           sender_id=data['sender_id'])
        db.session.add(newFriend)
        db.session.commit()
        return {'message': 'Success'}
    except:
        return {'error': ['An error occurred adding a friend']}
예제 #7
0
 def test_monkey_list(self):
     m1 = User(name='admin2', email='*****@*****.**', age=25)
     m2 = User(name='test2', email='*****@*****.**', age=27)
     f = Friend(m2.id, approved=True, bestfriend=False)
     db.session.add(f)
     db.session.commit()
     m1.tag.append(f)
     db.session.commit()
     response = self.client.get('/', follow_redirects=True)
     self.assertIn('admin', response.data)
     response = self.client.get('/friends?id=1', follow_redirects=True)
     self.assertIn('Welcome! admin', response.data)
예제 #8
0
 def test_sort_by_bfriend(self):
     e1 = User(name='admine2', email='*****@*****.**', age=25)
     e2 = User(name='teste2', email='*****@*****.**', age=27)
     db.session.add_all([e1, e2])
     f = Friend(friend_account=e2.id, approved=True, bestfriend=True)
     db.session.add(f)
     db.session.commit()
     e1.tag.append(f)
     db.session.commit()
     response = self.client.get(url_for('fast.sortbybfriend'),
                                follow_redirects=True)
     self.assertIn('Sort by Best friends', response.data)
예제 #9
0
 def test_sort_by_nfriends(self):
     d1 = User(name='admind2', email='*****@*****.**', age=25)
     d2 = User(name='testd2', email='*****@*****.**', age=27)
     db.session.add_all([d1, d2])
     f = Friend(friend_account=d2.id, approved=True, bestfriend=False)
     db.session.add(f)
     db.session.commit()
     d1.tag.append(f)
     db.session.commit()
     response = self.client.get(url_for('fast.sortbynfriends'),
                                follow_redirects=True)
     self.assertIn('Sort by number of friends', response.data)
예제 #10
0
 def test_user_unfriend(self):
     e1 = User(name='admine2', email='*****@*****.**', age=25)
     e2 = User(name='teste2', email='*****@*****.**', age=27)
     db.session.add_all([e1, e2])
     f = Friend(friend_account=e2.id, approved=True, bestfriend=True)
     db.session.add(f)
     db.session.commit()
     e1.tag.append(f)
     db.session.commit()
     response = self.client.delete('/unFriend?id2=%d&id=%d' %
                                   (e1.id, e2.id),
                                   follow_redirects=True)
     self.assertTrue('admine2 is removed!', response.data)
예제 #11
0
 def test_best_friend(self):
     e1 = User(name='admine2', email='*****@*****.**', age=25)
     e2 = User(name='teste2', email='*****@*****.**', age=27)
     db.session.add_all([e1, e2])
     f = Friend(friend_account=e2.id, approved=True, bestfriend=True)
     db.session.add(f)
     db.session.commit()
     e1.tag.append(f)
     db.session.commit()
     response = self.client.post('/bestFriend?id2=%d&id=%d' %
                                 (e1.id, e2.id),
                                 follow_redirects=True)
     self.assertTrue('Thank you! Now, Julia Smith is your best friend!!',
                     response.data)
예제 #12
0
def accept_friend_request(id):
    current_user_id = current_user.get_id()
    # current_user_id = 1
    invite = Invite.query.filter(Invite.invitee_id == current_user_id,
                                 Invite.inviter_id == id,
                                 Invite.type == 'friend').first()
    # current_user = User.query.get(current_user_id)
    # inviter = User.query.get(id)
    # current_user.friends.append(inviter)
    friends = Friend(user_one_id=id, user_two_id=current_user_id)
    db.session.add(friends)
    db.session.delete(invite)
    db.session.commit()
    return invite.to_dict()
예제 #13
0
 def test_friend_confirm(self):
     e1 = User(name='admine2', email='*****@*****.**', age=25)
     e2 = User(name='teste2', email='*****@*****.**', age=27)
     db.session.add_all([e1, e2])
     f = Friend(friend_account=e2.id, approved=True, bestfriend=True)
     db.session.add(f)
     db.session.commit()
     u1 = User.query.get(e1.id)
     self.assertTrue(e1.id == u1.id)
     u1.tag.append(f)
     db.session.commit()
     response = self.client.put('/confirm?id=%d&id2=%d' % (e2.id, e1.id),
                                follow_redirects=True)
     self.assertTrue('Thank you! Now,teste2 is your Friend!! ',
                     response.data)
예제 #14
0
파일: test.py 프로젝트: AnkushAppy/smaV2
 def test_are_friends(self):
     u1_name = 'john'
     u1_email = '*****@*****.**'
     u2_name = 'alex'
     u2_email = '*****@*****.**'
     u1 = User(username=u1_name,email=u1_email,password='******')
     u2 = User(username=u2_name, email=u2_email, password='******')
     db.session.add(u1)
     db.session.add(u2)
     db.session.commit()
     f = Friend(first_username=u1_name,
                second_username=u2_name,
                status='Accepted',timestamp=datetime.datetime.utcnow(),action_username=u1_name)
     db.session.add(f)
     db.session.commit()
     self.assertTrue(Friend.are_friends(u1_name,u2_name))
예제 #15
0
 def test_user_friend(self):
     u = User(username='******', email='*****@*****.**', password='******')
     v = User(username='******', email='*****@*****.**', password='******')
     f = Friend(first_username='******',
                second_username='******',
                status='pending',
                timestamp=datetime.datetime.utcnow(),
                action_username='******')
     # john have send friend request to kim, kim should confirm now
     db.session.add(u)
     db.session.add(v)
     db.session.add(f)
     db.session.commit()
     rv = self.login('john', 'hello')
     assert 'Hello john!! Your email: [email protected]' in rv.data
     rv = self.logout()
     assert 'Please Enter Login Credentials' in rv.data
     rv = self.login('kim', 'hello')
     assert 'Hello kim!! Your email: [email protected]' in rv.data
     assert 'Reject' in rv.data
     assert '/user/add/john' in rv.data
     # print 'Request friendship, reject, confirm checked'
     # friendship got accepted by kim. now both should have name in their friend list
     path = '/user/add/john'
     rv = self.profile(path)
     assert '/user/john' in rv.data
     # print 'confirm friend link working'
     rv = self.logout()
     rv = self.login('john', 'hello')
     assert 'Hello john!! Your email: [email protected]' in rv.data
     assert '/user/kim' in rv.data
     path = '/user/kim'
     rv = self.profile(path)
     assert '/user/john' in rv.data
     #    print rv.data
     #   print 'friend profile link working'
     path = '/user/unfriend/kim'
     rv = self.profile(path)
     assert 'Add Friend' in rv.data
     #   print rv.data
     path = '/user/add/kim'
     rv = self.profile(path)
     assert 'Current status: pending' in rv.data
예제 #16
0
파일: test.py 프로젝트: AnkushAppy/smaV2
 def test_count_friends(self):
     u1_name = 'john'
     u1_email = '*****@*****.**'
     u2_name = 'alex'
     u2_email = '*****@*****.**'
     u3_name = 'cat'
     u3_email = '*****@*****.**'
     u1 = User(username=u1_name, email=u1_email, password='******')
     u2 = User(username=u2_name, email=u2_email, password='******')
     u3 = User(username=u3_name, email=u3_email, password='******')
     db.session.add(u1)
     db.session.add(u2)
     db.session.add(u3)
     db.session.commit()
     status = 'Accepted'
     time = datetime.datetime.utcnow()
     f1 = Friend(first_username=u1_name,second_username=u2_name,status=status,timestamp=time,action_username=u1_name)
     f2 = Friend(first_username=u1_name, second_username=u3_name, status=status, timestamp=time,action_username=u3_name)
     db.session.add(f1)
     db.session.add(f2)
     db.session.commit()
     self.assertEqual(Friend.count_friends(u1_name),2)
예제 #17
0
 def test_message(self):
     u = User(username='******', email='*****@*****.**', password='******')
     v = User(username='******', email='*****@*****.**', password='******')
     f = Friend(first_username='******',
                second_username='******',
                status='Accepted',
                timestamp=datetime.datetime.utcnow(),
                action_username='******')
     m1 = Message(id=random.randint(1000000, 9999999),
                  first_username='******',
                  second_username='******',
                  chat='Hello kim, :)',
                  timestamp=datetime.datetime.utcnow(),
                  chat_by='john')
     db.session.add(u)
     db.session.add(v)
     db.session.add(f)
     db.session.add(m1)
     db.session.commit()
     self.login('john', 'hello')
     self.profile('/user/kim')
     rv = self.profile('/user/kim/message')
     assert 'Hello kim, :)' in rv.data
예제 #18
0
def friend2(current_monkey_id, new_friend_names):
    """ Select friends for a monkey """
    monkeys = Monkey.query.all()
    monkeynames = [(monkey.name, monkey.name) for monkey in monkeys]
    monkeynames.sort()
    current_monkey = Monkey.query.get(current_monkey_id)
    oldfriends = current_monkey.friends
    oldfriendnames = [oldfriend.name for oldfriend in oldfriends]
    oldfriendnames.sort()
    oldfriendnames.append(None)
    #form = SelectManyMonkeyForm(example=oldfriendnames)
    #form.example.label='Select Friends for ' + current_monkey.name + \
    #    ' (old friends are pre-selected)'
    #form.example.choices=monkeynames

    if True:
        #update number of friends
        monkeys = Monkey.query.all()
        for monkey in monkeys:
            print "MNalku, LEN", monkey.name, len(
                monkey.friends), monkey.friends

        #check for no friends at all for this monkey
        for name in new_friend_names:
            if (name.find('None') != -1):
                current_monkey.lenfriends = 0
                new_friend_names = []

        new_friends = Monkey.query.filter(Monkey.name.in_(new_friend_names))
        old_friends = Monkey.query.filter(Monkey.name.in_(oldfriendnames))

        for new_friend in new_friends:
            print "new_friend", new_friend.name
        for old_friend in old_friends:
            print "old_friend", old_friend.name

        #Add new friends, this is a two way relation
        #that is friends are friends in both ways
        for new_friend in new_friends:
            if (new_friend.name not in oldfriendnames):
                friend = Friend(name=new_friend.name,
                                monkey_id=current_monkey_id)
                print "new friend to", current_monkey.name, current_monkey_id
                print "new friend is", friend.name
                print "pointing to", friend.monkey_id
                db.session.add(friend)
                # the other way round, but not doublecount
                #being friend with oneself
                if (new_friend.name != current_monkey.name):
                    print "adding friend2"
                    friend2 = Friend(name=current_monkey.name,
                                     monkey_id=new_friend.id)
                    db.session.add(friend2)
        #delete old friends that are not new friends
        deletenames = list((set(oldfriendnames) | set(new_friend_names)) - \
            set(new_friend_names))
        deletenames.remove(None)
        print "aa:", list((set(oldfriendnames) | set(new_friend_names)))
        print "dd:", oldfriendnames, new_friend_names
        print "deletenames", deletenames
        friends1 = Friend.query.filter(Friend.name.in_(deletenames))
        friends2 = Friend.query.filter_by(monkey_id=current_monkey.id)
        delete_friends = friends1.intersect(friends2)
        for friend in delete_friends:
            print "1friend--del", friend.name, friend.monkey_id
            db.session.delete(friend)
        #also delete the other way round
        del_friends = Monkey.query.filter(Monkey.name.in_(deletenames))
        deletefriend_ids = [delfriend.id for delfriend in del_friends]

        print "deletefriend_ids", deletefriend_ids
        friends1 = Friend.query.filter(Friend.monkey_id.in_(deletefriend_ids))
        friends2 = Friend.query.filter_by(name=current_monkey.name)
        for fr in friends1:
            print "del21::", fr.name, fr.monkey_id
        for fr in friends2:
            print "del22::", fr.name, fr.monkey_id
        delete_friends = friends1.intersect(friends2)
        for friend in delete_friends:
            print "2friend--del", friend.name, friend.monkey_id
            db.session.delete(friend)
        db.session.commit()
        #update number of friends
        monkeys = Monkey.query.all()
        for monkey in monkeys:
            monkey.lenfriends = len(monkey.friends)
            print "MN, LEN", monkey.name, len(monkey.friends), monkey.friends
        db.session.commit()
        #check whether we should delete best friend if a friend has been deleted
        deletenames = [dn.encode('utf8') for dn in deletenames]
        print "current_monkey.best_friend_name in deletenames",\
            current_monkey.best_friend_name, deletenames
        if current_monkey.best_friend_name in deletenames:
            print "DEL BF"
            current_monkey.best_friend_name = None
        for monkey in del_friends:
            if monkey.best_friend_name == current_monkey.name:
                monkey.best_friend_name = None
        db.session.commit()
    return
예제 #19
0
def default(request):
    contextdict = {}

    if request.user.is_anonymous():
        return contextdict
    else:
        rooms = []
        user = request.user
        ri = RoomInstance.objects.filter(listofusers__icontains = user, expirydate__gt = datetime.now())

        for room in ri:
            timeleft = int(timedelta.total_seconds(room.expirydate - datetime.today()))
            roomdict = {
                'roomname' : room.roomname,
                'expirydate' : timeleft,
            }
            rooms.append(roomdict)
        contextdict['rooms'] = rooms

        if is_lazy_user(user) == False and request.user.is_authenticated():
            userprofile = UserProfile.objects.get(user=user.id)
            pendingfriends = json.loads(userprofile.pendingfriends)
            friendinvites = []

            for friend in pendingfriends:
                friendinvitedict = {
                    'username' : friend['username']
                }
                friendinvites.append(friendinvitedict)

            contextdict['friendinvites'] = friendinvites
            pendingnotifications = json.loads(userprofile.pendingnotifications)
            
            pending = []
            for notification in pendingnotifications:
                notificationdict = {
                    'message' : notification['message'],
                    'notificationid' : notification['notificationid']
                }
                pending.append(notificationdict)

            contextdict['pendingnotifications'] = pending

            contextdict['notificationslength'] = len(contextdict['friendinvites']) + len(contextdict['pendingnotifications'])
    if request.method == 'POST':
        result = json.loads(json.dumps(request.POST))
        if 'type' in result:
            if  result['type'] == "addfriend":
                friend_user = User.objects.get(username=result['sender'])
                # If there is no relationship between users,
                # create one
                if not Friend.objects.filter(user1=user, user2=friend_user) and not Friend.objects.filter(user1=friend_user, user2=user):
                    addfriend = Friend(user1=user, user2=friend_user)
                    addfriend.save()

                    user = UserProfile.objects.get(user=request.user)
                    removepending(user, result['sender'], request.user)
                    friendprofile = UserProfile.objects.get(user=friend_user.id)
                    pendingnotifications = json.loads(friendprofile.pendingnotifications)
                    message = {
                        "message" : "You are now friends with " + str(request.user), 
                        "reason": "Accepted",
                        "notificationid": ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(7))}
                    pendingnotifications.insert(0,message)
                    friendprofile.pendingnotifications = json.dumps(pendingnotifications)
                    friendprofile.save()
            elif result['type'] == "declinefriend":
                user = UserProfile.objects.get(user=request.user)
                removepending(user, result['sender'], request.user)
            elif result['type'] == "removenotification":

                user = UserProfile.objects.get(user=request.user)
                pendingnotifications = json.loads(user.pendingnotifications)
                savednotificaitons = []
                for notification in pendingnotifications:
                    if result['notificationid'] != notification['notificationid']:
                        savednotificaitons.append(notification)
                userupdate = UserProfile.objects.filter(user=request.user)
                userupdate.update(pendingnotifications=json.dumps(savednotificaitons))
    return contextdict
예제 #20
0
def make_cmd(cmd=None, name=None):
    a = Admin.query.first()
    admin_cid = a.chat_id
    app.logger.info(f'Command: {cmd}')
    need_update = False

    if (cmd == 'обновить_друга') and name:
        app.logger.info(f'Adding friend...')
        f = Friend.query.first()
        if f:
            Friend.query.delete()
            db.session.commit()
        r = Friend(name=str(name).lower())
        db.session.add(r)
        need_update = True

    elif (cmd == 'добавить_взыскателя') and name:
        app.logger.info(f'Adding claimant...')
        r = Claimant(name=str(name).lower())
        db.session.add(r)
        need_update = True

    # elif cmd == 'add_several_claimants':
    #     print('adding several claimants')
    #     claims =
    #     r = Claimant(name=name)
    #     db.session.add(r)
    #     need_update = True

    elif (cmd == 'отправить_всем') and name:
        cs_raw = Claimant.query.all()
        cs = [x.name for x in cs_raw]
        links_raw = Link.query.distinct(Link.from_chat_id)
        chats = [x.from_chat_id for x in links_raw if x.claimant in cs]
        for clai in chats:
            bot.sendMessage(chat_id=clai, text=name)
            time.sleep(1)
        bot.sendMessage(chat_id=admin_cid,
                        text='Сообщение отправлено всем взыскателям.')

    elif cmd == 'показать_друга':
        friend = Friend.query.first()
        if friend:
            text = friend.name
        else:
            text = 'No friend'
        bot.sendMessage(chat_id=admin_cid, text=text)

    elif cmd == 'показать_взыскателей':
        cs_raw = Claimant.query.all()
        cs = [x.name for x in cs_raw]
        if cs:
            bot.sendMessage(chat_id=admin_cid, text=(', '.join(cs)))
        else:
            bot.sendMessage(chat_id=admin_cid, text='No claimants')

    elif cmd == 'help':
        bot.sendMessage(chat_id=admin_cid,
                        text='''Для настройки бота надо:

Перед запуском приложения в файле config.py указать username админа бота, в формате без "@", либо же указать в переменной окружения 'ADMIN', пример "test_user0"
Админ должен найти бота "ClaimantBot" и написать ему "/start", дождаться ответа бота со справкой.
Админ с помощью команд "/обновить_друга" и "/добавить_взыскателя" может обновлять username друга и добавлять username взыскателей соответственно, например: нажать кнопку "/обновить_друга", дожидаемся ответа бота, отправляем username друга "test_user1"; нажать кнопку  "/добавить_взыскателя", дожидаемся ответа бота, отправляем username взыскателя "test_user2".
После добавления друга командой "/обновить_друга" друг должен найти бота и отправить ему любое сообщение, бот ответит "Все готово!"
После добавления взыскателей они должны найти бота, отправить ему сообщение, эти сообщения попадают к другу, друг может отвечать на них с помощью стандартного функционала телеграма "ответить".
Для админа также существуют команды:

/показать_друга - показывает username друга
/показать_взыскателей - показывает username всех взыскателей
/удалить_всех - удаляет username и друга, и всех взыскателей
/удалить_взыскателя - удаляет username взыскателя, используется: нажатие кнопки команды, дожидаемся ответа бота, отправляем username взыскателя
/статистика - показывает статистику использования бота''')

    elif cmd == 'test_cmd':
        return 'all is good'

    elif cmd == 'удалить_всех':
        app.logger.info(f'Deleting all...')
        Friend.query.delete()
        Claimant.query.delete()
        need_update = True

    elif (cmd == 'удалить_взыскателя') and name:
        app.logger.info(f'Deleting claimant...')
        app.logger.info(f'{name}')
        # b = Claimant.query.filter_by(name=str(name).lower()).first()
        # if b:
        #     app.logger.info(f'{b.name}')
        #     b.delete()
        #     db.session.commit()
        Claimant.query.filter_by(name=str(name).lower()).delete()
        need_update = True

    elif cmd == 'статистика':
        b = datetime.now()
        count_today = Message.query.filter(
            Message.timestamp >= datetime(b.year, b.month, b.day))
        count_daily = Message.query.filter(
            Message.timestamp >= (b - timedelta(days=1)))
        claimant_today = count_today.filter(
            Message.from_claimant == True).count()
        claimant_daily = count_daily.filter(
            Message.from_claimant == True).count()
        count_today = count_today.count()
        count_daily = count_daily.count()
        last_7day = Message.query.filter(
            Message.timestamp >= (datetime(b.year, b.month, b.day)) -
            timedelta(days=7))
        claimant_last_7day = last_7day.filter(
            Message.from_claimant == True).count()
        last_30day = Message.query.filter(
            Message.timestamp >= (datetime(b.year, b.month, b.day)) -
            timedelta(days=30))
        claimant_last_30day = last_30day.filter(
            Message.from_claimant == True).count()
        last_7day = last_7day.count()
        last_30day = last_30day.count()
        count_all = Message.query
        claimant_count_all = count_all.filter(
            Message.from_claimant == True).count()
        count_all = count_all.count()

        resp = f'''Сообщений за этот день: {count_today}
Сообщений за последние сутки: {count_daily}
Сообщений за этот день от взыскателей: {claimant_today}
Сообщений за последние сутки от взыскателей: {claimant_daily}
Сообщений за неделю: {last_7day}
Сообщений за месяц: {last_30day}
Сообщений за неделю от взыскателей: {claimant_last_7day}
Сообщений за месяц от взыскателей: {claimant_last_30day}
Всего сообщений: {count_all}
Всего сообщений от взыскателей: {claimant_count_all}\n'''

        claimants = Claimant.query.all()
        claimants = [str(cl.name).lower() for cl in claimants]
        for cl in claimants:
            base_query = Message.query.filter(Message.from_user == cl)
            resp += f'  {cl}: {base_query.filter(Message.timestamp >= datetime(b.year, b.month, b.day)).count()} за день, \
{base_query.filter(Message.timestamp >= (b - timedelta(days=1))).count()} за сутки, \
{base_query.filter(Message.timestamp >= (datetime(b.year, b.month, b.day)) - timedelta(days=7)).count()} за неделю, \
{base_query.count()} сообщений всего.\n'

        bot.sendMessage(chat_id=admin_cid, text=resp)
    else:
        bot.sendMessage(chat_id=admin_cid, text='Что-то не так...')

    if need_update:
        db.session.commit()
        bot.sendMessage(chat_id=admin_cid, text='Сделано!')
        app.logger.info(f'Successful db commit!')
예제 #21
0
def init_db(remove_file=None):
    """ 
    Initialise a database with some values 
    for testing and playing around 
    """
    from app import db
    from config import basedir
    import os.path
    from app.models import Monkey, Friend

    if remove_file:
        try:
            os.remove(remove_file)
        except:
            pass

    db.create_all()

    admin = Monkey(name='admin', age=12, email='*****@*****.**')
    guest = Monkey(name='guest', age=12, email='*****@*****.**')
    veeti = Monkey(name='veeti', age=3, email='*****@*****.**')
    kerttu = Monkey(name='kerttu', age=7, email='*****@*****.**')
    kukka = Monkey(name='kukka', age=10, email='*****@*****.**')
    db.session.add(admin)
    db.session.add(guest)
    db.session.add(veeti)
    db.session.add(kerttu)
    db.session.add(kukka)
    db.session.commit()

    adminf = Friend(name='guest', to_monkey = admin)
    guestf = Friend(name='admin', to_monkey = guest)
    veetif1 = Friend(name='kerttu', to_monkey = veeti)
    veetif2 = Friend(name='kukka', to_monkey = veeti)
    kerttuf = Friend(name='veeti', to_monkey = kerttu)
    kukkaf = Friend(name='veeti', to_monkey = kukka)
    kukkaf2 = Friend(name='kukka', to_monkey = kukka)
    db.session.add(adminf)
    db.session.add(guestf)
    db.session.add(veetif1)
    db.session.add(veetif2)
    db.session.add(kerttuf)
    db.session.add(kukkaf)
    db.session.add(kukkaf2)
    db.session.commit()

    m1 = Monkey.query.get(1)
    m1.lenfriends = 1
    m1.best_friend_name = "guest"
    m2 = Monkey.query.get(2)
    m2.lenfriends = 1
    m2.best_friend_name = "admin"
    m3 = Monkey.query.get(3)
    m3.lenfriends = 2
    m3.best_friend_name = "kerttu"
    m4 = Monkey.query.get(4)
    m4.lenfriends = 1
    m4.best_friend_name = "veeti"
    m5 = Monkey.query.get(5)
    m5.lenfriends = 2
    m5.best_friend_name = "veeti"

    db.session.commit()