Example #1
0
def create_group(tid, gname):
    """Create a new group.

    Get a groupname posted from a logged in user. Check to see if the group exists, if it does notify the user.
    If the group does not exist create it and add the user as a member/owner.
    """
    if gname == '':
        return {'status': 0, 'message': "The group name cannot be empty!"}
    if db.groups.find_one({'name': gname}) is not None:
        return {'status': 2, 'message': "This group exists, would you like to join it?"}
    db.groups.insert({"name": gname, "owners": [tid], "members": [tid], "gid": common.token()})
    return {'status': 1, 'message': "Successfully created the group"}
Example #2
0
def register_team(request):
    """Register a new team.

    Checks that an email address, team name, adviser name, affiliation, and password were sent from the browser.
    If any of these are missing a status:0 is returned with a message saying that all fields must be provided.
    Verifies that no teams exist with the specified name, if one exists a status:0 with a message is returned.
    If the 'joingroup' flag is empty or false and the passed 'group' is not empty we check to see if a group with that
    name exists in the database, if it does we return a status:2 and a message saying the the group exists, and give
    the user the option to join it.
    If no failure at this point the function hashes the password and inserts the data into a new db document
    in the teams collection.
    If the passed 'group' was empty we now return a status:1 with a successful registration message. If the 'joingroup'
    flag was set/true (and 'group' exists) we search for the group, if it does NOT exist we create it and add the new
    team as an owner and member.  If it does exist we add the team as a member of the group.
    If 'joingroup' is not set/false but 'group' exists then we create the new group and add the user as an owner/member,
    we already know that the group does not exist (would have been caught at the beginning).
    """
    email = request.form.get('email', '')
    teamname = request.form.get('teamname', '')
    adviser = request.form.get('name', '')
    affiliation = request.form.get('aff', '')
    pwd = request.form.get('password', '')
    gname = request.form.get('group', '').lower().strip('')
    joingroup = 'true' #request.form.get('joingroup', '')
    print {email, teamname, pwd}
    if '' in {email, teamname, pwd}:
        return {'success': 0, 'message': "Please fill in all of the required fields."}
    if db.teams.find({'teamname': teamname}).count() != 0:
        return {'success': 0, 'message': "That team name is already registered."}
    # if joingroup != 'true' and gname != '':
        # if db.groups.find({'name': gname}).count() != 0:
            # return {'success': 2, 'message': "The group name you have entered exists, would you like to join it?"}

    tid = common.token()
    db.teams.insert({'email': str(email),
                     'advisor': str(adviser),
                     'teamname': str(teamname),
                     'affiliation': str(affiliation),
                     'pwhash': bcrypt.hashpw(str(pwd), bcrypt.gensalt(8)),
                     'tid': tid})
    if gname == '':
        return {'success': 1, 'message': "Success! You have successfully registered."}

    if joingroup == 'true':
        if db.groups.find({'name': gname}).count() == 0:
            group.create_group(tid, gname)
        else:
            db.groups.update({'name': gname}, {'$push': {'members': tid}})
            return {'success': 1, 'message': 'Success! You have been added to the group!'}
    else:
        group.create_group(tid, gname)
        return {'success': 1, 'message': "Success! You are registered and have created your group."}
