L E
L E

Reputation: 3

C# discord bot get member count in my server

I am studying C# while developing a Discord bot.

How do I get the number of members on my server?

I found SocketGuild.MemberCount:

https://discord.foxbot.me/docs/api/Discord.WebSocket.SocketGuild.html

But the SocketGuild constructor doesn't exist.

The way I've tried:

SocketGuild socketGuild = new SocketGuild(); // impossible.
int temp = socketGuild.MemberCount;

How can I fix it?

Upvotes: 0

Views: 1235

Answers (1)

Sani Huttunen
Sani Huttunen

Reputation: 24385

You need to get the SocketGuildChannel from the client object that is connected to the server. From reading the documentation then something like this should work:

First connect to the server (snippet taken from documentation guide):

private DiscordSocketClient _client;

public async Task MainAsync()
{
    _client = new DiscordSocketClient();

    _client.Log += Log;

    //  You can assign your bot token to a string, and pass that in to connect.
    //  This is, however, insecure, particularly if you plan to have your code hosted in a public repository.
    var token = "token";

    // Some alternative options would be to keep your token in an Environment Variable or a standalone file.
    // var token = Environment.GetEnvironmentVariable("NameOfYourEnvironmentVariable");
    // var token = File.ReadAllText("token.txt");
    // var token = JsonConvert.DeserializeObject<AConfigurationClass>(File.ReadAllText("config.json")).Token;

    await _client.LoginAsync(TokenType.Bot, token);
    await _client.StartAsync();

    // Block this task until the program is closed.
    await Task.Delay(-1);
}

Get the number of members:

public int GetGuildMemberCount(SocketChannel channel)
{
    var guild = (channel as SocketGuildChannel)?.Guild;
    return guild?.MemberCount;
}

Call it with

var channelId = xxxxxx; // The snowflake identifier of the channel (e.g. 381889909113225237).
var channel = _client.GetChannel(channelID);
var memberCount = GetGuildMemberCount(channel);

Or you could perhaps use the client directly to get the SocketGuild

var guildId = xxxxxx; // The guild snowflake identifier.
var guild = _client.GetGuild(guildId);
var memberCount = guild?.MemberCount;

Disclaimer: Examples above are untested and constructed from my understanding of the documentation.

Upvotes: 1

Related Questions