def save_followers_with_botness(user):
    followers = get_followers("@" + user)
    db.saveUser(user)
    for follower in followers:
        screen_name = follower.screen_name
        if db.hasFollower(fromName=screen_name, toName=user):
            print("Already checked @" + screen_name + " skipping for now.")
            continue
        follower_botness = botornotapi.get_bot_or_not("@" + screen_name)
        if follower_botness is not None:
            db.saveFollower(user, follower, follower_botness)
            print("Saved follower @" + screen_name + " for @" + user)
        else:
            print("Botness for @" + screen_name + " is none.")
Beispiel #2
0
def signupUser() :
    if request.method == 'GET':
        return render_template('signupUser.html')
    else :
        email = request.form["email"]
        name = request.form["name"]
        rollNo = request.form["rollNumber"]
        password = request.form["password"]

        user = fetchUserWithEmail(email)
        if user:
            return render_template('signupUser.html', email=email, name=name, rollNumber=rollNo, errorText="Email already exists!")    
        else :
            saveUser(email, name, "6IST-"+rollNo, password)
            return redirect("/loginUser")
Beispiel #3
0
 def save(self):
     j = db.saveUser(self.user)
     self.user = j.get('user')
     self.status = j.get('status', '')
     self.request = j.get('request', {})
     self.step = j.get('step', '')
     self.info = j.get('info')
Beispiel #4
0
def check_declaration(bot, update):
    user = db.saveUser(update.message.from_user)
    update.message.reply_text(
        '''РАЗРЕШЕНИТЕ ЗНАЦИ ПРИ ПОПЪЛВАНЕ СА БУКВИ НА КИРИЛИЦА И ЦИФРИ. МОЛЯ НЕ ИЗПОЛЗВАЙТЕ ""
Всички полета със * са задължителни.
Если не желаете заполнять поле, введите знак "-" (минус)
''')
    next_step(bot, update, user)
Beispiel #5
0
def save_followers_with_botness(account_handle):
    followers = get_followers("@" + account_handle)
    user = TWITTER_API.get_user(account_handle)
    timestamp = time.strftime("%d.%m.%Y %H:%M:%S", time.localtime())
    print(timestamp)
    print("Save user @%s and the followers (twitter reported %d)  ..." %
          (account_handle, user.followers_count))
    db.saveUser(user)
    for follower in followers:
        follower_handle = follower.screen_name
        if db.hasFollower(fromName=follower_handle, toName=account_handle):
            print("Already checked @" + follower_handle +
                  " ... skipping for now.")
            continue
        follower_botness = botornotapi.get_bot_or_not("@" + follower_handle)
        if follower_botness is not None:
            db.saveFollower(user, follower, follower_botness)
            print("Saved follower @%s for @%s with botness %f" %
                  (follower_handle, account_handle, follower_botness['score']))
        else:
            print("Botness is none for @" + follower_handle)
Beispiel #6
0
def chat():
    username = request.args.get('username')
    room = request.args.get('room')
    allUsers = getAllUsersInRoom(room)
    allMessages = getAllMessages(room)
    pfp = random.randrange(1, 5)

    if username and room:
        # Save new user or change its status to 'connected' if exists
        if (findUser(username, room) == 0):
            saveUser(username, room, pfp)
        else:
            updateUserStatus(username, room, True)

        return render_template('chat.html',
                               username=username,
                               room=room,
                               pfp=pfp,
                               users=allUsers,
                               messages=allMessages)
    else:
        return redirect(url_for('home'))
Beispiel #7
0
def text_input(bot, update):
    user = db.saveUser(update.message.from_user)
    request, step = declaration.checkDeclaration(user)
    text = update.message.text.strip()
    if text == '-':
        text = ""
    if step is not None:
        if step in [key for key in declaration.docFields]:
            field = declaration.docFields.get(step) or {}
            if text == '' and field.get('required', False):
                update.message.reply_text(
                    f'''Поле обязательно для заполнения.''')
            else:
                if field.get('multiple', False):
                    request['doc'][step] = re.split(r'\W+', text)
                else:
                    request['doc'][step] = text
                update.message.reply_text(
                    f'''_Сохранено "{step}": {request['doc'][step]}_''',
                    parse_mode='Markdown')
        else:
            dt = request['dt']

            text, result = utils.checkDate(text)
            if result is not None:
                update.message.reply_text(result)
                next_step(bot, update, user)
                return

            if step.get('key') == 'date_from':
                dt['from'] = text
            if step.get('key') == 'date_to':
                dt['to'] = text
            request['dt'] = dt
        _, step = declaration.checkDeclaration(user)
        user = db.saveDeclaration(update.message.from_user, request, step)
        next_step(bot, update, user)
