Last active 1450565359

Multicraft Python Cloudbot plugin

Revision 8690fe1e9a472852f82379429606a6c252b31f00

multicraft.py Raw
1# For use with CloudBot (http://git.io/cbgit), although it'll also work as a Python module
2# ('import multicraft; data = multicraft.multicraft("METHOD PARAM=VALUE")')
3# Full API documentation coming soon (better than Multicraft's PHP-specific documentation, I'm hoping)
4
5# This file (multicraft.py) Copyright 2013 Steven Smith (blha303). All Rights Reserved.
6# GPLv3 license (because CloudBot is GPL)
7# http://opensource.org/licenses/GPL-3.0
8
9from util import hook, http
10from urllib import urlencode
11import json
12
13url = "MULTICRAFTURL/api.php"
14user = "USER"
15apikey = 'APIKEY'
16
17
18@hook.command(adminonly=True)
19def multicraft(inp, reply=''):
20 """multicraft <method> [option=value]... - Call multicraft server"""
21 def getqstring(method, user, key, data={}):
22 values = []
23 for k, v in data.iteritems():
24 values.append(v)
25 key = http.get("http://blha303.com.au/md5.php?q=%s%s%s%s"
26 % (key, method, user, "".join(values)))
27 string = urlencode(dict(_MulticraftAPIMethod=method,
28 _MulticraftAPIUser=user,
29 _MulticraftAPIKey=key))
30 string += "&" + urlencode(data)
31 return string
32
33 method = inp.split(" ")[0]
34 moredata = {}
35 if len(inp.split(" ")) > 1:
36 for i in inp.split(" ")[1:]:
37 if not "=" in i:
38 return "Invalid data at '%s'." % i
39 moredata[i.split("=")[0]] = i.split("=")[1]
40 data = http.get_json(url, post_data=getqstring(method, user, apikey, data=moredata))
41 if not data['success']:
42 return "Failure: %s" % ", ".join(data['errors'])
43 else:
44 return json.dumps(data['data'])
45
46def getCommand(inp, method):
47 """ for methods with only an 'id' parameter, like getUser
48 example usage: getCommand("1", "getUser") will return
49 {"User": {"lang": "", "email": "...", "global_role": "...",
50 "id": "1", "name": "admin"}} as a JSON string """
51 try:
52 id = int(inp.split(" ")[0])
53 except:
54 return "id must be an integer."
55 data = multicraft("%s id=%s" % (method, id))
56 if not "Failure: " in data:
57 return data
58 else:
59 return None
60
61def updateCommand(inp, method):
62 """ For methods that take field>value parameters.
63 inp should be a string, "field=value field=value ..."
64 Example: updateCommand("name=admin email=admin@localhost.local", "findUsers")
65 returns {"Users": {"1": "admin"}} as a JSON string """
66 inp = inp.split(" ")
67 def fix(text):
68 return str(text).replace('"', "'").replace("u'", "'")
69 dats = {}
70 for i in inp:
71 if not "=" in i:
72 return "Invalid data at %s" % i
73 dats[i.split("=")[0]] = i.split("=")[1]
74 fields = []
75 values = []
76 for k in dats:
77 fields.append(k)
78 values.append(dats[k])
79 data = multicraft("%s field=%s value=%s" % (method, fix(fields), fix(values)))
80 if not "Failure: " in data:
81 return data
82 else:
83 return None
84
85@hook.command(adminonly=True)
86def mcrestart(inp):
87 """mcrestart <id> - Restart specified server. Admin only. id must be an integer."""
88 data = getCommand(inp, "restartServer")
89 if data == "[]":
90 return "Success restarting server %s" % inp.split(" ")[0]
91 else:
92 return "Error restarting server %s. Invalid server ID?" % inp.split(" ")[0]
93
94@hook.command(adminonly=True, autohelp=False)
95def mclist():
96 """mclist - List servers."""
97 out = ""
98 data = multicraft("listServers")
99 if not "Failure " in data:
100 data = json.loads(data)["Servers"]
101 for k in data:
102 v = data[k]
103 if out == "":
104 out = "%s (%s)" % (v, k)
105 else:
106 out = out + ", " + "%s (%s)" % (v, k)
107 return "Servers: " + out
108 else:
109 return data
110
111@hook.command(adminonly=True)
112def mcfindusers(inp):
113 """mcfindusers [name=value] [email=value] ... - Find user matching name, email, role, etc"""
114 data = updateCommand(inp, "findUsers")
115 if data:
116 data = json.loads(data)
117 if data["Users"] == []:
118 return "No results."
119 else:
120 out = ""
121 for i in data["Users"]:
122 if not out:
123 out = "%s (%s)" % (data["Users"][i], i)
124 else:
125 out = out + ", %s (%s)" % (data["Users"][i], i)
126 return "Users: %s" % out
127 else:
128 return "Error getting data!"