Advertisement
Guest User

ctbans.py

a guest
Jul 2nd, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 13.32 KB | None | 0 0
  1. import admin.admin as auth
  2. auth.startConnection("elevatedgaming.net", "user", "pass", "db name")
  3.  
  4. import logger.logger as log
  5.  
  6. import threading
  7. import time
  8. import codecs
  9. import datetime
  10. import pymysql
  11. import re
  12.  
  13. from listeners import on_tick_listener_manager, OnLevelShutdown
  14. from core import AutoUnload
  15. from events import Event
  16. from players.helpers import index_from_userid, index_from_steamid
  17. from players.entity import Player
  18. from filters.players import PlayerIter
  19. from path import Path
  20. from plugins.info import PluginInfo
  21. from messages import HintText, SayText2
  22. from filters.recipients import RecipientFilter
  23. from commands.client import ClientCommand
  24. from commands.say import SayCommand
  25. from commands import CommandReturn
  26. from engines.sound import Sound, SOUND_FROM_WORLD
  27. from menus import PagedMenu, SimpleMenu, PagedOption, SimpleOption
  28. from events.hooks import PreEvent
  29.  
  30. base_path = Path(__file__).parent
  31. MODNAME = base_path.namebase
  32.  
  33. DENIEDSOUND = Sound("buttons/weapon_cant_buy.wav")
  34. NAVSOUND = Sound('buttons/button14.wav')
  35. EXITSOUND = Sound('common/wpn_hudoff.wav')
  36. SELECTSOUND = Sound('common/talk.wav')
  37.  
  38. #info = PluginInfo()
  39. #info.author = "Shen Li"
  40. #info.basename = MODNAME
  41. #info.description = "Implements a CT Ban Module"
  42. #info.name = "EgN's CT Ban Mod"
  43. #info.version = "1.1.0"
  44. #info.url = "http://elevatedgaming.net"
  45.  
  46. datadict = dict()
  47.  
  48. def timeparser(timestr):
  49.     ints = re.findall(r'\d+', timestr)
  50.     strs = re.findall(r'\D+', timestr)
  51.     if strs:
  52.         sec = 0
  53.         try: sec += int(ints[strs.index("s")])
  54.         except: pass
  55.         try: sec += int(ints[strs.index("m")])*60
  56.         except: pass
  57.         try: sec += int(ints[strs.index("min")])*60
  58.         except: pass
  59.         try: sec += int(ints[strs.index("h")])*60*60
  60.         except: pass
  61.         try: sec += int(ints[strs.index("d")])*60*60*24
  62.         except: pass
  63.         try: sec += int(ints[strs.index("mon")])*60*60*24*30.44
  64.         except: pass
  65.         try: sec += int(ints[strs.index("M")])*60*60*24*30.44
  66.         except: pass
  67.         try: sec += int(ints[strs.index("b")])*60*60*24*30.44
  68.         except: pass
  69.         try: sec += int(ints[strs.index("w")])*60*60*24*7
  70.         except: pass
  71.         try: sec += int(ints[strs.index("W")])*60*60*24*7
  72.         except: pass
  73.         try: sec += int(ints[strs.index("y")])*60*60*24*365.24
  74.         except: pass
  75.         try: sec += int(ints[strs.index("Y")])*60*60*24*365.24
  76.         except: pass
  77.         return int(sec)
  78.     else:
  79.         return int(ints[0])
  80.  
  81. def steamid_from_networkid(networkid):
  82.     #Old: [U:1:2*B+A] -> New: STEAM_0:A:B
  83.     if networkid[:6] == "STEAM_":
  84.         return networkid
  85.     else:
  86.         accountid, universe = divmod(int(networkid.split(':')[2][:-1]), 2)
  87.         steamid = "STEAM_0:{0}:{1}".format(universe, accountid)
  88.         return steamid
  89.  
  90. class AudiblePagedMenu(PagedMenu):
  91.     def __init__(self, nav_callback=None, exit_callback=None, *args, **kwargs):
  92.         self.nav_callback = nav_callback
  93.         self.exit_callback = exit_callback
  94.         super().__init__(*args, **kwargs)
  95.  
  96.     def _select(self, ply_index, choice):
  97.         if choice in (8,9):
  98.             NAVSOUND.play(RecipientFilter(ply_index))
  99.             try:
  100.                 self.nav_callback(ply_index, choice)
  101.             except TypeError:
  102.                 pass
  103.         elif choice == 0:
  104.             EXITSOUND.play(RecipientFilter(ply_index))
  105.             try:
  106.                 self.exit_callback(ply_index, choice)
  107.             except TypeError:
  108.                 pass
  109.         else:
  110.             SELECTSOUND.play(RecipientFilter(ply_index))
  111.         return super()._select(ply_index, choice)
  112.  
  113. class StoppableSPThread(threading.Thread, AutoUnload):
  114.     def __init__(self, accuracy=1, *args, **kwargs):
  115.         super().__init__(*args, **kwargs)
  116.         self.accuracy = accuracy
  117.         on_tick_listener_manager.register_listener(self._tick)
  118.         self._stop = threading.Event()
  119.         self._finished = threading.Event()
  120.  
  121.     def run(self):
  122.         while not self.stopped:
  123.             try:
  124.                 self.do()
  125.             except Exception:
  126.                 except_hooks.print_exception()
  127.             time.sleep(self.accuracy)
  128.         on_tick_listener_manager.unregister_listener(self._tick)
  129.         self._finished.set()
  130.  
  131.     def do(self):
  132.         raise NotImplementedError("Some exception to indicate that this should be overridden")
  133.  
  134.     def _tick(self):
  135.         pass
  136.  
  137.     def stop(self):
  138.         self._stop.set()
  139.  
  140.     @property
  141.     def stopped(self):
  142.         return self._stop.is_set()
  143.  
  144.     @property
  145.     def finished(self):
  146.         return self._finished.is_set()
  147.  
  148.     _unload_instance = stop
  149.    
  150. class DBThread(StoppableSPThread):
  151.     def __init__(self, *args, **kwargs):
  152.         super().__init__(*args, **kwargs)
  153.  
  154.     def prime(self, *args, **kwargs):
  155.         super().__init__(*args, **kwargs)
  156.  
  157.     def do(self):
  158.         banlist = list()
  159.         conn = pymysql.connect(
  160.             host='elevatedgaming.net', port=3306, user='user', passwd="passwd", db='sloppy_forums', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor
  161.             )
  162.         cursor = conn.cursor()
  163.         cursor.execute("SELECT * FROM ctbans")
  164.         results = cursor.fetchall()
  165.         for result in results:
  166.             banlist.append({
  167.                 "index": result["index"],
  168.                 "name": codecs.getdecoder('unicode_escape')(result["name"]),
  169.                 "steamid": result["steamid"],
  170.                 "time": int(result["time"]),
  171.                 "duration": int(result["duration"]),
  172.                 "admin": result["admin"],
  173.                 "comment": result["comment"],
  174.                 "unban":result["unban"]})
  175.         #log.Write("Downloaded {0} CT bans from the database.".format(str(len(banlist))))
  176.         bans.update(banlist)
  177.         self.stop()
  178.         cursor.close()
  179.         conn.close()
  180.  
  181. class BanQuery(threading.Thread):
  182.     def __init__(self, steamid, name, admin, duration, comment):
  183.         threading.Thread.__init__(self)
  184.         self.steamid = steamid
  185.         self.name = name
  186.         self.admin = admin
  187.         self.duration = duration
  188.         self.comment = comment
  189.         if not self.comment: self.comment = "NULL"
  190.         else: self.comment = "'%s'" % self.comment.replace("'","''")
  191.  
  192.     def run(self):
  193.         conn = pymysql.connect(
  194.             host='elevatedgaming.net', port=3306, user='user', passwd="passwd", db='sloppy_forums', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor
  195.             )
  196.         cursor = conn.cursor()
  197.         cursor.execute("INSERT INTO `ctbans` (`name`, `steamid`, `time`, `duration`, `admin`, `comment`) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', {5})".format(self.name.replace("'","''"), self.steamid, int(time.time()), self.duration, auth.getID(self.admin.steamid), self.comment))
  198.         if self.duration > 0:
  199.             SayText2(message="\x05EgN Jailbreak| \x04{0} \x01CT banned player \x04{1} \x01until {2}.".format(self.admin.name, self.name, datetime.datetime.fromtimestamp(int(time.time()) + self.duration).strftime('%Y-%m-%d %H:%M:%S'))).send(RecipientFilter())
  200.         else:
  201.             SayText2(message="\x05EgN Jailbreak| \x04{0} \x01CT banned player \x04{1} \x01permanently.".format(self.admin.name, self.name)).send(RecipientFilter())
  202.         log.Write("Executed ban: {0} {1} {2} {3}".format(self.steamid, self.name, self.duration, auth.getID(self.admin.steamid)))  
  203.         bans.refresh()
  204.         cursor.close()
  205.         conn.close()
  206.        
  207. class Bans(object):
  208.     def __init__(self):
  209.         self.bans = list()
  210.         self.piped = False
  211.  
  212.     def update(self, banlist):
  213.         self.bans = banlist
  214.         self.piped = True
  215.    
  216.     def refresh(self):
  217.         DBThread().start()
  218.  
  219.     def player(self, steamid):
  220.         info = list()
  221.         steamid = steamid_from_networkid(steamid)
  222.         for x in self.bans:
  223.             if x["steamid"] == steamid:
  224.                 info.append(x)
  225.         return (len(info), info)
  226.  
  227.     def ban(player, admin, dur=0, comment=False):
  228.         target = player
  229.         admin = Player(admin)
  230.         steamid = steamid_from_networkid(target.steamid)
  231.         if bans.isbanned(steamid):
  232.             SayText2(message="\x05EgN Jailbreak| \x01That player is already CT banned.").send(RecipientFilter(admin.index))
  233.             return False
  234.         if not auth.isImmune(admin.steamid, target.steamid):
  235.             SayText2(message="\x05EgN Jailbreak| \x01Target is immune.").send(RecipientFilter(admin.index))
  236.             return False
  237.         SayText2(message="\x05EgN Jailbreak| \x01Your CT ban is being processed.").send(RecipientFilter(admin.index))
  238.         try:
  239.             BanQuery(steamid, target.name, admin, dur, comment).start()
  240.         except:
  241.             log.Write("Couldn't execute ban '{0}' '{1}' '{2}'".format(steamid, admin, dur))
  242.             return False
  243.         target.team = 2
  244.         HintText(message="You have been banned from CT!").send(RecipientFilter(target.index))
  245.                    
  246.     def isbanned(self, steamid):
  247.         steamid = steamid_from_networkid(steamid)
  248.         bans = self.player(steamid)
  249.         if bans[0] > 0:
  250.             for x in bans[1]:
  251.                 if x["unban"]:
  252.                     continue
  253.                 if x["duration"] == 0:
  254.                     return True
  255.                 elif x["time"] + x["duration"] > time.time():
  256.                     return True
  257.         return False
  258.  
  259. bans = Bans()
  260. bans.refresh()
  261.  
  262. def players(index):
  263.     admin = Player(index)
  264.     valid = list()
  265.     for player in PlayerIter():
  266.         if "BOT" in player.steamid:
  267.             continue
  268.         if not auth.isImmune(admin.steamid, player.steamid):
  269.             continue
  270.         if bans.isbanned(player.steamid):
  271.             valid.append((True, player))
  272.             continue
  273.         valid.append((False, player))
  274.     return valid
  275.  
  276. class PlayerMenu(AudiblePagedMenu):
  277.     def __init__(self):
  278.         super().__init__(select_callback = self.select_callback, exit_callback = self.exit_callback, top_separator=" "*40, bottom_separator=" ")
  279.  
  280.     def _select(self, ply_index, choice):
  281.         if choice in (0, 10):
  282.             EXITSOUND.play(ply_index)
  283.             MainMenu().send(ply_index)
  284.             return None
  285.         return super()._select(ply_index, choice)
  286.  
  287.     def send(self, index):
  288.         self.description = "Select a Player to CT Ban:"
  289.         self[:] = [PagedOption(p[1].name, highlight=False if bool(p[0]) else True) for num, p in enumerate(players(index))]
  290.         super().send(index)
  291.  
  292.     def select_callback(self, self2, index, option):
  293.         if option.highlight:
  294.             LengthMenu(get_player_from_name(option.text)).send(index)
  295.         else:
  296.             SayText2(message="\x05EgN Jailbreak| \x01That player is already CT banned.").send(RecipientFilter(index))
  297.  
  298.     def exit_callback(self, *args):
  299.         self.send()
  300.  
  301. class LengthMenu(AudiblePagedMenu):
  302.     def __init__(self, player):
  303.         self.player = player
  304.         super().__init__(select_callback = self.select_callback, exit_callback = self.exit_callback, top_separator=" "*40, bottom_separator=" ")
  305.  
  306.     def _select(self, ply_index, choice):
  307.         if choice in (0, 10):
  308.             EXITSOUND.play(ply_index)
  309.             MainMenu().send(ply_index)
  310.             return None
  311.         return super()._select(ply_index, choice)
  312.  
  313.     def send(self, index):
  314.         self.description = "Select the length of the Ban:"
  315.         self[:] = [PagedOption(s, highlight=True) for num, s in enumerate(["30m", "1h", "12h", "1d", "3d", "1w", "Permanent"])]
  316.         super().send(index)
  317.  
  318.     def select_callback(self, self2, index, option):
  319.         if option.text in "Permanent":
  320.             duration = 0
  321.         else:
  322.             duration = timeparser(option.text)
  323.         ReasonMenu(self.player, duration).send(index)
  324.  
  325.     def exit_callback(self, *args):
  326.         self.send()
  327.  
  328. class ReasonMenu(AudiblePagedMenu):
  329.     def __init__(self, player, length):
  330.         self.player = player
  331.         self.length = length
  332.         super().__init__(select_callback = self.select_callback, exit_callback = self.exit_callback, top_separator=" "*40, bottom_separator=" ")
  333.  
  334.     def _select(self, ply_index, choice):
  335.         if choice in (0, 10):
  336.             EXITSOUND.play(ply_index)
  337.             MainMenu().send(ply_index)
  338.             return None
  339.         return super()._select(ply_index, choice)
  340.  
  341.     def send(self, index):
  342.         self.description = "Select the reason for the Ban:"
  343.         self[:] = [PagedOption(s, highlight=True) for num, s in enumerate(["Gun Plant", "Freekill", "Camping Secrets", "Camping Armory", "Freeshooting", "False Orders", "Gunspam"])]
  344.         super().send(index)
  345.  
  346.     def select_callback(self, self2, index, option):
  347.         Bans.ban(player=self.player, admin=index, dur=self.length, comment=option.text)
  348.         self.send(index)
  349.  
  350.     def exit_callback(self, *args):
  351.         self.send()
  352.  
  353. class MainMenu(SimpleMenu):
  354.     def __init__(self):
  355.         super().__init__(select_callback = self.select_callback, build_callback = self.build_callback)
  356.  
  357.     def build_callback(self, *args):
  358.         self.clear()
  359.         self += ["CTBans",
  360.         " "]
  361.         self.append(SimpleOption(1, 'CT Ban a Player'))
  362.         self += [" ",
  363.         "0. Exit"]
  364.  
  365.     def select_callback(self, self2, index, option, *args):
  366.         SELECTSOUND.play(index)
  367.         PlayerMenu().send(index)
  368.  
  369. @OnLevelShutdown
  370. def listen_new_map():
  371.     bans.refresh()
  372.  
  373. @Event("round_end")
  374. def round_event(event):
  375.     for player in PlayerIter():
  376.         if bans.isbanned(player.steamid) and player.team == 3:
  377.             player.team = 2
  378.  
  379. #@ClientCommand('jointeam')
  380. #def jointeam_callback(command, index):
  381. #   player = Player(index)
  382. #   if int(command[1]) == 3 and bans.isbanned(player.steamid):
  383. #       player.team = 2
  384. #       SayText2(message="\x05EgN Jailbreak| \x01You are banned from joining the Counter Terrorist team.").send(RecipientFilter(index))
  385. #       HintText(message="You are banned from CT!").send(RecipientFilter(index))
  386. #       DENIEDSOUND.play(RecipientFilter(index))
  387. #       return CommandReturn.BLOCK
  388.  
  389. def get_player_from_name(name):
  390.     for player in PlayerIter():
  391.         if name.lower() in player.name.lower():
  392.             return player
  393.  
  394. def command_callback(command, index):
  395.     admin = Player(index)
  396.     if auth.hasFlag(admin.steamid, "ctban"):
  397.         args = tuple(command)[1:]
  398.         if len(args) == 0:
  399.             MainMenu().send(index)
  400.         else:
  401.             player = get_player_from_name(args[0])
  402.             duration = timeparser(args[1])
  403.             reason = " ".join(args[2:])
  404.             Bans.ban(player=player, admin=admin, dur=duration, comment=reason)
  405.     else:
  406.         DENIEDSOUND.play(RecipientFilter(index))
  407.         SayText2(message="\x05EgN Jailbreak| \x01You do not have permission to execute this command.").send(RecipientFilter(index))
  408.  
  409. @SayCommand('!ctban')
  410. def say_command(command, index, teamonly):
  411.     command_callback(command, index)
  412.    
  413. @SayCommand('/ctban')
  414. def say_command(command, index, teamonly):
  415.     command_callback(command, index)
  416.     return CommandReturn.BLOCK
  417.  
  418. @ClientCommand("egn_ctban")
  419. def say_command(command, index):
  420.     command_callback(command, index)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement