def handle_read(self): self.buff += self.recv(4096) if self.buff != "": m = re.search(self.pattern, self.buff) self.buff = "" sbserver.playerMessage(self.cn, green('Translation: ') + white(m.group(1))) remove_request(self.cn, self)
def warnNickReserved(cn, count, sessid): try: p = player(cn) except ValueError: return try: nickacct = p.warn_nickacct if nickacct.nick != sbserver.playerName(cn) or sessid != sbserver.playerSessionId(cn): p.warning_for_login = False return except (AttributeError, ValueError): p.warning_for_login = False return if isLoggedIn(cn): user = loggedInAs(cn) if nickacct.user_id != user.id: ban(cn, 0, 'Use of reserved name', -1) p.warning_for_login = False return if count > 4: ban(cn, 0, 'Use of reserved name', -1) p.warning_for_login = False return remaining = 25-(count*5) sbserver.playerMessage(cn, warning('Your name is reserved. You have ' + red('%i') + ' seconds to login or be kicked.') % remaining) addTimer(5000, warnNickReserved, (cn, count+1, sessid))
def listMasterCommands(cn, args): str = 'Master commands: ' for cmd in command_info.items(): if cmd[1].public: str += cmd[1].command + ' ' elif cmd[1].master: str += cmd[1].command + ' ' sbserver.playerMessage(cn, info(str))
def onPlayerCommands(cn, args): if args != '': sbserver.playerMessage(cn, error('Usage: #playercommands')) else: msg = blue('Available commands: ') for command in command_info.keys(): msg += '#' + command + ' ' sbserver.playerMessage(cn, orange(msg))
def onReloadCmd(cn, args): '''@description Reload server plugins @usage @admin''' if args != '': raise ExtraArgumentError() else: sbserver.playerMessage(cn, yellow('NOTICE: ') + blue('Reloading server plugins. Fasten your seatbelts...')) reloadPlugins()
def pingLimiterCmd(cn, args): '''@description Enable or disable kicking high ping users @usage enable/disable''' if args == 'enable': limiter.enabled = True sbserver.playerMessage(cn, notice('Ping limiter enabled')) elif args == 'disable': limiter.enabled = False sbserver.playerMessage(cn, notice('Ping limiter disabled')) else: raise UsageError('enable/disable')
def onReqUnspectate(cn, tcn): if tcn != cn: if isAtLeastMaster(cn): sbserver.unspectate(tcn) else: insufficientPermissions(cn) else: if sbserver.masterMode() > 1 and not isAtLeastMaster(cn): sbserver.playerMessage(cn, error('Master mode is locked. You cannot unspectate.')) else: sbserver.unspectate(tcn)
def onLoginCommand(cn, args): '''@description Login to server account @usage email password @public''' args = args.split(' ') if len(args) != 2: raise UsageError() user = userAuth(args[0], args[1]) if user: login(cn, user) else: sbserver.playerMessage(cn, error('Invalid login.'))
def onGiveMaster(cn, args): '''@description Give master to a client @usage cn @master''' if args == '': raise UsageError() return try: tcn = int(args) except TypeError: raise UsageError() return sbserver.playerMessage(cn, info('You have given master to %s') % sbserver.playerName(tcn)) sbserver.setMaster(tcn)
def namesCmd(cn, args): '''@description Display names used by client @usage cn @public''' if master_required and not isAtLeastMaster(cn): insufficientPermissions(cn) return if args == '': raise UsageError() return try: tcn = int(args) names = dbmanager.query(IpToNick).filter(IpToNick.ip==sbserver.playerIpLong(tcn)).all() if len(names) == 0: sbserver.playerMessage(cn, info('No names found')) return except NoResultFound: sbserver.playerMessage(cn, info('No names found')) return except ValueError: sbserver.playerMessage(cn, error('Invalid cn')) return namestr = 'Other known names: ' for name in names: namestr += name.nick + ' ' sbserver.playerMessage(cn, info(namestr))
def onCommand(cn, command): '''@description Translate text using Google translator @usage text src_lang dest_lang @public''' if count_player_requests(cn) < player_fd_limit: cmd_list = command.split() length = len(cmd_list) query = None lang1 = from_lang lang2 = to_lang if length == 0: sbserver.playerMessage(cn, red(fault_message)) elif length == 1: query = cmd_list[0] elif length == 2: sbserver.playerMessage(cn, red(fault_message)) elif length > 2: if is_lang(cmd_list[length-2],langslist) and is_lang(cmd_list[length-1],langslist): query = "%20".join(cmd_list[:length-2]) lang1 = cmd_list[length-2] lang2 = cmd_list[length-1] else: sbserver.playerMessage(cn, red(fault_message)) if query: sd = SocketDispatch(host, port, header, url, pattern, cn) sd.write(query, lang1, lang2) add_request(cn, sd) else: sbserver.playerMessage(cn, red("Please wait for your translations to be handled before submitting new ones"))
def msgHelpText(cn, cmd): try: helpinfo = command_info[cmd] except KeyError: sbserver.playerMessage(cn, error('Command not found')) else: msgs = [] try: msgs.append(helpinfo.description) except AttributeError: pass for usage in helpinfo.usages: msgs.append(usage) for msg in msgs: sbserver.playerMessage(cn, info(msg))
def onVoteKick(cn, args): '''@description Vote to kick a player from server @usage <cn>''' if args == '': sbserver.playerMessage(cn, error('Usage #votekick <cn>')) else: try: tcn = int(args) if player(cn).votekick == tcn: sbserver.playerMessage(cn, error('You have already voted to kick that player.')) allow_vote = False else: allow_vote = True except AttributeError: allow_vote = True if allow_vote: sbserver.message(info(vktemp.substitute(colordict, voter=sbserver.playerName(cn), victim=sbserver.playerName(tcn)))) player(cn).votekick = int(args) checkVotes(int(args))
def onRegisterCommand(cn, args): '''@description Register account with server @usage email password @public''' args = args.split(' ') if len(args) != 2: raise UsageError() try: dbmanager.query(User).filter(User.email==args[0]).one() except NoResultFound: if not isValidEmail(args[0]): raise ArgumentValueError('Invalid email address') user = User(args[0], args[1]) session.add(user) session.commit() sbserver.playerMessage(cn, info('Account created')) return except MultipleResultsFound: pass raise StateError('An account with that email already exists')
def onMapVote(cn, mapname, mapmode): p = player(cn) if sbserver.mapName() == '': setMap(mapname, mapmode) elif isAtLeastMaster(cn) and sbserver.masterMode() > 0: setMap(mapname, mapmode) elif mapmode != sbserver.gameMode() and (lock_mode or not allow_modevote): p.message(error('You cannot vote for a new game mode')) else: try: vote = player(cn).gamevars['mapvote'] allow_vote = vote[0] != mapname and vote[1] != mapmode except KeyError: allow_vote = True if allow_vote: sbserver.message(info(request_temp.substitute(colordict, user=p.name(), modename=sbserver.modeName(mapmode), mapname=mapname))) p.gamevars['mapvote'] = (mapname, mapmode) else: sbserver.playerMessage(cn, error('You have already requested this map.')) countVotes()
def onLinkName(cn, args): '''@description Link name to server account, and reserve name. @usage @public''' if args != '': raise UsageError() if not isLoggedIn(cn): raise StateError('You must be logged in to link a name to your account') if sbserver.playerName(cn) in blocked_names: raise StateError('You can not reserve this name') try: dbmanager.query(NickAccount).filter(NickAccount.nick==sbserver.playerName(cn)).one() except NoResultFound: user = loggedInAs(cn) nickacct = NickAccount(sbserver.playerName(cn), user.id) session.add(nickacct) session.commit() sbserver.playerMessage(cn, info('Your name is now linked to your account.')) sbserver.playerMessage(cn, info('You may now login with /setmaster password')) return except MultipleResultsFound: pass raise StateError('Your name is already linked to an account')
def checkPlayers(self): addTimer(5000, self.checkPlayers, ()) if not self.enabled: return self.update_averages() if self.counter == 0: laggers = [] for player in players.all(): try: if not player.isSpectator() and player.avg_ping > self.max_ping: laggers.append(player.cn) except AttributeError: player.avg_ping = 0 remove_cns = [] for lagger in laggers: if lagger in self.warned_cns: ban(lagger, 0, 'lagging', -1) remove_cns.append(lagger) else: sbserver.playerMessage(lagger, warning('Your ping is too high. You will be kicked if it is not lowered.')) self.warned_cns.append(lagger) for r_cns in remove_cns: self.warned_cns.remove(r_cns)
def onNextMapCmd(cn, args): '''@description Display next map @usage @public''' if args != '': sbserver.playerMessage(cn, error('Usage: #nextmap')) else: try: sbserver.playerMessage(cn, info(nextmap_response.substitute(colordict, mapname=getSuccessor(sbserver.gameMode(), sbserver.mapName())))) except (KeyError, ValueError): sbserver.playerMessage(cn, error('Could not determine next map'))
def onNextMapCmd(cn, args): '''@description Display next map @usage @public''' if args != '': sbserver.playerMessage(cn, error('Usage: #nextmap')) else: try: sbserver.playerMessage( cn, info( nextmap_response.substitute(colordict, mapname=getSuccessor( sbserver.gameMode(), sbserver.mapName())))) except (KeyError, ValueError): sbserver.playerMessage(cn, error('Could not determine next map'))
def onDuelCommand(cn, args): if args == '': sbserver.playerMessage(cn, error('Usage: #duel <mapname> (mode) (cn) (cn)')) args = args.split(' ') players = sbserver.players() if len(players) != 2: sbserver.playerMessage(cn, error('There must be only two unspectated players to enter duel mode.')) else: if len(args) == 2: map = args[0] mode = int(args[1]) elif len(args) == 1: map = args[0] mode = sbserver.gameMode() else: sbserver.playerMessage(cn, error('Usage: #duel <mapname> (mode)')) return duelers[0] = players[0] duelers[1] = players[1] prev_mastermode = sbserver.masterMode() sbserver.setMasterMode(2) sbserver.message(green('Duel begins in...')) duelCountdown(5, map, mode)
def message(self, msg): '''Send message to client''' sbserver.playerMessage(self.cn, msg)
def userPrivSetCmd(cn, tcn, args): user_id = player(tcn).user.id if args == 'user': try: if isUser(player(tcn).user.id): sbserver.playerMessage(cn, error('%s already has user permissions.' % sbserver.playerName(tcn))) return except (ValueError, AttributeError): pass else: try: user = loggedInAs(tcn) except AttributeError: sbserver.playerMessage(cn, error('%s is not logged in.' % sbserver.playerName(tcn))) else: dbmanager.query(UserPrivilege).filter(UserPrivilege.user_id==user_id).update({ 'privilege': None }) session.add(UserPrivilege(0, user.id)) session.commit() sbserver.playerMessage(cn, info('User privilege has been given to %s (%s)' % (sbserver.playerName(tcn), user.email))) elif args == 'master': try: if isUserMaster(player(tcn).user.id): sbserver.playerMessage(cn, error('%s already has master permissions.' % sbserver.playerName(tcn))) return except (ValueError, AttributeError): pass else: try: user = loggedInAs(tcn) except AttributeError: sbserver.playerMessage(cn, error('%s is not logged in.' % sbserver.playerName(tcn))) else: dbmanager.query(UserPrivilege).filter(UserPrivilege.user_id==user_id).update({ 'privilege': None }) session.add(UserPrivilege(1, user.id)) session.commit() sbserver.playerMessage(cn, info('Master privilege has been given to %s (%s)' % (sbserver.playerName(tcn), user.email))) elif args == 'admin': try: if isUserAdmin(player(tcn).user.id): sbserver.playerMessage(cn, error('%s already has admin permissions.' % sbserver.playerName(tcn))) return except (ValueError, AttributeError): pass else: try: user = loggedInAs(tcn) except AttributeError: sbserver.playerMessage(cn, error('%s is not logged in.' % sbserver.playerName(tcn))) else: dbmanager.query(UserPrivilege).filter(UserPrivilege.user_id==user_id).update({ 'privilege': None }) session.add(UserPrivilege(2, user.id)) session.commit() sbserver.playerMessage(cn, info('Admin privilege has been given to %s (%s)' % (sbserver.playerName(tcn), user.email))) else: sbserver.playerMessage(cn, error('Privilege level must be \'master\' to set master permissions and \'admin\' to set master or admin permissions'))
def onAuthSuccess(cn, name): if currentAdmin() != None: sbserver.playerMessage(cn, error('Admin is present')) return sbserver.setMaster(cn)
p.message(info('Usage: ' + command + ' ' + usage)) except StateError, e: p.message(error(str(e))) except ArgumentValueError, e: p.message(error('Invalid argument. ' + str(e))) except ValueError: p.message(error('Value Error: Did you specify a valid cn?')) exceptionType, exceptionValue, exceptionTraceback = sys.exc_info() logging.warn('Uncaught ValueError raised in command handler.') logging.warn(traceback.format_exc()) except: exceptionType, exceptionValue, exceptionTraceback = sys.exc_info() logging.warn('Uncaught exception occured in command handler.') logging.warn(traceback.format_exc()) else: sbserver.playerMessage(cn, error('Command not found')) def onMsg(self, cn, text): if len(text) > 0 and self.prefixes.find(text[0]) != -1: cmd = text[1:].split(' ')[0] self.trigger(cn, cmd, text[len(cmd)+2:]) return False return True commandmanager = CommandManager() def registerCommandHandler(command, func): xsbs.help.loadCommandInfo(command, func) commandmanager.register(command, func) class commandHandler(object): def __init__(self, name):
def listAdminCommands(cn, args): str = 'Admin commands: ' for cmd in command_info.items(): str += cmd[1].command + ' ' sbserver.playerMessage(cn, info(str))
def greet(cn): sbserver.playerMessage(cn, motdstring)
def listPublicCommands(cn, args): str = 'Public commands: ' for cmd in command_info.items(): if cmd[1].public: str += cmd[1].command + ' ' sbserver.playerMessage(cn, info(str))
def onCommand(cn, command): for i in urllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'): if 'EST' in i: sbserver.playerMessage(cn, green('The Eastern Standard Time is: ') + white(i))
def insufficientPermissions(cn): sbserver.playerMessage(cn, error('Insufficient permissions'))
def echoingame(caller,msg): if caller[0]=="ingame": sbserver.playerMessage(caller[1],msg)
def onCommand(cn, command): sbserver.playerMessage(cn, green(command) + green(": ") + red(commands[command]))