BotClient.cs
1 using DiscordRewards; 2 using Logging; 3 using System.Net.Http.Json; 4 5 namespace TestNetRewarder 6 { 7 public class BotClient 8 { 9 private readonly Configuration configuration; 10 private readonly ILog log; 11 12 public BotClient(Configuration configuration, ILog log) 13 { 14 this.configuration = configuration; 15 this.log = log; 16 } 17 18 public async Task<bool> IsOnline() 19 { 20 var result = await HttpGet(); 21 return result == "Pong"; 22 } 23 24 public async Task<bool> SendRewards(EventsAndErrors command) 25 { 26 if (command == null) return false; 27 var result = await HttpPostJson(command); 28 log.Log("Reward response: " + result); 29 return result == "OK"; 30 } 31 32 private async Task<string> HttpGet() 33 { 34 try 35 { 36 var client = new HttpClient(); 37 var response = await client.GetAsync(GetUrl()); 38 return await response.Content.ReadAsStringAsync(); 39 } 40 catch (Exception ex) 41 { 42 log.Error(ex.ToString()); 43 return string.Empty; 44 } 45 } 46 47 private async Task<string> HttpPostJson<T>(T body) 48 { 49 try 50 { 51 using var client = new HttpClient(); 52 using var content = JsonContent.Create(body); 53 using var response = await client.PostAsync(GetUrl(), content); 54 return await response.Content.ReadAsStringAsync(); 55 } 56 catch (Exception ex) 57 { 58 log.Error(ex.ToString()); 59 return string.Empty; 60 } 61 } 62 63 private string GetUrl() 64 { 65 return $"{configuration.DiscordHost}:{configuration.DiscordPort}/api/reward"; 66 } 67 } 68 }