def kick(nick, reason='-', warn=False, mute=False, time=2): import ChatManager if '/' in nick: nick = nick.split('/')[0] #print nick.encode('unicode_escape') i = handle.getPlayerFromNick(nick) if i is not None: n = i.get_account_id() clid = i.getInputDevice().getClientID() name = i.getName(True) if mute: if clid not in ChatManager.mutedIDs: ChatManager.mutedIDs.append(clid) bs.screenMessage( u"{} Has Been Muted | Reason: {} | Muted For: {} Minutes". format(name, reason, time), transient=True) def unmute(clid): if clid in ChatManager.mutedIDs: ChatManager.mutedIDs.remove(clid) with bs.Context('UI'): bs.realTimer(time * 60 * 1000, bs.Call(unmute, clid)) if warn == True: if n in some.warn: some.warn[n] += 1 if some.warn[n] >= 3: some.banned.append(n) bs.screenMessage( u'Warn Limit Reached, Temporarily Banning Player', transient=True) k(reason, clid, name) return else: some.warn.update({n: 1}) bs.screenMessage( u"{} Has Been Warned | Reason: {} | Warn Count: {}/3".format( name, reason, some.warn[n]), transient=True) return else: k(reason, clid, name) return roster = bsInternal._getGameRoster() for i in roster: try: if bs.uni(i['displayString']).lower().find( bs.uni(nick).lower()) != -1 or str(i['clientID']) == nick: if not bs.uni(i['displayString']) == bs.uni(u'AwesomeLogic'): k(reason, int(i['clientID']), bs.uni(i['displayString'])) except Exception as e: print e
def run(): try: global old global maxPlayers global players_num roster = bsInternal._getGameRoster() players_num = len(roster) if len(roster) != 0 else 1 bsInternal._setPublicPartyMaxSize( min(max(9, len(roster) + 1), maxPlayers)) global banned banned = some.banned if roster != old: for i in roster: a = bs.uni(i['displayString']) # print a if a in banned: with bs.Context('UI'): bs.screenMessage( "You Have Been Banned. If The Ban Is Temporary, Try Joining After Some Time.", transient=True, clients=[int(i['clientID'])]) bsInternal._disconnectClient(int(i['clientID'])) if eval(i['specString'])["a"] in [ '', 'Server' ] and int(i['clientID']) != -1: with bs.Context('UI'): bs.screenMessage("Please Sign In and Join", transient=True, clients=[int(i['clientID'])]) bsInternal._disconnectClient(int(i['clientID'])) old = roster except Exception as e: pass bs.realTimer(2000, run)
def me(nick): if nick is None: return if isinstance(nick, bs.Player): n = nick.get_account_id() elif nick.startswith('pb'): n = nick else: return stats = db.getData(n) score = stats['s'] rank = db.getRank(n) points = stats['p'] message = bs.uni(stats['n']) message2 = u'\ue01f: ' + str(points) message3 = 'Total Score: ' + str(score) message4 = 'Rank: ' + str(rank) message5 = 'K: ' + str(stats['k']) message6 = 'D: ' + str(stats['d']) if n in joined: message7 = 'Time Spent: ' + str( datetime.timedelta(milliseconds=(bs.getRealTime() - joined[str(n)] + stats['tp']))).split('.', 2)[0] else: message7 = 'Time Spent: ' + \ str(datetime.timedelta(milliseconds=( stats['tp']))).split('.', 2)[0] bs.screenMessage(u' | '.join( [message, message2, message3, message4, message5, message6, message7])) clear(2500)
def _getName(self, full=False): nameRaw = name = self.profileNames[self.profileIndex] clamp = False if name == '_random': try: inputDevice = self._player.getInputDevice() except Exception: inputDevice = None if inputDevice is not None: name = inputDevice._getDefaultPlayerName() else: name = 'Invalid' if not full: clamp = True elif name == '__account__': try: inputDevice = self._player.getInputDevice() except Exception: inputDevice = None if inputDevice is not None: name = inputDevice._getAccountName(full) else: name = 'Invalid' if not full: clamp = True elif name == '_edit': # FIXME - this causes problems as an Lstr, but its ok to # explicitly translate for now since this is only shown on the host. name = (bs.Lstr( resource='createEditPlayerText', fallbackResource='editProfileWindow.titleNewText').evaluate()) else: # if we have a regular profile marked as global with an icon, # use it (for full only) if full: try: if self.profiles[nameRaw].get('global', False): icon = (bs.uni( self.profiles[nameRaw]['icon'] if 'icon' in self. profiles[nameRaw] else bs.getSpecialChar('logo'))) name = icon + name except Exception: bs.printException('Error applying global icon') else: # we now clamp non-full versions of names so there's at # least some hope of reading them in-game clamp = True if clamp: # in python < 3.5 some unicode chars can have length 2, so we need # to convert to raw int vals for safe trimming nameChars = bs.uniToInts(name) if len(nameChars) > 10: name = bs.uniFromInts(nameChars[:10]) + '...' return name
def getPlayerFromNick(nick): nick = bs.uni(nick[:-3] if nick.endswith('...') else nick) if '/' in nick: nick = nick.split('/')[0] if nick.isdigit(): if len(nick) == 3: for i in bsInternal._getForegroundHostActivity().players: if str(i.getInputDevice().getClientID()) == nick: return i if int(nick) < len(bsInternal._getForegroundHostActivity().players): return bsInternal._getForegroundHostActivity().players[int(nick)] else: for i in bsInternal._getForegroundHostActivity().players: if i.getName(True).lower().find(nick.lower()) != -1: return i else: return None
import bs import bsInternal import urllib2 import bsUtils import DB_Manager try: req = urllib2.Request('http://icanhazip.com', data=None) response = urllib2.urlopen(req, timeout=5) ip = str(bs.uni(response.read())).rstrip() except: ip = 'Failed To Fetch IP' port = str(bs.getConfig().get('Port', 43210)) def restart(): bsInternal._chatMessage('Rebooting Server... Thanks For Playing!') bsInternal._chatMessage('You Can Also Join Again Using IP & Port') text = 'IP: %s Port: %s' % (ip, port) bsInternal._chatMessage(text) bs.realTimer(3000, bs.Call(bs.quit)) bs.realTimer(3 * 60 * 60 * 1000, restart) def warn(): bs.screenMessage('Server is going to reboot in 1 minute', transient=True) bs.realTimer((3 * 60 * 60 * 1000) - 60000, warn)
def run(self): score_set = self.score_set for p_entry in score_set.getValidPlayers().values(): try: account_id = p_entry.getPlayer().get_account_id() except: continue clid = p_entry.getPlayer().getInputDevice().getClientID() account_name = bs.uni( p_entry.getPlayer().getInputDevice()._getAccountName(True)) if account_id is None: continue stats = db.getData(account_id) for i, k in db.defaults.items(): stats.setdefault(i, k) import handle if account_id in handle.joined: stats['tp'] += bs.getRealTime() - \ handle.joined[account_id] handle.joined[account_id] = bs.getRealTime() stats['k'] += p_entry.accumKillCount stats['d'] += p_entry.accumKilledCount stats['s'] += min(p_entry.accumScore, 250) stats['b'] += p_entry.accumBetrayCount stats['n'] = p_entry.getPlayer().getName(full=True, icon=False) bonus = min( int(((p_entry.accumScore / 10) + (p_entry.accumKillCount * 5)) / 2), 70) stats['p'] += min( (int(p_entry.accumScore / 10) + p_entry.accumKillCount * 5) / 2, 70) stats['c'] = p_entry.getPlayer().character high = p_entry.getPlayer().highlight high = 65536 * (high[0] * 255) + 256 * (high[1] * 255) + (high[2] * 255) stats['ch'] = high high = p_entry.getPlayer().color high = 65536 * (high[0] * 255) + 256 * (high[1] * 255) + (high[2] * 255) stats['cc'] = high stats['ls'] = datetime.datetime.now().strftime( '%d/%m/%Y, %H:%M:%S') if not account_name in stats['a']: stats['a'].append(account_name) db.saveData(account_id, stats, final=True) if some.earned_msg: bs.screenMessage(u'You have earned {} \ue01f'.format( min((int(p_entry.accumScore / 10) + p_entry.accumKillCount * 5) / 2, 70)), color=(0.5, 1, 0.5), transient=True, clients=[clid]) try: import weakref act = weakref.proxy(bsInternal._getForegroundHostActivity()) teams = {} for p in act.players: teams[p.getTeam()] = teams.get(p.getTeam(), 0) + 1 diff = max(teams.values()) - min(teams.values()) if diff >= 2: v = list(teams.values()) k = list(teams.keys()) maxTeam = (k[v.index(max(v))]) minTeam = (k[v.index(min(v))]) for i in range(diff - 1): p = maxTeam.players[i] bs.screenMessage( u'Changing {}\'s Team To Balance The Game'.format( p.getName()), transient=True) p._setData(team=minTeam, character=p.character, color=minTeam.color, highlight=p.highlight) info = p._getIconInfo() p._setIconInfo(info['texture'], info['tintTexture'], minTeam.color, p.highlight) break except: pass db.updateRanks() import gc gc.collect()
def _chatFilter(msg, clientID): msg = bs.uni(msg.rstrip()) if clientID == -1: return msg if some.chatMuted and not msg == '/unmute': bs.screenMessage('Admin Has Muted The Chat For Some Time', color=(1, 0, 0), clients=[clientID], transient=True) return None m = msg.split(' ')[0] a = msg.split(' ')[1:] if m in ['/pvtmsg','/dm','/pm']: try: def getPlayerFromMention(mention): for i in bsInternal._getForegroundHostActivity().players: if i.getName().lower().find(mention.lower()) != -1: return i else: return None def getPlayerFromClientID(clientID): for i in bsInternal._getForegroundHostActivity().players: if i.getInputDevice().getClientID() == clientID: return i else: return None if a[0].isdigit(): for player in bsInternal._getForegroundHostActivity().players: if a[0] == str(bsInternal._getForegroundHostSession().players.index(player)): fr = getPlayerFromClientID(clientID) what = ' '.join(a[1:]).encode('utf-8') to = player bs.screenMessage('Private Message Has Been Sent To {}: {}'.format(to.getName(True).encode('utf-8'),what),transient=True,clients=[fr.getInputDevice().getClientID()],color=(0,2,2)) bs.screenMessage('Private Message From {}: {}'.format(fr.getName(True).encode('utf-8'),what),transient=True,clients=[to.getInputDevice().getClientID()],color=(0,2,2)) else: to = getPlayerFromMention(a[0]) fr = getPlayerFromClientID(clientID) what = ' '.join(a[1:]) bs.screenMessage('Private Message Has Been Sent To {}: {}'.format(to.getName(True).encode('utf-8'),what),transient=True,clients=[fr.getInputDevice().getClientID()],color=(0,2,2)) bs.screenMessage('Private Message From {}: {}'.format(fr.getName(True).encode('utf-8'),what),transient=True,clients=[to.getInputDevice().getClientID()],color=(0,2,2)) return None except Exception as e: bs.screenMessage('Format: /pvtmsg <name> <message>') print e if clientID in mutedIDs: bs.screenMessage( 'Admin has muted you for some time. Pro Tip: Stop Begging or Spamming', color=(1, 0, 0), clients=[clientID], transient=True) return None r = bsInternal._getGameRoster() split = msg.split(' ') if split[0] in timeouts: timeout = timeouts[split[0]] * 1000 if clientID in last: if (bs.getRealTime() - last[clientID][split[0]]) < timeout: bs.screenMessage( '{} Rate-Limited. Please wait for {} seconds.'.format( split[0], timeouts[split[0]] - (bs.getRealTime() - last[clientID][split[0]]) / 1000), color=(1, 0, 0), clients=[clientID], transient=True) return None else: last[clientID][split[0]] = bs.getRealTime() else: last[clientID] = {} for i in timeouts.keys(): last[clientID][i] = -99999 for a in r: if a['clientID'] == clientID: if len(a['players']) > 0: name = a['players'][0]['name'] player = handle.getPlayerFromNick(name) account_id = '-' if player is None else player.get_account_id() playerInGame = True else: name = (a['displayString']) account_id = '-' playerInGame = False break else: print r return None name = bs.uni(name) #if not '/!' in msg: start_new_thread(db.logChat,(msg, name, account_id)) #Chat Logs if not db.getAdmin(account_id): import re old_msg = msg clean_msg = re.sub('[^A-Za-z0-9 ]+', '', msg) for word in filter_words: if re.search(r'\b({})\b'.format(word), clean_msg, re.IGNORECASE): cen = ''.join( random.choice(list('@#$%!')) for a in range(len(word))) clean_msg = re.sub(r'\b({})\b'.format(word), cen, clean_msg, flags=re.IGNORECASE) msg = clean_msg if msg != old_msg: import kicker kicker.kick(name, reason='Abuse', warn=True) return msg if msg.startswith('/trans '): if _googletrans: start_new_thread( trans, (' '.join(msg.split(' ')[2:]), name, msg.split(' ')[1])) if msg.startswith('/'): if playerInGame: cmds.append([clientID, msg]) return None if msg.startswith( tuple(['/kick', '/warn', '/mute', '/unmute', '/!'])) else msg else: bs.screenMessage('Please Join The Game First', color=(1, 0.5, 0.5), transient=True, clients=[clientID]) if 'admin' in msg.lower() or 'mod' in msg.lower( ) or 'promote' in msg.lower(): for i in ['pls', 'please', 'give', 'want', 'can i']: if i in msg.lower(): bs.screenMessage( 'Stop Begging For Admin! This Server is Self-Sufficient!', color=(1, 0, 0), transient=True, clients=[clientID]) import kicker kicker.kick(name, reason='Begging', warn=True) return msg # if not msg in some.trans: # t = msg # d = 'en' # lang = translator.detect(t) # if (lang.lang in supported_langs): # tym = translator.translate('Translating Your Message...',lang.lang).text # bs.screenMessage(tym, # color=(0, 0.5, 0.5), transient=True, clients=[clientID]) # tn = translator.translate(t, d).pronunciation # if tn is None: # tn = bs.utf8(translator.translate(t, d).text) # tc = bs.utf8(profanity.censor(tn)) # if tc != tn: # import kicker # kicker.kick(n, reason='Abuse', warn=True) # if tc.lower() != t.lower(): # msg = '{} ({}) > {} (en)'.format(msg,lang.lang,tc) if not msg.lower() in some.trans and _googletrans: start_new_thread(trans, (msg, name)) return msg