示例#1
0
def report(fro, chan, message):
    msg = ""
    try:
        # TODO: Rate limit
        # Get username, report reason and report info
        target, reason, additionalInfo = message[0], message[1], message[2]
        target = chat.fixUsernameForBancho(target)

        # Make sure the target is not foka
        if target == glob.BOT_NAME:
            raise exceptions.invalidUserException()

        # Make sure the user exists
        targetID = userUtils.getID(target)
        if targetID == 0:
            raise exceptions.userNotFoundException()

        # Make sure that the user has specified additional info if report reason is 'Other'
        if reason.lower() == "other" and not additionalInfo:
            raise exceptions.missingReportInfoException()

        # Get the token if possible
        chatlog = ""
        token = glob.tokens.getTokenFromUsername(userUtils.safeUsername(target), safe=True)
        if token is not None:
            chatlog = token.getMessagesBufferString()

        # Everything is fine, submit report
        glob.db.execute(
            "INSERT INTO reports (id, from_uid, to_uid, reason, chatlog, time, assigned) VALUES (NULL, %s, %s, %s, %s, %s, 0)",
            [userUtils.getID(fro), targetID, "{reason} - ingame {info}".format(reason=reason, info="({})".format(
                additionalInfo) if additionalInfo is not None else ""), chatlog, int(time.time())])
        msg = "You've reported {target} for {reason}{info}. A Community Manager will check your report as soon as possible. Every !report message you may see in chat wasn't sent to anyone, so nobody in chat, but admins, know about your report. Thank you for reporting!".format(
            target=target, reason=reason, info="" if additionalInfo is None else " (" + additionalInfo + ")")
        adminMsg = "{user} has reported {target} for {reason} ({info})".format(user=fro, target=target, reason=reason,
                                                                               info=additionalInfo)

        # Log report in #admin and on discord
        chat.sendMessage(glob.BOT_NAME, "#admin", adminMsg)
        log.warning(adminMsg, discord="cm")
    except exceptions.invalidUserException:
        msg = "Hello, {} here! You can't report me. I won't forget what you've tried to do. Watch out.".format(
            glob.BOT_NAME)
    except exceptions.invalidArgumentsException:
        msg = "Invalid report command syntax. To report an user, click on it and select 'Report user'."
    except exceptions.userNotFoundException:
        msg = "The user you've tried to report doesn't exist."
    except exceptions.missingReportInfoException:
        msg = "Please specify the reason of your report."
    except:
        raise
    finally:
        if msg != "":
            token = glob.tokens.getTokenFromUsername(fro)
            if token is not None:
                if token.irc:
                    chat.sendMessage(glob.BOT_NAME, fro, msg)
                else:
                    token.enqueue(serverPackets.notification(msg))
    return False
示例#2
0
    def mp_addRef():
        userID = userUtils.getID(fro)
        if not can_user_touch_lobby(get_match_id_from_channel(chan), userID,
                                    False, False):
            return False

        if len(message) < 2:
            raise exceptions.invalidArgumentsException(
                "Wrong syntax: !mp addref <ref username>")

        # check is correct nickname
        userID = userUtils.getID(fro)
        userRefID = userUtils.getIDSafe(message[1])
        if not userRefID:
            raise exceptions.invalidArgumentsException("User not found")

        if userID == userRefID:
            return False

        tokens = glob.tokens.getTokenFromUsername(userUtils.safeUsername(
            message[1]),
                                                  safe=True,
                                                  _all=True)
        if len(tokens) == 0:
            return "{} is not online".format(message[1])

        _match = glob.matches.matches[get_match_id_from_channel(chan)]
        if userRefID in _match.refs:
            return "This referre added already :) He can join with command !mp join {}".format(
                _match.matchID)

        _match.refs.append(userRefID)
        _match.sendUpdates()
        return "Added {} to match referre. He can join with command !mp join {}".format(
            userRefID, _match.matchID)
示例#3
0
def user_stats(fro, chan, message):
    args = [m.lower() for m in message]
    nickname = None
    mode = 0
    if len(args) < 1:
        nickname = fro
    else:
        nickname = args[0].lower()

    if len(args) > 1 and args[1].isdigit():
        mode = int(args[1])

    if mode > 3:
        return "mode is incorrect"

    user_id = userUtils.getID(nickname)
    if not user_id:
        return "User not found!"

    mode_str = gameModes.getGameModeForDB(mode)
    user = userUtils.getUserStats(user_id, mode)

    acc = "{0:.2f}%".format(user['accuracy'])
    return (
        f"User: {nickname}\n"
        f"ID: {user_id}\n"
        "---------------------\n"
        f"Stats for {mode_str} #{user['gameRank']}\n"
        f"Ranked score: {humanize(user['rankedScore'])}\n"
        f"Accuracy: {acc}\n"
        f"Play count: {humanize(user['playcount'])}\n"
        f"Total score: {humanize(user['totalScore'])}\n"
        f"PP count: {humanize(user['pp'])}"
    )
    def asyncGet(self):
        try:
            # Get request ip
            ip = self.getRequestIP()

            # Check arguments
            if not requestsManager.checkArguments(self.request.arguments,
                                                  ["c", "u", "h"]):
                raise exceptions.invalidArgumentsException(MODULE_NAME)

            # Get arguments
            username = self.get_argument("u")
            password = self.get_argument("h")
            replayID = self.get_argument("c")

            # Login check
            userID = userUtils.getID(username)
            if userID == 0:
                raise exceptions.loginFailedException(MODULE_NAME, userID)
            if not userUtils.checkLogin(userID, password, ip):
                raise exceptions.loginFailedException(MODULE_NAME, username)
            if userUtils.check2FA(userID, ip):
                raise exceptions.need2FAException(MODULE_NAME, username, ip)

            # Get user ID
            replayData = glob.db.fetch(
                "SELECT scores.*, users.username AS uname FROM scores LEFT JOIN users ON scores.userid = users.id WHERE scores.id = %s",
                [replayID])
            if replayData == None:
                replayData = glob.db.fetch(
                    "SELECT scores_relax.*, users.username AS uname FROM scores_relax LEFT JOIN users ON scores_relax.userid = users.id WHERE scores_relax.id = %s",
                    [replayID])
                fileName = "{}_relax/replay_{}.osr".format(
                    glob.conf.config["server"]["replayspath"], replayID)
            else:
                fileName = "{}/replay_{}.osr".format(
                    glob.conf.config["server"]["replayspath"], replayID)

            # Increment 'replays watched by others' if needed
            if replayData is not None:
                if username != replayData["uname"]:
                    userUtils.incrementReplaysWatched(replayData["userid"],
                                                      replayData["play_mode"])

            # Serve replay
            log.info("Serving replay_{}.osr".format(replayID))

            if os.path.isfile(fileName):
                with open(fileName, "rb") as f:
                    fileContent = f.read()
                self.write(fileContent)
            else:
                log.warning("Replay {} doesn't exist".format(replayID))
                self.write("")
        except exceptions.invalidArgumentsException:
            pass
        except exceptions.need2FAException:
            pass
        except exceptions.loginFailedException:
            pass
示例#5
0
def ban(fro, chan, message):
	# Get parameters
	for i in message:
		i = i.lower()
	target = message[0]
	reason = ' '.join(message[1:])

	# Make sure the user exists
	targetUserID = userUtils.getIDSafe(target)
	userID = userUtils.getID(fro)
	if not targetUserID:
		return "{}: user not found".format(target)

	if targetUserID < 1002 and userID > 1002:
		return "Nice try."
		
	if not reason:
		return "Please specify a reason for the ban."

	# Set allowed to 0
	userUtils.ban(targetUserID)

	# Send ban packet to the user if he's online
	targetToken = glob.tokens.getTokenFromUsername(userUtils.safeUsername(target), safe=True)
	if targetToken is not None:
		targetToken.enqueue(serverPackets.loginBanned())

	log.rap(userID, "has banned {}".format(target), True)
	return "RIP {}. You will not be missed.".format(target)
