Skip to content

Instantly share code, notes, and snippets.

@karl007
Created February 13, 2020 09:35
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karl007/521f6ab84a398ee27118ab89aae7a9dc to your computer and use it in GitHub Desktop.
Save karl007/521f6ab84a398ee27118ab89aae7a9dc to your computer and use it in GitHub Desktop.
[Matrix/Riot] kick all users of a room to delete it
#!/usr/bin/php
<?php
if(!function_exists('curl_init')) {
die('cURL not available!');
}
// check if there are every required arguments
if (count($argv) < 4) {
echo('USAGE: ' . $argv[0] . ' <URL> <TOKEN> <ROOM ALIAS|ID>');
echo 'this script shows all members of the given group, then you could kick alle users with a given reason';
die(1);
}
// set params from the cli arguments
$host = $argv[1];
$token = $argv[2];
$room = $argv[3];
try {
// check if the given room is an alias or already an id
if ($room[0] == '#') {
$room_id = getRoomId($room);
l('Found roomId for given alias: ' . $room_id);
} else {
$room_id = $room;
}
// find members of these room
$members = roomMembers($room_id);
l('Show active Memeberlist:');
foreach ($members as $member) {
l(' ' . $member['sender']);
}
l('Found ' . count($members) . ' active members');
// ask for execute the kick command
echo 'Enter OK if you would kick all members of this group: ';
$input = trim(fgets(STDIN));
if (strtoupper($input) == 'OK') {
$notKicked = [];
l('KICK all members of this group');
l('enter a reason for the kick (reason is showed to the user): ');
$reason = trim(fgets(STDIN));
l('enter a user_id which will not be kicked (enter for kick all users): ');
$keep_user_id = trim(fgets(STDIN));
l('**********************************************');
// kick all members
foreach ($members as $member) {
if ($keep_user_id && strtoupper($member['sender']) == strtoupper($keep_user_id))
continue;
try {
// without Exception, the kick was OK
kickUserFromRoom($room_id, $member['sender'], $reason);
l(' ' . $member['sender'] . ' kicked');
// OPTIONALLY: add a pause of 5sec to prevent a possible HTTP 429 "Too many requests"
// sleep(5);
} catch(\Exception $e) {
$notKicked[] = $member;
l( 'ERROR: ' . $member['sender'] . ' not kicked: ' . $e->getMessage());
}
}
// output the notKicked errors
if (!empty($notKicked)) {
l(count($notKicked) . ' members could not kicked:');
l('**********************************************');
foreach ($members as $member) {
l($member['sender']);
}
}
} else {
l('**********************************************');
l('script stopped without doing anything!');
}
die(0); // success
} catch(\Exception $e) {
echo($e->getMessage());
die(1); // error
}
/**
* return the list of the members
* @param string $room_id
* @return array
*/
function roomMembers($room_id) {
global $host, $token;
$result = request($host . '/_matrix/client/r0/rooms/'.$room_id.'/members', [
'access_token' => $token,
'membership' => 'join', // only active members
]);
return $result['chunk'];
}
/**
* get the room_id from the given alias
* @param string $room_alias
* @return string room_id
*/
function getRoomId($room_alias) {
global $host, $token;
$result = request($host . '/_matrix/client/r0/directory/room/' . $room_alias, [
'access_token' => $token,
]);
return $result['room_id'];
}
/**
* remove the given user from the given room with the given reason message
* @param string $room_id id of the room
* @param string $user_id id of th euser
* @param string $reason the text the user will see
*/
function kickUserFromRoom($room_id, $user_id, $reason = "") {
global $host, $token;
// without Exception, the kick was OK
request($host . '/_matrix/client/r0/rooms/' . $room_id . '/kick', [
'access_token' => $token,
], [
'reason' => $reason,
'user_id' => $user_id
]);
}
/**
* simple echo with a newline
* @param string $msg
*/
function l ($msg) {
echo $msg . "\n";
}
/**
* send a Json API Request
* @param string $url the destination URL
* @param array $query add these params as get arg
* @param array $postData list of post data for send as json encodet
* @param string $request_type GET|POST|DELETE|PUT
* @return array [description]
*/
function request($url, $query = null, $postData = null, $request_type = null) {
$curl = curl_init();
// add query to url
if (http_build_query($query)) {
$url .= '?' . http_build_query($query);
}
curl_setopt($curl, CURLOPT_URL, $url); // or use https://requestb.in/ for testing purposes
curl_setopt($curl, CURLOPT_FAILONERROR, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
if ($postData) {
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($postData));
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json', 'Accept:application/json')); // send JSON and expect JSON
// As said above, the target script needs to read `php://input`, not `$_POST`!
}
if ($request_type) {
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, strtoupper($request_type));
//// If the service is not able to parse the input stream, then use a regular POST request and a custom header
//// Use »$_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']« to read the incoming header variable
// curl_setopt($curl, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: PUT'));
}
//// Timeout in seconds
//curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 0);
//curl_setopt($curl, CURLOPT_TIMEOUT, 10);
//// Dont verify SSL certificate (eg. self-signed cert in testsystem)
//curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
//curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$output = curl_exec($curl);
if ($output === FALSE) {
throw new \Exception('An error has occurred: ' . curl_error($curl));
}
return json_decode($output, true);
}
@benthetechguy
Copy link

benthetechguy commented Jun 20, 2022

if ($keep_user_id && strtoupper($member['sender']) == strtoupper($keep_user_id))
	continue;

There should also be an elseif here that continues if the member about to be kicked happens to be the one doing the kicking. My username starts with B, which is high on the list alphabetically, so when I ran this script I was one of the first to be kicked and could therefore not kick anyone else. I was the only admin of the room, so it could not be deleted unless everyone else left by themselves.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment