API:Afiliación a grupo de usuario

This page is a translated version of the page API:User group membership and the translation is 100% complete.
Versión de MediaWiki:
1.16

Solicitud POST para agregar o eliminar usuarios de un grupo, otorgando o eliminando de este modo ciertos derechos de usuario.

API Documentación


action=userrights

(main | userrights)
  • This module requires read rights.
  • This module requires write rights.
  • This module only accepts POST requests.
  • Source: MediaWiki
  • License: GPL-2.0-or-later

Change a user's group membership.

Parameters:
user

User.

Type: user, by any of user name and user ID (e.g. "#12345")
userid
Deprecated.

Specify user=#ID instead.

Type: integer
add

Add the user to these groups, or if they are already a member, update the expiry of their membership in that group.

Values (separate with | or alternative): accountcreator, autopatrolled, bot, bureaucrat, checkuser, confirmed, flow-bot, import, interface-admin, ipblock-exempt, oversight, push-subscription-manager, steward, suppress, sysop, translationadmin, transwiki, uploader
expiry

Expiry timestamps. May be relative (e.g. 5 months or 2 weeks) or absolute (e.g. 2014-09-18T12:34:56Z). If only one timestamp is set, it will be used for all groups passed to the add parameter. Use infinite, indefinite, infinity, or never for a never-expiring user group.

Separate values with | or alternative.
Maximum number of values is 50 (500 for clients allowed higher limits).
Default: infinite
remove

Remove the user from these groups.

Values (separate with | or alternative): accountcreator, autopatrolled, bot, bureaucrat, checkuser, confirmed, flow-bot, import, interface-admin, ipblock-exempt, oversight, push-subscription-manager, steward, suppress, sysop, translationadmin, transwiki, uploader
reason

Reason for the change.

Default: (empty)
token

A "userrights" token retrieved from action=query&meta=tokens

For compatibility, the token used in the web UI is also accepted.

This parameter is required.
tags

Change tags to apply to the entry in the user rights log.

Values (separate with | or alternative): possible vandalism, repeating characters
Examples:
Add user FooBot to group bot, and remove from groups sysop and bureaucrat.
api.php?action=userrights&user=FooBot&add=bot&remove=sysop|bureaucrat&token=123ABC [open in sandbox]
Add the user with ID 123 to group bot, and remove from groups sysop and bureaucrat.
api.php?action=userrights&userid=123&add=bot&remove=sysop|bureaucrat&token=123ABC [open in sandbox]
Add user SometimeSysop to group sysop for 1 month.
api.php?action=userrights&user=SometimeSysop&add=sysop&expiry=1%20month&token=123ABC [open in sandbox]

Ejemplo

Para usar esta API, primero debes iniciar sesión para verificar tu propia membresía en el grupo de usuarios. Solo ciertos grupos tienen la capacidad de alterar los derechos de los usuarios a través de esta API. Consulta API:Login para obtener más detalles sobre cómo iniciar sesión.

Una vez que hayas iniciado sesión, solicita un GET para obtener userrightstoken .


La consulta, superior, se aplica a MediaWiki v1.24+; en versiones anteriores, el token userrights dependería del nombre del usuario cuyos derechos estaban siendo cambiados. La consulta se haría así:



Por razones de compatibilidad, la API también aceptará el token utilizado en la interfaz de usuario web.

Cualquiera que sea el método que elijas, una vez que tengas tu token, puedes usarlo para hacer tu solicitud userrights, como se ve abajo.

Solicitud POST

Elimina Bob del grupo bureaucrat y agréguelos al grupo sysop, otorgándoles derechos de administrador.


Respuesta

{
    "userrights": {
        "user": "Bob",
        "userid": 2793024,
        "removed": ["bureaucrat"],
        "added": ["sysop"]
    }
}

Código de muestra

Python

#!/usr/bin/python3

"""
    userrights.py

    MediaWiki API Demos
    Demo of `Userrights` module: Add and remove user rights by
    changing the user's group membership.
    MIT license
"""

import requests

S = requests.Session()

URL = "https://test.wikipedia.org/w/api.php"

# Step 1: Retrieve a login token
PARAMS_1 = {
    "action": "query",
    "meta": "tokens",
    "type": "login",
    "format": "json"
}

R = S.get(url=URL, params=PARAMS_1)
DATA = R.json()

LOGIN_TOKEN = DATA["query"]["tokens"]["logintoken"]