示例#6
0
    def asyncGet(self):
        try:
            args = {}
            try:
                # Check user auth because of sneaky people
                if not requestsManager.checkArguments(self.request.arguments,
                                                      ["u", "h"]):
                    raise exceptions.invalidArgumentsException(MODULE_NAME)
                username = self.get_argument("u")
                password = self.get_argument("h")
                ip = self.getRequestIP()
                userID = userUtils.getID(username)
                if not userUtils.checkLogin(userID, password):
                    raise exceptions.loginFailedException(
                        MODULE_NAME, username)
                if userUtils.check2FA(userID, ip):
                    raise exceptions.need2FAException(MODULE_NAME, username,
                                                      ip)
            except ValueError:
                raise exceptions.invalidArgumentsException(MODULE_NAME)

            # Pass all arguments otherwise it doesn't work
            for key, _ in self.request.arguments.items():
                args[key] = self.get_argument(key)

            response = requests.get("{}/web/osu-search-set.php?{}".format(
                glob.conf.config["beatmapserver"]["domain"], urlencode(args)))
            self.write(response.text)
        except Exception as e:
            log.error("search failed: {}".format(e))
            self.write("")
示例#7
0
def fokabotResponse(fro, chan, message):
	"""
	Check if a message has triggered FokaBot

	:param fro: sender username
	:param chan: channel name (or receiver username)
	:param message: chat mesage
	:return: FokaBot's response or False if no response
	"""
	for i in fokabotCommands.commands:
		# Loop though all commands
		if re.compile("^{}( (.+)?)?$".format(i["trigger"])).match(message.strip()):
			# message has triggered a command

			# Make sure the user has right permissions
			if i["privileges"] is not None:
				# Rank = x
				if userUtils.getPrivileges(userUtils.getID(fro)) & i["privileges"] == 0:
					return False

			# Check argument number
			message = message.split(" ")
			if i["syntax"] != "" and len(message) <= len(i["syntax"].split(" ")):
				return "Wrong syntax: {} {}".format(i["trigger"], i["syntax"])

			# Return response or execute callback
			if i["callback"] is None:
				return i["response"]
			else:
				return i["callback"](fro, chan, message[1:])

	# No commands triggered
	return False
示例#8
0
def restrict(fro, chan, message):
    # Get parameters
    for i in message:
        i = i.lower()
    target = message[0]

    # Make sure the user exists
    targetUserID = userUtils.getIDSafe(target)
    userID = userUtils.getID(fro)
    if not targetUserID:
        return "{}: user not found".format(target)

    # Put this user in restricted mode
    userUtils.restrict(targetUserID)

    # Send restricted mode packet to this user if he's online
    targetToken = glob.tokens.getTokenFromUsername(userUtils.safeUsername(target), safe=True)
    if targetToken is not None:
        targetToken.setRestricted()

    requests.get(glob.conf.config["discord"]["krbot"] + "api/v1/submitBanOrRestrict", params={
        'token': glob.conf.config["discord"]["krbotToken"],
        'banned': target,
        'type': 0,
        'author': fro
    })
    log.rap(userID, "has put {} in restricted mode".format(target), True)
    return "Bye bye {}. See you later, maybe.".format(target)
示例#9
0
 def mp_close():
     matchID = get_match_id_from_channel(chan)
     userID = userUtils.getID(fro)
     if not can_user_touch_lobby(matchID, userID):
         return False
     glob.matches.disposeMatch(matchID)
     return "Multiplayer match #{} disposed successfully".format(matchID)
