Edon
Edon

Reputation: 1216

How to send a channel message when a user changes status

I am trying to figure out how to send a message to a channel in discord when a user changes their status. I am trying to do this by calling a method that is in a separate file.

In my Program.cs

  public async Task StartAsync()
  {
    // Create instance of the class with the method I want to call
    Games statusChange = new Games();

    // call the method when a status changes
    _client.GuildMemberUpdated += statusChange.UpdateGameBeingPlayed;
  }

And the class I want to call (in a separate file):

public class Games : ModuleBase<SocketCommandContext>

    public async Task UpdateGameBeingPlayed(SocketGuildUser user, SocketUser userAgain)
    {
        // get channel id
        string strGuildId = user.Guild.Id.ToString();
        ulong ulongId = Convert.ToUInt64(strGuildId);

        // get the channel I want to update
        var channel = Context.Guild.GetChannel(ulongId) as SocketTextChannel; // Context here is undefined :(

        await channel.SendMessageAsync("a user has changed status!");
    } 
}

This implementation works until I try to use Context in my Games class. Context is undefined (because there is no context to get, I guess, not sure).

So I think the solution to this might be to import the _client from my Program.cs file and use it to send messages to the channel I want to update. However, I'm not sure how to do this.

So my questions are as follows:

  1. Is there any reason why _client should be private? I was told it should be, but never given an explanation.
  2. If passing around _client is the correct solution, how can I import it into my Games class?

Thanks!

Upvotes: 0

Views: 200

Answers (1)

Edon
Edon

Reputation: 1216

Poster here:

The answer was that I didn't need context to get channel after all, you can get channel from SocketGuildUser.

Working code:

public async Task UpdateGameBeingPlayed(SocketGuildUser user, SocketUser userAgain)
{
    string strGuildId = user.Guild.Id.ToString();
    ulong ulongId = Convert.ToUInt64(strGuildId);
    var channel = user.Guild.GetChannel(ulongId) as SocketTextChannel;
    await channel.SendMessageAsync("a user has changed status!");
}

Upvotes: 1

Related Questions