# Step 2: Send a post request to log in. See
# https://www.mediawiki.org/wiki/Manual:Bot_passwords
# for a special note on logging in using a simplified
# interface when accessing wikis via an application,
# rather than the GUI
PARAMS_2 = {
    "action": "login",
    "lgname": "username",
    "lgpassword": "password",
    "lgtoken": LOGIN_TOKEN,
    "format": "json"
}

R = S.post(URL, data=PARAMS_2)

# Step 3: Obtain a Userrights token
PARAMS_3 = {
    "action": "query",
    "format": "json",
    "meta": "tokens",
    "type": "userrights"
}

R = S.get(url=URL, params=PARAMS_3)
DATA = R.json()

USERRIGHTS_TOKEN = DATA["query"]["tokens"]["userrightstoken"]

# Step 4: Request to add or remove a user from a group
PARAMS_4 = {
    "action": "userrights",
    "format": "json",
    "user": "Bob",
    "add": "sysop",
    "remove": "bureaucrat",
    "reason": "OOPS! added Bob to the wrong group",
    "token": USERRIGHTS_TOKEN
}

R = S.post(URL, data=PARAMS_4)
DATA = R.json()

print(DATA)

PHP

<?php

/*
    userrights.php

    MediaWiki API Demos
    Demo of `Userrights` module: Add and remove user rights by
	changing the user's group membership.

    MIT license
*/

$endPoint = "http://dev.wiki.local.wmftest.net:8080/w/api.php";

$login_Token = getLoginToken(); // Step 1
loginRequest( $login_Token ); // Step 2
$userrights_Token = getUserRightsToken(); // Step 3
change_userrights( $userrights_Token ); // Step 4

// Step 1: GET request to fetch login token
function getLoginToken() {
	global $endPoint;

	$params1 = [
		"action" => "query",
		"meta" => "tokens",
		"type" => "login",
		"format" => "json"
	];

	$url = $endPoint . "?" . http_build_query( $params1 );

	$ch = curl_init( $url );
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
	curl_setopt( $ch, CURLOPT_COOKIEJAR, "cookie.txt" );
	curl_setopt( $ch, CURLOPT_COOKIEFILE, "cookie.txt" );

	$output = curl_exec( $ch );
	curl_close( $ch );

	$result = json_decode( $output, true );
	return $result["query"]["tokens"]["logintoken"];
}

// Step 2: POST request to log in. Use of main account for login is not
// supported. Obtain credentials via Special:BotPasswords
// (https://www.mediawiki.org/wiki/Special:BotPasswords) for lgname & lgpassword
function loginRequest( $logintoken ) {
	global $endPoint;

	$params2 = [
		"action" => "clientlogin",
		"username" => "username",
		"password" => "password",
		'loginreturnurl' => 'http://127.0.0.1:5000/',
		"logintoken" => $logintoken,
		"format" => "json"
	];

	$ch = curl_init();

	curl_setopt( $ch, CURLOPT_URL, $endPoint );
	curl_setopt( $ch, CURLOPT_POST, true );
	curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query( $params2 ) );
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
	curl_setopt( $ch, CURLOPT_COOKIEJAR, "cookie.txt" );
	curl_setopt( $ch, CURLOPT_COOKIEFILE, "cookie.txt" );

	$output = curl_exec( $ch );
	curl_close( $ch );

}

// Step 3: GET request to fetch userrights token
function getUserRightsToken() {
	global $endPoint;

	$params3 = [
		"action" => "query",
		"meta" => "tokens",
		"type" => "userrights",
		"format" => "json"
	];

	$url = $endPoint . "?" . http_build_query( $params3 );

	$ch = curl_init( $url );

	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
	curl_setopt( $ch, CURLOPT_COOKIEJAR, "cookie.txt" );
	curl_setopt( $ch, CURLOPT_COOKIEFILE, "cookie.txt" );

	$output = curl_exec( $ch );
	curl_close( $ch );

	$result = json_decode( $output, true );
	return $result["query"]["tokens"]["userrightstoken"];
}

// Step 4: POST request to add or remove a user from a group
function change_userrights( $userrightstoken ) {
	global $endPoint;

	$params4 = [
		"action" => "userrights",
		"user" => "ABCDEF",
		"add" => "bot",
		"expiry" => "infinite",
		"reason" => "API Testing",
		"token" => $userrightstoken,
		"format" => "json"
	];

	$ch = curl_init();

	curl_setopt( $ch, CURLOPT_URL, $endPoint );
	curl_setopt( $ch, CURLOPT_POST, true );
	curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query( $params4 ) );
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
	curl_setopt( $ch, CURLOPT_COOKIEJAR, "cookie.txt" );
	curl_setopt( $ch, CURLOPT_COOKIEFILE, "cookie.txt" );

	$output = curl_exec( $ch );
	curl_close( $ch );

	echo ( $output );
}