示例#10
0
    def mp_set():
        userID = userUtils.getID(fro)
        if not can_user_touch_lobby(get_match_id_from_channel(chan), userID):
            return False
        if len(message) < 2 or not message[1].isdigit() or \
                (len(message) >= 3 and not message[2].isdigit()) or \
                (len(message) >= 4 and not message[3].isdigit()):
            raise exceptions.invalidArgumentsException(
                "Wrong syntax: !mp set <teammode> [<scoremode>] [<size>]")
        _match = glob.matches.matches[get_match_id_from_channel(chan)]
        matchTeamType = int(message[1])
        matchScoringType = int(
            message[2]) if len(message) >= 3 else _match.matchScoringType
        if not 0 <= matchTeamType <= 3:
            raise exceptions.invalidArgumentsException(
                "Match team type must be between 0 and 3")
        if not 0 <= matchScoringType <= 3:
            raise exceptions.invalidArgumentsException(
                "Match scoring type must be between 0 and 3")
        oldMatchTeamType = _match.matchTeamType
        _match.matchTeamType = matchTeamType
        _match.matchScoringType = matchScoringType
        if len(message) >= 4:
            _match.forceSize(int(message[3]))
        if _match.matchTeamType != oldMatchTeamType:
            _match.initializeTeams()
        if _match.matchTeamType == matchTeamTypes.TAG_COOP or _match.matchTeamType == matchTeamTypes.TAG_TEAM_VS:
            _match.matchModMode = matchModModes.NORMAL

        _match.sendUpdates()
        return "Match settings have been updated!"
示例#11
0
 def mp_abort():
     userID = userUtils.getID(fro)
     if not can_user_touch_lobby(get_match_id_from_channel(chan), userID):
         return False
     _match = glob.matches.matches[get_match_id_from_channel(chan)]
     _match.abort()
     return "Match aborted!"
示例#12
0
    def can_user_touch_lobby(lobbyID: int,
                             uID: int,
                             checkUserIn: bool = False,
                             canRefEdit: bool = True):
        if lobbyID:
            match = glob.matches.matches[lobbyID]
            if checkUserIn:
                # check user is tourneyHost
                if match.isTourney and match.tourneyHost == uID:
                    return True

            # check user is hostUserID
            if match.hostUserID == uID:
                return True  # user can edit this

            if canRefEdit:
                # check user is ref
                if uID in match.refs:
                    return True

        # check user is tournament staff or its bot ;d
        if (userUtils.getPrivileges(userUtils.getID(fro)) & privileges.USER_TOURNAMENT_STAFF) > 0 or \
           fro == glob.BOT_NAME:
            return True

        return False
示例#13
0
 def mp_map():
     userID = userUtils.getID(fro)
     if not can_user_touch_lobby(get_match_id_from_channel(chan), userID,
                                 True):
         return False
     if len(message) < 2 or not message[1].isdigit() or (
             len(message) == 3 and not message[2].isdigit()):
         raise exceptions.invalidArgumentsException(
             "Wrong syntax: !mp map <beatmapid> [<gamemode>]")
     beatmapID = int(message[1])
     gameMode = int(message[2]) if len(message) == 3 else 0
     if gameMode < 0 or gameMode > 3:
         raise exceptions.invalidArgumentsException(
             "Gamemode must be 0, 1, 2 or 3")
     beatmapData = glob.db.fetch(
         "SELECT * FROM beatmaps WHERE beatmap_id = %s LIMIT 1",
         [beatmapID])
     if beatmapData is None:
         raise exceptions.invalidArgumentsException(
             "The beatmap you've selected couldn't be found in the database."
             "If the beatmap id is valid, please load the scoreboard first in "
             "order to cache it, then try again.")
     _match = glob.matches.matches[get_match_id_from_channel(chan)]
     _match.beatmapID = beatmapID
     _match.beatmapName = beatmapData["song_name"]
     _match.beatmapMD5 = beatmapData["beatmap_md5"]
     _match.gameMode = gameMode
     _match.resetReady()
     _match.sendUpdates()
     return "Match map has been updated"
