How to ban / unban a member from a channel?

How should I proceed to ban and unban a member from a channel ?

I tried different endpoints found in the api documentation :

  • api/v3/channels/{channelId}/users/ban
    => throws 401

  • api/v2/channel/{channelId}/users/ban
    => throws 401

  • sockets/channel.banUsers
    => throws 404

Obviously, I use them sending the proper body and headers.

I didn’t find any query in the sdk to achieve this.

Am I missing something here ?

Hello @jsharl error 401 is Unauthorized, means that you don’t have the permission to ban other users, you will have to be an admin. Another way for admin to ban users is via the console, please see the attached image below. If you have further questions, pls let us know :blush:

Means a channel moderator is not able to ban a member ?

Yes, correct, because moderator is a counted as a client role. In order to ban members, you must have administrator permission/role.

We tried everything regarding ban/unban or even mute/unmute but it seems like we can’t manage to make it work.

Everything I get is a 401 or a 404 in some cases.

For each channel we create, we want to be able to promote one or more members as moderator(s).
A moderator should be able to ban / unban (or mute / unmute ) basic members.

We want a former moderator for each room , and this moderator should be able to promote other members as moderator from the front-end of the app.

We don’t want the moderator to be global, but only for one room.

What would be the settings to achieve this?

Hi @jsharl since this action is not supported by our sdk as I mentioned above. Thus, I have double checked with the team for other possible ways, and yes, we do have a workaround to achieve this.

You can check for user role in your front-end first if they’re moderator or not. If yes, then you can call the ban user API using the hardcode admin access token. However, I would suggest you to build a ban API on your backend and inside that API, you can call Amity ban user API with the hardcode admin access token as it’s more secure and there’s no need for frontend update :pray:

Hi,
thx for your response.

You can check for user role in your front-end first if they’re moderator or not. If yes, then you can call the ban user API using the hardcode admin access token

Actually, this is what we are currently doing and talking about.

Can you please share your code with us? the team will help check, thank you :pray:

Base request for Amity :

async function amityRequest(body, endpoint, method) {
  const apiUrl = "https://api.eu.amity.co";
  const token = await checkAmityToken() // see below
    .catch((error) => {
      throw new Error(error);
    });

  const headers = {
    'Content-Type': 'application/json',
    Authorization: 'Bearer ' + token,
  };

  const response = await axios({
    headers,
    method,
    url: apiUrl + endpoint,
    body
  }).catch((error) => {
    throw new Error(error);
  });
  return response;
}

Function that gets the Amity token given a userId:
(This request is triggered at app launch)

export const getAmityToken: any = createAsyncThunk(
    'officialChatRoom/getAmityToken',
    async (userId, thunk) => {
        const result = await amityTokenRequest(`/api/v3/authentication/token?userId=${userId}`, 'get');
        return result.data; 
// The result is stored in the local storage
// Then a function called getAmityToken retrieves it (see base request above)
    }
);

Request from RTK :

(I guess the issue is somewhere here in the process… am I getting the good token ?)

export const banMember: any = createAsyncThunk(
    'officialChatRoom/banMember',
    async (data, thunk) => {
        const { channelId, body } = data;
        const result = await amityRequest(body, `/api/v3/channel/${channelId}/users/ban`, 'put');
        return result;
    }
);

Action called from the component after interaction:

dispatch(banMember(
                {
                    channelId: Config.APPID, // Config.APPID returns env variable data
                    body: {
                        channelId: Config.APPID,
                        userIds: [memberData._id],
                    }
                }
            )

Thx a lot for your time and help. :pray:

Hi @jsharl just to double confirm if you get the correct Admin access token that we mentioned, we’re referring to Amity’s console admin access token which you can generate from going to asc.amity.co

Log in → Settings → Admin Users → Click on setting icon in admin user
Screen Shot 2565-05-31 at 14.56.02

and there will be a popup, then click on Generate access token. You can hardcode this admin access token and use it when calling ban user API

Indeed, I was not using this one. I was using the token related to the user from :

`/api/v3/authentication/token?userId=${userId}`

So I generated the access token from the console and hardcode it in the api request header, like so :

async function amityRequest(body, endpoint, method) {
  const apiUrl = "https://api.eu.amity.co";
  const token = '1d2u3m4m5y6t7o8k9e0n'; // access token from the console

  let headers = {
    'Content-Type': 'application/json',
    Authorization: 'Bearer ' + token,
  };

  const response = await axios({
    headers,
    method,
    url: apiUrl + endpoint,
    body
  }).catch((error) => {
    console.log(error);
  });
  return response;
}

Issue is the same, I get a 404.

Hi @jsharl can you please help try the new code snippet below and see if the issue still persists?

async function amityRequest() {
  const axios = require('axios').default;
  const apiUrl = "https://api.sg.amity.co";
  const token = '${adminToken}'; // access token from the console

  let headers = {
    'Content-Type': 'application/json',
    Authorization: 'Bearer ' + token,
  };

  var data = JSON.stringify({
    "userId": "${userId}"
  });

  const response = await axios({
    headers: headers,
    method: 'post',
    url: apiUrl + '/api/v2/users/ban',
    data: data
  }).catch((error) => {
    console.log(error);
  });
  console.log(JSON.stringify(response));
  return response;
}

Thank you

Hi Andrew,

Thx for your response.

I just tried your solution and I get a code 422.

Plus, what I’m trying to achieve is to ban a user for particular channel and not globally so I think I would need to send the channelId at some point.

ps: since I’m in europe , I used this url :
const apiUrl = "https://api.eu.amity.co";

Hi @jsharl The 422 error is caused by a parameter error when calling an API, can you help share with us your request body?

Hi @SocialPlus_Support ,

Here’s the body I sent the last time I tried :

Action triggered from the component :

 dispatch(banMember(
                {
                    body: JSON.stringify({
                        "userId": memberData._id,
                    })
                }
            )

Request from RTK :

export const banMember: any = createAsyncThunk(
    'officialChatRoom/banMember',
    async (data, thunk) => {
        const { body } = data;
        console.log(body);
        const result = await amityBanRequest(body, `/api/v2/users/ban`, 'post');

        return result;
    }
);

Just so you got the request parameters / headers :

async function amityBanRequest(body, endpoint, method) {
  const apiUrl = "https://api.eu.amity.co";
  const token = 'dummyadmintokenfromtheconsole';

  let headers = {
    'Content-Type': 'application/json',
    Authorization: 'Bearer ' + token,
  };

  const response = await axios({
    headers,
    method,
    url: apiUrl + endpoint,
    body
  }).catch((error) => {
    console.log(error);

  });
  console.log(headers,
    method,
    apiUrl + endpoint,
    body);
  return response;
}

Hi @jsharl

Please change the “body” key inside axios({ }) to “data” key instead as shown below.

data: JSON.stringify({
    "userId": "${userId}"
  })