Beispiel #8
0
def save_followers_with_botness(account_handle):
    global TOTAL_FOLLOWERS_SKIPPED, TOTAL_FOLLOWERS_WITH_BOTNESS, TOTAL_FOLLOWERS_WITHOUT_BOTNESS
    user = TWITTER_API.get_user(account_handle)
    db.saveUser(user)
    timestamp = datetime.now()
    db.saveToImportLog(
        IMPORT_KEY, {
            'accounts': {
                account_handle: {
                    'tw_followers_count': user.followers_count,
                    'account_saved_at': timestamp.timestamp()
                }
            }
        })
    print(timestamp.strftime("%d.%m.%Y %H:%M:%S"))
    print(
        "Saved user @%s, now getting the followers (twitter reported %d)  ..."
        % (account_handle, user.followers_count))

    followers = get_followers(account_handle)
    for follower in followers:
        follower_handle = follower.screen_name
        if db.hasFollower(fromName=follower_handle, toName=account_handle):
            TOTAL_FOLLOWERS_SKIPPED += 1
            db.saveToImportLog(
                IMPORT_KEY, {
                    'accounts': {
                        account_handle: {
                            'followers_skipped': {
                                follower_handle: 'existed'
                            }
                        }
                    },
                    'followers_skipped': TOTAL_FOLLOWERS_SKIPPED
                })
            print("Already checked @" + follower_handle +
                  " ... skipping for now.")
            continue
        follower_botness = botornotapi.get_bot_or_not("@" + follower_handle)
        if follower_botness is not None:
            db.saveFollower(user, follower, follower_botness)
            TOTAL_FOLLOWERS_WITH_BOTNESS += 1
            db.saveToImportLog(
                IMPORT_KEY, {
                    'accounts': {
                        account_handle: {
                            'followers': {
                                follower_handle: follower_botness['score']
                            }
                        }
                    },
                    'followers_with_botness': TOTAL_FOLLOWERS_WITH_BOTNESS
                })
            print("Saved follower @%s for @%s with botness %d" %
                  (follower_handle, account_handle,
                   follower_botness['score'] * 100))
        else:
            TOTAL_FOLLOWERS_WITHOUT_BOTNESS += 1
            db.saveToImportLog(
                IMPORT_KEY, {
                    'accounts': {
                        account_handle: {
                            'followers_without_botness': {
                                follower_handle: None
                            }
                        }
                    },
                    'followers_without_botness':
                    TOTAL_FOLLOWERS_WITHOUT_BOTNESS
                })
            print("Botness is none for @" + follower_handle)

    # done with followers loop, save timestamp
    timestamp = datetime.now()
    db.saveToImportLog(
        IMPORT_KEY,
        {'accounts': {
            account_handle: {
                'ended_at': timestamp.timestamp()
            }
        }})
