Compare commits
11 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4027cf7268 | ||
|
|
c76f8373ef | ||
|
|
a59f67785c | ||
|
|
f7626300ea | ||
|
|
14b6c6905a | ||
|
|
513996a351 | ||
|
|
3bc7963a7a | ||
|
|
37d425bb65 | ||
|
|
b3b6d15a32 | ||
|
|
a85194d7be | ||
|
|
760dc48968 |
@@ -125,8 +125,9 @@ def on_player_chat(event):
|
||||
data = safe_open_json()
|
||||
if event.isCancelled():
|
||||
return
|
||||
if not data[playerid]:
|
||||
if not playerid in data:
|
||||
return
|
||||
|
||||
event.setMessage(multiple_replace(data[playerid], event.getMessage()))
|
||||
|
||||
if (event.getPlayer().hasPermission("essentials.chat.color")):
|
||||
@@ -135,4 +136,3 @@ def on_player_chat(event):
|
||||
event.setCancelled(True)
|
||||
plugin_header(recipient=event.getPlayer(), name="Chat Alias")
|
||||
msg(event.getPlayer(), "&7The message generated was too long and was not sent. :/")
|
||||
|
||||
|
||||
129
login.py
Normal file
129
login.py
Normal file
@@ -0,0 +1,129 @@
|
||||
from wrapper import *
|
||||
from passlib.hash import pbkdf2_sha256 as crypt
|
||||
|
||||
@event_handler("player_login","normal", utils = True)
|
||||
def player_join(*args):
|
||||
player = args[1]
|
||||
if not player.registered:
|
||||
player.authenticated = True
|
||||
player.msg("Successfully logged in!")
|
||||
|
||||
"""
|
||||
@event_handler("player.PlayerCommandPreprocessEvent", "lowest")
|
||||
def on_login_command(event):
|
||||
player = event.player
|
||||
password = event.message.replace("/login", "").replace(" ", "")
|
||||
event.message = event.player.name + " Attempting to login!"
|
||||
event.cancelled = True
|
||||
|
||||
@async(daemon = True)
|
||||
def check_pass(player, password):
|
||||
print password
|
||||
if not player.registered:
|
||||
player.msg("You are not registered! use /register <password> to register!")
|
||||
return
|
||||
else:
|
||||
if crypt.verify(password, player.password):
|
||||
player.authenticated = True
|
||||
player.msg("Successfully logged in!")
|
||||
else:
|
||||
print event.message
|
||||
player.msg("Wrong password!")
|
||||
check_pass(player, password)"""
|
||||
|
||||
@command("login")
|
||||
@async(daemon = True)
|
||||
def on_login_command(**kwargs):
|
||||
player = kwargs["sender"]
|
||||
args = kwargs["args"]
|
||||
|
||||
if not player.registered:
|
||||
player.msg("You are not registered! use /register <password> to register!")
|
||||
return
|
||||
if len(args) > 1:
|
||||
player.msg("The syntax is /login <password>")
|
||||
return
|
||||
elif len(args) is 1:
|
||||
if crypt.verify(args[0], player.password):
|
||||
player.authenticated = True
|
||||
player.msg("Successfully logged in!")
|
||||
else:
|
||||
player.msg("Wrong password!")
|
||||
|
||||
@command("changepass")
|
||||
@async(daemon = True)
|
||||
def on_changepass_command(**kwargs):
|
||||
player = kwargs["sender"]
|
||||
args = kwargs["args"]
|
||||
|
||||
if not player.registered:
|
||||
player.msg("You are not registered! use /register <password> to register!")
|
||||
return
|
||||
|
||||
if len(args) < 2:
|
||||
player.msg("The syntax is /login <current_password> <new_password>")
|
||||
return
|
||||
elif len(args) is 2:
|
||||
if crypt.verify(args[0], player.password):
|
||||
player.password = crypt.encrypt(args[1], rounds=200000, salt_size=16)
|
||||
player.msg("Successfully changed your password!")
|
||||
player.save()
|
||||
else:
|
||||
player.msg("You have entered an incorrect current password!")
|
||||
|
||||
@command("removepass")
|
||||
@async(daemon = True)
|
||||
def on_removepass_command(**kwargs):
|
||||
player = kwargs["sender"]
|
||||
args = kwargs["args"]
|
||||
|
||||
if not player.registered:
|
||||
player.msg("You are not registered! use /register <password> to register!")
|
||||
return
|
||||
|
||||
if len(args) < 1:
|
||||
player.msg("The syntax is /removepass <current_password>")
|
||||
return
|
||||
|
||||
elif len(args) is 1:
|
||||
if crypt.verify(args[0], player.password):
|
||||
player.password = "None"
|
||||
player.registered = False
|
||||
player.save()
|
||||
player.msg("Successfully removed your password!")
|
||||
else:
|
||||
player.msg("You have entered an incorrect current password!")
|
||||
|
||||
|
||||
|
||||
|
||||
@command("register")
|
||||
@async(daemon = True)
|
||||
def on_register_command(**kwargs):
|
||||
player = kwargs["sender"]
|
||||
args = kwargs["args"]
|
||||
if len(args) > 1:
|
||||
player.msg("The syntax is /register <password>")
|
||||
return
|
||||
elif len(args) is 1:
|
||||
if player.registered:
|
||||
player.msg("You are already registered!")
|
||||
return
|
||||
player.password = crypt.encrypt(args[0], rounds=200000, salt_size=16)
|
||||
player.registered = True
|
||||
print player.password
|
||||
player.save()
|
||||
player.msg("Successfully registered!")
|
||||
|
||||
|
||||
blocked_events = ["block.BlockBreakEvent", "block.BlockPlaceEvent", "player.PlayerMoveEvent",
|
||||
"player.AsyncPlayerChatEvent","player.PlayerTeleportEvent",
|
||||
"player.PlayerInteractEvent"]
|
||||
|
||||
for event in blocked_events:
|
||||
@event_handler(event_name = event, priority = "highest")
|
||||
def on_blocked_event(event):
|
||||
if not event.player.authenticated:
|
||||
event.cancelled = True
|
||||
|
||||
|
||||
275
loginsecurity.py
275
loginsecurity.py
@@ -1,275 +0,0 @@
|
||||
from helpers import *
|
||||
from passlib.hash import pbkdf2_sha256 as crypt
|
||||
from basecommands import simplecommand
|
||||
import time
|
||||
import threading
|
||||
from login_secrets import * #Don't forget to make login_secrets aswell
|
||||
import mysqlhack
|
||||
from com.ziclix.python.sql import zxJDBC
|
||||
from java.lang import Runnable
|
||||
|
||||
wait_time = 60 #seconds
|
||||
admin_perm = "utils.loginsecurity.admin"
|
||||
min_pass_length = 8
|
||||
blocked_events = ["block.BlockBreakEvent", "block.BlockPlaceEvent", "player.PlayerMoveEvent","player.AsyncPlayerChatEvent"]
|
||||
|
||||
|
||||
|
||||
|
||||
def matches(password,user):
|
||||
thread = threading.Thread(target=matches_thread, args = (password,user))
|
||||
thread.start()
|
||||
|
||||
|
||||
def matches_thread(password, user):
|
||||
hashed = get_pass(uid(user))
|
||||
py_player = get_py_player(user)
|
||||
if crypt.verify(password, hashed):
|
||||
if py_player.logging_in:
|
||||
py_player.logging_in = False
|
||||
msg(user, "&aLogged in successfully!")
|
||||
else:
|
||||
if py_player.logging_in:
|
||||
msg(user, "&cInvalid password!")
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@simplecommand("cgpass",
|
||||
usage = "<password> <new password>",
|
||||
description = "Changes your password",
|
||||
senderLimit = 0,
|
||||
helpNoargs = True)
|
||||
def change_pass_command(sender, command, label, args):
|
||||
|
||||
py_player = get_py_player(sender)
|
||||
|
||||
if py_player.logging_in:
|
||||
return "&cYou are not logged in"
|
||||
if not len(args) == 2:
|
||||
return "&cInvalid arguments"
|
||||
|
||||
password = args[0]
|
||||
new_password = args[1]
|
||||
uuid = uid(sender)
|
||||
|
||||
if is_registered(uuid):
|
||||
change_pass(uuid, crypt.encrypt(new_password, rounds=200000, salt_size=16))
|
||||
return "&aPassword changed"
|
||||
return "&cYou are not registered"
|
||||
|
||||
|
||||
|
||||
|
||||
@simplecommand("login",
|
||||
usage = "<password>",
|
||||
description = "Logs you in if <password> matches your password.",
|
||||
senderLimit = 0,
|
||||
helpNoargs = True)
|
||||
def login_command(sender, command, label, args):
|
||||
py_player = get_py_player(sender)
|
||||
|
||||
if not py_player.logging_in:
|
||||
msg(sender,"&cAlready logged in!")
|
||||
|
||||
password = args[0]
|
||||
matches(password, sender)
|
||||
|
||||
|
||||
|
||||
|
||||
@simplecommand("register",
|
||||
usage = "<password>",
|
||||
description = "Registers you with <password>. Next time you join, log in with /login",
|
||||
senderLimit = 0,
|
||||
helpNoargs = True)
|
||||
def register_command(sender, command, label, args):
|
||||
|
||||
py_player = get_py_player(sender)
|
||||
|
||||
if len(args) > 1:
|
||||
return "&cPassword can only be one word!"
|
||||
|
||||
uuid = uid(sender)
|
||||
if is_registered(uuid):
|
||||
return "&cYou are already registered!"
|
||||
|
||||
password = args[0]
|
||||
|
||||
if len(password) < min_pass_length:
|
||||
return "&cThe password has to be made up of at least %s characters!" % min_pass_length
|
||||
|
||||
create_pass(uuid, password)
|
||||
return "&cPassword set. Use /login <password> upon join."
|
||||
|
||||
|
||||
|
||||
|
||||
@simplecommand("rmpass",
|
||||
description = "Removes your password if the password matches",
|
||||
senderLimit = 0,
|
||||
amax = 0,
|
||||
helpNoargs = False)
|
||||
def rmpass_command(sender, command, label, args):
|
||||
|
||||
py_player = get_py_player(sender)
|
||||
|
||||
if py_player.logging_in:
|
||||
return "&cYou are not logged in"
|
||||
|
||||
if not is_registered(uid(sender)):
|
||||
return "&cYou are not registered!"
|
||||
|
||||
if py_player.logging_in == False:
|
||||
delete_pass(uid(sender))
|
||||
return "&aPassword removed successfully. You will not be prompted anymore."
|
||||
return "&cFailed to remove password, please contact a staff member"
|
||||
|
||||
|
||||
|
||||
|
||||
@simplecommand("rmotherpass",
|
||||
aliases = ["lacrmpass"],
|
||||
usage = "<user>",
|
||||
senderLimit = -1,
|
||||
description = "Removes password of <user> and sends them a notification",
|
||||
helpNoargs = True)
|
||||
def rmotherpass_command(sender, command, label, args):
|
||||
|
||||
py_player = get_py_player(sender)
|
||||
|
||||
if py_player.logging_in:
|
||||
return "&cYou are not logged in"
|
||||
|
||||
if not sender.hasPermission(admin_perm):
|
||||
noperm(sender)
|
||||
return
|
||||
|
||||
user = server.getOfflinePlayer(args[0])
|
||||
|
||||
if is_registered(uid(user)):
|
||||
delete_pass(uid(user))
|
||||
runas(server.getConsoleSender(), colorify("mail send %s &cYour password was reset by a staff member. Use &6/register&c to set a new one." % user.getName()))
|
||||
return "&aPassword of %s reset successfully" % user.getName()
|
||||
return "&cThat player could not be found (or is not registered)"
|
||||
|
||||
def change_pass(uuid, pw):
|
||||
conn = zxJDBC.connect(mysql_database, mysql_user, mysql_pass, "com.mysql.jdbc.Driver")
|
||||
curs = conn.cursor()
|
||||
curs.execute("UPDATE secret SET pass = ? WHERE uuid = ?", (pw,uuid,))
|
||||
conn.commit()
|
||||
curs.close()
|
||||
conn.close()
|
||||
|
||||
def get_pass(uuid):
|
||||
conn = zxJDBC.connect(mysql_database, mysql_user, mysql_pass, "com.mysql.jdbc.Driver")
|
||||
curs = conn.cursor()
|
||||
curs.execute("SELECT pass FROM secret WHERE uuid = ?", (uuid,))
|
||||
results = curs.fetchall()
|
||||
curs.close()
|
||||
conn.close()
|
||||
return results[0][0]
|
||||
|
||||
def create_pass(uuid,pw):
|
||||
thread = threading.Thread(target=create_pass_thread, args=(uuid,pw))
|
||||
thread.start()
|
||||
|
||||
def create_pass_thread(uuid, pw):
|
||||
pw = crypt.encrypt(pw, rounds=200000, salt_size=16)
|
||||
conn = zxJDBC.connect(mysql_database, mysql_user, mysql_pass, "com.mysql.jdbc.Driver")
|
||||
curs = conn.cursor()
|
||||
curs.execute("INSERT INTO secret VALUES (?,?)", (uuid,pw,))
|
||||
conn.commit()
|
||||
curs.close()
|
||||
conn.close()
|
||||
|
||||
def is_registered(uuid):
|
||||
conn = zxJDBC.connect(mysql_database, mysql_user, mysql_pass, "com.mysql.jdbc.Driver")
|
||||
curs = conn.cursor()
|
||||
curs.execute("SELECT EXISTS(SELECT * FROM secret WHERE uuid = ?)", (uuid,))
|
||||
results = curs.fetchall()
|
||||
curs.close()
|
||||
conn.close()
|
||||
if results[0][0] == 1:
|
||||
return True
|
||||
return False
|
||||
|
||||
def delete_pass(uuid):
|
||||
conn = zxJDBC.connect(mysql_database, mysql_user, mysql_pass, "com.mysql.jdbc.Driver")
|
||||
curs = conn.cursor()
|
||||
curs.execute("DELETE FROM secret WHERE uuid = ?", (uuid,))
|
||||
conn.commit()
|
||||
curs.close()
|
||||
conn.close()
|
||||
|
||||
@hook.event("player.PlayerJoinEvent", "highest")
|
||||
def on_join(event):
|
||||
user = event.getPlayer()
|
||||
py_player = get_py_player(event.getPlayer())
|
||||
if is_registered(uid(user)):
|
||||
msg(event.getPlayer(), "&4You will be disconnected after 60 seconds if you don't &alogin")
|
||||
msg(user, "&cUse /login <password>")
|
||||
py_player.logging_in = True
|
||||
py_player.login_time = time.time()
|
||||
return
|
||||
elif user.hasPermission(admin_perm):
|
||||
pass #Do what? force them to make a password, lots of code, maybe just message us on slack?
|
||||
|
||||
#This shouldn't be needed anymore as py_player gets removed anyway.
|
||||
"""
|
||||
|
||||
@hook.event("player.PlayerQuitEvent", "high")
|
||||
def on_quit(event):
|
||||
if event.getPlayer().getName() in logging_in:
|
||||
del logging_in[event.getPlayer().getName()]
|
||||
"""
|
||||
|
||||
##Threading start
|
||||
class kick_class(Runnable):
|
||||
|
||||
def __init__(self, player):
|
||||
self.player = player
|
||||
|
||||
def run(self):
|
||||
if self.player.isOnline():
|
||||
self.player.kickPlayer(colorify("&aLogin timed out"))
|
||||
|
||||
def kick_thread():
|
||||
while True:
|
||||
time.sleep(1)
|
||||
now = time.time()
|
||||
for py_player in py_players:
|
||||
if py_player.logging_in:
|
||||
if now - py_player.login_time > wait_time:
|
||||
player = py_player.player
|
||||
kick = kick_class(player)
|
||||
server.getScheduler().runTask(server.getPluginManager().getPlugin("RedstonerUtils"), kick)
|
||||
|
||||
|
||||
"""if name in logging_in:
|
||||
del logging_in[name]
|
||||
break
|
||||
"""
|
||||
|
||||
|
||||
thread = threading.Thread(target = kick_thread)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
##Threading end
|
||||
|
||||
for blocked_event in blocked_events:
|
||||
@hook.event(blocked_event, "high")
|
||||
def on_blocked_event(event):
|
||||
user = get_py_player(event.getPlayer())
|
||||
if user.logging_in:
|
||||
event.setCancelled(True)
|
||||
|
||||
@hook.event("player.PlayerCommandPreprocessEvent","normal")
|
||||
def pre_command_proccess(event):
|
||||
player = get_py_player(event.getPlayer())
|
||||
if player.logging_in:
|
||||
args = event.getMessage().split(" ")
|
||||
if not args[0].lower() == "/login":
|
||||
msg(player.player, "&4You need to login before you do that!")
|
||||
event.setCancelled(True)
|
||||
13
main.py
13
main.py
@@ -11,12 +11,10 @@ sys.path += ['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/usr/l
|
||||
try:
|
||||
# Library that adds a bunch of re-usable methods which are used in nearly all other modules
|
||||
from helpers import *
|
||||
from wrapper import *
|
||||
#from wrapper import *
|
||||
except:
|
||||
print("[RedstonerUtils] ERROR: Failed to import Wrapper:")
|
||||
print(print_traceback())
|
||||
|
||||
|
||||
error("[RedstonerUtils] ERROR: Failed to import Wrapper:")
|
||||
error(print_traceback())
|
||||
|
||||
@hook.enable
|
||||
def on_enable():
|
||||
@@ -34,7 +32,10 @@ info("Loading RedstonerUtils...")
|
||||
|
||||
|
||||
# Import all modules, in this order
|
||||
shared["load_modules"] = ["test"]
|
||||
shared["load_modules"] = [
|
||||
"test",
|
||||
# "login",
|
||||
]
|
||||
|
||||
shared["modules"] = {}
|
||||
for module in shared["load_modules"]:
|
||||
|
||||
@@ -13,11 +13,23 @@ class mysql_connect:
|
||||
if args is None:
|
||||
return self.curs.execute(query)
|
||||
else:
|
||||
print query
|
||||
print args
|
||||
return self.curs.execute(query, args)
|
||||
|
||||
def fetchall(self):
|
||||
return self.curs.fetchall()
|
||||
|
||||
@property
|
||||
def columns(self):
|
||||
self.execute("SHOW COLUMNS FROM utils_players")
|
||||
fetched = self.fetchall()
|
||||
columns = []
|
||||
|
||||
for row in fetched:
|
||||
columns.append(row[0])
|
||||
return columns
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
|
||||
@@ -5,6 +5,14 @@ import java.util.UUID as UUID
|
||||
import org.bukkit.Material as Material
|
||||
import org.bukkit.block.BlockFace as BlockFace
|
||||
|
||||
"""
|
||||
# About permissions:
|
||||
# To use the command, the user needs to have utils.serversigns.
|
||||
# To use ANY subcommand, the user needs to have utils.serversigns.<subcommand> IN ADDITION to the previously mentioned node.
|
||||
# To be able to add commands as messages to a sign, a user will need the node utils.serversigns.command.
|
||||
# To be able to claim a sign for another player or to edit signs that the user doesn't own, they will need utils.serversigns.admin.
|
||||
"""
|
||||
|
||||
blocked_cmds = ("pex", "kick", "ban", "tempban", "pyeval", "sudo", "stop", "reload", "op", "deop", "whitelist")
|
||||
|
||||
def load_signs():
|
||||
@@ -24,6 +32,18 @@ signs = load_signs() # {("world", x, y, z): ["owner_id", "msg1", "msg2"]}
|
||||
|
||||
lines = {} # Accumulated messages so players can have longer messages: {"Dico200": "Message...........", ""}
|
||||
|
||||
@hook.enable
|
||||
def check_all_signs():
|
||||
# Check if all saved signs actually represent a sign block. There are ways to break the signs without the plugin knowing.
|
||||
for loc in dict(signs): # Can't change dict size during iteration, using a copy
|
||||
world = server.getWorld(loc[0])
|
||||
if world and world.getBlockAt(loc[1], loc[2], loc[3]).getType() in (Material.SIGN_POST, Material.WALL_SIGN):
|
||||
continue
|
||||
del signs[loc]
|
||||
info("[Server Signs] Couldn't find a %s, removed the data for the sign that was once there." % identifySign(loc))
|
||||
save_signs()
|
||||
|
||||
|
||||
def fromLoc(bLoc):
|
||||
"""
|
||||
# Returns a tuple containing the (bukkit)location's world's name and its x, y and z coordinates
|
||||
@@ -222,9 +242,6 @@ def svs_command(sender, command, label, args):
|
||||
return signsMsg("Removed all messages and the owner from the %s, it can now be claimed" % signName, 'a')
|
||||
#-------------------------------------------------------------------------------------------------------
|
||||
|
||||
|
||||
|
||||
|
||||
@hook.event("player.PlayerInteractEvent")
|
||||
def on_click(event):
|
||||
if str(event.getAction()) != "RIGHT_CLICK_BLOCK":
|
||||
@@ -254,25 +271,22 @@ faces = {
|
||||
|
||||
@hook.event("block.BlockBreakEvent", "monitor")
|
||||
def on_break(event):
|
||||
try:
|
||||
global checking_block
|
||||
if checking_block or event.isCancelled():
|
||||
return
|
||||
global checking_block
|
||||
if checking_block or event.isCancelled():
|
||||
return
|
||||
|
||||
block = event.getBlock()
|
||||
if block.getType() in (Material.SIGN_POST, Material.WALL_SIGN):
|
||||
check_sign(event, block, attached = False)
|
||||
block = event.getBlock()
|
||||
if block.getType() in (Material.SIGN_POST, Material.WALL_SIGN):
|
||||
check_sign(event, block, attached = False)
|
||||
|
||||
for block_face, data_values in faces.iteritems():
|
||||
block2 = block.getRelative(block_face)
|
||||
if block2.getType() == Material.WALL_SIGN and block2.getData() in data_values:
|
||||
check_sign(event, block2)
|
||||
for block_face, data_values in faces.iteritems():
|
||||
block2 = block.getRelative(block_face)
|
||||
if block2.getType() == Material.WALL_SIGN and block2.getData() in data_values:
|
||||
check_sign(event, block2)
|
||||
|
||||
block3 = block.getRelative(BlockFace.UP)
|
||||
if block3.getType() == Material.SIGN_POST:
|
||||
check_sign(event, block3)
|
||||
except:
|
||||
error(trace())
|
||||
block3 = block.getRelative(BlockFace.UP)
|
||||
if block3.getType() == Material.SIGN_POST:
|
||||
check_sign(event, block3)
|
||||
|
||||
|
||||
def check_sign(event, block, attached = True):
|
||||
@@ -287,6 +301,7 @@ def check_sign(event, block, attached = True):
|
||||
save_signs()
|
||||
msg(player, signsMsg("Reset the %s which you just broke" % identifySign(loc)))
|
||||
|
||||
|
||||
def can_build2(player, block):
|
||||
global checking_block
|
||||
event = BlockBreakEvent(block, player)
|
||||
|
||||
2
setup.sh
2
setup.sh
@@ -91,7 +91,7 @@ echo -e "\n> All plugins downloaded"
|
||||
|
||||
cd "redstoner-utils.py.dir"
|
||||
echo -e "\n> Duplicating sample files"
|
||||
for file in ls ./*.example; do
|
||||
for file in ./*.example; do
|
||||
cp -v "$file" "$(echo "$file" | rev | cut -d "." -f 2- | rev)"
|
||||
done
|
||||
|
||||
|
||||
80
util_events.py
Normal file
80
util_events.py
Normal file
@@ -0,0 +1,80 @@
|
||||
from thread_utils import *
|
||||
|
||||
MONITOR_PRIORITY = "monitor"
|
||||
HIGHEST_PRIORITY = "highest"
|
||||
HIGH_PRIORITY = "high"
|
||||
NORMAL_PRIORITY = "normal"
|
||||
LOW_PRIORITY = "low"
|
||||
LOWEST_PRIORITY = "lowest"
|
||||
|
||||
priorities = ["lowest","low","normal","high","highest","monitor"]
|
||||
events = []
|
||||
|
||||
class base_event():
|
||||
def __init__(self,event_name):
|
||||
self.name = event_name
|
||||
self.cancelled = False
|
||||
self._handlers = [ [],[],[],[],[],[] ]
|
||||
|
||||
self.cancelled_lock = threading.Lock()
|
||||
|
||||
def add_handler(self,function,priority):
|
||||
for prior in priorities:
|
||||
if prior == priority:
|
||||
self._handlers[priorities.index(prior)].append(function)
|
||||
|
||||
def fire(self,*args):
|
||||
for priority in self._handlers:
|
||||
for handler in priority:
|
||||
handler(self,*args)
|
||||
|
||||
def set_cancelled(self,state):
|
||||
with self.cancelled_lock:
|
||||
self.cancelled = state
|
||||
|
||||
|
||||
class utils_events(base_event):
|
||||
def __init__(self,event_name):
|
||||
base_event.__init__(self,event_name)
|
||||
|
||||
|
||||
def add_event(event_name, event_class = base_event):
|
||||
"""
|
||||
# Adds a new event type of the given class with the given name
|
||||
"""
|
||||
event = event_class(event_name)
|
||||
events.append(event)
|
||||
|
||||
def fire_event(event_name,*args):
|
||||
"""
|
||||
# Calls the ehe event with the given arguments
|
||||
"""
|
||||
for event in events:
|
||||
if event.name == event_name:
|
||||
event.call(*args)
|
||||
return event
|
||||
|
||||
def check_events(event_name):
|
||||
"""
|
||||
# Returns whether there is an event with the name event_name
|
||||
"""
|
||||
for event in events:
|
||||
if event.name == event_name:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
#Decorator
|
||||
def utils_event(event_name, priority, create_event=base_event):
|
||||
def event_decorator(function):
|
||||
def wrapper(*args, **kwargs):
|
||||
pass
|
||||
|
||||
if not check_events(event_name): #Check if the event exists, if not create it.
|
||||
add_event(event_name,create_event)
|
||||
|
||||
for event in events: #Go through the list of events, find the one we need and call all of its handlers
|
||||
if event.name == event_name:
|
||||
event.add_handler(function,priority)
|
||||
return wrapper
|
||||
return event_decorator
|
||||
53
vanish.py
53
vanish.py
@@ -13,7 +13,7 @@ def is_vanished(player):
|
||||
return uid(player) in vanished
|
||||
|
||||
|
||||
#this can be used to silently set the vanished state of a player
|
||||
#this can be used to silently set the vanished state of a player I guess.
|
||||
def set_state(player, state):
|
||||
if state == is_vanished(player):
|
||||
return
|
||||
@@ -37,6 +37,10 @@ def disable_vanish(target):
|
||||
player.showPlayer(target)
|
||||
|
||||
|
||||
def get_online_vanished_players():
|
||||
return (player.getPlayer() for player in (retrieve_player(uuid) for uuid in vanished) if player.isOnline())
|
||||
|
||||
|
||||
@simplecommand("vanish",
|
||||
aliases = ["v"],
|
||||
usage = "[on/off]",
|
||||
@@ -48,45 +52,38 @@ def disable_vanish(target):
|
||||
helpSubcmd = True
|
||||
)
|
||||
def vanish_command(sender, command, label, args):
|
||||
try:
|
||||
current_state = is_vanished(sender)
|
||||
new_state = not current_state
|
||||
current_state = is_vanished(sender)
|
||||
new_state = not current_state
|
||||
|
||||
if len(args) == 1:
|
||||
arg = args[0].lower()
|
||||
if arg == "on":
|
||||
new_state = True
|
||||
elif arg == "off":
|
||||
new_state = False
|
||||
if len(args) == 1:
|
||||
arg = args[0].lower()
|
||||
if arg == "on":
|
||||
new_state = True
|
||||
elif arg == "off":
|
||||
new_state = False
|
||||
|
||||
if current_state == new_state:
|
||||
return "&cYou were %s vanished!" % ("already" if current_state else "not yet")
|
||||
|
||||
set_state(sender, new_state)
|
||||
return "&a%s vanish mode!" % ("Enabled" if new_state else "Disabled")
|
||||
except:
|
||||
error(trace())
|
||||
Validate.isTrue(current_state != new_state, "&cYou were %s vanished!" % ("already" if current_state else "not yet"))
|
||||
set_state(sender, new_state)
|
||||
return "&a%s vanish mode!" % ("Enabled" if new_state else "Disabled")
|
||||
|
||||
|
||||
@hook.event("player.PlayerJoinEvent")
|
||||
def on_player_join(event):
|
||||
player = event.getPlayer()
|
||||
|
||||
if not is_authorized(player):
|
||||
for uuid in vanished:
|
||||
player.hidePlayer(retrieve_player(uuid))
|
||||
|
||||
elif is_vanished(player):
|
||||
msg(player, "&cKeep in mind that you are still vanished! Use /vanish to disable.")
|
||||
for vanished in get_online_vanished_players():
|
||||
player.hidePlayer(vanished)
|
||||
|
||||
|
||||
@hook.event("player.PlayerQuitEvent")
|
||||
def on_player_quit(event):
|
||||
player = event.getPlayer()
|
||||
|
||||
if not is_authorized(player):
|
||||
for uuid in vanished:
|
||||
player.showPlayer(retrieve_player(uuid))
|
||||
for vanished in get_online_vanished_players():
|
||||
player.showPlayer(vanished)
|
||||
|
||||
elif is_vanished(player):
|
||||
disable_vanish(player)
|
||||
|
||||
|
||||
@simplecommand("vanishother",
|
||||
@@ -110,9 +107,7 @@ def vanishother_command(sender, command, label, args):
|
||||
elif arg == "off":
|
||||
new_state = False
|
||||
|
||||
if current_state == new_state:
|
||||
return "&cThat player was already vanished!" if current_state else "&cThat player was not yet vanished!"
|
||||
|
||||
Validate.isTrue(current_state != new_state, "&cThat player was %s vanished!" % ("already" if current_state else "not yet"))
|
||||
set_state(target, new_state)
|
||||
|
||||
enabled_str = "enabled" if new_state else "disabled"
|
||||
|
||||
@@ -8,4 +8,5 @@ Before you run away from this if the class you need to use isn't here, please cr
|
||||
from helpers import *
|
||||
from wrapper_event import *
|
||||
from wrapper_player import *
|
||||
from wrapper_command import *
|
||||
from wrapper_command import *
|
||||
from util_events import utils_event, fire_event, utils_events
|
||||
@@ -1,11 +1,328 @@
|
||||
from wrapper_player import *
|
||||
from helpers import *
|
||||
|
||||
def command(command = "help"):
|
||||
def decorator(wrapped):
|
||||
@hook.command(command)
|
||||
def wrapper(sender, command, label, args):
|
||||
class Command(object):
|
||||
"""
|
||||
# Documentation to come.s
|
||||
"""
|
||||
|
||||
SENDER_ANY = 0
|
||||
SENDER_PLAYER = 1
|
||||
SENDER_CONSOLE = 2
|
||||
|
||||
ACTION_IGNORE = 3
|
||||
ACTION_SYNTAXERROR = 4
|
||||
ACTION_DISPLAYSYNTAX = 5
|
||||
ACTION_DISPLAYHELP = 6
|
||||
|
||||
def __init__(self,
|
||||
command,
|
||||
parent = None,
|
||||
aliases = tuple(),
|
||||
permission = None,
|
||||
description = "Description",
|
||||
type = 0,
|
||||
no_arg_action = 3,
|
||||
help_request_action = 3,
|
||||
arguments = tuple(),
|
||||
):
|
||||
|
||||
self.command = command.lower()
|
||||
self.aliases = tuple(alias.lower() for alias in aliases)
|
||||
self.description = description
|
||||
self.type = type
|
||||
self.no_arg_action = no_arg_action
|
||||
self.help_request_action = help_request_action
|
||||
self.arguments = arguments
|
||||
self.parent = parent
|
||||
self.sub_commands = Command_dict()
|
||||
|
||||
# ---- Check if argument layout is valid ----
|
||||
prev_arg = arguments[0] if len(arguments) > 0 else None
|
||||
for arg_info in arguments[1:]:
|
||||
|
||||
if not prev_arg.required and arg_info.required:
|
||||
raise Argument_exception("Command: %s; There may not be required arguments after non-required arguments" % command)
|
||||
|
||||
if prev_arg.type == Argument.MESSAGE:
|
||||
raise Argument_exception("Command: %s; An argument of type MESSAGE may not be followed by other arguments" % command)
|
||||
|
||||
prev_arg = arg_info
|
||||
|
||||
# ---- Add self to parent sub_commands and set permission node ----
|
||||
perm_builder = "utils"
|
||||
if self.parent == None:
|
||||
root_commands[self.command] = self
|
||||
else:
|
||||
try:
|
||||
return wrapped(sender = py_players[sender], command = command, label = label, args = args)
|
||||
except:
|
||||
print(print_traceback())
|
||||
return decorator
|
||||
parent_route = self.parent.split(" ")
|
||||
parent_sub_commands = root_commands
|
||||
parent_obj = None
|
||||
for cmd_name in parent_route:
|
||||
parent_obj = parent_sub_commands[cmd_name]
|
||||
parent_sub_commands = parent_obj.sub_commands
|
||||
|
||||
parent_obj.sub_commands[self.command] = self
|
||||
|
||||
except KeyError as e:
|
||||
raise Argument_exception("Error occurred while setting up command hierarchy: " + e.message + "\n" + trace())
|
||||
|
||||
perm_builder += "." + (permission if permission else command).lower()
|
||||
|
||||
def __call__(self, handler):
|
||||
"""
|
||||
# To clarify: This function is called when you 'call' an instance of a class.
|
||||
# This means, that Command() calls __init__() and Command()() calls __call__().
|
||||
# This makes it possible to use class instances for decoration. The decorator is this function.
|
||||
"""
|
||||
self.handler = handler
|
||||
|
||||
if self.parent == None:
|
||||
@hook.command(self.command, aliases = self.aliases)
|
||||
def run(sender, command, label, args):
|
||||
"""
|
||||
# This function will take care of prefixing and colouring of messages in the future.
|
||||
# So it's very much WIP.
|
||||
"""
|
||||
try:
|
||||
message = self.execute(sender, command, label, args)
|
||||
except Command_exception as e:
|
||||
message = e.message
|
||||
except Argument_exception as e:
|
||||
message = e.message
|
||||
except Exception:
|
||||
error(trace())
|
||||
return True
|
||||
if message:
|
||||
sender.sendMessage(message)
|
||||
return True
|
||||
|
||||
return handler
|
||||
|
||||
def execute(self, sender, command, label, args):
|
||||
try:
|
||||
return self.sub_commands[args[0].lower()].execute(sender, command, label, args[1:])
|
||||
except (KeyError, IndexError):
|
||||
return self.execute_checks(sender, command, label, args)
|
||||
|
||||
def execute_checks(self, sender, command, label, args):
|
||||
|
||||
# ---- Check sender type ----
|
||||
if is_player(sender):
|
||||
Validate.is_true(self.type != Command.SENDER_CONSOLE, "That command can only be used by the console")
|
||||
#sender = py_players.__getattr__(sender)
|
||||
else:
|
||||
Validate.is_true(self.type != Command.SENDER_PLAYER, "That command can only be used by players")
|
||||
|
||||
# ---- Check permission ----
|
||||
Validate.is_authorized(sender, self.permission)
|
||||
|
||||
# ---- Check if a help message is expected ----
|
||||
if len(args) == 0:
|
||||
action = self.no_arg_action
|
||||
elif args[0].lower() == "help":
|
||||
action = self.help_request_action
|
||||
else:
|
||||
action = Command.ACTION_IGNORE
|
||||
|
||||
if action != Command.ACTION_IGNORE:
|
||||
if action == Command.ACTION_SYNTAXERROR:
|
||||
return "&cInvalid syntax, please try again."
|
||||
if action == Command.ACTION_DISPLAYSYNTAX:
|
||||
return self.syntax()
|
||||
if action == Command.ACTION_DISPLAYHELP:
|
||||
return self.help()
|
||||
|
||||
# ---- Set up passed arguments, prepare for handler call ----
|
||||
scape = Command_scape(args, self.arguments, command, label)
|
||||
if is_player(sender):
|
||||
#sender = py_players[sender]
|
||||
pass
|
||||
|
||||
return self.handler(sender, self, scape)
|
||||
# @Command("hello") def on_hello_command(sender, command, scape/args)
|
||||
|
||||
def syntax(self):
|
||||
return " ".join(tuple(arg_info.syntax() for arg_info in self.arguments))
|
||||
|
||||
def help(self):
|
||||
syntax = self.syntax()
|
||||
return syntax #WIP...
|
||||
|
||||
class Argument():
|
||||
|
||||
"""
|
||||
# A more advanced implementation of amin and amax, though it doesn't do exactly the same.
|
||||
# You can now pass a list of Argument objects which define what the argument represents.
|
||||
# In the process of doing so, you can set an argument type, one of the ones mentioned below.
|
||||
# For example, if Argument.PLAYER is given, the server will be searched for the given player, and
|
||||
# they will be passed as the argument, instead of a string representing their name.
|
||||
#
|
||||
# Feel free to add your own argument types. If you want to make a change to the API to make it different,
|
||||
# please don't do so on your own behalf.
|
||||
"""
|
||||
|
||||
STRING = 0
|
||||
INTEGER = 1
|
||||
FLOAT = 2
|
||||
PLAYER = 3
|
||||
OFFLINE_PLAYER = 4
|
||||
MESSAGE = 5
|
||||
|
||||
def __init__(self, name, type, definition, required = True):
|
||||
self.name = name
|
||||
self.type = type
|
||||
self.definition = definition
|
||||
self.required = required
|
||||
|
||||
def syntax(self):
|
||||
syntax = self.name
|
||||
if self.type == Argument.MESSAGE:
|
||||
syntax += "..."
|
||||
return (("<%s>" if self.required else "[%s]") % syntax)
|
||||
|
||||
class Validate():
|
||||
|
||||
"""
|
||||
# Much like what you often see in Java.
|
||||
# Instead of having to check if a condition is met, and if not,
|
||||
# sending the player a message and returning true,
|
||||
# You can use one of these methods to check the condition, and
|
||||
# pass a message if it's not met.
|
||||
#
|
||||
# For example:
|
||||
# > if not sender.hasPermission("utils.smth"):
|
||||
# noperm(sender)
|
||||
# return True
|
||||
#
|
||||
# Can be replaced with:
|
||||
# > Validate.is_authorized(sender, "utils.smth")
|
||||
#
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def is_true(expression, fail_message):
|
||||
if not expression:
|
||||
raise Command_exception(fail_message)
|
||||
|
||||
@staticmethod
|
||||
def not_none(obj, fail_message):
|
||||
if obj == None:
|
||||
raise Command_exception(fail_message)
|
||||
|
||||
@staticmethod
|
||||
def is_authorized(player, permission, msg = "You do not have permission to use that command"):
|
||||
if not player.hasPermission(permission):
|
||||
raise Command_exception(msg)
|
||||
|
||||
@staticmethod
|
||||
def is_player(sender):
|
||||
if not is_player(sender):
|
||||
raise Command_exception("That command can only be used by players")
|
||||
|
||||
@staticmethod
|
||||
def is_console(sender):
|
||||
if is_player(sender):
|
||||
raise Command_exception("That command can only be used by the console")
|
||||
|
||||
"""
|
||||
# ---------- API classes ----------
|
||||
"""
|
||||
|
||||
class Command_dict(dict):
|
||||
#{"cmd1" : cmd_object}
|
||||
def __getattr__(self, alias):
|
||||
for cmd_name, cmd_obj in self.iteritems():
|
||||
if alias == cmd_name or alias in cmd_obj.aliases:
|
||||
return cmd_obj
|
||||
raise KeyError("Subcommand '%s' was not found" % alias)
|
||||
|
||||
root_commands = Command_dict() # {"command": command_object}
|
||||
|
||||
class Command_exception(Exception):
|
||||
|
||||
def __init__(self, message):
|
||||
self.message = message
|
||||
|
||||
class Command_scape(list):
|
||||
|
||||
def __init__(self, args, arg_layout, command, label):
|
||||
super(list, self).__init__()
|
||||
self.raw = args
|
||||
self.arg_layout = arg_layout
|
||||
self.command = command
|
||||
self.label = label
|
||||
|
||||
has_message = False
|
||||
for i in range(len(arg_layout)):
|
||||
arg_info = arg_layout[i]
|
||||
|
||||
given = (len(args) >= i + 1)
|
||||
if arg_info.required and not given:
|
||||
raise Argument_exception("You must specify the " + arg_info.name)
|
||||
|
||||
if not given:
|
||||
self.append(None)
|
||||
continue
|
||||
|
||||
given_arg = args[i]
|
||||
arg_type = arg_info.type
|
||||
|
||||
if arg_type == Argument.STRING:
|
||||
self.append(given_arg)
|
||||
|
||||
elif arg_type == Argument.INTEGER:
|
||||
try:
|
||||
value = int(given_arg)
|
||||
except ValueError:
|
||||
raise Argument_exception("The %s has to be a round number" % arg_info.name)
|
||||
self.append(value)
|
||||
|
||||
elif arg_type == Argument.FLOAT:
|
||||
try:
|
||||
value = float(given_arg)
|
||||
except ValueError:
|
||||
raise Argument_exception("The %s has to be a number" % arg_info.name)
|
||||
self.append(value)
|
||||
|
||||
elif arg_type == Argument.PLAYER:
|
||||
target = server.getPlayer(given_arg)
|
||||
if target == None:
|
||||
raise Argument_exception("The %s has to be an online player" % arg_info.name)
|
||||
self.append(target)
|
||||
#self.append(py_players[target])
|
||||
|
||||
elif arg_type == Argument.OFFLINE_PLAYER:
|
||||
try:
|
||||
# Code to get the PY PLAYER by name. Possibly, uid(server.getOfflinePlayer(given_arg)) can be used?
|
||||
pass
|
||||
except KeyError:
|
||||
raise Argument_exception("The %s has to be an existing player" % arg_info.name)
|
||||
self.append(None)
|
||||
|
||||
elif arg_type == Argument.MESSAGE:
|
||||
self.append(" ".join(args[i:]))
|
||||
has_message = True
|
||||
else:
|
||||
error("Argument type not found: %d" % arg_type)
|
||||
raise Argument_exception("A weird thing has happened, please contact an administrator")
|
||||
|
||||
if not has_message:
|
||||
self.remainder = args[len(arg_layout):]
|
||||
else:
|
||||
self.remainder = None
|
||||
|
||||
def has_flag(self, flag, check_all = False):
|
||||
return (("-" + flag) in self.raw) if check_all else (("-" + flag) in self.remainder)
|
||||
|
||||
def get_raw(self):
|
||||
return self.raw
|
||||
|
||||
def get_arg_layout(self):
|
||||
return self.arg_layout
|
||||
|
||||
class Argument_exception(Exception):
|
||||
|
||||
def __init__(self, message):
|
||||
self.message = message
|
||||
|
||||
|
||||
@@ -1,22 +1,56 @@
|
||||
from wrapper import *
|
||||
from util_events import utils_event, utils_events
|
||||
from wrapper_player import *
|
||||
from traceback import format_exc as print_traceback
|
||||
|
||||
class py_event:
|
||||
def __init__(self,event):
|
||||
self.event = event
|
||||
try:
|
||||
self.player = py_players[event.getPlayer()]
|
||||
except:
|
||||
warn("Player doesn't exist")
|
||||
class py_event(object):
|
||||
def __init__(self,event):
|
||||
self.event = event
|
||||
try:
|
||||
self.player = py_players[event.getPlayer()]
|
||||
except:
|
||||
warn("Player doesn't exist")
|
||||
|
||||
@property
|
||||
def cancelled(self):
|
||||
return self.event.isCancelled()
|
||||
|
||||
@cancelled.setter
|
||||
def cancelled(self, value):
|
||||
self.event.setCancelled(value)
|
||||
|
||||
@property
|
||||
def message(self):
|
||||
try:
|
||||
return self.event.getMessage()
|
||||
except:
|
||||
raise AttributeError
|
||||
|
||||
@message.setter
|
||||
def message(self, msg):
|
||||
try:
|
||||
self.event.setMessage(msg)
|
||||
except:
|
||||
raise AttributeError
|
||||
|
||||
def event_handler(event_name = None, priority = "normal", utils = False):
|
||||
if not utils:
|
||||
def decorator(wrapped):
|
||||
@hook.event(event_name, priority)
|
||||
def wrapper(event):
|
||||
try:
|
||||
wrapped(py_event(event))
|
||||
except:
|
||||
print(print_traceback())
|
||||
return decorator
|
||||
elif utils:
|
||||
def decorator(wrapped):
|
||||
@utils_event(event_name, priority, create_event = utils_events)
|
||||
def wrapper(*args):
|
||||
try:
|
||||
wrapped(*args)
|
||||
except:
|
||||
print(print_traceback())
|
||||
return decorator
|
||||
|
||||
def event_handler(event_name = None, priority = "normal"):
|
||||
def decorator(wrapped):
|
||||
@hook.event(event_name, priority)
|
||||
def wrapper(event):
|
||||
try:
|
||||
wrapped(py_event(event))
|
||||
except:
|
||||
print(print_traceback())
|
||||
return decorator
|
||||
|
||||
|
||||
@@ -1,29 +1,84 @@
|
||||
import time
|
||||
import mysqlhack
|
||||
from mysql_utils import *
|
||||
from util_events import fire_event
|
||||
from thread_utils import *
|
||||
from players_secret import *
|
||||
#from players_secret import *
|
||||
from datetime import datetime
|
||||
from com.ziclix.python.sql import zxJDBC
|
||||
from traceback import format_exc as print_traceback
|
||||
|
||||
class py_player:
|
||||
class py_player(object):
|
||||
def __init__(self,player):
|
||||
self.player = player
|
||||
self.logging_in = True
|
||||
self.authenticated = False
|
||||
self.login_time = time.time()
|
||||
self.logging_in = False
|
||||
|
||||
self.props = {
|
||||
"uuid":self.uuid,
|
||||
"name":self.name,
|
||||
"nickname":self.name,
|
||||
"registered":False,
|
||||
"password":"None",
|
||||
"banned":False,
|
||||
"banned_reason":None,
|
||||
"played_time":time.time() - self.login_time,
|
||||
"last_login":datetime.now(),
|
||||
"first_seen":datetime.now(),
|
||||
}
|
||||
|
||||
def __setattr__(self, attribute, value):
|
||||
if not attribute in dir(self):
|
||||
if not 'props' in self.__dict__:
|
||||
self.__dict__[attribute] = value
|
||||
else:
|
||||
self.props[attribute] = value
|
||||
else:
|
||||
object.__setattr__(self, attribute, value)
|
||||
|
||||
def __getattr__(self, attribute):
|
||||
try:
|
||||
return self.props[attribute]
|
||||
except:
|
||||
raise AttributeError("Attribute %s does not exist on this py_player" % attribute)
|
||||
|
||||
def save(self):
|
||||
properties = []
|
||||
keys = []
|
||||
columns = []
|
||||
|
||||
with mysql_connect() as sql:
|
||||
columns = sql.columns
|
||||
|
||||
for key, value in self.props.items():
|
||||
if key not in columns:
|
||||
with mysql_connect() as sql:
|
||||
if isinstance(value, int):
|
||||
sql.execute("ALTER TABLE utils_players ADD %s INT" % key)
|
||||
elif isinstance(value, str):
|
||||
sql.execute("ALTER TABLE utils_players ADD %s TEXT" % key)
|
||||
elif isinstance(value, bool):
|
||||
sql.execute("ALTER TABLE utils_players ADD %s TINYINT(1)" % key)
|
||||
if key == "uuid":
|
||||
continue
|
||||
keys.append(key+"=?")
|
||||
properties.append(value)
|
||||
print value
|
||||
properties.append(self.props["uuid"])
|
||||
keys = str(tuple(keys)).replace("\'","").replace("(","").replace(")","")
|
||||
|
||||
|
||||
with mysql_connect() as sql:
|
||||
sql.execute("UPDATE utils_players set %s WHERE uuid = ?" % keys, properties)
|
||||
|
||||
self.nickname = self.name
|
||||
self.registered = False
|
||||
self.password = "None"
|
||||
self.banned = False
|
||||
self.banned_reason = "You have been banned!"
|
||||
self.played_time = time.time() - self.login_time
|
||||
self.last_login = datetime.now()
|
||||
self.first_seen = datetime.now()
|
||||
|
||||
def kick(self, kick_message = "You have been kicked from the server!"):
|
||||
self.player.KickPlayer(kick_message)
|
||||
|
||||
def msg(self, message):
|
||||
self.player.sendMessage(message)
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
return self.player.getName()
|
||||
@@ -31,6 +86,7 @@ class py_player:
|
||||
@property
|
||||
def uuid(self):
|
||||
return str(self.player.getUniqueId())
|
||||
|
||||
|
||||
|
||||
class Py_players:
|
||||
@@ -57,31 +113,72 @@ py_players = Py_players()
|
||||
|
||||
@async(daemon=True)
|
||||
def fetch_player(player):
|
||||
properties = []
|
||||
keys = []
|
||||
for key, value in player.props.iteritems():
|
||||
keys.append(key)
|
||||
properties.append(value)
|
||||
|
||||
with mysql_connect() as sql:
|
||||
sql.execute("SELECT * FROM utils_players WHERE uuid = ?", (player.uuid,))
|
||||
result = sql.fetchall()
|
||||
|
||||
if len(result) is 0:
|
||||
with mysql_connect() as sql:
|
||||
sql.execute("INSERT INTO utils_players \
|
||||
(uuid, name, nickname, registered, password, banned, \
|
||||
banned_reason, played_time, last_login, first_seen) \
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
|
||||
args=(player.uuid, player.name, player.nickname, player.registered,
|
||||
player.password, player.banned,
|
||||
player.banned_reason, player.played_time,
|
||||
player.last_login, player.first_seen))
|
||||
sql.execute("INSERT INTO utils_players %s \
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" % str(tuple(keys)).replace("\'","")
|
||||
,args=tuple(properties))
|
||||
|
||||
elif len(result) is 1:
|
||||
keys = []
|
||||
props = result[0]
|
||||
with mysql_connect() as sql:
|
||||
sql.execute("SHOW COLUMNS FROM utils_players")
|
||||
result = sql.fetchall()
|
||||
for row in result:
|
||||
keys.append(row[0])
|
||||
|
||||
for key in keys:
|
||||
player.props[key] = props[keys.index(key)]
|
||||
|
||||
for prop in properties:
|
||||
print str(prop)
|
||||
|
||||
else:
|
||||
player.kick("Something went wrong while loading your player data, please contact an admin")
|
||||
return
|
||||
|
||||
player.logging_in = False
|
||||
player.msg("You have succesfully logged into redstoner!")
|
||||
fire_event("player_login", player)
|
||||
|
||||
|
||||
|
||||
|
||||
blocked_events = ["block.BlockBreakEvent", "block.BlockPlaceEvent", "player.PlayerMoveEvent",
|
||||
"player.AsyncPlayerChatEvent","player.PlayerTeleportEvent",
|
||||
"player.PlayerCommandPreprocessEvent", "player.PlayerInteractEvent"]
|
||||
|
||||
for event in blocked_events:
|
||||
@hook.event(event,"highest")
|
||||
def on_blocked_event(event):
|
||||
"""player = py_players[event.getPlayer()]
|
||||
if player.logging_in:
|
||||
event.setCancelled(True)"""
|
||||
pass
|
||||
#test
|
||||
|
||||
|
||||
|
||||
@hook.event("player.PlayerJoinEvent","lowest")
|
||||
def on_join(event):
|
||||
player = py_player(event.getPlayer())
|
||||
try:
|
||||
player = py_player(event.getPlayer())
|
||||
except:
|
||||
error(print_traceback())
|
||||
time.sleep(10)
|
||||
py_players.append(player)
|
||||
fetch_player(player)
|
||||
player.msg("Your input will be blocked for a short while")
|
||||
#fetch_player(player)
|
||||
|
||||
|
||||
@hook.event("player.PlayerQuitEvent","highest")
|
||||
|
||||
Reference in New Issue
Block a user