Example #3
0
def register_team(request):
    """Register a new team.

    Checks that an email address, team name, adviser name, affiliation, and password were sent from the browser.
    If any of these are missing a status:0 is returned with a message saying that all fields must be provided.
    Verifies that no teams exist with the specified name, if one exists a status:0 with a message is returned.
    If the 'joingroup' flag is empty or false and the passed 'group' is not empty we check to see if a group with that
    name exists in the database, if it does we return a status:2 and a message saying the the group exists, and give
    the user the option to join it.
    If no failure at this point the function hashes the password and inserts the data into a new db document
    in the teams collection.
    If the passed 'group' was empty we now return a status:1 with a successful registration message. If the 'joingroup'
    flag was set/true (and 'group' exists) we search for the group, if it does NOT exist we create it and add the new
    team as an owner and member.  If it does exist we add the team as a member of the group.
    If 'joingroup' is not set/false but 'group' exists then we create the new group and add the user as an owner/member,
    we already know that the group does not exist (would have been caught at the beginning).
    """
    email = request.form.get('email', '')
    teamname = request.form.get('team', '')
    affiliation = request.form.get('aff', '')
    pwd = request.form.get('pass', '')
    #gname = request.form.get('group', '').lower().strip('').encode('utf8')
    #joingroup = request.form.get('joingroup', '').encode('utf8')
    joingroup = 'false'

    if '' in {email, teamname, affiliation, pwd}:
        return {'status': 0, 'message': "请填写必须的信息."}

    email = email.encode('utf8').strip()
    teamname = teamname.encode('utf8').strip()
    affiliataion = affiliation.encode('utf8').strip()
    pwd = pwd.encode('utf8')

    if db.teams.find({'teamname': teamname}).count() != 0:
        return {'status': 0, 'message': "用户名已经被使用."}
    if db.teams.find({'email': email}).count() != 0:
        return {'status': 0, 'message': "邮箱已经被使用."}

    if len(teamname) > 20:
        return {'status': 0, 'message': "用户名请不要太长.."}
    if '<' in teamname or '>' in teamname:
        return {'status': 0, 'message': "用户名不可包含尖括号. 请尝试使用≺⋖≤⩽≪等符号. 谢谢."}

    tid = common.token()
    db.teams.insert({'email': email,
                     'teamname': teamname,
                     'affiliation': affiliation,
                     'pwhash': bcrypt.hashpw(pwd, bcrypt.gensalt(8)),
                     'email_verified': False,
                     'tid': tid})
    utilities.prepare_verify_email(teamname, email)
    return {'status': 1, 'message': "注册成功. 请访问邮箱查收验证邮件."}
Example #4
0
def register_team(request):
    """Register a new team.

    Checks that an email address, team name, adviser name, affiliation, and password were sent from the browser.
    If any of these are missing a status:0 is returned with a message saying that all fields must be provided.
    Verifies that no teams exist with the specified name, if one exists a status:0 with a message is returned.
    If the 'joingroup' flag is empty or false and the passed 'group' is not empty we check to see if a group with that
    name exists in the database, if it does we return a status:2 and a message saying the the group exists, and give
    the user the option to join it.
    If no failure at this point the function hashes the password and inserts the data into a new db document
    in the teams collection.
    If the passed 'group' was empty we now return a status:1 with a successful registration message. If the 'joingroup'
    flag was set/true (and 'group' exists) we search for the group, if it does NOT exist we create it and add the new
    team as an owner and member.  If it does exist we add the team as a member of the group.
    If 'joingroup' is not set/false but 'group' exists then we create the new group and add the user as an owner/member,
    we already know that the group does not exist (would have been caught at the beginning).
    """
    email = request.form.get('email', '')
    teamname = request.form.get('team', '')
    adviser = request.form.get('name', '')
    affiliation = request.form.get('aff', '')
    pwd = request.form.get('pass', '')
    gname = request.form.get('group', '').lower().strip('')
    joingroup = request.form.get('joingroup', '')

    if '' in {email, teamname, adviser, affiliation, pwd}:
        return {'status': 0, 'message': "Please fill in all of the required fields."}
    if db.teams.find({'teamname': teamname}).count() != 0:
        return {'status': 0, 'message': "That team name is already registered."}
    if joingroup != 'true' and gname != '':
        if db.groups.find({'name': gname}).count() != 0:
            return {'status': 2, 'message': "The group name you have entered exists, would you like to join it?"}

    tid = common.token()
    db.teams.insert({'email': str(email),
                     'advisor': str(adviser),
                     'teamname': str(teamname),
                     'affiliation': str(affiliation),
                     'pwhash': bcrypt.hashpw(str(pwd), bcrypt.gensalt(8)),
                     'tid': tid})
    if gname == '':
        return {'status': 1, 'message': "Success! You have successfully registered."}

    if joingroup == 'true':
        if db.groups.find({'name': gname}).count() == 0:
            group.create_group(tid, gname)
        else:
            db.groups.update({'name': gname}, {'$push': {'members': tid}})
            return {'status': 1, 'message': 'Success! You have been added to the group!'}
    else:
        group.create_group(tid, gname)
        return {'status': 1, 'message': "Success! You are registered and have created your group."}
Example #5
0
def create_group(tid, gname):
    """Create a new group.

    Get a groupname posted from a logged in user. Check to see if the group exists, if it does notify the user.
    If the group does not exist create it and add the user as a member/owner.
    """
    if gname == '':
        return {'status': 0, 'message': "The group name cannot be empty!"}
    if db.groups.find_one({'name': gname}) is not None:
        return {
            'status': 2,
            'message': "This group exists, would you like to join it?"
        }
    db.groups.insert({
        "name": gname,
        "owners": [tid],
        "members": [tid],
        "gid": common.token()
    })
    return {'status': 1, 'message': "Successfully created the group"}