def register(tg_id, response):
    if not db.getUserById(tg_id):  # if user is not registered, register them
        print('user not found')
        db.saveUser(tg_id=tg_id, first_name="", last_name="")
        db.getUserById(tg_id)

        db.saveControlBoard(tg_id, 0)  # start a trace on control board table

    current_count = db.getCurrentCount(tg_id)

    # saving user details in database
    if current_count == 1:
        if response.lower() in ['no', '2']:
            db.deleteUser(tg_id)
            return 'Ok. Maybe later. You can continue registration by clicking /register .'
    if current_count == 2:
        if response.lower().strip() in ['male', '1']:
            db.saveGender(tg_id, 'male')
        elif response.lower().strip() == ['female', '2']:
            db.saveGender(tg_id, 'female')
        else:
            return 'Invalid gender. Try again'
    elif current_count == 3:
        try:
            age = int(response)
            if 0 < age < 120:
                db.saveAge(tg_id, age)
            else:
                return 'Invalid age'
        except ValueError:
            return 'Invalid age'
    elif current_count == 4:
        if not response:
            return 'Sorry, did you forget to write the name? Try again'
        else:
            db.saveFirstName(tg_id, response)
    elif current_count == 5:
        if not response:
            return 'Sorry, did you forget to write the name? Try again'
        else:
            db.saveLastName(tg_id, response)
            db.saveFinishedRegistration(tg_id)

    # if user has finished registration, stop asking registration questions, and control board trace
    if db.getFinishedRegistration(tg_id) is None:
        can_continue = True
    else:
        can_continue = False

    if current_count >= 6:
        pass
    else:
        db.saveControlBoard(tg_id, current_count + 1)

    # return registration question from database if user hasn't finished registering
    if can_continue:
        nextQ = db.getQuestion(current_count + 1)
        if 'our system' in nextQ:
            nextQ += '\n1 - Yes\n2 - No'
        elif '[male/female]' in nextQ:
            nextQ += '\n1 - Yes\n2 - No'
        return nextQ
    else:
        # go to diagnosis part if registration is complete
        if db.getOnGoingUser(tg_id) is None:

            # asking user to describe condition
            db.saveOnGoingUser(tg_id)
            return 'How are you feeling today? Describe your condition'
        else:
            INVALID_INITIAL_SYMPTOM = 'Please say that again, i couldn\'t get you. \nExplain how you feel. eg, ' \
                                      '"i feel pain on my back" '
            if response.lower() == '0':
                db.deleteUserOngoingDiagnosis(tg_id)
                db.deleteUserSymptoms(tg_id)
                db.deleteUserCurrentSymptom(tg_id)
                db.deleteCurrentQuestion(tg_id)
                return 'Diagnosis stoppped. You can start by typing *diagnose start*'
            elif response.lower() in ['yes', '1']:
                if db.getCurrentQuestion(tg_id) is None:
                    return INVALID_INITIAL_SYMPTOM
                db.saveSymptom(tg_id,
                               db.getCurrentQuestion(tg_id)[1], 'present')
            elif response.lower() in ['no', '2']:
                if db.getCurrentQuestion(tg_id) is None:
                    return INVALID_INITIAL_SYMPTOM
                db.saveSymptom(tg_id,
                               db.getCurrentQuestion(tg_id)[1], 'absent')
            elif 'dont know' in response.lower(
            ) or 'don\'t know' in response.lower() or response.lower() == '3':
                if db.getCurrentQuestion(tg_id) is None:
                    return INVALID_INITIAL_SYMPTOM
                db.saveSymptom(tg_id,
                               db.getCurrentQuestion(tg_id)[1], 'unknown')
            else:
                symptoms = sendParse(response)
                print(f'PARSE SYMPTOMS: {symptoms}')

                if len(symptoms) > 0 and 'understand' not in symptoms:
                    for symptom in symptoms:
                        s_id = symptom['id']
                        choice = symptom['choice_id']
                        db.saveInitialSymptom(tg_id, s_id, choice, 1)
                else:
                    if db.getCurrentQuestion(tg_id):
                        return f'Invalid answer\n\n{db.getCurrentQuestion(tg_id)[2]}\n1 - Yes\n2 - No\n3 - Dont know' \
                               f'\n\n0 - Cancel diagnosis and restart '
                    else:
                        return 'Describe how you feel. Example, I feel pain in my joints '

            symptoms = db.getSymptoms(tg_id)
            # print(f'API HANDLER symptoms: {symptoms}')
            age = db.getAge(tg_id)
            # print(f'API HANDLER age: {age}')
            sex = db.getGender(tg_id)
            sex = sex.lower()
            # print(f'API HANDLER sex: {sex}')

            response = make_chuka_api_request(age, sex, symptoms)
            # print(f'API HANDLER response: {response}')

            response = loads(response)

            if 'next_question' in response:
                nextQuestionId = response["next_question"]["items"][0]["id"]
                db.updateCurrentQuestion(tg_id, nextQuestionId,
                                         response["next_question"]["text"])
                return f'{response["next_question"]["text"]}\n1 - Yes\n2 - No\n3 - Dont know\n\n_0 - Cancel diagnosis_' \
                       f'and restart_ '
            elif 'stop' in response:
                conditions = response['conditions']
                message = "After Diagnosis, the following conditions were discovered:\n\n"

                for condition in conditions:
                    name = condition['name']
                    prob = float(condition['probability']) * 100
                    prob = round(prob, 2)
                    prob = f'{prob} %'

                    message += f'Name\t: {name}\nProbability: {prob}\n\n'

                return message
            else:
                return 'Could not get any response. Press /diagnose to restart.'