2017-10-19 31 views
1

我想創建一個命令,返回當前玩特定遊戲的公會成員的數量。Discord.NET玩同一遊戲的用戶

示例(!是我的前綴):!打了英雄聯盟。

如果有5名成員打聯賽的傳奇,輸出:

There are 5 users currently playing League of Legends.

我設置以下,從調試我能夠拿起v.Game.toString()返回正確的字符串,但由於某種原因,如果語句不觸發。它還捕捉到每當成員不玩遊戲時引發的異常(我認爲它是空的?),是否有解決方法?爲什麼這不算有多少成員玩某個遊戲?

[Command("playing")] 
    public async Task playingGame(params string[] s) 
    { 
     string gameName = ""; 
     int count = 0; 

     for (int i = 0; i < s.Length; i++) 
     { 
      gameName += s[i] + " "; 
     } 

     await Context.Channel.SendMessageAsync("Looking for: " + gameName); 

     var u = Context.Guild.Users; 
     foreach (var v in u) 
     { 
      await Context.Channel.SendMessageAsync("v = " + v.ToString()); 
      try 
      { 
       await Context.Channel.SendMessageAsync(v.Game.ToString()); 
       if (v.Game.ToString().ToLower().Equals(gameName.ToLower())) 
       { 
        count++; 
        await Context.Channel.SendMessageAsync("Found match, count = " + count); 
       } 
      } 
      catch (Exception x) 
      { 
       await Context.Channel.SendMessageAsync("Exception throw caught"); 
      } 
     } 

     if (count > 1) { 
      await Context.Channel.SendMessageAsync("There are " + count + " users currently playing " + gameName + "."); 
     } 
     else if (count == 1) 
     { 
      await Context.Channel.SendMessageAsync("There is " + count + " user currently playing " + gameName + "."); 
     } 
     else if (count == 0) 
     { 
      await Context.Channel.SendMessageAsync("No one is currently playing " + gameName + "."); 
     } 
    } 

這是例外:

System.ArgumentException: Argument cannot be blank 
Parameter name: Content 
at Discord.Preconditions.NotNullOrEmpty(String obj, String name, String msg) 
at Discord.API.DiscordRestApiClient.<CreateMessageAsync>d__77.MoveNext() 
--- End of stack trace from previous location where exception was thrown --- 

產品圖,其中if語句應該觸發(用戶名封鎖隱私的原因):

enter image description here

+0

可以共享例外? – aloisdg

+0

@aloisdg添加了if語句應該觸發的異常消息和圖片。 –

+0

我知道這個字符串是空的,因爲他們沒有玩遊戲,所以它沒有被初始化。我主要關心的是if語句沒有觸發, –

回答

1

沒有必要有params string[] s爲遊戲參數。只需使用Remainder屬性即可。

我也簡化了這個代碼很多

[Command("playing")] 
    public async Task GetUsersPlaying([Remainder]string game) 
    { 
     await Context.Message.DeleteAsync(); 

     var users = Context.Guild.Users.Where(x => x.Game.ToString() == game).Distinct().Select(x => x.Username); 
     var count = users.Count(); 

     var SeparatedList = string.Join(", ", users); 

     string message; 
     if (count > 1) 
      message = $"There are {count} users playing {game}. [{SeparatedList}]"; 
     else if (count == 1) 
      message = $"There is {count} user playing {game}. [{SeparatedList}]"; 
     else 
      message = $"There is no one playing {game}."; 

     await Context.Channel.SendMessageAsync(message); 
    } 
+0

這很優雅,使用Linq。爲了在句子後顯示球員列表,我將如何創建這些x成員名稱的列表? –

+1

你也可以從'UserList'中獲得計數,而不是有一個完全不同的變量。 – Unknown