示例#14
0
 def mp_invite():
     userID = userUtils.getID(fro)
     if not can_user_touch_lobby(get_match_id_from_channel(chan), userID,
                                 True):
         return False
     if len(message) < 2:
         raise exceptions.invalidArgumentsException(
             "Wrong syntax: !mp invite <username>")
     username = message[1].strip()
     if not username:
         raise exceptions.invalidArgumentsException(
             "Please provide a username")
     userID = userUtils.getIDSafe(username)
     if userID is None:
         raise exceptions.userNotFoundException("No such user")
     token = glob.tokens.getTokenFromUserID(userID, ignoreIRC=True)
     if token is None:
         raise exceptions.invalidUserException(
             "That user is not connected to bancho right now.")
     _match = glob.matches.matches[get_match_id_from_channel(chan)]
     _match.invite(999, userID)
     token.enqueue(
         serverPackets.notification(
             "Please accept the invite you've just received from {} to "
             "enter your tourney match.".format(glob.BOT_NAME)))
     return "An invite to this match has been sent to {}".format(username)
示例#15
0
 def mp_clear_host():
     matchID = get_match_id_from_channel(chan)
     userID = userUtils.getID(fro)
     if not can_user_touch_lobby(matchID, userID):
         return False
     glob.matches.matches[matchID].removeHost()
     return "Host has been removed from this match"
示例#16
0
 def mp_unlock():
     matchID = get_match_id_from_channel(chan)
     userID = userUtils.getID(fro)
     if not can_user_touch_lobby(matchID, userID):
         return False
     glob.matches.matches[matchID].isLocked = False
     return "This match has been unlocked"
示例#17
0
def recommend(fro, chan, message):
    user_id = userUtils.getID(fro)
    user = userUtils.getUserStats(user_id, 0)

    params = {
        'pp': user['pp'],
        'token': glob.conf.config["kotrik"]["pprapi"]
    }
    mega_pp_recommendation = requests.get("https://api.kotrik.ru/api/recommendMap", params=params)
    result = None
    try:
        result = json.loads(mega_pp_recommendation.text)
    except:
        return "I can't recommend you, because api is broken("

    mods = generalUtils.readableMods(result['m'])
    if mods == "":
        mods = "nomod"

    formatResult = "[http://osu.ppy.sh/b/{bid} {art} - {name} [{diff}]] Stars: {stars} | BPM: {bpm} | Length: {length} | PP: {pps} {mods}".format(
        bid=result['b'],
        art=result['art'],
        name=result['t'],
        diff=result['v'],
        stars=result['d'],
        bpm=result['bpm'],
        length=kotrikhelper.secondsToFormatted(result['l']),
        pps=result['pp99'],
        mods=f"+{mods}"
    )

    return formatResult
示例#18
0
    def asyncGet(self):
        try:
            requestsManager.printArguments(self)

            # Check user auth because of sneaky people
            if not requestsManager.checkArguments(self.request.arguments,
                                                  ["u", "h"]):
                raise exceptions.invalidArgumentsException(MODULE_NAME)
            username = self.get_argument("u")
            password = self.get_argument("h")
            userID = userUtils.getID(username)
            if not userUtils.checkLogin(userID, password):
                raise exceptions.loginFailedException(MODULE_NAME, username)

            beatmapSetId = int(self.get_argument("s"))
            beatmapIds = self.get_argument("b").split(',')
            oldOsz2Hash = self.get_argument("z")

            if userID != 1000:
                return self.write(
                    return_errorcode(5, "f**k you, you are NOT Xxdstem"))
            glob.db.execute(
                "DELETE FROM gatari_beatmapsets WHERE user_id = {} AND active = -1"
                .format(userID))
            bmInfo = fetch_info(beatmapSetId, False)
            if beatmapSetId > 0 and bmInfo is not None:
                if authenticate_creator(userID, bmInfo["user_id"],
                                        username) == False:
                    return self.write(return_errorcode(1, ""))
                if (bmInfo["ranked"] > 0
                        and has_special_permissions(username) == False):
                    return self.write(return_errorcode(3, ""))
            else:
                uploadcap = check_remaining_uploadcap(userID)
                if (uploadcap == 0):
                    return self.write(
                        return_errorcode(
                            6, "You have exceeded your submission cap"))
                if (uploadcap == -1):
                    return self.write(
                        return_errorcode(6,
                                         "Only druzhbans can submit beatmaps"))
                beatmapSetId = create_beatmapset(userID, username)
                newSubmit = True

            serverHash = get_osz2_file_hash(beatmapSetId)
            fullSubmit = newSubmit or oldOsz2Hash == "0" or serverHash is None or serverHash != oldOsz2Hash
            self.write("0\n\
				{}\n\
				{}\n\
				{}\n\
				{}\n\
				0\n\
				{}".format(beatmapSetId, self.get_argument("b"),
               "1" if fullSubmit == True else "2", int(uploadcap), 0))

        except exceptions.invalidArgumentsException:
            pass
        except exceptions.loginFailedException:
            pass
示例#19
0
def ban(fro, chan, message):
    # Get parameters
    for i in message:
        i = i.lower()
    target = message[0]

    # Make sure the user exists
    targetUserID = userUtils.getIDSafe(target)
    userID = userUtils.getID(fro)
    if not targetUserID:
        return "{}: user not found".format(target)

    # Set allowed to 0
    userUtils.ban(targetUserID)

    # Send ban packet to the user if he's online
    targetToken = glob.tokens.getTokenFromUsername(userUtils.safeUsername(target), safe=True)
    if targetToken is not None:
        targetToken.enqueue(serverPackets.loginBanned())

    # Posting to discord
    requests.get(glob.conf.config["discord"]["krbot"] + "api/v1/submitBanOrRestrict", params={
        'token': glob.conf.config["discord"]["krbotToken"],
        'banned': target,
        'type': 1,
        'author': fro
    })
    log.rap(userID, "has banned {}".format(target), True)
    return "RIP {}. You will not be missed.".format(target)
示例#20
0
def fokabotCommands(token, sender, channel, message):
    msg = message.strip()
    userID = userUtils.getID(sender)
    userPr = userUtils.getPrivileges(userID)
    for command in yohaneCommands.commands:
        # Loop though all commands
        if re.compile("^{}( (.+)?)?$".format(command["trigger"])).match(msg):
            # message has triggered a command

            # Make sure the user has right permissions
            if command["privileges"] is not None:
                if userPr & command["privileges"] != command['privileges']:
                    return False

            # Check argument number
            message = message.strip().split(" ")
            if command["syntax"] != "" and len(message) <= len(
                    command["syntax"].split(" ")):
                return "Wrong syntax: {} {}".format(command["trigger"],
                                                    command["syntax"])

            # Return response or execute callback
            if command["callback"] is None:
                return command["response"]
            else:
                return command["callback"](token, sender, channel, message[1:])

    return None
示例#21
0
    def mp_mods():
        userID = userUtils.getID(fro)
        if not can_user_touch_lobby(get_match_id_from_channel(chan), userID,
                                    True):
            return False
        if len(message) < 2:
            raise exceptions.invalidArgumentsException(
                "Wrong syntax: !mp <mod1> [<mod2>] ...")
        _match = glob.matches.matches[get_match_id_from_channel(chan)]
        newMods = 0
        freeMod = False
        for _mod in message[1:]:
            if _mod.lower().strip() == "hd":
                newMods |= mods.HIDDEN
            elif _mod.lower().strip() == "hr":
                newMods |= mods.HARDROCK
            elif _mod.lower().strip() == "dt":
                newMods |= mods.DOUBLETIME
            elif _mod.lower().strip() == "fl":
                newMods |= mods.FLASHLIGHT
            elif _mod.lower().strip() == "fi":
                newMods |= mods.FADEIN
            if _mod.lower().strip() == "none":
                newMods = 0

            if _mod.lower().strip() == "freemod":
                freeMod = True

        _match.matchModMode = matchModModes.FREE_MOD if freeMod else matchModModes.NORMAL
        _match.resetReady()
        if _match.matchModMode == matchModModes.FREE_MOD:
            _match.resetMods()
        _match.changeMods(newMods)
        return "Match mods have been updated!"
