Last active 1450565359

Multicraft Python Cloudbot plugin

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) created by Steven Smith (blha303) 2013
6# GPLv3 license (because CloudBot is GPL)
7# http://opensource.org/licenses/GPL-3.0
8
9# Updated to use hashlib instead of calling an external website for md5 hashing
10# For a working example of this, join irc.esper.net #xD and ask blha303 for a demonstration of multicraft.py
11
12from util import hook, http
13from urllib import urlencode
14import json
15import hashlib
16
17url = "MULTICRAFTURL/api.php"
18user = "USER"
19apikey = 'APIKEY'
20
21
22@hook.command(adminonly=True)
23def multicraft(inp, reply=''):
24 """multicraft <method> [option=value]... - Call multicraft server"""
25 def getqstring(method, user, key, data={}):
26 values = []
27 for k, v in data.iteritems():
28 values.append(v)
29 key = hashlib.md5("%s%s%s%s" % (key, method, user, "".join(values))).hexdigest()
30 string = urlencode(dict(_MulticraftAPIMethod=method,
31 _MulticraftAPIUser=user,
32 _MulticraftAPIKey=key))
33 string += "&" + urlencode(data)
34 return string
35
36 method = inp.split(" ")[0]
37 moredata = {}
38 if len(inp.split(" ")) > 1:
39 for i in inp.split(" ")[1:]:
40 if not "=" in i:
41 return "Invalid data at '%s'." % i
42 moredata[i.split("=")[0]] = i.split("=")[1]
43 data = http.get_json(url, post_data=getqstring(method, user, apikey,
44 data=moredata))
45 if not data['success']:
46 return "Failure: %s" % ", ".join(data['errors'])
47 else:
48 return json.dumps(data['data'])
49
50
51def getCommand(inp, method):
52 try:
53 id = int(inp.split(" ")[0])
54 except:
55 return "id must be an integer."
56 data = multicraft("%s id=%s" % (method, id))
57 if not "Failure: " in data:
58 return data
59 else:
60 return None
61
62
63def updateCommand(inp, method):
64 inp = inp.split(" ")
65
66 def fix(text):
67 return str(text).replace('"', "'").replace("u'", "'")
68
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"
80 % (method, fix(fields), fix(values)))
81 if not "Failure: " in data:
82 return data
83 else:
84 return None
85
86
87@hook.command(adminonly=True)
88def mcrestart(inp):
89 """mcrestart <id> - Restart specified server.
90 Admin only. id must be an integer."""
91 data = getCommand(inp, "restartServer")
92 if data == "[]":
93 return "Success restarting server %s" % inp.split(" ")[0]
94 else:
95 return "Error restarting server %s." \
96 "Invalid server ID?" % inp.split(" ")[0]
97
98
99@hook.command(adminonly=True, autohelp=False)
100def mclist(inp):
101 """mclist - List servers."""
102 out = ""
103 data = multicraft("listServers")
104 if not "Failure " in data:
105 data = json.loads(data)["Servers"]
106 for k in data:
107 v = data[k]
108 if out == "":
109 out = "%s (%s)" % (v, k)
110 else:
111 out = out + ", " + "%s (%s)" % (v, k)
112 return "Servers: " + out
113 else:
114 return data
115
116
117@hook.command(adminonly=True)
118def mcfindusers(inp):
119 """mcfindusers [name=value] [email=value] ...
120 - Find user matching name, email, role, etc"""
121 data = updateCommand(inp, "findUsers")
122 if data:
123 data = json.loads(data)
124 if data["Users"] == []:
125 return "No results."
126 else:
127 out = ""
128 for i in data["Users"]:
129 if not out:
130 out = "%s (%s)" % (data["Users"][i], i)
131 else:
132 out = out + ", %s (%s)" % (data["Users"][i], i)
133 return "Users: %s" % out
134 else:
135 return "Error getting data!"
136