Ejemplo n.º 1
0
def answer_to_all(message):
    db = PostgreSQL()
    user = User(message.from_user.id, db)
    if user.isNew():
        hello(message)
        return
    if user.isInGame(db):
        cur_game = Game(user, db)
        if message.text == cur_game.get_right_answer():
            bot.send_message(
                message.chat.id,
                text=message.from_user.first_name + ", you are right!!!",
                reply_markup=telebot.types.ReplyKeyboardRemove(selective=True))
            user.addWin(db)
        else:
            bot.send_message(
                message.chat.id,
                text=message.from_user.first_name + ",sorry, you are wrong(((",
                reply_markup=telebot.types.ReplyKeyboardRemove(selective=True))
            user.addGame(db)
        cur_game.finish(db)
    else:
        logging.info('Text received from a user without active game')
        bot.send_message(message.chat.id, config.default_msg)
    db.close()
Ejemplo n.º 2
0
def delete_user(message):
    try:
        logging.info('Deleting a user')
        db = PostgreSQL()
        if not User.exists(message.chat.id, db):
            bot.send_message(message.chat.id, text=config.already_deleted)
            return True
        user = User(message.from_user.id, db)
        if user.delete(db):
            bot.send_message(
                message.chat.id,
                text=config.user_deleted,
                reply_markup=telebot.types.ReplyKeyboardRemove(selective=True))
        db.close()
    except:
        bot.send_message(
            message.chat.id,
            text=config.internalError,
            reply_markup=telebot.types.ReplyKeyboardRemove(selective=True))
        logging.error("Command /delete_me failed with internalError: ",
                      exc_info=True)
Ejemplo n.º 3
0
def end_game(message):
    try:
        logging.info('Finishing a game')
        db = PostgreSQL()
        user = User(message.from_user.id, db)
        if user.isInGame(db):
            curr_game = Game(user, db)
            curr_game.finish(db)
            bot.send_message(
                message.chat.id,
                text=config.game_stopped,
                reply_markup=telebot.types.ReplyKeyboardRemove(selective=True))
        else:
            bot.send_message(message.chat.id, text=config.no_game_to_stop)
        db.close()
    except:
        bot.send_message(
            message.chat.id,
            text=config.internalError,
            reply_markup=telebot.types.ReplyKeyboardRemove(selective=True))
        logging.error("Command /end_game failed with internalError: ",
                      exc_info=True)
Ejemplo n.º 4
0
def play(message):
    try:
        logging.info('Game command received')
        db = PostgreSQL()
        new_game = Game(User(message.from_user.id, db), db)
        bot.send_message(
            message.chat.id,
            'User ' + message.from_user.first_name + ' has started the game')
        bot.send_voice(message.chat.id, new_game.get_song_file_id())
        bot.reply_to(message,
                     text=message.from_user.first_name +
                     " please, choose the option",
                     reply_markup=prepareMarkupKeybord(new_game))
        db.close()
    except:
        bot.send_message(
            message.chat.id,
            text=config.internalError,
            reply_markup=telebot.types.ReplyKeyboardRemove(selective=True))
        logging.error("Command /game failed with internalError: ",
                      exc_info=True)
Ejemplo n.º 5
0
def get_user(username):
    cur = mysql.connection.cursor()
    selector = "SELECT * FROM User WHERE username=%(usr)s"
    cur.execute(selector, {'usr': username})
    if cur.rowcount == 0:
        return None
    row = cur.fetchone()
    split_pass = row['password'].split("$")
    result = User(row['username'], row['firstname'], row['lastname'],
                  split_pass[2], row['email'])
    result.set_salt(split_pass[1])
    selector = "SELECT albumid, title  FROM Album WHERE username=%(usr)s"
    cur.execute(selector, {'usr': username})
    rows = cur.fetchall()
    for row in rows:
        result.add_entry(row['albumid'], row['title'])
    return result
Ejemplo n.º 6
0
 def load_entities_from_config(self, path: str):
     """Loads entities from all yaml files inside a directory"""
     for config, file in yaml_utils.for_yaml_in(path):
         name = config.get("name", None) or file[:-5]
         entity_type: str = config.get("type") or EntityType.COMPOSED.value
         if not EntityType.contains(entity_type):
             raise ConfigError(f"entity type {entity_type} not found")
         entity_type: EntityType = EntityType(entity_type)
         entity_settings = config.get("settings", {})
         if entity_type != EntityType.COMPOSED:
             try:
                 entity = self._template_builder.get(entity_type)(
                     self, name, config, entity_settings)
                 self.add_entity(name, entity)
                 # TODO: user
                 self.core.bus.dispatch(
                     created_event(entity, User.new_admin()))
             except TypeError:
                 raise ConfigError(
                     f"builder for entity type {entity_type} not found!")
         else:
             self.add_entity(
                 name, self._default_builder(name, config, entity_settings))
Ejemplo n.º 7
0
def user_api():
    username = ''
    print 'got to func'
    print 'got hereereee'
    if request.method == 'POST':
        req = request.get_json(force=True)
        errors = []
        if ('username' not in req) or ('firstname' not in req) or (
                'lastname' not in req) or ('email' not in req) or (
                    'password1' not in req) or ('password2' not in req):
            errors.append('You did not provide the necessary fields')
            return jsonify(generate_error_response(errors)), 422
        if (req['username'] == '') or (req['email'] == '') or (
                req['password1'] == '') or (req['password2'] == ''):
            errors.append('You did not provide the necessary fields')
            return jsonify(generate_error_response(errors)), 422
        if req['password1'] != req['password2']:
            errors.append('Passwords do not match')
        user = User(req['username'], req['firstname'], req['lastname'],
                    req['password1'], req['email'])
        errors = errors + user.validate()
        temp_user = extensions.get_user(req['username'])
        if temp_user != None:
            errors.append('This username is taken')
        if errors != []:
            return jsonify(generate_error_response(errors)), 422
        user.create_salt()
        user.hash_pass()
        extensions.add_user(user)
        username = req['username']
        if username == '':
            if 'username' not in session:
                return send_401()
        return get_api_user_helper(username)
    print "GOT HERE"
    if 'username' not in session:
        return send_401()
    username = session['username']
    return get_api_user_helper(username)
Ejemplo n.º 8
0
    def read_user_data(self, USER_PATH):
        # 静态方法 读取测试用户csv数据
        bufferedReader = open(USER_PATH, "r")
        user_dict = dict()

        # 读取首行,看是否为空
        if (bufferedReader.readline() is None):
            pass
        # 读取每一行信息
        for strLine in bufferedReader:
            user = User()
            strLine = strLine.strip('\n')
            strSet = strLine.split(",")
            userID = strSet[0]
            income = int(strSet[1])
            entertainment = int(strSet[2])
            babyLabel = int(strSet[3])
            gender = int(strSet[4])
            shop_label = int(strSet[5])
            user_labels = strSet[1] + strSet[2] + strSet[3] + strSet[
                4] + strSet[5]

            user.set_user_id(userID)
            user.set_income(income)
            user.set_baby_label(babyLabel)
            user.set_gender(gender)
            user.set_shop_label(shop_label)
            user.set_entertainment(entertainment)
            user.set_user_labels(user_labels)
            user_dict[userID] = user

        bufferedReader.close()
        return user_dict
Ejemplo n.º 9
0
async def ws_handler(websocket, path):
    user = User(websocket, db, clients)
    await user.listen_messages()