Example #6
0
async def run(logger):
    logger.debug("Loading settings from file...")
    config = load_config()
    logger.debug("Loaded settings from file!")
    token = config['token']
    intents = discord.Intents.default()
    intents.members = True
    logger.debug("Checking version...")
    #figure out what we're logging in as
    tokenfilename, database, ver = get_release_level()
    logger.debug(f"Logging in as '{ver}'")
    if ver == 'stable':
        if config['owner_id'] == "538193752913608704" and (
                os.path.exists('devtoken.txt')
                or os.path.exists('betatoken.txt')
        ) and not "--nologin" in sys.argv:
            print(
                "You're attempting to start the production version of Maximilian when you have other versions available.\nAre you sure you want to do this? \nIf you're certain this won't break anything, enter 'Yes, do as I say!' below.\n"
            )
            if input() == "Yes, do as I say!":
                print("\nOk, starting Maximilian.\n")
                await asyncio.sleep(1)
            else:
                print("You need to type 'Yes, do as I say!' exactly as shown.")
                os._exit(5)
        commit = ''
    else:
        token = common.token().get(tokenfilename)
        logger.debug("Getting latest commit hash...")
        commit = get_latest_commit()
        logger.debug("Done getting latest commit hash.")
    logger.debug("Setting up some stuff")
    bot = commands.Bot(
        command_prefix=core.get_prefix,
        owner_id=int(config['owner_id']),
        intents=intents,
        activity=discord.Activity(
            type=discord.ActivityType.playing,
            name=f" v0.6.2{f'-{commit}' if commit else ''} ({ver})"))
    #set up some important stuff
    bot.database = database
    bot.logger = logger
    if parse_version(discord.__version__).major < 2:
        bot.logger.debug("using dpy 1.x")
        bot.IS_DPY_2 = False
    else:
        bot.IS_DPY_2 = True
        bot.logger.debug("using dpy 2.x")
        bot.logger.warning(
            "It looks like Maximilian is using discord.py 2.x. Use of dpy2 is not recommended for now due to some serious bugs."
        )
        await asyncio.sleep(1)
    try:
        #experimental i18n, not used at the moment
        #initialize_i18n(bot)
        pass
    except:
        if '--i18n-errors' in sys.argv:
            traceback.print_exc()
        logger.critical(
            'i18n initialization failed! Does the translation file exist?')
        os._exit(53)
    await wrap_event(bot)
    #show version information
    bot.logger.warning(
        f"Starting maximilian-{ver} v0.6.2{f'-{commit}' if commit else ''}{' with Jishaku enabled ' if '--enablejsk' in sys.argv else ' '}(running on Python {sys.version_info.major}.{sys.version_info.minor} and discord.py {discord.__version__}) "
    )
    #parse additional arguments (ip, enablejsk, noload)
    bot.noload = []
    bot.logger.debug("Parsing command line arguments...")
    parse_arguments(bot, sys.argv)
    bot.logger.debug("Done parsing command line arguments.")
    bot.guildlist = []
    bot.prefixes = {}
    bot.responses = []
    bot.start_time = time.time()
    bot.dbinst = common.db(bot, config['dbp'])
    bot.logger.debug("Done setting up stuff.")
    #try to connect to database, exit if it fails
    bot.logger.info(
        f"Attempting to connect to database '{bot.database}' on '{bot.dbip}'..."
    )
    try:
        bot.dbinst.connect(bot.database)
        bot.logger.info("Connected to database successfully.")
        bot.dbdisabled = False
    except pymysql.err.OperationalError:
        bot.logger.critical(
            f"Couldn't connect to database! \nMaybe try running setup.sh again?"
        )
        os._exit(96)
    #make sure all tables exist
    try:
        bot.dbinst.ensure_tables()
    except pymysql.OperationalError:
        bot.logger.error(
            "Unable to create one or more tables! Does `maximilianbot` not have the CREATE permission?"
        )
    #now that we've got most stuff set up, load extensions
    load_extensions(bot)
    #and log in
    print("Logging in...")
    if not "--nologin" in sys.argv:
        await bot.start(token)