From 82d9d524bdb8ce2f54855589e44ce3a20ba1af37 Mon Sep 17 00:00:00 2001 From: cclauss Date: Mon, 17 Jun 2019 19:21:30 +0200 Subject: [PATCH] Fix seven contrib files with Python syntax errors (#5446) * Fix seven contrib files with Python syntax errors Signed-off-by: cclauss --- changelog.d/5446.misc | 1 + contrib/cmdclient/console.py | 109 +++++++++++---------- contrib/cmdclient/http.py | 13 +-- contrib/graph/graph.py | 5 +- contrib/graph/graph3.py | 21 ++-- contrib/jitsimeetbridge/jitsimeetbridge.py | 67 ++++++------- contrib/scripts/kick_users.py | 34 ++++--- 7 files changed, 131 insertions(+), 119 deletions(-) create mode 100644 changelog.d/5446.misc diff --git a/changelog.d/5446.misc b/changelog.d/5446.misc new file mode 100644 index 0000000000..e5209be0a6 --- /dev/null +++ b/changelog.d/5446.misc @@ -0,0 +1 @@ +Update Python syntax in contrib/ to Python 3. diff --git a/contrib/cmdclient/console.py b/contrib/cmdclient/console.py index 4918fa1a9a..462f146113 100755 --- a/contrib/cmdclient/console.py +++ b/contrib/cmdclient/console.py @@ -15,6 +15,7 @@ # limitations under the License. """ Starts a synapse client console. """ +from __future__ import print_function from twisted.internet import reactor, defer, threads from http import TwistedHttpClient @@ -109,7 +110,7 @@ class SynapseCmd(cmd.Cmd): by using $. E.g. 'config roomid room1' then 'raw get /rooms/$roomid'. """ if len(line) == 0: - print json.dumps(self.config, indent=4) + print(json.dumps(self.config, indent=4)) return try: @@ -123,8 +124,8 @@ class SynapseCmd(cmd.Cmd): ] for key, valid_vals in config_rules: if key == args["key"] and args["val"] not in valid_vals: - print "%s value must be one of %s" % (args["key"], - valid_vals) + print("%s value must be one of %s" % (args["key"], + valid_vals)) return # toggle the http client verbosity @@ -133,11 +134,11 @@ class SynapseCmd(cmd.Cmd): # assign the new config self.config[args["key"]] = args["val"] - print json.dumps(self.config, indent=4) + print(json.dumps(self.config, indent=4)) save_config(self.config) except Exception as e: - print e + print(e) def do_register(self, line): """Registers for a new account: "register " @@ -153,7 +154,7 @@ class SynapseCmd(cmd.Cmd): pwd = getpass.getpass("Type a password for this user: ") pwd2 = getpass.getpass("Retype the password: ") if pwd != pwd2 or len(pwd) == 0: - print "Password mismatch." + print("Password mismatch.") pwd = None else: password = pwd @@ -174,12 +175,12 @@ class SynapseCmd(cmd.Cmd): # check the registration flows url = self._url() + "/register" json_res = yield self.http_client.do_request("GET", url) - print json.dumps(json_res, indent=4) + print(json.dumps(json_res, indent=4)) passwordFlow = None for flow in json_res["flows"]: if flow["type"] == "m.login.recaptcha" or ("stages" in flow and "m.login.recaptcha" in flow["stages"]): - print "Unable to register: Home server requires captcha." + print("Unable to register: Home server requires captcha.") return if flow["type"] == "m.login.password" and "stages" not in flow: passwordFlow = flow @@ -189,7 +190,7 @@ class SynapseCmd(cmd.Cmd): return json_res = yield self.http_client.do_request("POST", url, data=data) - print json.dumps(json_res, indent=4) + print(json.dumps(json_res, indent=4)) if update_config and "user_id" in json_res: self.config["user"] = json_res["user_id"] self.config["token"] = json_res["access_token"] @@ -215,7 +216,7 @@ class SynapseCmd(cmd.Cmd): reactor.callFromThread(self._do_login, user, p) #print " got %s " % p except Exception as e: - print e + print(e) @defer.inlineCallbacks def _do_login(self, user, password): @@ -227,13 +228,13 @@ class SynapseCmd(cmd.Cmd): } url = self._url() + path json_res = yield self.http_client.do_request("POST", url, data=data) - print json_res + print(json_res) if "access_token" in json_res: self.config["user"] = user self.config["token"] = json_res["access_token"] save_config(self.config) - print "Login successful." + print("Login successful.") @defer.inlineCallbacks def _check_can_login(self): @@ -242,10 +243,10 @@ class SynapseCmd(cmd.Cmd): # submitting! url = self._url() + path json_res = yield self.http_client.do_request("GET", url) - print json_res + print(json_res) if "flows" not in json_res: - print "Failed to find any login flows." + print("Failed to find any login flows.") defer.returnValue(False) flow = json_res["flows"][0] # assume first is the one we want. @@ -275,9 +276,9 @@ class SynapseCmd(cmd.Cmd): json_res = yield self.http_client.do_request("POST", url, data=urllib.urlencode(args), jsonreq=False, headers={'Content-Type': ['application/x-www-form-urlencoded']}) - print json_res + print(json_res) if 'sid' in json_res: - print "Token sent. Your session ID is %s" % (json_res['sid']) + print("Token sent. Your session ID is %s" % (json_res['sid'])) def do_emailvalidate(self, line): """Validate and associate a third party ID @@ -297,7 +298,7 @@ class SynapseCmd(cmd.Cmd): json_res = yield self.http_client.do_request("POST", url, data=urllib.urlencode(args), jsonreq=False, headers={'Content-Type': ['application/x-www-form-urlencoded']}) - print json_res + print(json_res) def do_3pidbind(self, line): """Validate and associate a third party ID @@ -317,7 +318,7 @@ class SynapseCmd(cmd.Cmd): json_res = yield self.http_client.do_request("POST", url, data=urllib.urlencode(args), jsonreq=False, headers={'Content-Type': ['application/x-www-form-urlencoded']}) - print json_res + print(json_res) def do_join(self, line): """Joins a room: "join " """ @@ -325,7 +326,7 @@ class SynapseCmd(cmd.Cmd): args = self._parse(line, ["roomid"], force_keys=True) self._do_membership_change(args["roomid"], "join", self._usr()) except Exception as e: - print e + print(e) def do_joinalias(self, line): try: @@ -333,7 +334,7 @@ class SynapseCmd(cmd.Cmd): path = "/join/%s" % urllib.quote(args["roomname"]) reactor.callFromThread(self._run_and_pprint, "POST", path, {}) except Exception as e: - print e + print(e) def do_topic(self, line): """"topic [set|get] []" @@ -343,17 +344,17 @@ class SynapseCmd(cmd.Cmd): try: args = self._parse(line, ["action", "roomid", "topic"]) if "action" not in args or "roomid" not in args: - print "Must specify set|get and a room ID." + print("Must specify set|get and a room ID.") return if args["action"].lower() not in ["set", "get"]: - print "Must specify set|get, not %s" % args["action"] + print("Must specify set|get, not %s" % args["action"]) return path = "/rooms/%s/topic" % urllib.quote(args["roomid"]) if args["action"].lower() == "set": if "topic" not in args: - print "Must specify a new topic." + print("Must specify a new topic.") return body = { "topic": args["topic"] @@ -362,7 +363,7 @@ class SynapseCmd(cmd.Cmd): elif args["action"].lower() == "get": reactor.callFromThread(self._run_and_pprint, "GET", path) except Exception as e: - print e + print(e) def do_invite(self, line): """Invite a user to a room: "invite " """ @@ -373,7 +374,7 @@ class SynapseCmd(cmd.Cmd): reactor.callFromThread(self._do_invite, args["roomid"], user_id) except Exception as e: - print e + print(e) @defer.inlineCallbacks def _do_invite(self, roomid, userstring): @@ -393,29 +394,29 @@ class SynapseCmd(cmd.Cmd): if 'public_key' in pubKeyObj: pubKey = nacl.signing.VerifyKey(pubKeyObj['public_key'], encoder=nacl.encoding.HexEncoder) else: - print "No public key found in pubkey response!" + print("No public key found in pubkey response!") sigValid = False if pubKey: for signame in json_res['signatures']: if signame not in TRUSTED_ID_SERVERS: - print "Ignoring signature from untrusted server %s" % (signame) + print("Ignoring signature from untrusted server %s" % (signame)) else: try: verify_signed_json(json_res, signame, pubKey) sigValid = True - print "Mapping %s -> %s correctly signed by %s" % (userstring, json_res['mxid'], signame) + print("Mapping %s -> %s correctly signed by %s" % (userstring, json_res['mxid'], signame)) break except SignatureVerifyException as e: - print "Invalid signature from %s" % (signame) - print e + print("Invalid signature from %s" % (signame)) + print(e) if sigValid: - print "Resolved 3pid %s to %s" % (userstring, json_res['mxid']) + print("Resolved 3pid %s to %s" % (userstring, json_res['mxid'])) mxid = json_res['mxid'] else: - print "Got association for %s but couldn't verify signature" % (userstring) + print("Got association for %s but couldn't verify signature" % (userstring)) if not mxid: mxid = "@" + userstring + ":" + self._domain() @@ -428,7 +429,7 @@ class SynapseCmd(cmd.Cmd): args = self._parse(line, ["roomid"], force_keys=True) self._do_membership_change(args["roomid"], "leave", self._usr()) except Exception as e: - print e + print(e) def do_send(self, line): """Sends a message. "send " """ @@ -453,10 +454,10 @@ class SynapseCmd(cmd.Cmd): """ args = self._parse(line, ["type", "roomid", "qp"]) if not "type" in args or not "roomid" in args: - print "Must specify type and room ID." + print("Must specify type and room ID.") return if args["type"] not in ["members", "messages"]: - print "Unrecognised type: %s" % args["type"] + print("Unrecognised type: %s" % args["type"]) return room_id = args["roomid"] path = "/rooms/%s/%s" % (urllib.quote(room_id), args["type"]) @@ -468,7 +469,7 @@ class SynapseCmd(cmd.Cmd): key_value = key_value_str.split("=") qp[key_value[0]] = key_value[1] except: - print "Bad query param: %s" % key_value + print("Bad query param: %s" % key_value) return reactor.callFromThread(self._run_and_pprint, "GET", path, @@ -508,14 +509,14 @@ class SynapseCmd(cmd.Cmd): args = self._parse(line, ["method", "path", "data"]) # sanity check if "method" not in args or "path" not in args: - print "Must specify path and method." + print("Must specify path and method.") return args["method"] = args["method"].upper() valid_methods = ["PUT", "GET", "POST", "DELETE", "XPUT", "XGET", "XPOST", "XDELETE"] if args["method"] not in valid_methods: - print "Unsupported method: %s" % args["method"] + print("Unsupported method: %s" % args["method"]) return if "data" not in args: @@ -524,7 +525,7 @@ class SynapseCmd(cmd.Cmd): try: args["data"] = json.loads(args["data"]) except Exception as e: - print "Data is not valid JSON. %s" % e + print("Data is not valid JSON. %s" % e) return qp = {"access_token": self._tok()} @@ -553,7 +554,7 @@ class SynapseCmd(cmd.Cmd): try: timeout = int(args["timeout"]) except ValueError: - print "Timeout must be in milliseconds." + print("Timeout must be in milliseconds.") return reactor.callFromThread(self._do_event_stream, timeout) @@ -566,7 +567,7 @@ class SynapseCmd(cmd.Cmd): "timeout": str(timeout), "from": self.event_stream_token }) - print json.dumps(res, indent=4) + print(json.dumps(res, indent=4)) if "chunk" in res: for event in res["chunk"]: @@ -669,9 +670,9 @@ class SynapseCmd(cmd.Cmd): data=data, qparams=query_params) if alt_text: - print alt_text + print(alt_text) else: - print json.dumps(json_res, indent=4) + print(json.dumps(json_res, indent=4)) def save_config(config): @@ -680,16 +681,16 @@ def save_config(config): def main(server_url, identity_server_url, username, token, config_path): - print "Synapse command line client" - print "===========================" - print "Server: %s" % server_url - print "Type 'help' to get started." - print "Close this console with CTRL+C then CTRL+D." + print("Synapse command line client") + print("===========================") + print("Server: %s" % server_url) + print("Type 'help' to get started.") + print("Close this console with CTRL+C then CTRL+D.") if not username or not token: - print "- 'register ' - Register an account" - print "- 'stream' - Connect to the event stream" - print "- 'create ' - Create a room" - print "- 'send ' - Send a message" + print("- 'register ' - Register an account") + print("- 'stream' - Connect to the event stream") + print("- 'create ' - Create a room") + print("- 'send ' - Send a message") http_client = TwistedHttpClient() # the command line client @@ -705,7 +706,7 @@ def main(server_url, identity_server_url, username, token, config_path): http_client.verbose = "on" == syn_cmd.config["verbose"] except: pass - print "Loaded config from %s" % config_path + print("Loaded config from %s" % config_path) except: pass @@ -736,7 +737,7 @@ if __name__ == '__main__': args = parser.parse_args() if not args.server: - print "You must supply a server URL to communicate with." + print("You must supply a server URL to communicate with.") parser.print_help() sys.exit(1) diff --git a/contrib/cmdclient/http.py b/contrib/cmdclient/http.py index c833f3f318..1bd600e148 100644 --- a/contrib/cmdclient/http.py +++ b/contrib/cmdclient/http.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +from __future__ import print_function from twisted.web.client import Agent, readBody from twisted.web.http_headers import Headers from twisted.internet import defer, reactor @@ -141,15 +142,15 @@ class TwistedHttpClient(HttpClient): headers_dict["User-Agent"] = ["Synapse Cmd Client"] retries_left = 5 - print "%s to %s with headers %s" % (method, url, headers_dict) + print("%s to %s with headers %s" % (method, url, headers_dict)) if self.verbose and producer: if "password" in producer.data: temp = producer.data["password"] producer.data["password"] = "[REDACTED]" - print json.dumps(producer.data, indent=4) + print(json.dumps(producer.data, indent=4)) producer.data["password"] = temp else: - print json.dumps(producer.data, indent=4) + print(json.dumps(producer.data, indent=4)) while True: try: @@ -161,7 +162,7 @@ class TwistedHttpClient(HttpClient): ) break except Exception as e: - print "uh oh: %s" % e + print("uh oh: %s" % e) if retries_left: yield self.sleep(2 ** (5 - retries_left)) retries_left -= 1 @@ -169,8 +170,8 @@ class TwistedHttpClient(HttpClient): raise e if self.verbose: - print "Status %s %s" % (response.code, response.phrase) - print pformat(list(response.headers.getAllRawHeaders())) + print("Status %s %s" % (response.code, response.phrase)) + print(pformat(list(response.headers.getAllRawHeaders()))) defer.returnValue(response) def sleep(self, seconds): diff --git a/contrib/graph/graph.py b/contrib/graph/graph.py index afd1d446b4..e174ff5026 100644 --- a/contrib/graph/graph.py +++ b/contrib/graph/graph.py @@ -1,3 +1,4 @@ +from __future__ import print_function # Copyright 2014-2016 OpenMarket Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -48,7 +49,7 @@ def make_graph(pdus, room, filename_prefix): c = colors.pop() color_map[o] = c except: - print "Run out of colours!" + print("Run out of colours!") color_map[o] = "black" graph = pydot.Dot(graph_name="Test") @@ -93,7 +94,7 @@ def make_graph(pdus, room, filename_prefix): end_name = make_name(i, o) if end_name not in node_map: - print "%s not in nodes" % end_name + print("%s not in nodes" % end_name) continue edge = pydot.Edge(node_map[start_name], node_map[end_name]) diff --git a/contrib/graph/graph3.py b/contrib/graph/graph3.py index 7d3b4d7eb6..fe1dc81e90 100644 --- a/contrib/graph/graph3.py +++ b/contrib/graph/graph3.py @@ -1,3 +1,4 @@ +from __future__ import print_function # Copyright 2016 OpenMarket Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -26,19 +27,19 @@ from six import string_types def make_graph(file_name, room_id, file_prefix, limit): - print "Reading lines" + print("Reading lines") with open(file_name) as f: lines = f.readlines() - print "Read lines" + print("Read lines") events = [FrozenEvent(json.loads(line)) for line in lines] - print "Loaded events." + print("Loaded events.") events.sort(key=lambda e: e.depth) - print "Sorted events" + print("Sorted events") if limit: events = events[-int(limit):] @@ -55,7 +56,7 @@ def make_graph(file_name, room_id, file_prefix, limit): content = json.dumps(unfreeze(event.get_dict()["content"]), indent=4) content = content.replace("\n", "
\n") - print content + print(content) content = [] for key, value in unfreeze(event.get_dict()["content"]).items(): if value is None: @@ -74,7 +75,7 @@ def make_graph(file_name, room_id, file_prefix, limit): content = "
\n".join(content) - print content + print(content) label = ( "<" @@ -102,7 +103,7 @@ def make_graph(file_name, room_id, file_prefix, limit): node_map[event.event_id] = node graph.add_node(node) - print "Created Nodes" + print("Created Nodes") for event in events: for prev_id, _ in event.prev_events: @@ -120,15 +121,15 @@ def make_graph(file_name, room_id, file_prefix, limit): edge = pydot.Edge(node_map[event.event_id], end_node) graph.add_edge(edge) - print "Created edges" + print("Created edges") graph.write('%s.dot' % file_prefix, format='raw', prog='dot') - print "Created Dot" + print("Created Dot") graph.write_svg("%s.svg" % file_prefix, prog='dot') - print "Created svg" + print("Created svg") if __name__ == "__main__": parser = argparse.ArgumentParser( diff --git a/contrib/jitsimeetbridge/jitsimeetbridge.py b/contrib/jitsimeetbridge/jitsimeetbridge.py index 15f8e1c48b..e82d1be5d2 100644 --- a/contrib/jitsimeetbridge/jitsimeetbridge.py +++ b/contrib/jitsimeetbridge/jitsimeetbridge.py @@ -8,8 +8,9 @@ we set the remote SDP at which point the stream ends. Our video never gets to the bridge. Requires: -npm install jquery jsdom +npm install jquery jsdom """ +from __future__ import print_function import gevent import grequests @@ -51,7 +52,7 @@ class TrivialMatrixClient: req = grequests.get(url) resps = grequests.map([req]) obj = json.loads(resps[0].content) - print "incoming from matrix",obj + print("incoming from matrix",obj) if 'end' not in obj: continue self.token = obj['end'] @@ -60,22 +61,22 @@ class TrivialMatrixClient: def joinRoom(self, roomId): url = MATRIXBASE+'rooms/'+roomId+'/join?access_token='+self.access_token - print url + print(url) headers={ 'Content-Type': 'application/json' } req = grequests.post(url, headers=headers, data='{}') resps = grequests.map([req]) obj = json.loads(resps[0].content) - print "response: ",obj + print("response: ",obj) def sendEvent(self, roomId, evType, event): url = MATRIXBASE+'rooms/'+roomId+'/send/'+evType+'?access_token='+self.access_token - print url - print json.dumps(event) + print(url) + print(json.dumps(event)) headers={ 'Content-Type': 'application/json' } req = grequests.post(url, headers=headers, data=json.dumps(event)) resps = grequests.map([req]) obj = json.loads(resps[0].content) - print "response: ",obj + print("response: ",obj) @@ -85,31 +86,31 @@ xmppClients = {} def matrixLoop(): while True: ev = matrixCli.getEvent() - print ev + print(ev) if ev['type'] == 'm.room.member': - print 'membership event' + print('membership event') if ev['membership'] == 'invite' and ev['state_key'] == MYUSERNAME: roomId = ev['room_id'] - print "joining room %s" % (roomId) + print("joining room %s" % (roomId)) matrixCli.joinRoom(roomId) elif ev['type'] == 'm.room.message': if ev['room_id'] in xmppClients: - print "already have a bridge for that user, ignoring" + print("already have a bridge for that user, ignoring") continue - print "got message, connecting" + print("got message, connecting") xmppClients[ev['room_id']] = TrivialXmppClient(ev['room_id'], ev['user_id']) gevent.spawn(xmppClients[ev['room_id']].xmppLoop) elif ev['type'] == 'm.call.invite': - print "Incoming call" + print("Incoming call") #sdp = ev['content']['offer']['sdp'] #print "sdp: %s" % (sdp) #xmppClients[ev['room_id']] = TrivialXmppClient(ev['room_id'], ev['user_id']) #gevent.spawn(xmppClients[ev['room_id']].xmppLoop) elif ev['type'] == 'm.call.answer': - print "Call answered" + print("Call answered") sdp = ev['content']['answer']['sdp'] if ev['room_id'] not in xmppClients: - print "We didn't have a call for that room" + print("We didn't have a call for that room") continue # should probably check call ID too xmppCli = xmppClients[ev['room_id']] @@ -146,7 +147,7 @@ class TrivialXmppClient: return obj def sendAnswer(self, answer): - print "sdp from matrix client",answer + print("sdp from matrix client",answer) p = subprocess.Popen(['node', 'unjingle/unjingle.js', '--sdp'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) jingle, out_err = p.communicate(answer) jingle = jingle % { @@ -156,28 +157,28 @@ class TrivialXmppClient: 'responder': self.jid, 'sid': self.callsid } - print "answer jingle from sdp",jingle + print("answer jingle from sdp",jingle) res = self.sendIq(jingle) - print "reply from answer: ",res + print("reply from answer: ",res) self.ssrcs = {} jingleSoup = BeautifulSoup(jingle) for cont in jingleSoup.iq.jingle.findAll('content'): if cont.description: self.ssrcs[cont['name']] = cont.description['ssrc'] - print "my ssrcs:",self.ssrcs + print("my ssrcs:",self.ssrcs) gevent.joinall([ gevent.spawn(self.advertiseSsrcs) ]) def advertiseSsrcs(self): - time.sleep(7) - print "SSRC spammer started" + time.sleep(7) + print("SSRC spammer started") while self.running: ssrcMsg = "%(nick)s" % { 'tojid': "%s@%s/%s" % (ROOMNAME, ROOMDOMAIN, self.shortJid), 'nick': self.userId, 'assrc': self.ssrcs['audio'], 'vssrc': self.ssrcs['video'] } res = self.sendIq(ssrcMsg) - print "reply from ssrc announce: ",res + print("reply from ssrc announce: ",res) time.sleep(10) @@ -186,19 +187,19 @@ class TrivialXmppClient: self.matrixCallId = time.time() res = self.xmppPoke("" % (self.nextRid(), HOST)) - print res + print(res) self.sid = res.body['sid'] - print "sid %s" % (self.sid) + print("sid %s" % (self.sid)) res = self.sendIq("") res = self.xmppPoke("" % (self.nextRid(), self.sid, HOST)) res = self.sendIq("") - print res + print(res) self.jid = res.body.iq.bind.jid.string - print "jid: %s" % (self.jid) + print("jid: %s" % (self.jid)) self.shortJid = self.jid.split('-')[0] res = self.sendIq("") @@ -217,13 +218,13 @@ class TrivialXmppClient: if p.c and p.c.nick: u['nick'] = p.c.nick.string self.muc['users'].append(u) - print "muc: ",self.muc + print("muc: ",self.muc) # wait for stuff while True: - print "waiting..." + print("waiting...") res = self.sendIq("") - print "got from stream: ",res + print("got from stream: ",res) if res.body.iq: jingles = res.body.iq.findAll('jingle') if len(jingles): @@ -232,15 +233,15 @@ class TrivialXmppClient: elif 'type' in res.body and res.body['type'] == 'terminate': self.running = False del xmppClients[self.matrixRoom] - return + return def handleInvite(self, jingle): self.initiator = jingle['initiator'] self.callsid = jingle['sid'] p = subprocess.Popen(['node', 'unjingle/unjingle.js', '--jingle'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) - print "raw jingle invite",str(jingle) + print("raw jingle invite",str(jingle)) sdp, out_err = p.communicate(str(jingle)) - print "transformed remote offer sdp",sdp + print("transformed remote offer sdp",sdp) inviteEvent = { 'offer': { 'type': 'offer', @@ -252,7 +253,7 @@ class TrivialXmppClient: } matrixCli.sendEvent(self.matrixRoom, 'm.call.invite', inviteEvent) -matrixCli = TrivialMatrixClient(ACCESS_TOKEN) +matrixCli = TrivialMatrixClient(ACCESS_TOKEN) # Undefined name gevent.joinall([ gevent.spawn(matrixLoop) diff --git a/contrib/scripts/kick_users.py b/contrib/scripts/kick_users.py index 5dfaec3ad0..b4a14385d0 100755 --- a/contrib/scripts/kick_users.py +++ b/contrib/scripts/kick_users.py @@ -1,10 +1,16 @@ #!/usr/bin/env python +from __future__ import print_function from argparse import ArgumentParser import json import requests import sys import urllib +try: + raw_input +except NameError: # Python 3 + raw_input = input + def _mkurl(template, kws): for key in kws: template = template.replace(key, kws[key]) @@ -13,7 +19,7 @@ def _mkurl(template, kws): def main(hs, room_id, access_token, user_id_prefix, why): if not why: why = "Automated kick." - print "Kicking members on %s in room %s matching %s" % (hs, room_id, user_id_prefix) + print("Kicking members on %s in room %s matching %s" % (hs, room_id, user_id_prefix)) room_state_url = _mkurl( "$HS/_matrix/client/api/v1/rooms/$ROOM/state?access_token=$TOKEN", { @@ -22,13 +28,13 @@ def main(hs, room_id, access_token, user_id_prefix, why): "$TOKEN": access_token } ) - print "Getting room state => %s" % room_state_url + print("Getting room state => %s" % room_state_url) res = requests.get(room_state_url) - print "HTTP %s" % res.status_code + print("HTTP %s" % res.status_code) state_events = res.json() if "error" in state_events: - print "FATAL" - print state_events + print("FATAL") + print(state_events) return kick_list = [] @@ -44,15 +50,15 @@ def main(hs, room_id, access_token, user_id_prefix, why): kick_list.append(event["state_key"]) if len(kick_list) == 0: - print "No user IDs match the prefix '%s'" % user_id_prefix + print("No user IDs match the prefix '%s'" % user_id_prefix) return - print "The following user IDs will be kicked from %s" % room_name + print("The following user IDs will be kicked from %s" % room_name) for uid in kick_list: - print uid + print(uid) doit = raw_input("Continue? [Y]es\n") if len(doit) > 0 and doit.lower() == 'y': - print "Kicking members..." + print("Kicking members...") # encode them all kick_list = [urllib.quote(uid) for uid in kick_list] for uid in kick_list: @@ -69,14 +75,14 @@ def main(hs, room_id, access_token, user_id_prefix, why): "membership": "leave", "reason": why } - print "Kicking %s" % uid + print("Kicking %s" % uid) res = requests.put(kick_url, data=json.dumps(kick_body)) if res.status_code != 200: - print "ERROR: HTTP %s" % res.status_code + print("ERROR: HTTP %s" % res.status_code) if res.json().get("error"): - print "ERROR: JSON %s" % res.json() - - + print("ERROR: JSON %s" % res.json()) + + if __name__ == "__main__": parser = ArgumentParser("Kick members in a room matching a certain user ID prefix.")