Ejemplo n.º 10
0
def GenerateFile(request):
    from objects.User import User
    from objects.Bank import Bank
    from objects.Branch import ATM, Branch
    from objects.Product import Product
    country = request.POST.get('country')
    bank_number = int(request.POST.get('bank_num'))
    branch_number = int(request.POST.get('branch_num'))
    product_number = int(request.POST.get('product_num'))
    atm_number = int(request.POST.get('atm_num'))
    months = int(request.POST.get('months'))
    input_path = request.POST.get('input_path')

    output_path = request.POST.get('output_path')

    user_list = User.generator_for_file("{}options.xlsx".format(input_path))

    branch_list = []
    atm_list = []
    product_list = []
    bank_list = Bank.generate_from_file(bank_number)
    for bank in bank_list:
        branch_list.extend(Branch.generate_from_file(bank, branch_number))
        atm_list.extend(ATM.generate_from_file(bank, atm_number))
        product_list.extend(Product.generate_from_file(bank, product_number))

    account_list = []
    for user in user_list:
        branch_tmp = random.choice(branch_list)
        account1 = user.create_account(branch_tmp, "CURRENT", user.country,
                                       user.current)
        account1.set_behavior(
            income=user.current,
            spending_frequency={
                "food": user.food,
                "utility": user.utility,
                "clothing": user.clothing,
                "auto": user.auto,
                "health": user.health,
                "entertainment": user.entertainment,
                "gift": user.gift,
                "education": user.education,
                "fee": user.fee
            },
            housing_type={"RENT": -user.rent} if user.rent > 0 else None)
        account_list.append(account1)

        branch_tmp = random.choice(branch_list)
        account2 = user.create_account(branch_tmp, "SAVING", user.country,
                                       user.savings)
        account2.set_behavior(income=user.savings)
        account_list.append(account2)

    from datetime import date
    from datetime import timedelta
    date_start = date.today() - timedelta(days=months * 30)
    transaction_list = []
    for i in range(months):
        date_start = date_start + timedelta(days=30)
        for account in account_list:
            transaction_list.extend(account.generateTransaction(date_start))

    try:
        import os
        os.makedirs(output_path)
    except:
        pass
    with open('{}sandbox_pretty.json'.format(output_path), 'w') as outfile:
        json.dump(
            {
                "users": user_list,
                "banks": bank_list,
                "branches": branch_list,
                "accounts": account_list,
                "atms": atm_list,
                # "counterparties":counterparty_list,
                "products": product_list,
                "transactions": transaction_list
            },
            outfile,
            default=lambda x: x.dict(),
            indent=4)

    customer_list = []
    for user in user_list:
        for bank in bank_list:
            customer_list.append(user.create_customer(bank))

    with open('{}customers_pretty.json'.format(output_path), 'w') as outfile:
        json.dump(customer_list, outfile, default=lambda x: x.dict(), indent=4)

    wb = load_workbook("{}counterparties.xlsx".format(input_path))

    sheet_selected = [
        sheetname for sheetname in wb.sheetnames if country in sheetname
    ]

    dataframe = pd.read_excel("{}counterparties.xlsx".format(input_path),
                              sheet_name=sheet_selected,
                              header=None,
                              index_col=None,
                              skiprows=3)

    df = pd.DataFrame()
    for i, j in dataframe.items():
        df = pd.DataFrame(j)

    df.columns = [
        'type', 'name', 'reference', 'value', 'frequency', 'logo', 'homepage'
    ]

    df.type = df["type"].apply(lambda x: re.split('_|/', x)[0].lower())
    #df.frequency = df["frequency"].apply(lambda x: str("0") if x is np.nan else frequecy_mapping[x.lower()])

    df = pd.DataFrame({
        "type":
        df["type"].apply(lambda x: re.split('_|/', x)[0].lower()),
        "name":
        df["name"],
        #"value" : df["value"],
        #"frequency" : df["frequency"].apply(lambda x: str("0") if x is np.nan else frequecy_mapping[x.lower()]),
        "logo":
        df["logo"],
        "homepage":
        df["homepage"]
    })

    df_list = []
    for i, rows in df.iterrows():
        df_list.append({
            "name":
            rows['name'],
            "category":
            rows['type'],
            "superCategory":
            rows['type'],
            "logoUrl":
            rows['logo'] if rows['logo'] is not np.nan else "",
            "homePageUrl":
            rows['homepage'] if rows['homepage'] is not np.nan else "",
            "region":
            country
        })

    with open('{}counterparty_pretty.json'.format(output_path),
              'w') as outfile:
        json.dump(df_list, outfile, default=lambda x: x.dict(), indent=4)
    return JsonResponse({'state': True})
Ejemplo n.º 11
0
 def new_context(self, topic: str):
     return Context(User.new_admin(), remote=True)
Ejemplo n.º 12
0
 def __init__(self, user: User = None, remote: bool = False) -> None:
     self.user: User = user or User.new()
     self.remote = remote
Ejemplo n.º 13
0
 def admin(external=False) -> "Context":
     return Context(user=User.new_admin(), remote=external)