def tempban(self, client, reason='', duration=2, admin=None, silent=False, *kwargs): """ Tempban a client. :param client: The client to tempban :param reason: The reason for this tempban :param duration: The duration of the tempban :param admin: The admin who performed the tempban :param silent: Whether or not to announce this tempban """ if client.hide: # exclude bots return self.debug('TEMPBAN : client: %s, duration: %s, reason: %s', client, duration, reason) if isinstance(client, str): clients = self.clients.getByMagic(client) if len(clients) != 1: return else: client = clients[0] if admin: banduration = minutesStr(duration) variables = self.getMessageVariables(client=client, reason=reason, admin=admin, banduration=banduration) fullreason = self.getMessage('temp_banned_by', variables) else: banduration = minutesStr(duration) variables = self.getMessageVariables(client=client, reason=reason, banduration=banduration) fullreason = self.getMessage('temp_banned', variables) fullreason = self.stripColors(fullreason) reason = self.stripColors(reason) self.do_tempban(client, duration, reason) if not silent and fullreason != '': self.say(fullreason) self.queueEvent( self.getEvent("EVT_CLIENT_BAN_TEMP", { 'reason': reason, 'duration': duration, 'admin': admin }, client))
def tempban(self, client, reason='', duration=2, admin=None, silent=False, *kwargs): """\ tempban a given player on the game server and in case of success fire the event ('EVT_CLIENT_BAN_TEMP', data={'reason': reason, 'duration': duration, 'admin': admin}, client=target) """ if client.hide: # exclude bots return self.debug('TEMPBAN : client: %s, duration: %s, reason: %s', client, duration, reason) if isinstance(client, basestring): clients = self.clients.getByMagic(client) if len(clients) != 1: return else: client = client[0] if admin: fullreason = self.getMessage( 'temp_banned_by', self.getMessageVariables(client=client, reason=reason, admin=admin, banduration=minutesStr(duration))) else: fullreason = self.getMessage( 'temp_banned', self.getMessageVariables(client=client, reason=reason, banduration=minutesStr(duration))) fullreason = self.stripColors(fullreason) reason = self.stripColors(reason) self.do_tempban(client, duration, reason) if not silent and fullreason != '': self.say(fullreason) self.queueEvent( self.getEvent("EVT_CLIENT_BAN_TEMP", { 'reason': reason, 'duration': duration, 'admin': admin }, client))
def test_minutesStr(self): for test_data, expected in { "3s": "3 seconds", "4m": "4 minutes", "41": "41 minutes", "2h": "2 hours", "2.5h": "2.5 hours", "3d": "3 days", "5w": "5 weeks", 0: "0 second", 0.5: "30 seconds", 60: "1 hour", 90: "1.5 hour", 120: "2 hours", 122: "2 hours", 1266: "21.1 hours", 1440: "1 day", 3600: "2.5 days", 10080: "1 week", 15120: "1.5 week", 60480: "6 weeks", 525600: "1 year", 861984: "1.6 year", 1051200: "2 years", 10512000: "20 years", }.items(): result = functions.minutesStr(test_data) if expected != result: self.fail("%r, expecting '%s' but got '%s'" % (test_data, expected, result))
def test_minutesStr(self): for test_data, expected in { '3s': '3 seconds', '4m': '4 minutes', '41': '41 minutes', '2h': '2 hours', '2.5h': '2.5 hours', '3d': '3 days', '5w': '5 weeks', 0: '0 second', 0.5: '30 seconds', 60: '1 hour', 90: '1.5 hour', 120: '2 hours', 122: '2 hours', 1266: '21.1 hours', 1440: '1 day', 3600: '2.5 days', 10080: '1 week', 15120: '1.5 week', 60480: '6 weeks', 525600: '1 year', 861984: '1.6 year', 1051200: '2 years', 10512000: '20 years', }.items(): result = functions.minutesStr(test_data) if expected != result: self.fail("%r, expecting '%s' but got '%s'" % (test_data, expected, result))
def onBan(self, event): """ Perform operations when EVT_CLIENT_BAN or EVT_CLIENT_BAN_TEMP is received. :param event: An EVT_CLIENT_BAN or and EVT_CLIENT_BAN_TEMP event. """ admin = event.data['admin'] if admin is None: # do not display B3 autokick/bans otherwise it can # mess up the IRC chat (suppose to send notices from a # server with TK plugin enabled) and the bot could # be G-Lined. return client = event.client reason = event.data['reason'] message = '[%sBAN%s] %s%s%s banned %s%s%s' % (RED, RESET, ORANGE, admin.name, RESET, ORANGE, client.name, RESET) if reason: # if there is a reason attached to the ban, append it to the notice message += ' [reason : %s%s%s]' % (RED, self.console.stripColors(reason), RESET) duration = 'permanent' if 'duration' in event.data: # if there is a duration convert it duration = minutesStr(event.data['duration']) # append the duration to the ban notice message += ' [duration : %s%s%s]' % (RED, duration, RESET) for name, channel in self.ircbot.channels.iteritems(): if channel.showbans: # if showbans is enabled, broadcast the notice channel.message(message)
def cmd_ultrab3(self, data, client=None, cmd=None): """\ - list ultra information about the server. """ if not self.console.storage.status(): cmd.sayLoudOrPM(client, '^7Cannot lookup, database apears to be ^1DOWN') return False #Get SQL information players = self.console.storage.query("""SELECT * FROM clients """) total_admins = self.console.storage.query("""SELECT id FROM clients WHERE (group_bits='32' OR group_bits='256' OR group_bits='4096' OR group_bits='65536' OR group_bits='2097152') """) total_regulars = self.console.storage.query("""SELECT id FROM clients WHERE group_bits='2' """) follow = self.console.storage.query("""SELECT id FROM following """) totalbans = self.console.storage.query("""SELECT id FROM penalties WHERE (type = "tempban" OR type = "ban") """) permbans = self.console.storage.query("""SELECT id FROM penalties WHERE type= 'ban' AND time_expire = '-1' """) warns = self.console.storage.query("""SELECT c.id, c.name, p.time_expire FROM penalties p, clients c WHERE p.client_id = c.id AND p.inactive = 0 AND type='Warning' AND p.time_expire >= UNIX_TIMESTAMP() """) tempbans = self.console.storage.query("""SELECT id FROM penalties WHERE type= 'tempban' AND inactive = 0 AND time_expire >= UNIX_TIMESTAMP() """) cmd.sayLoudOrPM(client, '^7Version: ^1%s' % b3.version) cmd.sayLoudOrPM(client, '^7Uptime: [^2%s^7]' % (functions.minutesStr(self.console.upTime() / 60.0))) cmd.sayLoudOrPM(client, "^7Total Players: ^5%s" % players.rowcount) cmd.sayLoudOrPM(client, "^7Admins: ^5%s" % total_admins.rowcount) cmd.sayLoudOrPM(client, "^7Regulars: ^5%s" % total_regulars.rowcount) cmd.sayLoudOrPM(client, "^7Players in Watchlist: ^5%s" % follow.rowcount) cmd.sayLoudOrPM(client, "^7Permbans: ^5%s" % permbans.rowcount) cmd.sayLoudOrPM(client, "^7Active Tempbans: ^5%s" % tempbans.rowcount) cmd.sayLoudOrPM(client, "^7Active Warnings: ^5%s" % warns.rowcount)
def penalizeClientBadname(penalty, client, data=""): """ monkey patch the censor plugin """ b3log.info("%s gets penalized with a %s" % (client.name, penalty.type)) if penalty.duration: b3log.info("\tduration: %s" % minutesStr(penalty.duration)) if penalty.reason: b3log.info("\treason: %s" % penalty.reason) if penalty.keyword: b3log.info("\treasonkeyword: %s" % penalty.keyword)
def cmd_ultrab3(self, data, client=None, cmd=None): """\ or <variable> - list ultra information about b3. """ if not self.console.storage.status(): cmd.sayLoudOrPM(client, '^7Cannot lookup, database apears to be ^1DOWN') return False #Get SQL information players = self.console.storage.query("""SELECT * FROM clients """) total_admins = self.console.storage.query("""SELECT id FROM clients WHERE (group_bits='32' OR group_bits='256' OR group_bits='4096' OR group_bits='65536' OR group_bits='2097152') """) total_regulars = self.console.storage.query("""SELECT id FROM clients WHERE group_bits='2' """) follow = self.console.storage.query("""SELECT id FROM following """) totalbans = self.console.storage.query("""SELECT id FROM penalties WHERE (type = "tempban" OR type = "ban") """) permbans = self.console.storage.query("""SELECT id FROM penalties WHERE type= 'ban' AND time_expire = '-1' """) warns = self.console.storage.query("""SELECT c.id, c.name, p.time_expire FROM penalties p, clients c WHERE p.client_id = c.id AND p.inactive = 0 AND type='Warning' AND p.time_expire >= UNIX_TIMESTAMP() """) tempbans = self.console.storage.query("""SELECT id FROM penalties WHERE type= 'tempban' AND inactive = 0 AND time_expire >= UNIX_TIMESTAMP() """) uptime = functions.minutesStr(self.console.upTime() / 60.0) if data is None or data=='': cmd.sayLoudOrPM(client, '^7Version: ^1%s' % b3.version) cmd.sayLoudOrPM(client, '^7Uptime: [^2%s^7]' % uptime) cmd.sayLoudOrPM(client, "^7Total Players: ^5%s" % players.rowcount) cmd.sayLoudOrPM(client, "^7Admins: ^5%s" % total_admins.rowcount) cmd.sayLoudOrPM(client, "^7Regulars: ^5%s" % total_regulars.rowcount) cmd.sayLoudOrPM(client, "^7Players in Watchlist: ^5%s" % follow.rowcount) cmd.sayLoudOrPM(client, "^7Permbans: ^5%s" % permbans.rowcount) cmd.sayLoudOrPM(client, "^7Active Tempbans: ^5%s" % tempbans.rowcount) cmd.sayLoudOrPM(client, "^7Active Warnings: ^5%s" % warns.rowcount) return False else: input = self._adminPlugin.parseUserCmd(data) variable = input[0] if (variable == "b3version") or (variable == "version"): cmd.sayLoudOrPM(client, '^7Version: ^1%s' % b3.version) elif (variable == "b3uptime") or (variable == "uptime"): cmd.sayLoudOrPM(client, '^7Uptime: [^2%s^7]' % uptime) elif (variable == "b3players") or (variable == "players") or (variable == "allplayers") or (variable == "totalplayers"): cmd.sayLoudOrPM(client, "^7Total Players: ^5%s" % players.rowcount) elif (variable == "b3admins") or (variable == "admins"): cmd.sayLoudOrPM(client, "^7Admins: ^5%s" % total_admins.rowcount) elif (variable == "b3regulars") or (variable == "regulars") or (variable == "regs"): cmd.sayLoudOrPM(client, "^7Regulars: ^5%s" % total_regulars.rowcount) elif (variable == "watchlist") or (variable == "follow") or (variable == "following") or (variable == "b3watchlist"): cmd.sayLoudOrPM(client, "^7Players in Watchlist: ^5%s" % follow.rowcount) elif (variable == "permbans") or (variable == "totalbans") or (variable == "bans") or (variable == "pbans"): cmd.sayLoudOrPM(client, "^7Permbans: ^5%s" % permbans.rowcount) elif (variable == "tempbans") or (variable == "tbans") or (variable == "totaltempbans"): cmd.sayLoudOrPM(client, "^7Active Tempbans: ^5%s" % tempbans.rowcount) elif (variable == "currentmap") or (variable == "map"): cmd.sayLoudOrPM(client, "^7Current map: ^2%s" % self.console.getCvar('mapname').getString()) elif (variable == "warns") or (variable == "warnings") or (variable == "activewarnings"): cmd.sayLoudOrPM(client, "^7Active Warnings: ^5%s" % warns.rowcount) else: client.message("Couldn't find your request")
def onBan(self, event): """ Perform operations when EVT_CLIENT_BAN or EVT_CLIENT_BAN_TEMP is received. :param event: An EVT_CLIENT_BAN or and EVT_CLIENT_BAN_TEMP event. """ admin = event.data["admin"] client = event.client reason = event.data["reason"] server = self.stripColors(str(dict['sv_hostname'])).title() if admin == None: admin_name = "B3" else: admin_name = admin.name embed = { "title": "B3 Ban", "description": "**%s** Banned **%s**" % (self.stripColors(admin_name), self.stripColors(client.name)), "timestamp": datetime.datetime.now().isoformat(), "color": 15466496, "fields": [{ "name": "Server", "value": server, "inline": False }] } if reason: # if there is a reason attached to the ban, append it to the notice embed["fields"].append({ "name": "Reason", "value": self.stripColors(reason.replace(',', '')), "inline": True }) duration = "permanent" if 'duration' in event.data: # if there is a duration convert it duration = minutesStr(event.data['duration']) # append the duration to the ban notice embed["fields"].append({ "name": "Duration", "value": duration, "inline": True }) self.discordEmbeddedPush(embed)
def short_minuteStr(text): return ( minutesStr(text) .replace(" seconds", "s") .replace(" second", "s") .replace(" minutes", "min") .replace(" minute", "min") .replace(" hours", "hr") .replace(" hour", "hr") )
def _start_autostop_timer(self, client, duration, admin=None): str_duration = minutesStr(duration / 60.0) self.plugin.info("starting auto-stop demo timer for %s and %s" % (client.name, str_duration)) t = self._auto_stop_timers.get(client.guid, None) if t: # stop eventually existing auto-stop timer for that player t.cancel() t = self._auto_stop_timers[client.guid] = Timer(duration, self._autostop_recording_player, [client]) t.start() if admin: admin.message("demo for %s will stop in %s" % (client.name, str_duration))
def _start_autostop_timer(self, client, duration, admin=None): str_duration = minutesStr(duration/60.0) self.plugin.info("starting auto-stop demo timer for %s and %s" % (client.name, str_duration)) t = self._auto_stop_timers.get(client.guid, None) if t: # stop eventually existing auto-stop timer for that player t.cancel() t = self._auto_stop_timers[client.guid] = Timer(duration, self._autostop_recording_player, [client]) t.start() if admin: admin.message("demo for %s will stop in %s" % (client.name, str_duration))
def tempban(self, client, reason='', duration=2, admin=None, silent=False, *kwargs): """ Tempban a client. :param client: The client to tempban :param reason: The reason for this tempban :param duration: The duration of the tempban :param admin: The admin who performed the tempban :param silent: Whether or not to announce this tempban """ if client.bot: # exclude bots return self.debug('TEMPBAN : client: %s - duration: %s - reason: %s', client, duration, reason) if isinstance(client, basestring): clients = self.clients.getByMagic(client) if len(clients) != 1: return else: client = clients[0] if admin: banduration = minutesStr(duration) variables = self.getMessageVariables(client=client, reason=reason, admin=admin, banduration=banduration) fullreason = self.getMessage('temp_banned_by', variables) else: banduration = minutesStr(duration) variables = self.getMessageVariables(client=client, reason=reason, banduration=banduration) fullreason = self.getMessage('temp_banned', variables) fullreason = self.stripColors(fullreason) reason = self.stripColors(reason) self.do_tempban(client, duration, reason) if not silent and fullreason != '': self.say(fullreason) data = {'reason': reason, 'duration': duration, 'admin': admin} self.queueEvent(self.getEvent("EVT_CLIENT_BAN_TEMP", data=data, client=client))
def _ban_event(self, event): self.debug("Processing ban event") c = event.client lastBan = c.lastBan if lastBan and lastBan.adminId and lastBan.timeAdd >= c.timeEdit: self.debug("Banned by admin %s" % lastBan.adminId) admin = self._adminPlugin.findClientPrompt('@%s' % str(lastBan.adminId), None) s = '[%d] %s was banned by %s for %s because %s' % (c.id, c.name, admin.name, functions.minutesStr(lastBan.duration), lastBan.reason) self.post_update(s) else: self.debug("Banned by bot")
def onBan(self, event): """ Perform operations when EVT_CLIENT_BAN or EVT_CLIENT_BAN_TEMP is received. :param event: An EVT_CLIENT_BAN or and EVT_CLIENT_BAN_TEMP event. """ admin = event.data['admin'] client = event.client reason = event.data['reason'] embed = { "title": "B3 Ban", "description": '**%s** Banned **%s**' % (admin.name, client.name), "timestamp": datetime.datetime.now().isoformat(), "color": 15466496, "fields": [{ "name": "Server", "value": self._serverName, "inline": False }] } if reason: # if there is a reason attached to the ban, append it to the notice embed["fields"].append({ "name": "Reason", "value": self.console.stripColors(reason), "inline": True }) duration = 'permanent' if 'duration' in event.data: # if there is a duration convert it duration = minutesStr(event.data['duration']) # append the duration to the ban notice embed["fields"].append({ "name": "Duration", "value": duration, "inline": True }) self.discordEmbeddedPush(embed)
def tempban(self, client, reason='', duration=2, admin=None, silent=False, *kwargs): """ Tempban a client. """ from b3.functions import minutesStr print('>>>tempbanning %s for %s (%s)' % (client.name, reason, minutesStr(duration))) data = {'reason': reason, 'duration': duration, 'admin': admin} self.queueEvent( self.getEvent('EVT_CLIENT_BAN_TEMP', data=data, client=client)) client.disconnect()
def start_vote_session(self, client=None): if self.last_vote_start_time: now = time.time() how_long_ago = now - self.last_vote_start_time next_vote_allowed_seconds = self.last_vote_start_time + (self.vote_interval * 60) - now if how_long_ago < self.vote_interval * 60: self.info( "cannot start vote because a previous vote started less than %s" % minutesStr(self.vote_interval)) if client: client.message(self.getMessage('votemap_feedback_interval_error', {'time': minutesStr("%ss" % next_vote_allowed_seconds)})) return # get the maps to choose from available_maps = self._getAvailableMaps() self.debug("available maps : %s" % available_maps) current_mapinfo = self._get_current_mapinfo() excluded_maps = [] if self.exclude_current_map: excluded_maps.append(current_mapinfo) if self.exclude_next_map: excluded_maps.append(self._get_next_mapinfo()) options = self.map_options_pickup_strategy(available_maps, self.number_of_vote_options, current_mapinfo, excluded_maps) if len(options) >= 2: self.current_vote_session = VoteSession(self, self._adminPlugin, self._messages) for mapinfo in options: mapinfo['label'] = self._make_map_label(mapinfo) self.current_vote_session.addOption(mapinfo) self.current_vote_session.start() self.console.say(self.getMessage("vote_announcement_started")) time.sleep(.5) self.announce_vote_options() self.current_vote_session_timer = Timer(interval=self.vote_duration * 60, function=self.stop_current_vote_session) self.current_vote_session_timer.start() if client: client.message(self.getMessage('votemap_feedback_success')) else: self.warning("cannot start a vote with less than 2 options") if client: client.message(self.getMessage('votemap_feedback_not_enough_maps'))
def warnClient(self, sclient, keyword, admin=None, timer=True, data='', newDuration=None): try: duration, warning = self.getWarning(keyword) except: duration, warning = self.getWarning('generic') warning = '%s %s' % (warning, keyword) if newDuration: duration = newDuration warnRecord = sclient.warn(duration, warning, keyword, admin, data) warning = sclient.exactName + '^7, ' + warning if timer: sclient.setvar(self, 'warnTime', self.console.time()) warnings = sclient.numWarnings try: pmglobal = self.config.get('warn', 'pm_global') except ConfigParser.NoOptionError: pmglobal = '0' if pmglobal == '1': msg = self.config.getTextTemplate('warn', 'message', warnings=warnings, reason=warning) sclient.message(msg) if admin: admin.message(msg) else: self.console.say(self.config.getTextTemplate('warn', 'message', warnings=warnings, reason=warning)) if warnings >= self.config.getint('warn', 'instant_kick_num'): self.warnKick(sclient, admin) elif warnings >= self.config.getint('warn', 'alert_kick_num'): duration = functions.minutesStr(self.warnKickDuration(sclient)) warn = sclient.lastWarning if warn: self.console.say(self.config.getTextTemplate('warn', 'alert', name=sclient.exactName, warnings=warnings, duration=duration, reason=warn.reason)) else: self.console.say(self.config.getTextTemplate('warn', 'alert', name=sclient.exactName, warnings=warnings, duration=duration, reason='Too many warnings')) sclient.setvar(self, 'checkWarn', True) t = threading.Timer(25, self.checkWarnKick, (sclient, admin, data)) t.start() return warnRecord
def onEvent(self, event): if event.type and event.client.name in self.reportedplayers: lastBan = event.client.lastBan embed = DiscordEmbed(self.url, color=0xFFFFFF) if not (event.type == b3.events.EVT_CLIENT_DISCONNECT): embed.set_mapview( 'https://www.iconsdb.com/icons/download/green/checkmark-16.png' ) if (event.type == b3.events.EVT_CLIENT_DISCONNECT): if (event.type == b3.events.EVT_CLIENT_BAN): self.debug("Shouldn't happen") if (event.type == b3.events.EVT_CLIENT_KICK): embed.set_desc("%s has been kicked." % (event.client.name)) embed.set_footnote() elif (event.type == b3.events.EVT_CLIENT_BAN): embed.set_desc(event.client.name + " has been banned by " + self._adminPlugin.findClientPrompt( '@%s' % str(lastBan.adminId), None).name) embed.set_footnote( text="Reason: " + self.stripColors(lastBan.reason.replace(',', ''))) elif (event.type == b3.events.EVT_CLIENT_BAN_TEMP): embed.set_desc("%s has been temporarily banned by %s for %s" % (event.client.name, self._adminPlugin.findClientPrompt( '@%s' % str(lastBan.adminId), None).name, functions.minutesStr(lastBan.duration))) embed.set_footnote( text="Reason: " + self.stripColors(lastBan.reason.replace(',', ''))) elif (event.type == b3.events.EVT_CLIENT_DISCONNECT) and not lastBan: embed.set_desc("%s has left the game." % (event.client.name)) embed.set_footnote() embed.post() self.reportedplayers.remove(event.client.name) if len(self.reportedplayers) > 6: self.reportedplayers.pop(0)
def onBan(self, event): """ Perform operations when EVT_CLIENT_BAN or EVT_CLIENT_BAN_TEMP is received. :param event: An EVT_CLIENT_BAN or and EVT_CLIENT_BAN_TEMP event. """ admin = event.data['admin'] client = event.client reason = event.data['reason'] message = '[B3 BAN] Server: `%s` Admin: `%s` Banned `%s`' % ( self._serverName, admin.name, client.name) if reason: # if there is a reason attached to the ban, append it to the notice message += ' Reason : `%s`' % (self.console.stripColors(reason)) duration = 'permanent' if 'duration' in event.data: # if there is a duration convert it duration = minutesStr(event.data['duration']) # append the duration to the ban notice message += ' [duration : `%s`]' % (duration) self.discordPush(message)
def onBan(self, event): """ Perform operations when EVT_CLIENT_BAN or EVT_CLIENT_BAN_TEMP is received. :param event: An EVT_CLIENT_BAN or and EVT_CLIENT_BAN_TEMP event. """ admin = event.data['admin'] if admin is None: # do not display B3 autokick/bans otherwise it can # mess up the IRC chat (suppose to send notices from a # server with TK plugin enabled) and the bot could # be G-Lined. return client = event.client reason = event.data['reason'] message = '[%sBAN%s] %s%s%s banned %s%s%s' % ( RED, RESET, ORANGE, admin.name, RESET, ORANGE, client.name, RESET) if reason: # if there is a reason attached to the ban, append it to the notice message += ' [reason : %s%s%s]' % ( RED, self.console.stripColors(reason), RESET) duration = 'permanent' if 'duration' in event.data: # if there is a duration convert it duration = minutesStr(event.data['duration']) # append the duration to the ban notice message += ' [duration : %s%s%s]' % (RED, duration, RESET) for name, channel in self.ircbot.channels.iteritems(): if channel.showbans: # if showbans is enabled, broadcast the notice channel.message(message)
client.message("Error while querying bf3stats.com. %s" % err) else: self.__send_bf3stats_response(client, targetted_player, cmd, stats) def do_cmd_bf3stats_with_update(self, client, targetted_player, cmd): try: stats = self.get_updated_stats(targetted_player) except NoStat: client.message("bf3stats.com has no stats for %s, requesting update..." % targetted_player.name) self.update_service.request_update( player_name=targetted_player.name, client=client, callback=self.callback_player_update, callback_args=(client, targetted_player, cmd), ) except Bf3statsError, err: client.message("Error while querying bf3stats.com. %s" % err) else: self.__send_bf3stats_response(client, targetted_player, cmd, stats) if stats.data_age > self.age_triggering_player_update: client.message( "stats are more than %s old, requesting update..." % minutesStr("%ss" % self.age_triggering_player_update) ) self.update_service.request_update( player_name=targetted_player.name, client=client, callback=self.callback_player_update, callback_args=(client, targetted_player, cmd), )
self.port_1337_penalty = penalty.lower() except Exception, err: self.warning(err) self.port_1337_penalty = PENALTY_DEFAULT self.info('1337 port penalty : %s' % self.port_1337_penalty) try: duration = self.config.get('settings', 'tempban_duration') duration_minutes = time2minutes(duration) if duration_minutes <= 0: raise HaxbusterurtConfigError( "bad value for tempban_duration \"%s\"" % duration) self.tempban_duration = duration_minutes except Exception, err: self.warning(err) self.info('tempban duration : %s' % minutesStr(self.tempban_duration)) def enable(self): b3.plugin.Plugin.enable(self) self.checkAllClients() def onEvent(self, event): if not event.client: return if event.type == b3.events.EVT_CLIENT_AUTH: self.checkHacks(event.client) if event.client.maxLevel >= self._adminLevel: self.onAdminConnect(event.client) def onAdminConnect(self, client):
def tempban(self, client, reason='', duration=2, admin=None, silent=False, *kwargs): """\ tempban a given player on the game server and in case of success fire the event ('EVT_CLIENT_BAN_TEMP', data={'reason': reason, 'duration': duration, 'admin': admin}, client=target) """ if client.hide: # exclude bots return self.debug('TEMPBAN : client: %s, duration: %s, reason: %s', client, duration, reason) if isinstance(client, basestring): clients = self.clients.getByMagic(client) if len(clients) != 1: return else: client = client[0] if admin: fullreason = self.getMessage('temp_banned_by', self.getMessageVariables(client=client, reason=reason, admin=admin, banduration=minutesStr(duration))) else: fullreason = self.getMessage('temp_banned', self.getMessageVariables(client=client, reason=reason, banduration=minutesStr(duration))) fullreason = self.stripColors(fullreason) reason = self.stripColors(reason) self.do_tempban(client, duration, reason) if not silent and fullreason != '': self.say(fullreason) self.queueEvent(self.getEvent("EVT_CLIENT_BAN_TEMP", {'reason': reason, 'duration': duration, 'admin': admin}, client))
def cmd_ultrauserinfo(self, data, client=None, cmd=None): """\ <name> - display player's ultra information. """ if not self.console.storage.status(): cmd.sayLoudOrPM(client, '^7Cannot lookup, database apears to be ^1DOWN') return False input = self._adminPlugin.parseUserCmd(data) input = data.split(' ',1) if not input: client.message('^7correct syntax is ^2!ultrauserinfo ^7<name>') return False cid = input[0] sclient = self._adminPlugin.findClientPrompt(cid, client) if not sclient: client.message('^7correct syntax is ^2!ultrauserinfo ^7<name>') return self._country_format = '^1%(city)s ^7[^3%(country_name)s^7]' bans = self.get_all_player_bans(sclient) location = self.get_client_location(sclient) clients = self.console.clients.getClientsByLevel() cursor = self.console.storage.query(self._SELECT_QUERY % sclient.id) if location: country = translate(self._country_format % location) cmd.sayLoudOrPM(client, self.getMessage('general_info', sclient.cid, sclient.exactName, sclient.id, sclient.maxGroup.name, sclient.maxLevel, sclient.connections, sclient.ip, country)) else: cmd.sayLoudOrPM(client, '^7%s: %s^7 [^2@%s^7] is a ^2%s^7 [^1%s^7], connected: ^6%s ^7times. ^4%s ^7from: %s' % (sclient.cid, sclient.exactName, sclient.id, sclient.maxGroup.name, sclient.maxLevel, sclient.connections, sclient.ip)) if sclient not in clients: cmd.sayLoudOrPM(client, 'Last seen: %s' % self.console.formatTime(sclient.timeEdit)) if cursor.rowcount > 0: r = cursor.getRow() admin = self._adminPlugin.findClientPrompt("@%s" % r['admin_id'], client) if admin: admin_name = admin.name else: admin_name = 'B3' if r['reason'] and r['reason'] != '' and r['reason'] != 'None': reason = r['reason'] else: reason = self._DEFAULT_REASON cmd.sayLoudOrPM(client, self.getMessage('watchlist_info', admin_name, reason)) else: cmd.sayLoudOrPM(client, "") if sclient: warns = sclient.numWarnings myaliases = [] for a in sclient.aliases: myaliases.append('%s' % a.alias) if len(myaliases) > 4: myaliases.append('^7[^2more^7]') break if len(myaliases): cmd.sayLoudOrPM(client, "^3Aliases^7: %s" % (', '.join(myaliases))) else: cmd.sayLoudOrPM(client, '') if warns: msg = '' warn = sclient.firstWarning if warn: expire = functions.minutesStr((warn.timeExpire - (self.console.time())) / 60) msg = '^7. expires in ^5%s' % expire warn = sclient.lastWarning if warn: msg += '^7: ^3%s' % warn.reason message = '^1Warnings^7: ^4%s %s' % (warns, msg) else: message = '' cmd.sayLoudOrPM(client, message) if len(bans) == 0: return True cmd.sayLoudOrPM(client, "^1Past Bans^7: ^4%s" % len(bans)) for b in bans: cmd.sayLoudOrPM(client, b)
else: self.port_1337_penalty = penalty.lower() except Exception, err: self.warning(err) self.port_1337_penalty = PENALTY_DEFAULT self.info('1337 port penalty : %s' % self.port_1337_penalty) try: duration = self.config.get('settings', 'tempban_duration') duration_minutes = time2minutes(duration) if duration_minutes <= 0: raise HaxbusterurtConfigError("bad value for tempban_duration \"%s\"" % duration) self.tempban_duration = duration_minutes except Exception, err: self.warning(err) self.info('tempban duration : %s' % minutesStr(self.tempban_duration)) def enable(self): b3.plugin.Plugin.enable(self) self.checkAllClients() def onEvent(self, event): if not event.client: return if event.type == b3.events.EVT_CLIENT_AUTH: self.checkHacks(event.client) if event.client.maxLevel >= self._adminLevel: self.onAdminConnect(event.client)
def cmd_report(self, data, client, cmd=None): """ <player> <reason> - report a player to the admins. Surround their name in single quotes if it contains spaces. """ # First check to see if the client is banned if client.id not in self._banned_status: self._banned_status[client.id] = self._is_banned(client.id) if self._banned_status[client.id]: client.message(self._client_banned_message) return if not data: client.message('^7You must supply a player to report and a reason') else: if client.id not in self._currentReports: self._currentReports[client.id] = 0 if self._currentReports[client.id] >= self._max_report_count: # The client has been reporting too many players too quickly, tell them to slow down client.message(self._report_spam % (self._reporter_limit, minutesStr(str(self._report_interval) + 's'))) return quotes = re.match(r"'(.*?)'(.*)", data) decoded_quotes = None reason = None if quotes: decoded_quotes = quotes.group(1).lower() reason = quotes.group(2).lower() data = data.split(' ', 1) if reason is None: reason = data[1] if len(data) == 1: client.message('^7You must supply a reason') return found = False decoded = data[0].lower() # Grab current admins # TODO: Potentially use getClientsByLevel if we want to customize level admins = self._adminPlugin.getAdmins() # Grab all clients clients = self.console.clients.getClientsByLevel() matches = [] # The client has previously tried to report a player # and received multiple matches, if they enter an integer # assume it's to narrow down to a specific player if client.id in self._matches: matchlist = self._matches[client.id] try: val = int(decoded) if val >= len(matchlist): client.message('Index out of range, please report player again') self._matches.pop(client.id) # Remove previous player indexes return matches = [matchlist[val]] self._matches.pop(client.id) found = True except ValueError: # Client did not enter an int index, assume they're retrying with a different name found = False self._matches.pop(client.id) # Either the client has not previously attempted to report a player, # or the index they provided was not in range. Search again if not found: # Grab all matching names/cids/ids matches = [c for c in clients if decoded in c.name.lower()] if decoded == 'noname': # If "noname" specified (all special characters=blank name), add those # with an empty name/those only their @id as their name to the list matches.extend([c for c in clients if c.name == '' or c.name[:1] == '@']) if decoded_quotes: extras = [c for c in clients if decoded_quotes in c.name.lower()] for extra in extras: if extra not in matches: matches.append(extra) # matches.extend([c for c in clients if decoded_quotes in c.name.lower()]) # No matches found if len(matches) == 0: client.message(self._no_matches) # Single match found, report the player elif len(matches) == 1: match = matches[0] self._currentReports[client.id] += 1 cur_time = self.milli_time() t = Timer(self._report_interval, self.dec_count, [client.id, cur_time]) self._reportTimers[cur_time] = t self._reportTimers[cur_time].start() no_admins = True if len(admins) > 0: player_id = match.id client.message('Reporting %s to admins.' % match.name) self._send_report(client, player_id, data[1]) reports = self._get_report(player_id) for admin in admins: self._admin_report(admin, client.name, client.cid, match.name, match.cid, reason, reports) no_admins = False # Send TS messages no_admins = self._send_ts_messages(client, match, data, no_admins) if no_admins: client.message(self._no_admins_msg) # Multiple matches found. Present a list to the user else: self._matches[client.id] = matches client.message(self._multiple_matches) matchstring = '^7' + matches[0].name + '[^20^7]' for i in range(1, len(matches)): matchstring += ', ' + matches[i].name + '[^2' + str(i) + '^7]' client.message(matchstring)