示例#22
0
    def mp_timer():
        matchID = get_match_id_from_channel(chan)
        userID = userUtils.getID(fro)
        if not can_user_touch_lobby(matchID, userID):
            return False

        if len(message) < 2 or not message[1].isdigit() or int(message[1]) < 1:
            return "Wrong argument"
        secondsWatch = int(message[1])

        match = glob.matches.matches[matchID]
        if match.timerRunned:
            chat.sendMessage(
                glob.BOT_NAME, chan,
                "You can't run another timer, if you had another runned timer.\nEnter !mp aborttimer to stop."
            )
            return False

        def _decreaseTimer(t):
            if match.timerForce:
                chat.sendMessage(glob.BOT_NAME, chan, "Time is up!")
                match.timerForce = False
                match.timerRunned = False
            elif t <= 0:
                chat.sendMessage(glob.BOT_NAME, chan, "Time is up!")
                match.timerRunned = False
            else:
                if t % 10 == 0 or t <= 5:
                    chat.sendMessage(glob.BOT_NAME, chan,
                                     "Timer ends in {} seconds.".format(t))
                threading.Timer(1.00, _decreaseTimer, [t - 1]).start()

        match.timerRunned = True
        threading.Timer(1.00, _decreaseTimer, [secondsWatch - 1]).start()
        return "Timer started!"
示例#23
0
def userDeniedMessage(sender, target, message):
	return packetHelper.buildPacket(packetIDs.server_userDMCancel, [
		[sender, dataTypes.STRING],
		[message, dataTypes.STRING],
		[target, dataTypes.STRING],
		[userUtils.getID(sender), dataTypes.SINT32]
	])
示例#24
0
 def mp_settings():
     userID = userUtils.getID(fro)
     if not can_user_touch_lobby(get_match_id_from_channel(chan), userID):
         return False
     _match = glob.matches.matches[get_match_id_from_channel(chan)]
     msg = "PLAYERS IN THIS MATCH:\n"
     empty = True
     for slot in _match.slots:
         if slot.user is None:
             continue
         readable_statuses = {
             slotStatuses.READY: "ready",
             slotStatuses.NOT_READY: "not ready",
             slotStatuses.NO_MAP: "no map",
             slotStatuses.PLAYING: "playing",
         }
         if slot.status not in readable_statuses:
             readable_status = "???"
         else:
             readable_status = readable_statuses[slot.status]
         empty = False
         msg += "* [{team}] <{status}> ~ {username}{mods}\n".format(
             team="red" if slot.team == matchTeams.RED else
             "blue" if slot.team == matchTeams.BLUE else "!! no team !!",
             status=readable_status,
             username=glob.tokens.tokens[slot.user].username,
             mods=" (+ {})".format(generalUtils.readableMods(slot.mods))
             if slot.mods > 0 else "")
     if empty:
         msg += "Nobody.\n"
     return msg
示例#25
0
def sendMessage(fro, to, message):
	return packetHelper.buildPacket(packetIDs.server_sendMessage, [
		[fro, dataTypes.STRING],
		[message, dataTypes.STRING],
		[to, dataTypes.STRING],
		[userUtils.getID(fro), dataTypes.SINT32]
	])
示例#26
0
    def mp_removeRef():
        userID = userUtils.getID(fro)
        if not can_user_touch_lobby(get_match_id_from_channel(chan), userID,
                                    False, False):
            return False

        if len(message) < 2:
            raise exceptions.invalidArgumentsException(
                "Wrong syntax: !mp removeref <ref username>")

        userRefID = userUtils.getIDSafe(message[1])
        if not userRefID:
            raise exceptions.invalidArgumentsException("User not found")

        _match = glob.matches.matches[get_match_id_from_channel(chan)]
        if not userRefID in _match.refs:
            return "This user is not referre."

        _match.refs.remove(userRefID)
        _match.sendUpdates()
        chat.partChannel(userRefID,
                         "#multi_{}".format(_match.matchID),
                         kick=True)
        chat.partChannel(userRefID, "#multiplayer", kick=True)
        return "Match referre was deleted!"
示例#27
0
	def asyncPost(self):
		try:
			# Required arguments check
			if not requestsManager.checkArguments(self.request.arguments, ("u", "p", "a")):
				raise exceptions.invalidArgumentsException(MODULE_NAME)

			# Get arguments
			username = self.get_argument("u")
			password = self.get_argument("p")
			action = self.get_argument("a").strip().lower()

			# IP for session check
			ip = self.getRequestIP()

			# Login and ban check
			userID = userUtils.getID(username)
			if userID == 0:
				raise exceptions.loginFailedException(MODULE_NAME, userID)
			if not userUtils.checkLogin(userID, password, ip):
				raise exceptions.loginFailedException(MODULE_NAME, username)
			if userUtils.check2FA(userID, ip):
				raise exceptions.need2FAException(MODULE_NAME, userID, ip)
			if userUtils.isBanned(userID):
				raise exceptions.userBannedException(MODULE_NAME, username)

			# Action (depends on 'action' parameter, not on HTTP method)
			if action == "get":
				self.write(self._getComments())
			elif action == "post":
				self._addComment()
		except (exceptions.loginFailedException, exceptions.need2FAException, exceptions.userBannedException):
			self.write("error: no")
示例#28
0
    def mp_make():
        if len(message) < 2:
            raise exceptions.invalidArgumentsException(
                "Wrong syntax: !mp make <name>")
        matchName = " ".join(message[1:]).strip()
        if not matchName:
            raise exceptions.invalidArgumentsException(
                "Match name must not be empty!")
        userID = userUtils.getID(fro)

        for (_, __match) in glob.matches.matches.items():
            if __match.hostUserID == userID:
                return "You have opened match {}, please close it before use this command!".format(
                    __match.matchID)

        matchID = glob.matches.createMatch(matchName,
                                           generalUtils.stringMd5(
                                               generalUtils.randomString(32)),
                                           0,
                                           "Tournament",
                                           "",
                                           0,
                                           userID,
                                           isTourney=True)
        glob.matches.matches[matchID].sendUpdates()
        return "Tourney match #{} created!".format(matchID)
示例#29
0
def fokabotResponse(fro, chan, message):
	"""
	Check if a message has triggered FokaBot

	:param fro: sender username
	:param chan: channel name (or receiver username)
	:param message: chat mesage
	:return: FokaBot's response or False if no response
	"""
	cmd, vals = None, None
	for (k, v) in mainHandler.store.handlers.items():
		if message.strip().startswith(k):
			cmd, vals = k, v
			break

	if not cmd:
		return False

	if vals['privileges'] and userUtils.getPrivileges(userUtils.getID(fro)) & vals["privileges"] == 0 and fro != glob.BOT_NAME:
		return False

	args = shlex.split(message.strip()[len(cmd):])
	syntaxargs = shlex.split(vals['syntax'])
	if vals['syntax'] != "" and len(args) < len(syntaxargs):
		return f"Wrong syntax: {cmd} {vals['syntax']}"

	return mainHandler.store.call_command(cmd, fro, chan, args)
示例#30
0
    def asyncPost(self):
        try:
            if glob.debug:
                requestsManager.printArguments(self)

            # Make sure screenshot file was passed
            if "ss" not in self.request.files:
                raise exceptions.invalidArgumentsException(MODULE_NAME)

            # Check user auth because of sneaky people
            if not requestsManager.checkArguments(self.request.arguments,
                                                  ["u", "p"]):
                raise exceptions.invalidArgumentsException(MODULE_NAME)
            username = self.get_argument("u")
            password = self.get_argument("p")
            ip = self.getRequestIP()
            userID = userUtils.getID(username)
            if not verify_password(userID, password):
                raise exceptions.loginFailedException(MODULE_NAME, username)
            if not userUtils.checkBanchoSession(userID, ip):
                raise exceptions.noBanchoSessionException(
                    MODULE_NAME, username, ip)

            # Rate limit
            if glob.redis.get("lets:screenshot:{}".format(userID)) is not None:
                return self.write("no")
            glob.redis.set("lets:screenshot:{}".format(userID), 1, 60)

            while os.path.exists(
                    path := BASE_PATH.format(generalUtils.randomString(8))):
                pass