JavaScript

/*  
    userrights.js
 
    MediaWiki API Demos
    Demo of `Userrights` module: Add and remove user rights by
	changing the user's group membership.

    MIT license
*/

var request = require('request').defaults({jar: true}),
    url = "http://dev.wiki.local.wmftest.net:8080/w/api.php";

// Step 1: GET request to fetch login token
function getLoginToken() {
    var params_0 = {
        action: "query",
        meta: "tokens",
        type: "login",
        format: "json"
    };

    request.get({ url: url, qs: params_0 }, function (error, res, body) {
        if (error) {
            return;
        }
        var data = JSON.parse(body);
        loginRequest(data.query.tokens.logintoken);
    });
}

// Step 2: POST request to log in. 
// Use of main account for login is not
// supported. Obtain credentials via Special:BotPasswords
// (https://www.mediawiki.org/wiki/Special:BotPasswords) for lgname & lgpassword
function loginRequest(login_token) {
    var params_1 = {
        action: "clientlogin",
        username: "username",
        password: "password",
        loginreturnurl: "http://127.0.0.1:5000/",
        logintoken: login_token,
        format: "json"
    };

    request.post({ url: url, form: params_1 }, function (error, res, body) {
        if (error) {
            return;
        }
        getUserRightsToken();
    });
}

// Step 3: GET request to fetch UserRights token
function getUserRightsToken() {
    var params_2 = {
        action: "query",
        meta: "tokens",
        type: "userrights",
        format: "json"
    };

    request.get({ url: url, qs: params_2 }, function(error, res, body) {
        if (error) {
            return;
        }
        var data = JSON.parse(body);
        userrights(data.query.tokens.userrightstoken);
    });
}

// Step 4: POST request to add or remove a user from a group
function userrights(userrights_token) {
    var params_3 = {
        action: "userrights",
        user: "ABCDEFG",
        add: "bot",
        expiry: "infinite",
        reason: "API Testing",
        token: userrights_token,
        format: "json"
    };

    request.post({ url: url, form: params_3 }, function (error, res, body) {
        if (error) {
            return;
        }
        console.log(body);
    });
}

// Start From Step 1
getLoginToken();

MediaWiki JS

/*
	userrights.js

	MediaWiki API Demos
	Demo of `Userrights` module: Add and remove user rights by
    changing the user's group membership.

	MIT License
*/

var params = {
		action: 'userrights',
		user: 'ABCD',
		add: 'sysop',
		reason: 'Added ABCD to the sysop group',
		format: 'json'
	},
	api = new mw.Api();

api.postWithToken( 'userrights', params ).done( function ( data ) {
	console.log( data );
} );

Errores posibles

Código Info
nouser Se debe establecer el parámetro user.
nosuchuser El usuario "user" no existe
Esto puede suceder al intentar cambiar los derechos de un usuario anónimo.
notoken Se debe establecer el parámetro token.
badtoken La ficha CSRF no es válida.
readonly La wiki está actualmente en modo de solo lectura.

Historial de parámetros

  • v1.23: Introducido userid

Notas adicionales

  • Por defecto, solo los usuarios del grupo burócrata pueden otorgar o eliminar derechos de usuario.
  • Algunos wikis permiten que los no burócratas otorguen o eliminen derechos de una base limitada, como restringir esas habilidades a la cuenta propia del usuario.
  • Si no posees la capacidad de otorgar o eliminar derechos al usuario objetivo, la API no arrojará un error; en cambio, los campos add y remove en la respuesta simplemente contendrán matrices vacías.

Véase también

  • Help:Derechos de usuarios y grupos - describe cómo los derechos de usuario y la pertenencia a grupos funcionan con mayor detalle
  • Special:ListGroupRights - Lista todos los derechos y privilegios conferidos a cada grupo de usuarios en un wiki en particular.
  • Special:UserRights - Una manera GUI para agregar o eliminar derechos de usuario, disponible en wikis que ejecutan v1.29+.
  • API:Usuarios - consigue información sobre una lista de usuarios, incluidos sus grupos y derechos.