【问题标题】:How to send a channel message when a user changes status如何在用户更改状态时发送频道消息
【发布时间】:2023-03-26 08:57:01
【问题描述】:

我试图弄清楚当用户更改其状态时如何将消息发送到不和谐的频道。我试图通过调用单独文件中的方法来做到这一点。

在我的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;
  }

以及我要调用的类(在单独的文件中):

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!");
    } 
}

这个实现一直有效,直到我尝试在我的 Games 类中使用 Context。上下文未定义(因为没有上下文可获取,我猜,不确定)。

所以我认为解决这个问题的方法可能是从我的 Program.cs 文件中导入 _client 并使用它向我要更新的频道发送消息。但是,我不确定如何执行此操作。

所以我的问题如下:

  1. _client 是否应该是私有的?有人告诉我 应该是,但从未给出解释。
  2. 如果传递 _client 是正确的解决方案,我如何将它导入到我的 Games 类中?

谢谢!

【问题讨论】:

    标签: c# discord discord.net


    【解决方案1】:

    这里是海报:

    答案是我毕竟不需要上下文来获取频道,你可以从 SocketGuildUser 获取频道。

    工作代码:

    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!");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-30
      • 2021-10-20
      • 2019-01-12
      • 1970-01-01
      • 2021-11-23
      • 2018-12-09
      • 2021-01-01
      相关资源
      最近更新 更多