Merge branch 'refactoring' into 'master'

Refactoring

See merge request open/Geekbot.net!11
This commit is contained in:
Daan 2018-05-02 23:10:39 +00:00
commit ce1a3d057a
104 changed files with 867 additions and 735 deletions

View file

@ -5,9 +5,11 @@ using Discord;
using Discord.Commands; using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Geekbot.net.Lib.ErrorHandling;
using Geekbot.net.Lib.Localization;
using StackExchange.Redis; using StackExchange.Redis;
namespace Geekbot.net.Commands namespace Geekbot.net.Commands.Admin
{ {
[Group("admin")] [Group("admin")]
[RequireUserPermission(GuildPermission.Administrator)] [RequireUserPermission(GuildPermission.Administrator)]

View file

@ -5,9 +5,11 @@ using Discord;
using Discord.Commands; using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Geekbot.net.Lib.ErrorHandling;
using Geekbot.net.Lib.UserRepository;
using StackExchange.Redis; using StackExchange.Redis;
namespace Geekbot.net.Commands namespace Geekbot.net.Commands.Admin
{ {
[Group("mod")] [Group("mod")]
[RequireUserPermission(GuildPermission.KickMembers)] [RequireUserPermission(GuildPermission.KickMembers)]

View file

@ -4,9 +4,12 @@ using Discord;
using Discord.Commands; using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Geekbot.net.Lib.ErrorHandling;
using Geekbot.net.Lib.Logger;
using Geekbot.net.Lib.UserRepository;
using StackExchange.Redis; using StackExchange.Redis;
namespace Geekbot.net.Commands namespace Geekbot.net.Commands.Admin
{ {
[Group("owner")] [Group("owner")]
[RequireUserPermission(GuildPermission.Administrator)] [RequireUserPermission(GuildPermission.Administrator)]

View file

@ -6,9 +6,11 @@ using Discord;
using Discord.Commands; using Discord.Commands;
using Discord.Net; using Discord.Net;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Geekbot.net.Lib.ErrorHandling;
using Geekbot.net.Lib.ReactionListener;
using StackExchange.Redis; using StackExchange.Redis;
namespace Geekbot.net.Commands namespace Geekbot.net.Commands.Admin
{ {
[Group("role")] [Group("role")]
public class Role : ModuleBase public class Role : ModuleBase

View file

@ -3,8 +3,9 @@ using System.Threading.Tasks;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Geekbot.net.Lib.ErrorHandling;
namespace Geekbot.net.Commands namespace Geekbot.net.Commands.Admin
{ {
public class Say : ModuleBase public class Say : ModuleBase
{ {

View file

@ -2,8 +2,10 @@
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Geekbot.net.Lib.ErrorHandling;
using Geekbot.net.Lib.UserRepository;
namespace Geekbot.net.Commands namespace Geekbot.net.Commands.Games
{ {
[Group("battletag")] [Group("battletag")]
public class BattleTag : ModuleBase public class BattleTag : ModuleBase

View file

@ -3,11 +3,12 @@ using System.Threading.Tasks;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Geekbot.net.Lib.ErrorHandling;
using Geekbot.net.Lib.UserRepository;
using OverwatchAPI; using OverwatchAPI;
using OverwatchAPI.Config; using OverwatchAPI.Config;
using StackExchange.Redis;
namespace Geekbot.net.Commands namespace Geekbot.net.Commands.Games
{ {
[Group("ow")] [Group("ow")]
public class Overwatch : ModuleBase public class Overwatch : ModuleBase

View file

@ -4,9 +4,10 @@ using System.Threading.Tasks;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Geekbot.net.Lib.ErrorHandling;
using PokeAPI; using PokeAPI;
namespace Geekbot.net.Commands namespace Geekbot.net.Commands.Games
{ {
public class Pokedex : ModuleBase public class Pokedex : ModuleBase
{ {

View file

@ -2,9 +2,11 @@
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Geekbot.net.Lib.ErrorHandling;
using Geekbot.net.Lib.Localization;
using StackExchange.Redis; using StackExchange.Redis;
namespace Geekbot.net.Commands namespace Geekbot.net.Commands.Games
{ {
public class Roll : ModuleBase public class Roll : ModuleBase
{ {

View file

@ -1,15 +1,15 @@
using System; using System;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Geekbot.net.Lib.ErrorHandling;
using StackExchange.Redis; using StackExchange.Redis;
using Utf8Json; using Utf8Json;
namespace Geekbot.net.Commands namespace Geekbot.net.Commands.Integrations.Google
{ {
public class Google : ModuleBase public class Google : ModuleBase
{ {
@ -40,7 +40,7 @@ namespace Geekbot.net.Commands
var url = new Uri($"https://kgsearch.googleapis.com/v1/entities:search?languages=en&limit=1&query={searchText}&key={apiKey}"); var url = new Uri($"https://kgsearch.googleapis.com/v1/entities:search?languages=en&limit=1&query={searchText}&key={apiKey}");
var responseString = client.DownloadString(url); var responseString = client.DownloadString(url);
var response = JsonSerializer.Deserialize<GoogleKgApiResponse>(responseString); var response = JsonSerializer.Deserialize<GoogleKgApiResponseDto>(responseString);
if (!response.ItemListElement.Any()) if (!response.ItemListElement.Any())
{ {
@ -48,13 +48,13 @@ namespace Geekbot.net.Commands
return; return;
} }
var data = response.ItemListElement.First().Result; var data = response.ItemListElement.First().ResultDto;
var eb = new EmbedBuilder(); var eb = new EmbedBuilder();
eb.Title = data.Name; eb.Title = data.Name;
if(!string.IsNullOrEmpty(data.Description)) eb.WithDescription(data.Description); if(!string.IsNullOrEmpty(data.Description)) eb.WithDescription(data.Description);
if(!string.IsNullOrEmpty(data.DetailedDescription?.Url)) eb.WithUrl(data.DetailedDescription.Url); if(!string.IsNullOrEmpty(data.DetailedDtoDescription?.Url)) eb.WithUrl(data.DetailedDtoDescription.Url);
if(!string.IsNullOrEmpty(data.DetailedDescription?.ArticleBody)) eb.AddField("Details", data.DetailedDescription.ArticleBody); if(!string.IsNullOrEmpty(data.DetailedDtoDescription?.ArticleBody)) eb.AddField("Details", data.DetailedDtoDescription.ArticleBody);
if(!string.IsNullOrEmpty(data.Image?.ContentUrl)) eb.WithThumbnailUrl(data.Image.ContentUrl); if(!string.IsNullOrEmpty(data.ImageDto?.ContentUrl)) eb.WithThumbnailUrl(data.ImageDto.ContentUrl);
await ReplyAsync("", false, eb.Build()); await ReplyAsync("", false, eb.Build());
} }
@ -64,37 +64,5 @@ namespace Geekbot.net.Commands
_errorHandler.HandleCommandException(e, Context); _errorHandler.HandleCommandException(e, Context);
} }
} }
public class GoogleKgApiResponse
{
public List<GoogleKgApiElement> ItemListElement { get; set; }
public class GoogleKgApiElement
{
public GoogleKgApiResult Result { get; set; }
public double ResultScore { get; set; }
}
public class GoogleKgApiResult
{
public string Name { get; set; }
public string Description { get; set; }
public GoogleKgApiImage Image { get; set; }
public GoogleKgApiDetailed DetailedDescription { get; set; }
}
public class GoogleKgApiImage
{
public string ContentUrl { get; set; }
public string Url { get; set; }
}
public class GoogleKgApiDetailed
{
public string ArticleBody { get; set; }
public string Url { get; set; }
public string License { get; set; }
}
}
} }
} }

View file

@ -0,0 +1,9 @@
namespace Geekbot.net.Commands.Integrations.Google
{
public class GoogleKgApiDetailedDto
{
public string ArticleBody { get; set; }
public string Url { get; set; }
public string License { get; set; }
}
}

View file

@ -0,0 +1,8 @@
namespace Geekbot.net.Commands.Integrations.Google
{
public class GoogleKgApiElementDto
{
public GoogleKgApiResultDto ResultDto { get; set; }
public double ResultScore { get; set; }
}
}

View file

@ -0,0 +1,8 @@
namespace Geekbot.net.Commands.Integrations.Google
{
public class GoogleKgApiImageDto
{
public string ContentUrl { get; set; }
public string Url { get; set; }
}
}

View file

@ -0,0 +1,9 @@
using System.Collections.Generic;
namespace Geekbot.net.Commands.Integrations.Google
{
public class GoogleKgApiResponseDto
{
public List<GoogleKgApiElementDto> ItemListElement { get; set; }
}
}

View file

@ -0,0 +1,10 @@
namespace Geekbot.net.Commands.Integrations.Google
{
public class GoogleKgApiResultDto
{
public string Name { get; set; }
public string Description { get; set; }
public GoogleKgApiImageDto ImageDto { get; set; }
public GoogleKgApiDetailedDto DetailedDtoDescription { get; set; }
}
}

View file

@ -5,9 +5,11 @@ using System.Threading.Tasks;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Geekbot.net.Lib.Converters;
using Geekbot.net.Lib.ErrorHandling;
using MtgApiManager.Lib.Service; using MtgApiManager.Lib.Service;
namespace Geekbot.net.Commands namespace Geekbot.net.Commands.Integrations
{ {
public class Magicthegathering : ModuleBase public class Magicthegathering : ModuleBase
{ {

View file

@ -4,8 +4,10 @@ using System.Web;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Geekbot.net.Lib.Clients;
using Geekbot.net.Lib.ErrorHandling;
namespace Geekbot.net.Commands namespace Geekbot.net.Commands.Integrations
{ {
public class Mal : ModuleBase public class Mal : ModuleBase
{ {

View file

@ -0,0 +1,12 @@
namespace Geekbot.net.Commands.Integrations.UbranDictionary
{
internal class UrbanListItemDto
{
public string Definition { get; set; }
public string Permalink { get; set; }
public string ThumbsUp { get; set; }
public string Word { get; set; }
public string Example { get; set; }
public string ThumbsDown { get; set; }
}
}

View file

@ -0,0 +1,10 @@
using System.Collections.Generic;
namespace Geekbot.net.Commands.Integrations.UbranDictionary
{
internal class UrbanResponseDto
{
public string[] Tags { get; set; }
public List<UrbanListItemDto> List { get; set; }
}
}

View file

@ -1,14 +1,14 @@
using System; using System;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Net.Http; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Geekbot.net.Lib.ErrorHandling;
using Newtonsoft.Json; using Newtonsoft.Json;
namespace Geekbot.net.Commands namespace Geekbot.net.Commands.Integrations.UbranDictionary
{ {
public class UrbanDictionary : ModuleBase public class UrbanDictionary : ModuleBase
{ {
@ -33,7 +33,7 @@ namespace Geekbot.net.Commands
response.EnsureSuccessStatusCode(); response.EnsureSuccessStatusCode();
var stringResponse = await response.Content.ReadAsStringAsync(); var stringResponse = await response.Content.ReadAsStringAsync();
var definitions = JsonConvert.DeserializeObject<UrbanResponse>(stringResponse); var definitions = JsonConvert.DeserializeObject<UrbanResponseDto>(stringResponse);
if (definitions.List.Count == 0) if (definitions.List.Count == 0)
{ {
await ReplyAsync("That word hasn't been defined..."); await ReplyAsync("That word hasn't been defined...");
@ -63,21 +63,5 @@ namespace Geekbot.net.Commands
_errorHandler.HandleCommandException(e, Context); _errorHandler.HandleCommandException(e, Context);
} }
} }
private class UrbanResponse
{
public string[] Tags { get; set; }
public List<UrbanListItem> List { get; set; }
}
private class UrbanListItem
{
public string Definition { get; set; }
public string Permalink { get; set; }
public string ThumbsUp { get; set; }
public string Word { get; set; }
public string Example { get; set; }
public string ThumbsDown { get; set; }
}
} }
} }

View file

@ -6,12 +6,13 @@ using System.Threading.Tasks;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Geekbot.net.Lib.ErrorHandling;
using HtmlAgilityPack; using HtmlAgilityPack;
using StackExchange.Redis; using StackExchange.Redis;
using WikipediaApi; using WikipediaApi;
using WikipediaApi.Page; using WikipediaApi.Page;
namespace Geekbot.net.Commands namespace Geekbot.net.Commands.Integrations
{ {
public class Wikipedia : ModuleBase public class Wikipedia : ModuleBase
{ {

View file

@ -2,11 +2,12 @@
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Geekbot.net.Lib.ErrorHandling;
using Google.Apis.Services; using Google.Apis.Services;
using Google.Apis.YouTube.v3; using Google.Apis.YouTube.v3;
using StackExchange.Redis; using StackExchange.Redis;
namespace Geekbot.net.Commands namespace Geekbot.net.Commands.Integrations
{ {
public class Youtube : ModuleBase public class Youtube : ModuleBase
{ {

View file

@ -1,58 +1,54 @@
using System; using System;
using System.Net.Http; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Newtonsoft.Json; using Geekbot.net.Lib.ErrorHandling;
using Newtonsoft.Json;
namespace Geekbot.net.Commands
{ namespace Geekbot.net.Commands.Randomness.Cat
public class Cat : ModuleBase {
{ public class Cat : ModuleBase
private readonly IErrorHandler _errorHandler; {
private readonly IErrorHandler _errorHandler;
public Cat(IErrorHandler errorHandler)
{ public Cat(IErrorHandler errorHandler)
_errorHandler = errorHandler; {
} _errorHandler = errorHandler;
}
[Command("cat", RunMode = RunMode.Async)]
[Remarks(CommandCategories.Randomness)] [Command("cat", RunMode = RunMode.Async)]
[Summary("Return a random image of a cat.")] [Remarks(CommandCategories.Randomness)]
public async Task Say() [Summary("Return a random image of a cat.")]
{ public async Task Say()
try {
{ try
using (var client = new HttpClient()) {
{ using (var client = new HttpClient())
try {
{ try
client.BaseAddress = new Uri("https://aws.random.cat"); {
var response = await client.GetAsync("/meow"); client.BaseAddress = new Uri("https://aws.random.cat");
response.EnsureSuccessStatusCode(); var response = await client.GetAsync("/meow");
response.EnsureSuccessStatusCode();
var stringResponse = await response.Content.ReadAsStringAsync();
var catFile = JsonConvert.DeserializeObject<CatResponse>(stringResponse); var stringResponse = await response.Content.ReadAsStringAsync();
var eb = new EmbedBuilder(); var catFile = JsonConvert.DeserializeObject<CatResponseDto>(stringResponse);
eb.ImageUrl = catFile.File; var eb = new EmbedBuilder();
await ReplyAsync("", false, eb.Build()); eb.ImageUrl = catFile.File;
} await ReplyAsync("", false, eb.Build());
catch }
{ catch
await ReplyAsync("Seems like the dog cought the cat (error occured)"); {
} await ReplyAsync("Seems like the dog cought the cat (error occured)");
} }
} }
catch (Exception e) }
{ catch (Exception e)
_errorHandler.HandleCommandException(e, Context); {
} _errorHandler.HandleCommandException(e, Context);
} }
}
private class CatResponse }
{
public string File { get; set; }
}
}
} }

View file

@ -0,0 +1,7 @@
namespace Geekbot.net.Commands.Randomness.Cat
{
internal class CatResponseDto
{
public string File { get; set; }
}
}

View file

@ -1,72 +1,73 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Geekbot.net.Lib.Media; using Geekbot.net.Lib.ErrorHandling;
using Geekbot.net.Lib.Media;
namespace Geekbot.net.Commands
{ namespace Geekbot.net.Commands.Randomness
public class CheckEm : ModuleBase {
{ public class CheckEm : ModuleBase
private readonly IMediaProvider _checkEmImages; {
private readonly IErrorHandler _errorHandler; private readonly IMediaProvider _checkEmImages;
private readonly IErrorHandler _errorHandler;
public CheckEm(IMediaProvider mediaProvider, IErrorHandler errorHandler)
{ public CheckEm(IMediaProvider mediaProvider, IErrorHandler errorHandler)
_checkEmImages = mediaProvider; {
_errorHandler = errorHandler; _checkEmImages = mediaProvider;
} _errorHandler = errorHandler;
}
[Command("checkem", RunMode = RunMode.Async)]
[Remarks(CommandCategories.Randomness)] [Command("checkem", RunMode = RunMode.Async)]
[Summary("Check for dubs")] [Remarks(CommandCategories.Randomness)]
public async Task MuhDubs() [Summary("Check for dubs")]
{ public async Task MuhDubs()
try {
{ try
var number = new Random().Next(10000000, 99999999); {
var dubtriqua = ""; var number = new Random().Next(10000000, 99999999);
var dubtriqua = "";
var ns = GetIntArray(number);
if (ns[7] == ns[6]) var ns = GetIntArray(number);
{ if (ns[7] == ns[6])
dubtriqua = "DUBS"; {
if (ns[6] == ns[5]) dubtriqua = "DUBS";
{ if (ns[6] == ns[5])
dubtriqua = "TRIPS"; {
if (ns[5] == ns[4]) dubtriqua = "TRIPS";
dubtriqua = "QUADS"; if (ns[5] == ns[4])
} dubtriqua = "QUADS";
} }
}
var sb = new StringBuilder();
sb.AppendLine($"Check em {Context.User.Mention}"); var sb = new StringBuilder();
sb.AppendLine($"**{number}**"); sb.AppendLine($"Check em {Context.User.Mention}");
if (!string.IsNullOrEmpty(dubtriqua)) sb.AppendLine($"**{number}**");
sb.AppendLine($":tada: {dubtriqua} :tada:"); if (!string.IsNullOrEmpty(dubtriqua))
sb.AppendLine(_checkEmImages.GetCheckem()); sb.AppendLine($":tada: {dubtriqua} :tada:");
sb.AppendLine(_checkEmImages.GetCheckem());
await ReplyAsync(sb.ToString());
} await ReplyAsync(sb.ToString());
catch (Exception e) }
{ catch (Exception e)
_errorHandler.HandleCommandException(e, Context); {
} _errorHandler.HandleCommandException(e, Context);
} }
}
private int[] GetIntArray(int num)
{ private int[] GetIntArray(int num)
var listOfInts = new List<int>(); {
while (num > 0) var listOfInts = new List<int>();
{ while (num > 0)
listOfInts.Add(num % 10); {
num = num / 10; listOfInts.Add(num % 10);
} num = num / 10;
}
listOfInts.Reverse();
return listOfInts.ToArray(); listOfInts.Reverse();
} return listOfInts.ToArray();
} }
}
} }

View file

@ -0,0 +1,7 @@
namespace Geekbot.net.Commands.Randomness.Chuck
{
internal class ChuckNorrisJokeResponseDto
{
public string Value { get; set; }
}
}

View file

@ -4,9 +4,10 @@ using System.Net.Http.Headers;
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Geekbot.net.Lib.ErrorHandling;
using Newtonsoft.Json; using Newtonsoft.Json;
namespace Geekbot.net.Commands namespace Geekbot.net.Commands.Randomness.Chuck
{ {
public class ChuckNorrisJokes : ModuleBase public class ChuckNorrisJokes : ModuleBase
{ {
@ -34,7 +35,7 @@ namespace Geekbot.net.Commands
response.EnsureSuccessStatusCode(); response.EnsureSuccessStatusCode();
var stringResponse = await response.Content.ReadAsStringAsync(); var stringResponse = await response.Content.ReadAsStringAsync();
var data = JsonConvert.DeserializeObject<ChuckNorrisJokeResponse>(stringResponse); var data = JsonConvert.DeserializeObject<ChuckNorrisJokeResponseDto>(stringResponse);
await ReplyAsync(data.Value); await ReplyAsync(data.Value);
} }
catch (HttpRequestException) catch (HttpRequestException)
@ -48,10 +49,5 @@ namespace Geekbot.net.Commands
_errorHandler.HandleCommandException(e, Context); _errorHandler.HandleCommandException(e, Context);
} }
} }
private class ChuckNorrisJokeResponse
{
public string Value { get; set; }
}
} }
} }

View file

@ -0,0 +1,7 @@
namespace Geekbot.net.Commands.Randomness.Dad
{
internal class DadJokeResponseDto
{
public string Joke { get; set; }
}
}

View file

@ -4,9 +4,10 @@ using System.Net.Http.Headers;
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Geekbot.net.Lib.ErrorHandling;
using Newtonsoft.Json; using Newtonsoft.Json;
namespace Geekbot.net.Commands namespace Geekbot.net.Commands.Randomness.Dad
{ {
public class DadJokes : ModuleBase public class DadJokes : ModuleBase
{ {
@ -34,7 +35,7 @@ namespace Geekbot.net.Commands
response.EnsureSuccessStatusCode(); response.EnsureSuccessStatusCode();
var stringResponse = await response.Content.ReadAsStringAsync(); var stringResponse = await response.Content.ReadAsStringAsync();
var data = JsonConvert.DeserializeObject<DadJokeResponse>(stringResponse); var data = JsonConvert.DeserializeObject<DadJokeResponseDto>(stringResponse);
await ReplyAsync(data.Joke); await ReplyAsync(data.Joke);
} }
catch (HttpRequestException) catch (HttpRequestException)
@ -48,10 +49,5 @@ namespace Geekbot.net.Commands
_errorHandler.HandleCommandException(e, Context); _errorHandler.HandleCommandException(e, Context);
} }
} }
private class DadJokeResponse
{
public string Joke { get; set; }
}
} }
} }

View file

@ -4,9 +4,10 @@ using System.Threading.Tasks;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Geekbot.net.Lib.ErrorHandling;
using Newtonsoft.Json; using Newtonsoft.Json;
namespace Geekbot.net.Commands namespace Geekbot.net.Commands.Randomness.Dog
{ {
public class Dog : ModuleBase public class Dog : ModuleBase
{ {
@ -33,7 +34,7 @@ namespace Geekbot.net.Commands
response.EnsureSuccessStatusCode(); response.EnsureSuccessStatusCode();
var stringResponse = await response.Content.ReadAsStringAsync(); var stringResponse = await response.Content.ReadAsStringAsync();
var dogFile = JsonConvert.DeserializeObject<DogResponse>(stringResponse); var dogFile = JsonConvert.DeserializeObject<DogResponseDto>(stringResponse);
var eb = new EmbedBuilder(); var eb = new EmbedBuilder();
eb.ImageUrl = dogFile.Url; eb.ImageUrl = dogFile.Url;
await ReplyAsync("", false, eb.Build()); await ReplyAsync("", false, eb.Build());
@ -49,10 +50,5 @@ namespace Geekbot.net.Commands
_errorHandler.HandleCommandException(e, Context); _errorHandler.HandleCommandException(e, Context);
} }
} }
private class DogResponse
{
public string Url { get; set; }
}
} }
} }

View file

@ -0,0 +1,7 @@
namespace Geekbot.net.Commands.Randomness.Dog
{
internal class DogResponseDto
{
public string Url { get; set; }
}
}

View file

@ -3,8 +3,9 @@ using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Geekbot.net.Lib.ErrorHandling;
namespace Geekbot.net.Commands namespace Geekbot.net.Commands.Randomness
{ {
public class EightBall : ModuleBase public class EightBall : ModuleBase
{ {

View file

@ -3,7 +3,7 @@ using Discord.Commands;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Geekbot.net.Lib.Media; using Geekbot.net.Lib.Media;
namespace Geekbot.net.Commands namespace Geekbot.net.Commands.Randomness
{ {
public class Fortune : ModuleBase public class Fortune : ModuleBase
{ {

View file

@ -3,8 +3,9 @@ using System.Net;
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Geekbot.net.Lib.ErrorHandling;
namespace Geekbot.net.Commands namespace Geekbot.net.Commands.Randomness
{ {
public class Gdq : ModuleBase public class Gdq : ModuleBase
{ {

View file

@ -4,7 +4,7 @@ using Discord.Commands;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Geekbot.net.Lib.Media; using Geekbot.net.Lib.Media;
namespace Geekbot.net.Commands namespace Geekbot.net.Commands.Randomness
{ {
public class RandomAnimals : ModuleBase public class RandomAnimals : ModuleBase
{ {

View file

@ -3,9 +3,10 @@ using System.Threading.Tasks;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Geekbot.net.Lib.ErrorHandling;
using StackExchange.Redis; using StackExchange.Redis;
namespace Geekbot.net.Commands namespace Geekbot.net.Commands.Randomness
{ {
public class Ship : ModuleBase public class Ship : ModuleBase
{ {

View file

@ -4,9 +4,10 @@ using System.Threading.Tasks;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Geekbot.net.Lib.ErrorHandling;
using StackExchange.Redis; using StackExchange.Redis;
namespace Geekbot.net.Commands namespace Geekbot.net.Commands.Randomness
{ {
public class Slap : ModuleBase public class Slap : ModuleBase
{ {

View file

@ -4,9 +4,11 @@ using System.Threading.Tasks;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Geekbot.net.Lib.ErrorHandling;
using Geekbot.net.Lib.Levels;
using StackExchange.Redis; using StackExchange.Redis;
namespace Geekbot.net.Commands namespace Geekbot.net.Commands.User
{ {
public class GuildInfo : ModuleBase public class GuildInfo : ModuleBase
{ {
@ -51,12 +53,5 @@ namespace Geekbot.net.Commands
_errorHandler.HandleCommandException(e, Context); _errorHandler.HandleCommandException(e, Context);
} }
} }
public static string FirstCharToUpper(string input)
{
if (string.IsNullOrEmpty(input))
throw new ArgumentException("ARGH!");
return input.First().ToString().ToUpper() + input.Substring(1);
}
} }
} }

View file

@ -3,9 +3,11 @@ using System.Threading.Tasks;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Geekbot.net.Lib.ErrorHandling;
using Geekbot.net.Lib.Localization;
using StackExchange.Redis; using StackExchange.Redis;
namespace Geekbot.net.Commands namespace Geekbot.net.Commands.User
{ {
public class Karma : ModuleBase public class Karma : ModuleBase
{ {

View file

@ -6,9 +6,13 @@ using System.Threading.Tasks;
using Discord.Commands; using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Geekbot.net.Lib.Converters;
using Geekbot.net.Lib.ErrorHandling;
using Geekbot.net.Lib.Logger;
using Geekbot.net.Lib.UserRepository;
using StackExchange.Redis; using StackExchange.Redis;
namespace Geekbot.net.Commands namespace Geekbot.net.Commands.User.Rank
{ {
public class Rank : ModuleBase public class Rank : ModuleBase
{ {
@ -69,7 +73,7 @@ namespace Geekbot.net.Commands
} }
if (type == "Messages") sortedList.RemoveAt(0); if (type == "Messages") sortedList.RemoveAt(0);
var highscoreUsers = new Dictionary<RankUserPolyfill, int>(); var highscoreUsers = new Dictionary<RankUserPolyfillDto, int>();
var listLimiter = 1; var listLimiter = 1;
var failedToRetrieveUser = false; var failedToRetrieveUser = false;
foreach (var user in sortedList) foreach (var user in sortedList)
@ -80,7 +84,7 @@ namespace Geekbot.net.Commands
var guildUser = _userRepository.Get((ulong) user.Name); var guildUser = _userRepository.Get((ulong) user.Name);
if (guildUser.Username != null) if (guildUser.Username != null)
{ {
highscoreUsers.Add(new RankUserPolyfill highscoreUsers.Add(new RankUserPolyfillDto
{ {
Username = guildUser.Username, Username = guildUser.Username,
Discriminator = guildUser.Discriminator Discriminator = guildUser.Discriminator
@ -88,7 +92,7 @@ namespace Geekbot.net.Commands
} }
else else
{ {
highscoreUsers.Add(new RankUserPolyfill highscoreUsers.Add(new RankUserPolyfillDto
{ {
Id = user.Name Id = user.Name
}, (int) user.Value); }, (int) user.Value);
@ -143,11 +147,4 @@ namespace Geekbot.net.Commands
} }
} }
} }
internal class RankUserPolyfill
{
public string Username { get; set; }
public string Discriminator { get; set; }
public string Id { get; set; }
}
} }

View file

@ -0,0 +1,9 @@
namespace Geekbot.net.Commands.User.Rank
{
internal class RankUserPolyfillDto
{
public string Username { get; set; }
public string Discriminator { get; set; }
public string Id { get; set; }
}
}

View file

@ -3,9 +3,11 @@ using System.Threading.Tasks;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Geekbot.net.Lib.ErrorHandling;
using Geekbot.net.Lib.Levels;
using StackExchange.Redis; using StackExchange.Redis;
namespace Geekbot.net.Commands namespace Geekbot.net.Commands.User
{ {
public class Stats : ModuleBase public class Stats : ModuleBase
{ {

View file

@ -3,8 +3,9 @@ using System.Threading.Tasks;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Geekbot.net.Lib.ErrorHandling;
namespace Geekbot.net.Commands namespace Geekbot.net.Commands.Utils
{ {
public class AvatarGetter : ModuleBase public class AvatarGetter : ModuleBase
{ {

View file

@ -8,9 +8,10 @@ using Discord;
using Discord.Commands; using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Geekbot.net.Lib.ErrorHandling;
using Newtonsoft.Json; using Newtonsoft.Json;
namespace Geekbot.net.Commands namespace Geekbot.net.Commands.Utils.Changelog
{ {
public class Changelog : ModuleBase public class Changelog : ModuleBase
{ {
@ -51,7 +52,7 @@ namespace Geekbot.net.Commands
}); });
var sb = new StringBuilder(); var sb = new StringBuilder();
foreach (var commit in commits.Take(10)) foreach (var commit in commits.Take(10))
sb.AppendLine($"- {commit.Commit.Message} ({commit.Commit.Author.Date:yyyy-MM-dd})"); sb.AppendLine($"- {commit.Commit.Message} ({commit.Commit.AuthorDto.Date:yyyy-MM-dd})");
eb.Description = sb.ToString(); eb.Description = sb.ToString();
eb.WithFooter(new EmbedFooterBuilder eb.WithFooter(new EmbedFooterBuilder
{ {
@ -65,21 +66,5 @@ namespace Geekbot.net.Commands
_errorHandler.HandleCommandException(e, Context); _errorHandler.HandleCommandException(e, Context);
} }
} }
private class CommitDto
{
public CommitInfo Commit { get; set; }
}
private class CommitInfo
{
public CommitAuthor Author { get; set; }
public string Message { get; set; }
}
private class CommitAuthor
{
public DateTimeOffset Date { get; set; }
}
} }
} }

View file

@ -0,0 +1,9 @@
using System;
namespace Geekbot.net.Commands.Utils.Changelog
{
internal class CommitAuthorDto
{
public DateTimeOffset Date { get; set; }
}
}

View file

@ -0,0 +1,7 @@
namespace Geekbot.net.Commands.Utils.Changelog
{
internal class CommitDto
{
public CommitInfoDto Commit { get; set; }
}
}

View file

@ -0,0 +1,8 @@
namespace Geekbot.net.Commands.Utils.Changelog
{
internal class CommitInfoDto
{
public CommitAuthorDto AuthorDto { get; set; }
public string Message { get; set; }
}
}

View file

@ -2,8 +2,10 @@
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Geekbot.net.Lib.ErrorHandling;
using Geekbot.net.Lib.Localization;
namespace Geekbot.net.Commands namespace Geekbot.net.Commands.Utils
{ {
public class Choose : ModuleBase public class Choose : ModuleBase
{ {

View file

@ -6,7 +6,7 @@ using System.Threading.Tasks;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Lib; using Geekbot.net.Lib;
namespace Geekbot.net.Commands namespace Geekbot.net.Commands.Utils.Dice
{ {
public class Dice : ModuleBase public class Dice : ModuleBase
{ {
@ -112,12 +112,4 @@ namespace Geekbot.net.Commands
return new DiceTypeDto(); return new DiceTypeDto();
} }
} }
internal class DiceTypeDto
{
public string DiceType { get; set; }
public int Times { get; set; }
public int Sides { get; set; }
public int Mod { get; set; }
}
} }

View file

@ -0,0 +1,10 @@
namespace Geekbot.net.Commands.Utils.Dice
{
internal class DiceTypeDto
{
public string DiceType { get; set; }
public int Times { get; set; }
public int Sides { get; set; }
public int Mod { get; set; }
}
}

View file

@ -2,8 +2,10 @@
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Geekbot.net.Lib.Converters;
using Geekbot.net.Lib.ErrorHandling;
namespace Geekbot.net.Commands namespace Geekbot.net.Commands.Utils
{ {
public class Emojify : ModuleBase public class Emojify : ModuleBase
{ {

View file

@ -4,8 +4,9 @@ using System.Threading.Tasks;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Geekbot.net.Lib.ErrorHandling;
namespace Geekbot.net.Commands namespace Geekbot.net.Commands.Utils
{ {
public class Help : ModuleBase public class Help : ModuleBase
{ {

View file

@ -6,9 +6,10 @@ using Discord;
using Discord.Commands; using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Geekbot.net.Lib.ErrorHandling;
using StackExchange.Redis; using StackExchange.Redis;
namespace Geekbot.net.Commands namespace Geekbot.net.Commands.Utils
{ {
public class Info : ModuleBase public class Info : ModuleBase
{ {

View file

@ -2,7 +2,7 @@
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Lib; using Geekbot.net.Lib;
namespace Geekbot.net.Commands namespace Geekbot.net.Commands.Utils
{ {
public class Ping : ModuleBase public class Ping : ModuleBase
{ {

View file

@ -6,10 +6,13 @@ using System.Threading.Tasks;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Geekbot.net.Lib.Converters;
using Geekbot.net.Lib.ErrorHandling;
using Geekbot.net.Lib.UserRepository;
using Newtonsoft.Json; using Newtonsoft.Json;
using StackExchange.Redis; using StackExchange.Redis;
namespace Geekbot.net.Commands namespace Geekbot.net.Commands.Utils.Poll
{ {
[Group("poll")] [Group("poll")]
public class Poll : ModuleBase public class Poll : ModuleBase
@ -92,7 +95,7 @@ namespace Geekbot.net.Commands
pollMessage.AddReactionAsync(new Emoji(_emojiConverter.NumberToEmoji(i))); pollMessage.AddReactionAsync(new Emoji(_emojiConverter.NumberToEmoji(i)));
i++; i++;
}); });
var poll = new PollData var poll = new PollDataDto
{ {
Creator = Context.User.Id, Creator = Context.User.Id,
MessageId = pollMessage.Id, MessageId = pollMessage.Id,
@ -139,28 +142,28 @@ namespace Geekbot.net.Commands
} }
} }
private PollData GetCurrentPoll() private PollDataDto GetCurrentPoll()
{ {
try try
{ {
var currentPoll = _redis.HashGet($"{Context.Guild.Id}:Polls", Context.Channel.Id); var currentPoll = _redis.HashGet($"{Context.Guild.Id}:Polls", Context.Channel.Id);
return JsonConvert.DeserializeObject<PollData>(currentPoll.ToString()); return JsonConvert.DeserializeObject<PollDataDto>(currentPoll.ToString());
} }
catch catch
{ {
return new PollData(); return new PollDataDto();
} }
} }
private async Task<List<PollResult>> GetPollResults(PollData poll) private async Task<List<PollResultDto>> GetPollResults(PollDataDto poll)
{ {
var message = (IUserMessage) await Context.Channel.GetMessageAsync(poll.MessageId); var message = (IUserMessage) await Context.Channel.GetMessageAsync(poll.MessageId);
var results = new List<PollResult>(); var results = new List<PollResultDto>();
foreach (var r in message.Reactions) foreach (var r in message.Reactions)
try try
{ {
var option = int.Parse(r.Key.Name.ToCharArray()[0].ToString()); var option = int.Parse(r.Key.Name.ToCharArray()[0].ToString());
var result = new PollResult var result = new PollResultDto
{ {
Option = poll.Options[option - 1], Option = poll.Options[option - 1],
VoteCount = r.Value.ReactionCount VoteCount = r.Value.ReactionCount
@ -172,20 +175,5 @@ namespace Geekbot.net.Commands
results.Sort((x, y) => y.VoteCount.CompareTo(x.VoteCount)); results.Sort((x, y) => y.VoteCount.CompareTo(x.VoteCount));
return results; return results;
} }
private class PollData
{
public ulong Creator { get; set; }
public ulong MessageId { get; set; }
public bool IsFinshed { get; set; }
public string Question { get; set; }
public List<string> Options { get; set; }
}
private class PollResult
{
public string Option { get; set; }
public int VoteCount { get; set; }
}
} }
} }

View file

@ -0,0 +1,13 @@
using System.Collections.Generic;
namespace Geekbot.net.Commands.Utils.Poll
{
internal class PollDataDto
{
public ulong Creator { get; set; }
public ulong MessageId { get; set; }
public bool IsFinshed { get; set; }
public string Question { get; set; }
public List<string> Options { get; set; }
}
}

View file

@ -0,0 +1,8 @@
namespace Geekbot.net.Commands.Utils.Poll
{
internal class PollResultDto
{
public string Option { get; set; }
public int VoteCount { get; set; }
}
}

View file

@ -4,10 +4,11 @@ using System.Threading.Tasks;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Geekbot.net.Lib.ErrorHandling;
using Newtonsoft.Json; using Newtonsoft.Json;
using StackExchange.Redis; using StackExchange.Redis;
namespace Geekbot.net.Commands namespace Geekbot.net.Commands.Utils.Quote
{ {
[Group("quote")] [Group("quote")]
public class Quote : ModuleBase public class Quote : ModuleBase
@ -31,7 +32,7 @@ namespace Geekbot.net.Commands
var randomQuotes = _redis.SetMembers($"{Context.Guild.Id}:Quotes"); var randomQuotes = _redis.SetMembers($"{Context.Guild.Id}:Quotes");
var randomNumber = new Random().Next(randomQuotes.Length - 1); var randomNumber = new Random().Next(randomQuotes.Length - 1);
var randomQuote = randomQuotes[randomNumber]; var randomQuote = randomQuotes[randomNumber];
var quote = JsonConvert.DeserializeObject<QuoteObject>(randomQuote); var quote = JsonConvert.DeserializeObject<QuoteObjectDto>(randomQuote);
var embed = QuoteBuilder(quote, randomNumber + 1); var embed = QuoteBuilder(quote, randomNumber + 1);
await ReplyAsync("", false, embed.Build()); await ReplyAsync("", false, embed.Build());
} }
@ -159,7 +160,7 @@ namespace Geekbot.net.Commands
var success = _redis.SetRemove($"{Context.Guild.Id}:Quotes", quotes[id - 1]); var success = _redis.SetRemove($"{Context.Guild.Id}:Quotes", quotes[id - 1]);
if (success) if (success)
{ {
var quote = JsonConvert.DeserializeObject<QuoteObject>(quotes[id - 1]); var quote = JsonConvert.DeserializeObject<QuoteObjectDto>(quotes[id - 1]);
var embed = QuoteBuilder(quote); var embed = QuoteBuilder(quote);
await ReplyAsync($"**Removed #{id}**", false, embed.Build()); await ReplyAsync($"**Removed #{id}**", false, embed.Build());
} }
@ -186,7 +187,7 @@ namespace Geekbot.net.Commands
&& !msg.Content.ToLower().StartsWith("!")); && !msg.Content.ToLower().StartsWith("!"));
} }
private EmbedBuilder QuoteBuilder(QuoteObject quote, int id = 0) private EmbedBuilder QuoteBuilder(QuoteObjectDto quote, int id = 0)
{ {
var user = Context.Client.GetUserAsync(quote.UserId).Result; var user = Context.Client.GetUserAsync(quote.UserId).Result;
var eb = new EmbedBuilder(); var eb = new EmbedBuilder();
@ -199,7 +200,7 @@ namespace Geekbot.net.Commands
return eb; return eb;
} }
private QuoteObject CreateQuoteObject(IMessage message) private QuoteObjectDto CreateQuoteObject(IMessage message)
{ {
string image; string image;
try try
@ -211,7 +212,7 @@ namespace Geekbot.net.Commands
image = null; image = null;
} }
return new QuoteObject return new QuoteObjectDto
{ {
UserId = message.Author.Id, UserId = message.Author.Id,
Time = message.Timestamp.DateTime, Time = message.Timestamp.DateTime,
@ -220,12 +221,4 @@ namespace Geekbot.net.Commands
}; };
} }
} }
public class QuoteObject
{
public ulong UserId { get; set; }
public string Quote { get; set; }
public DateTime Time { get; set; }
public string Image { get; set; }
}
} }

View file

@ -0,0 +1,12 @@
using System;
namespace Geekbot.net.Commands.Utils.Quote
{
internal class QuoteObjectDto
{
public ulong UserId { get; set; }
public string Quote { get; set; }
public DateTime Time { get; set; }
public string Image { get; set; }
}
}

View file

@ -1,102 +0,0 @@
//using System;
//using System.IO;
//using System.Threading.Tasks;
//using Discord;
//using Discord.Commands;
//using Geekbot.net.Lib;
//
//namespace Geekbot.net.Commands
//{
// public class Voice : ModuleBase
// {
// private readonly IAudioUtils _audioUtils;
// private readonly IErrorHandler _errorHandler;
//
// public Voice(IErrorHandler errorHandler, IAudioUtils audioUtils)
// {
// _errorHandler = errorHandler;
// _audioUtils = audioUtils;
// }
//
// [Command("join")]
// public async Task JoinChannel()
// {
// try
// {
// // Get the audio channel
// var channel = (Context.User as IGuildUser)?.VoiceChannel;
// if (channel == null)
// {
// await Context.Channel.SendMessageAsync(
// "User must be in a voice channel, or a voice channel must be passed as an argument.");
// return;
// }
//
// // For the next step with transmitting audio, you would want to pass this Audio Client in to a service.
// var audioClient = await channel.ConnectAsync();
// _audioUtils.StoreAudioClient(Context.Guild.Id, audioClient);
// await ReplyAsync($"Connected to {channel.Name}");
// }
// catch (Exception e)
// {
// _errorHandler.HandleCommandException(e, Context);
// }
// }
//
// [Command("disconnect")]
// public async Task DisconnectChannel()
// {
// try
// {
// var audioClient = _audioUtils.GetAudioClient(Context.Guild.Id);
// if (audioClient == null)
// {
// await Context.Channel.SendMessageAsync("I'm not in a voice channel at the moment");
// return;
// }
//
// await audioClient.StopAsync();
// await ReplyAsync("Disconnected from channel!");
// _audioUtils.Cleanup(Context.Guild.Id);
// }
// catch (Exception e)
// {
// _errorHandler.HandleCommandException(e, Context);
// _audioUtils.Cleanup(Context.Guild.Id);
// }
// }
//
// [Command("ytplay")]
// public async Task ytplay(string url)
// {
// try
// {
// if (!url.Contains("youtube"))
// {
// await ReplyAsync("I can only play youtube videos");
// return;
// }
// var audioClient = _audioUtils.GetAudioClient(Context.Guild.Id);
// if (audioClient == null)
// {
// await ReplyAsync("I'm not in a voice channel at the moment");
// return;
// }
//
// var message = await Context.Channel.SendMessageAsync("Just a second, i'm still a bit slow at this");
// var ffmpeg = _audioUtils.CreateStreamFromYoutube(url, Context.Guild.Id);
// var output = ffmpeg.StandardOutput.BaseStream;
// await message.ModifyAsync(msg => msg.Content = "**Playing!** Please note that this feature is experimental");
// var discord = audioClient.CreatePCMStream(Discord.Audio.AudioApplication.Mixed);
// await output.CopyToAsync(discord);
// await discord.FlushAsync();
// _audioUtils.Cleanup(Context.Guild.Id);
// }
// catch (Exception e)
// {
// _errorHandler.HandleCommandException(e, Context);
// _audioUtils.Cleanup(Context.Guild.Id);
// }
// }
// }
//}

View file

@ -3,7 +3,7 @@
<OutputType>Exe</OutputType> <OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework> <TargetFramework>netcoreapp2.0</TargetFramework>
<ApplicationIcon>derp.ico</ApplicationIcon> <ApplicationIcon>derp.ico</ApplicationIcon>
<Version>1.1.0</Version> <Version>3.6.0</Version>
<Company>Pizza and Coffee Studios</Company> <Company>Pizza and Coffee Studios</Company>
<Authors>Pizza and Coffee Studios</Authors> <Authors>Pizza and Coffee Studios</Authors>
<Description>A Discord bot</Description> <Description>A Discord bot</Description>
@ -11,6 +11,7 @@
<NoWarn>NU1701</NoWarn> <NoWarn>NU1701</NoWarn>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="CommandLineParser" Version="2.2.1" />
<PackageReference Include="Discord.Net"> <PackageReference Include="Discord.Net">
<Version>1.0.2</Version> <Version>1.0.2</Version>
</PackageReference> </PackageReference>
@ -62,9 +63,6 @@
<None Update="Storage\squirrel"> <None Update="Storage\squirrel">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None> </None>
<None Update="Storage\Translations.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="Storage\turtles"> <None Update="Storage\turtles">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None> </None>
@ -74,6 +72,12 @@
<None Update="Storage\foxes"> <None Update="Storage\foxes">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None> </None>
<None Update="Lib\Localization\Translations.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Lib\Converters\MtgManaEmojis.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\WikipediaApi\WikipediaApi.csproj" /> <ProjectReference Include="..\WikipediaApi\WikipediaApi.csproj" />

View file

@ -4,7 +4,9 @@ using System.Threading.Tasks;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
using Geekbot.net.Lib; using Geekbot.net.Lib.Logger;
using Geekbot.net.Lib.ReactionListener;
using Geekbot.net.Lib.UserRepository;
using StackExchange.Redis; using StackExchange.Redis;
namespace Geekbot.net namespace Geekbot.net
@ -89,7 +91,6 @@ namespace Geekbot.net
if (message.Author.IsBot) return Task.CompletedTask; if (message.Author.IsBot) return Task.CompletedTask;
_logger.Information("Message", message.Content, SimpleConextConverter.ConvertSocketMessage(message)); _logger.Information("Message", message.Content, SimpleConextConverter.ConvertSocketMessage(message));
// _logger.Information($"[Message] {channel.Guild.Name} ({channel.Guild.Id}) - {message.Channel} ({message.Channel.Id}) - {message.Author.Username}#{message.Author.Discriminator} ({message.Author.Id}) - {message.Content}");
} }
catch (Exception e) catch (Exception e)
{ {

View file

@ -0,0 +1,12 @@
using System.Threading.Tasks;
using MyAnimeListSharp.Core;
namespace Geekbot.net.Lib.Clients
{
public interface IMalClient
{
bool IsLoggedIn();
Task<AnimeEntry> GetAnime(string query);
Task<MangaEntry> GetManga(string query);
}
}

View file

@ -1,10 +1,11 @@
using System.Threading.Tasks; using System.Threading.Tasks;
using Geekbot.net.Lib.Logger;
using MyAnimeListSharp.Auth; using MyAnimeListSharp.Auth;
using MyAnimeListSharp.Core; using MyAnimeListSharp.Core;
using MyAnimeListSharp.Facade.Async; using MyAnimeListSharp.Facade.Async;
using StackExchange.Redis; using StackExchange.Redis;
namespace Geekbot.net.Lib namespace Geekbot.net.Lib.Clients
{ {
public class MalClient : IMalClient public class MalClient : IMalClient
{ {
@ -66,11 +67,4 @@ namespace Geekbot.net.Lib
return response.Entries.Count == 0 ? null : response.Entries[0]; return response.Entries.Count == 0 ? null : response.Entries[0];
} }
} }
public interface IMalClient
{
bool IsLoggedIn();
Task<AnimeEntry> GetAnime(string query);
Task<MangaEntry> GetManga(string query);
}
} }

View file

@ -1,7 +1,7 @@
using System.Collections; using System.Collections;
using System.Text; using System.Text;
namespace Geekbot.net.Lib namespace Geekbot.net.Lib.Converters
{ {
public class EmojiConverter : IEmojiConverter public class EmojiConverter : IEmojiConverter
{ {
@ -90,10 +90,4 @@ namespace Geekbot.net.Lib
return returnString.ToString(); return returnString.ToString();
} }
} }
public interface IEmojiConverter
{
string NumberToEmoji(int number);
string TextToEmoji(string text);
}
} }

View file

@ -0,0 +1,8 @@
namespace Geekbot.net.Lib.Converters
{
public interface IEmojiConverter
{
string NumberToEmoji(int number);
string TextToEmoji(string text);
}
}

View file

@ -0,0 +1,7 @@
namespace Geekbot.net.Lib.Converters
{
public interface IMtgManaConverter
{
string ConvertMana(string mana);
}
}

View file

@ -0,0 +1,33 @@
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using Utf8Json;
namespace Geekbot.net.Lib.Converters
{
public class MtgManaConverter : IMtgManaConverter
{
private Dictionary<string, string> _manaDict;
public MtgManaConverter()
{
// these emotes can be found at https://discord.gg/bz8HyA7
var mtgEmojis = File.ReadAllText(Path.GetFullPath("./Lib/Converters/MtgManaEmojis.json"));
_manaDict = JsonSerializer.Deserialize<Dictionary<string, string>>(mtgEmojis);
}
public string ConvertMana(string mana)
{
var rgx = Regex.Matches(mana, @"(\{(.*?)\})");
foreach (Match manaTypes in rgx)
{
var m = _manaDict.GetValueOrDefault(manaTypes.Value);
if (!string.IsNullOrEmpty(m))
{
mana = mana.Replace(manaTypes.Value, m);
}
}
return mana;
}
}
}

View file

@ -0,0 +1,50 @@
{
"{0}": "<:mtg_0:415216130043412482>",
"{1}": "<:mtg_1:415216130253389835>",
"{2}": "<:mtg_2:415216130031091713>",
"{3}": "<:mtg_3:415216130467037194>",
"{4}": "<:mtg_4:415216130026635295>",
"{5}": "<:mtg_5:415216130492203008>",
"{6}": "<:mtg_6:415216130458779658>",
"{7}": "<:mtg_7:415216130190475265>",
"{8}": "<:mtg_8:415216130517630986>",
"{9}": "<:mtg_9:415216130500722689>",
"{10": "<:mtg_10:415216130450391051>",
"{11}": "<:mtg_11:415216130811101185>",
"{12}": "<:mtg_12:415216130525888532>",
"{13}": "<:mtg_13:415216130517631000>",
"{14}": "<:mtg_14:415216130165178370>",
"{15}": "<:mtg_15:415216130576089108>",
"{16}": "<:mtg_16:415216130358247425>",
"{17}": "<:mtg_17:415216130601517056>",
"{18}": "<:mtg_18:415216130462842891>",
"{19}": "<:mtg_19:415216130614099988>",
"{20}": "<:mtg_20:415216130656043038>",
"{W}": "<:mtg_white:415216131515744256>",
"{U}": "<:mtg_blue:415216130521694209>",
"{B}": "<:mtg_black:415216130873884683>",
"{R}": "<:mtg_red:415216131322806272>",
"{G}": "<:mtg_green:415216131180331009>",
"{S}": "<:mtg_s:415216131293446144>",
"{T}": "<:mtg_tap:415258392727257088>",
"{C}": "<:mtg_colorless:415216130706374666>",
"{2/W}": "<:mtg_2w:415216130446065664>",
"{2/U}": "<:mtg_2u:415216130429550592>",
"{2/B}": "<:mtg_2b:415216130160984065>",
"{2/R}": "<:mtg_2r:415216130454716436>",
"{2/G}": "<:mtg_2g:415216130420899840>",
"{W/U}": "<:mtg_wu:415216130970484736>",
"{W/B}": "<:mtg_wb:415216131222011914>",
"{U/R}": "<:mtg_ur:415216130962096128>",
"{U/B}": "<:mtg_ub:415216130865758218>",
"{R/W}": "<:mtg_rw:415216130878210057>",
"{G/W}": "<:mtg_gw:415216130567962646>",
"{G/U}": "<:mtg_gu:415216130739666945>",
"{B/R}": "<:mtg_br:415216130580283394>",
"{B/G}": "<:mtg_bg:415216130781609994>",
"{U/P}": "<:mtg_up:415216130861432842>",
"{R/P}": "<:mtg_rp:415216130597322783>",
"{G/P}": "<:mtg_gp:415216130760769546>",
"{W/P}": "<:mtg_wp:415216131541041172>",
"{B/P}": "<:mtg_bp:415216130664169482>"
}

View file

@ -2,10 +2,12 @@
using System.Net; using System.Net;
using Discord.Commands; using Discord.Commands;
using Discord.Net; using Discord.Net;
using Geekbot.net.Lib.Localization;
using Geekbot.net.Lib.Logger;
using SharpRaven; using SharpRaven;
using SharpRaven.Data; using SharpRaven.Data;
namespace Geekbot.net.Lib namespace Geekbot.net.Lib.ErrorHandling
{ {
public class ErrorHandler : IErrorHandler public class ErrorHandler : IErrorHandler
{ {
@ -90,10 +92,4 @@ namespace Geekbot.net.Lib
} }
public interface IErrorHandler
{
void HandleCommandException(Exception e, ICommandContext context, string errorMessage = "def");
void HandleHttpException(HttpException e, ICommandContext context);
}
} }

View file

@ -0,0 +1,12 @@
using System;
using Discord.Commands;
using Discord.Net;
namespace Geekbot.net.Lib.ErrorHandling
{
public interface IErrorHandler
{
void HandleCommandException(Exception e, ICommandContext context, string errorMessage = "def");
void HandleHttpException(HttpException e, ICommandContext context);
}
}

View file

@ -0,0 +1,7 @@
namespace Geekbot.net.Lib.Levels
{
public interface ILevelCalc
{
int GetLevel(int experience);
}
}

View file

@ -1,7 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
namespace Geekbot.net.Lib namespace Geekbot.net.Lib.Levels
{ {
public class LevelCalc : ILevelCalc public class LevelCalc : ILevelCalc
{ {
@ -30,9 +30,4 @@ namespace Geekbot.net.Lib
return returnVal; return returnVal;
} }
} }
public interface ILevelCalc
{
int GetLevel(int experience);
}
} }

View file

@ -0,0 +1,14 @@
using System.Collections.Generic;
using Discord.Commands;
namespace Geekbot.net.Lib.Localization
{
public interface ITranslationHandler
{
string GetString(ulong guildId, string command, string stringName);
Dictionary<string, string> GetDict(ICommandContext context);
Dictionary<string, string> GetDict(ICommandContext context, string command);
bool SetLanguage(ulong guildId, string language);
List<string> GetSupportedLanguages();
}
}

View file

@ -4,10 +4,11 @@ using System.IO;
using System.Linq; using System.Linq;
using Discord.Commands; using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
using Geekbot.net.Lib.Logger;
using StackExchange.Redis; using StackExchange.Redis;
using Utf8Json; using Utf8Json;
namespace Geekbot.net.Lib namespace Geekbot.net.Lib.Localization
{ {
public class TranslationHandler : ITranslationHandler public class TranslationHandler : ITranslationHandler
{ {
@ -30,7 +31,7 @@ namespace Geekbot.net.Lib
{ {
try try
{ {
var translationFile = File.ReadAllText(Path.GetFullPath("./Storage/Translations.json")); var translationFile = File.ReadAllText(Path.GetFullPath("./Lib/Localization/Translations.json"));
var rawTranslations = JsonSerializer.Deserialize<Dictionary<string, Dictionary<string, Dictionary<string, string>>>>(translationFile); var rawTranslations = JsonSerializer.Deserialize<Dictionary<string, Dictionary<string, Dictionary<string, string>>>>(translationFile);
var sortedPerLanguage = new Dictionary<string, Dictionary<string, Dictionary<string, string>>>(); var sortedPerLanguage = new Dictionary<string, Dictionary<string, Dictionary<string, string>>>();
foreach (var command in rawTranslations) foreach (var command in rawTranslations)
@ -152,13 +153,4 @@ namespace Geekbot.net.Lib
return _supportedLanguages; return _supportedLanguages;
} }
} }
public interface ITranslationHandler
{
string GetString(ulong guildId, string command, string stringName);
Dictionary<string, string> GetDict(ICommandContext context);
Dictionary<string, string> GetDict(ICommandContext context, string command);
bool SetLanguage(ulong guildId, string language);
List<string> GetSupportedLanguages();
}
} }

View file

@ -0,0 +1,42 @@
using System.Threading.Tasks;
using Discord;
namespace Geekbot.net.Lib.Logger
{
public class DiscordLogger : IDiscordLogger
{
private readonly GeekbotLogger _logger;
public DiscordLogger(GeekbotLogger logger)
{
_logger = logger;
}
public Task Log(LogMessage message)
{
var logMessage = $"[{message.Source}] {message.Message}";
switch (message.Severity)
{
case LogSeverity.Verbose:
_logger.Trace(message.Source, message.Message);
break;
case LogSeverity.Debug:
_logger.Debug(message.Source, message.Message);
break;
case LogSeverity.Info:
_logger.Information(message.Source, message.Message);
break;
case LogSeverity.Critical:
case LogSeverity.Error:
case LogSeverity.Warning:
if (logMessage.Contains("VOICE_STATE_UPDATE")) break;
_logger.Error(message.Source, message.Message, message.Exception);
break;
default:
_logger.Information(message.Source, $"{logMessage} --- {message.Severity}");
break;
}
return Task.CompletedTask;
}
}
}

View file

@ -1,18 +1,18 @@
using System; using System;
using Newtonsoft.Json; using Newtonsoft.Json;
namespace Geekbot.net.Lib namespace Geekbot.net.Lib.Logger
{ {
public class GeekbotLogger : IGeekbotLogger public class GeekbotLogger : IGeekbotLogger
{ {
private readonly bool _sumologicActive; private readonly bool _logAsJson;
private readonly NLog.Logger _logger; private readonly NLog.Logger _logger;
private readonly JsonSerializerSettings _serializerSettings; private readonly JsonSerializerSettings _serializerSettings;
public GeekbotLogger(bool sumologicActive) public GeekbotLogger(RunParameters runParameters, bool sumologicActive)
{ {
_sumologicActive = sumologicActive; _logAsJson = sumologicActive || runParameters.LogJson;
_logger = LoggerFactory.CreateNLog(sumologicActive); _logger = LoggerFactory.CreateNLog(runParameters, sumologicActive);
_serializerSettings = new JsonSerializerSettings _serializerSettings = new JsonSerializerSettings
{ {
ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
@ -21,6 +21,11 @@ namespace Geekbot.net.Lib
Information("Geekbot", "Using GeekbotLogger"); Information("Geekbot", "Using GeekbotLogger");
} }
public void Trace(string source, string message, object extra = null)
{
_logger.Trace(CreateLogString("Debug", source, message, null, extra));
}
public void Debug(string source, string message, object extra = null) public void Debug(string source, string message, object extra = null)
{ {
_logger.Debug(CreateLogString("Debug", source, message, null, extra)); _logger.Debug(CreateLogString("Debug", source, message, null, extra));
@ -43,7 +48,7 @@ namespace Geekbot.net.Lib
private string CreateLogString(string type, string source, string message, Exception stackTrace = null, object extra = null) private string CreateLogString(string type, string source, string message, Exception stackTrace = null, object extra = null)
{ {
if (_sumologicActive) if (_logAsJson)
{ {
var logObject = new GeekbotLoggerObject var logObject = new GeekbotLoggerObject
{ {
@ -63,22 +68,4 @@ namespace Geekbot.net.Lib
return $"[{source}] - [{m.Guild.Name} - {m.Channel.Name}] {m.User.Name}: {m.Message.Content}"; return $"[{source}] - [{m.Guild.Name} - {m.Channel.Name}] {m.User.Name}: {m.Message.Content}";
} }
} }
public class GeekbotLoggerObject
{
public DateTime Timestamp { get; set; }
public string Type { get; set; }
public string Source { get; set; }
public string Message { get; set; }
public Exception StackTrace { get; set; }
public object Extra { get; set; }
}
public interface IGeekbotLogger
{
void Debug(string source, string message, object extra = null);
void Information(string source, string message, object extra = null);
void Warning(string source, string message, Exception stackTrace = null, object extra = null);
void Error(string source, string message, Exception stackTrace, object extra = null);
}
} }

View file

@ -0,0 +1,10 @@
using System.Threading.Tasks;
using Discord;
namespace Geekbot.net.Lib.Logger
{
public interface IDiscordLogger
{
Task Log(LogMessage message);
}
}

View file

@ -0,0 +1,13 @@
using System;
namespace Geekbot.net.Lib.Logger
{
public interface IGeekbotLogger
{
void Trace(string source, string message, object extra = null);
void Debug(string source, string message, object extra = null);
void Information(string source, string message, object extra = null);
void Warning(string source, string message, Exception stackTrace = null, object extra = null);
void Error(string source, string message, Exception stackTrace, object extra = null);
}
}

View file

@ -0,0 +1,14 @@
using System;
namespace Geekbot.net.Lib.Logger
{
public class GeekbotLoggerObject
{
public DateTime Timestamp { get; set; }
public string Type { get; set; }
public string Source { get; set; }
public string Message { get; set; }
public Exception StackTrace { get; set; }
public object Extra { get; set; }
}
}

View file

@ -5,11 +5,11 @@ using NLog.Config;
using NLog.Targets; using NLog.Targets;
using SumoLogic.Logging.NLog; using SumoLogic.Logging.NLog;
namespace Geekbot.net.Lib namespace Geekbot.net.Lib.Logger
{ {
public class LoggerFactory public class LoggerFactory
{ {
public static Logger CreateNLog(bool sumologicActive) public static NLog.Logger CreateNLog(RunParameters runParameters, bool sumologicActive)
{ {
var config = new LoggingConfiguration(); var config = new LoggingConfiguration();
@ -36,8 +36,9 @@ namespace Geekbot.net.Lib
} }
else else
{ {
var minLevel = runParameters.Verbose ? LogLevel.Trace : LogLevel.Info;
config.LoggingRules.Add( config.LoggingRules.Add(
new LoggingRule("*", LogLevel.Trace, LogLevel.Fatal, new LoggingRule("*", minLevel, LogLevel.Fatal,
new ColoredConsoleTarget new ColoredConsoleTarget
{ {
Name = "Console", Name = "Console",
@ -47,7 +48,7 @@ namespace Geekbot.net.Lib
); );
config.LoggingRules.Add( config.LoggingRules.Add(
new LoggingRule("*", LogLevel.Trace, LogLevel.Fatal, new LoggingRule("*", minLevel, LogLevel.Fatal,
new FileTarget new FileTarget
{ {
Name = "File", Name = "File",

View file

@ -0,0 +1,26 @@
namespace Geekbot.net.Lib.Logger
{
public class MessageDto
{
public MessageContent Message { get; set; }
public IdAndName User { get; set; }
public IdAndName Guild { get; set; }
public IdAndName Channel { get; set; }
public class MessageContent
{
public string Content { get; set; }
public string Id { get; set; }
public int Attachments { get; set; }
public int ChannelMentions { get; set; }
public int UserMentions { get; set; }
public int RoleMentions { get; set; }
}
public class IdAndName
{
public string Id { get; set; }
public string Name { get; set; }
}
}
}

View file

@ -1,7 +1,7 @@
using Discord.Commands; using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
namespace Geekbot.net.Lib namespace Geekbot.net.Lib.Logger
{ {
public class SimpleConextConverter public class SimpleConextConverter
{ {
@ -68,29 +68,4 @@ namespace Geekbot.net.Lib
} }
} }
public class MessageDto
{
public MessageContent Message { get; set; }
public IdAndName User { get; set; }
public IdAndName Guild { get; set; }
public IdAndName Channel { get; set; }
public class MessageContent
{
public string Content { get; set; }
public string Id { get; set; }
public int Attachments { get; set; }
public int ChannelMentions { get; set; }
public int UserMentions { get; set; }
public int RoleMentions { get; set; }
}
public class IdAndName
{
public string Id { get; set; }
public string Name { get; set; }
}
}
} }

View file

@ -1,5 +1,6 @@
using System; using System;
using System.IO; using System.IO;
using Geekbot.net.Lib.Logger;
namespace Geekbot.net.Lib.Media namespace Geekbot.net.Lib.Media
{ {
@ -16,7 +17,7 @@ namespace Geekbot.net.Lib.Media
var rawFortunes = File.ReadAllText(path); var rawFortunes = File.ReadAllText(path);
_fortuneArray = rawFortunes.Split("%"); _fortuneArray = rawFortunes.Split("%");
_totalFortunes = _fortuneArray.Length; _totalFortunes = _fortuneArray.Length;
logger.Debug("Geekbot", "Loaded {totalFortunes} Fortunes"); logger.Trace("Geekbot", $"Loaded {_totalFortunes} Fortunes");
} }
else else
{ {
@ -29,9 +30,4 @@ namespace Geekbot.net.Lib.Media
return _fortuneArray[new Random().Next(0, _totalFortunes)]; return _fortuneArray[new Random().Next(0, _totalFortunes)];
} }
} }
public interface IFortunesProvider
{
string GetRandomFortune();
}
} }

View file

@ -0,0 +1,7 @@
namespace Geekbot.net.Lib.Media
{
public interface IFortunesProvider
{
string GetRandomFortune();
}
}

View file

@ -0,0 +1,14 @@
namespace Geekbot.net.Lib.Media
{
public interface IMediaProvider
{
string GetCheckem();
string GetPanda();
string GetCrossant();
string GetSquirrel();
string GetPumpkin();
string GetTurtle();
string GetPinguin();
string GetFox();
}
}

View file

@ -1,5 +1,6 @@
using System; using System;
using System.IO; using System.IO;
using Geekbot.net.Lib.Logger;
namespace Geekbot.net.Lib.Media namespace Geekbot.net.Lib.Media
{ {
@ -37,56 +38,56 @@ namespace Geekbot.net.Lib.Media
{ {
var rawLinks = File.ReadAllText(Path.GetFullPath("./Storage/checkEmPics")); var rawLinks = File.ReadAllText(Path.GetFullPath("./Storage/checkEmPics"));
_checkemImages = rawLinks.Split("\n"); _checkemImages = rawLinks.Split("\n");
_logger.Debug("Geekbot", $"Loaded {_checkemImages.Length} CheckEm Images"); _logger.Trace("Geekbot", $"Loaded {_checkemImages.Length} CheckEm Images");
} }
private void LoadPandas() private void LoadPandas()
{ {
var rawLinks = File.ReadAllText(Path.GetFullPath("./Storage/pandas")); var rawLinks = File.ReadAllText(Path.GetFullPath("./Storage/pandas"));
_pandaImages = rawLinks.Split("\n"); _pandaImages = rawLinks.Split("\n");
_logger.Debug("Geekbot", $"Loaded {_pandaImages.Length} Panda Images"); _logger.Trace("Geekbot", $"Loaded {_pandaImages.Length} Panda Images");
} }
private void BakeCroissants() private void BakeCroissants()
{ {
var rawLinks = File.ReadAllText(Path.GetFullPath("./Storage/croissant")); var rawLinks = File.ReadAllText(Path.GetFullPath("./Storage/croissant"));
_croissantImages = rawLinks.Split("\n"); _croissantImages = rawLinks.Split("\n");
_logger.Debug("Geekbot", $"Loaded {_croissantImages.Length} Croissant Images"); _logger.Trace("Geekbot", $"Loaded {_croissantImages.Length} Croissant Images");
} }
private void LoadSquirrels() private void LoadSquirrels()
{ {
var rawLinks = File.ReadAllText(Path.GetFullPath("./Storage/squirrel")); var rawLinks = File.ReadAllText(Path.GetFullPath("./Storage/squirrel"));
_squirrelImages = rawLinks.Split("\n"); _squirrelImages = rawLinks.Split("\n");
_logger.Debug("Geekbot", $"Loaded {_squirrelImages.Length} Squirrel Images"); _logger.Trace("Geekbot", $"Loaded {_squirrelImages.Length} Squirrel Images");
} }
private void LoadPumpkins() private void LoadPumpkins()
{ {
var rawLinks = File.ReadAllText(Path.GetFullPath("./Storage/pumpkin")); var rawLinks = File.ReadAllText(Path.GetFullPath("./Storage/pumpkin"));
_pumpkinImages = rawLinks.Split("\n"); _pumpkinImages = rawLinks.Split("\n");
_logger.Debug("Geekbot", $"Loaded {_pumpkinImages.Length} Pumpkin Images"); _logger.Trace("Geekbot", $"Loaded {_pumpkinImages.Length} Pumpkin Images");
} }
private void LoadTurtles() private void LoadTurtles()
{ {
var rawLinks = File.ReadAllText(Path.GetFullPath("./Storage/turtles")); var rawLinks = File.ReadAllText(Path.GetFullPath("./Storage/turtles"));
_turtlesImages = rawLinks.Split("\n"); _turtlesImages = rawLinks.Split("\n");
_logger.Debug("Geekbot", $"Loaded {_turtlesImages.Length} Turtle Images"); _logger.Trace("Geekbot", $"Loaded {_turtlesImages.Length} Turtle Images");
} }
private void LoadPinguins() private void LoadPinguins()
{ {
var rawLinks = File.ReadAllText(Path.GetFullPath("./Storage/pinguins")); var rawLinks = File.ReadAllText(Path.GetFullPath("./Storage/pinguins"));
_pinguinImages = rawLinks.Split("\n"); _pinguinImages = rawLinks.Split("\n");
_logger.Debug("Geekbot", $"Loaded {_pinguinImages.Length} Pinguin Images"); _logger.Trace("Geekbot", $"Loaded {_pinguinImages.Length} Pinguin Images");
} }
private void LoadFoxes() private void LoadFoxes()
{ {
var rawLinks = File.ReadAllText(Path.GetFullPath("./Storage/foxes")); var rawLinks = File.ReadAllText(Path.GetFullPath("./Storage/foxes"));
_foxImages = rawLinks.Split("\n"); _foxImages = rawLinks.Split("\n");
_logger.Debug("Geekbot", $"Loaded {_foxImages.Length} Foxes Images"); _logger.Trace("Geekbot", $"Loaded {_foxImages.Length} Foxes Images");
} }
public string GetCheckem() public string GetCheckem()
@ -129,16 +130,4 @@ namespace Geekbot.net.Lib.Media
return _foxImages[_random.Next(0, _foxImages.Length)]; return _foxImages[_random.Next(0, _foxImages.Length)];
} }
} }
public interface IMediaProvider
{
string GetCheckem();
string GetPanda();
string GetCrossant();
string GetSquirrel();
string GetPumpkin();
string GetTurtle();
string GetPinguin();
string GetFox();
}
} }

View file

@ -1,86 +0,0 @@
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace Geekbot.net.Lib
{
public class MtgManaConverter : IMtgManaConverter
{
private Dictionary<string, string> _manaDict;
public MtgManaConverter()
{
// these emotes can be found at https://discord.gg/bz8HyA7
var manaDict = new Dictionary<string, string>();
manaDict.Add("{0}", "<:mtg_0:415216130043412482>");
manaDict.Add("{1}", "<:mtg_1:415216130253389835>");
manaDict.Add("{2}", "<:mtg_2:415216130031091713>");
manaDict.Add("{3}", "<:mtg_3:415216130467037194>");
manaDict.Add("{4}", "<:mtg_4:415216130026635295>");
manaDict.Add("{5}", "<:mtg_5:415216130492203008>");
manaDict.Add("{6}", "<:mtg_6:415216130458779658>");
manaDict.Add("{7}", "<:mtg_7:415216130190475265>");
manaDict.Add("{8}", "<:mtg_8:415216130517630986>");
manaDict.Add("{9}", "<:mtg_9:415216130500722689>");
manaDict.Add("{10", "<:mtg_10:415216130450391051>");
manaDict.Add("{11}", "<:mtg_11:415216130811101185>");
manaDict.Add("{12}", "<:mtg_12:415216130525888532>");
manaDict.Add("{13}", "<:mtg_13:415216130517631000>");
manaDict.Add("{14}", "<:mtg_14:415216130165178370>");
manaDict.Add("{15}", "<:mtg_15:415216130576089108>");
manaDict.Add("{16}", "<:mtg_16:415216130358247425>");
manaDict.Add("{17}", "<:mtg_17:415216130601517056>");
manaDict.Add("{18}", "<:mtg_18:415216130462842891>");
manaDict.Add("{19}", "<:mtg_19:415216130614099988>");
manaDict.Add("{20}", "<:mtg_20:415216130656043038>");
manaDict.Add("{W}", "<:mtg_white:415216131515744256>");
manaDict.Add("{U}", "<:mtg_blue:415216130521694209>");
manaDict.Add("{B}", "<:mtg_black:415216130873884683>");
manaDict.Add("{R}", "<:mtg_red:415216131322806272>");
manaDict.Add("{G}", "<:mtg_green:415216131180331009>");
manaDict.Add("{S}", "<:mtg_s:415216131293446144>");
manaDict.Add("{T}", "<:mtg_tap:415258392727257088>");
manaDict.Add("{C}", "<:mtg_colorless:415216130706374666>");
manaDict.Add("{2/W}", "<:mtg_2w:415216130446065664>");
manaDict.Add("{2/U}", "<:mtg_2u:415216130429550592>");
manaDict.Add("{2/B}", "<:mtg_2b:415216130160984065>");
manaDict.Add("{2/R}", "<:mtg_2r:415216130454716436>");
manaDict.Add("{2/G}", "<:mtg_2g:415216130420899840>");
manaDict.Add("{W/U}", "<:mtg_wu:415216130970484736>");
manaDict.Add("{W/B}", "<:mtg_wb:415216131222011914>");
manaDict.Add("{U/R}", "<:mtg_ur:415216130962096128>");
manaDict.Add("{U/B}", "<:mtg_ub:415216130865758218>");
manaDict.Add("{R/W}", "<:mtg_rw:415216130878210057>");
manaDict.Add("{G/W}", "<:mtg_gw:415216130567962646>");
manaDict.Add("{G/U}", "<:mtg_gu:415216130739666945>");
manaDict.Add("{B/R}", "<:mtg_br:415216130580283394>");
manaDict.Add("{B/G}", "<:mtg_bg:415216130781609994>");
manaDict.Add("{U/P}", "<:mtg_up:415216130861432842>");
manaDict.Add("{R/P}", "<:mtg_rp:415216130597322783>");
manaDict.Add("{G/P}", "<:mtg_gp:415216130760769546>");
manaDict.Add("{W/P}", "<:mtg_wp:415216131541041172>");
manaDict.Add("{B/P}", "<:mtg_bp:415216130664169482>");
_manaDict = manaDict;
}
public string ConvertMana(string mana)
{
var rgx = Regex.Matches(mana, @"(\{(.*?)\})");
foreach (Match manaTypes in rgx)
{
var m = _manaDict.GetValueOrDefault(manaTypes.Value);
if (!string.IsNullOrEmpty(m))
{
mana = mana.Replace(manaTypes.Value, m);
}
}
return mana;
}
}
public interface IMtgManaConverter
{
string ConvertMana(string mana);
}
}

View file

@ -0,0 +1,14 @@
using System.Threading.Tasks;
using Discord;
using Discord.WebSocket;
namespace Geekbot.net.Lib.ReactionListener
{
public interface IReactionListener
{
bool IsListener(ulong id);
Task AddRoleToListener(string messageId, IEmote emoji, IRole role);
void RemoveRole(ISocketMessageChannel channel, SocketReaction reaction);
void GiveRole(ISocketMessageChannel message, SocketReaction reaction);
}
}

View file

@ -5,7 +5,7 @@ using Discord;
using Discord.WebSocket; using Discord.WebSocket;
using StackExchange.Redis; using StackExchange.Redis;
namespace Geekbot.net.Lib namespace Geekbot.net.Lib.ReactionListener
{ {
public class ReactionListener : IReactionListener public class ReactionListener : IReactionListener
{ {
@ -87,12 +87,4 @@ namespace Geekbot.net.Lib
await ((IGuildUser) reaction.User.Value).AddRoleAsync(role); await ((IGuildUser) reaction.User.Value).AddRoleAsync(role);
} }
} }
public interface IReactionListener
{
bool IsListener(ulong id);
Task AddRoleToListener(string messageId, IEmote emoji, IRole role);
void RemoveRole(ISocketMessageChannel channel, SocketReaction reaction);
void GiveRole(ISocketMessageChannel message, SocketReaction reaction);
}
} }

View file

@ -0,0 +1,26 @@
using System;
using CommandLine;
namespace Geekbot.net.Lib
{
public class RunParameters
{
[Option('V', "verbose", Default = false, HelpText = "Prints all messages to standard output.")]
public bool Verbose { get; set; }
[Option('r', "reset", Default = false, HelpText = "Resets the bot")]
public bool Reset { get; set; }
[Option('j', "log-json", Default = false, HelpText = "Logs messages as json")]
public bool LogJson { get; set; }
[Option("disable-api", Default = false, HelpText = "Disables the web api")]
public bool DisableApi { get; set; }
[Option('e', "expose-errors", Default = false, HelpText = "Shows internal errors in the chat")]
public bool ExposeErrors { get; set; }
[Option("token", Default = null, HelpText = "Set a new bot token")]
public string Token { get; set; }
}
}

View file

@ -0,0 +1,13 @@
using System.Threading.Tasks;
using Discord.WebSocket;
namespace Geekbot.net.Lib.UserRepository
{
public interface IUserRepository
{
Task<bool> Update(SocketUser user);
UserRepositoryUser Get(ulong userId);
string GetUserSetting(ulong userId, string setting);
bool SaveUserSetting(ulong userId, string setting, string value);
}
}

View file

@ -2,10 +2,11 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord.WebSocket; using Discord.WebSocket;
using Geekbot.net.Lib.Logger;
using StackExchange.Redis; using StackExchange.Redis;
using Utf8Json; using Utf8Json;
namespace Geekbot.net.Lib namespace Geekbot.net.Lib.UserRepository
{ {
public class UserRepository : IUserRepository public class UserRepository : IUserRepository
{ {
@ -121,23 +122,4 @@ namespace Geekbot.net.Lib
return true; return true;
} }
} }
public class UserRepositoryUser
{
public ulong Id { get; set; }
public string Username { get; set; }
public string Discriminator { get; set; }
public string AvatarUrl { get; set; }
public bool IsBot { get; set; }
public DateTimeOffset Joined { get; set; }
public List<string> UsedNames { get; set; }
}
public interface IUserRepository
{
Task<bool> Update(SocketUser user);
UserRepositoryUser Get(ulong userId);
string GetUserSetting(ulong userId, string setting);
bool SaveUserSetting(ulong userId, string setting, string value);
}
} }

View file

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
namespace Geekbot.net.Lib.UserRepository
{
public class UserRepositoryUser
{
public ulong Id { get; set; }
public string Username { get; set; }
public string Discriminator { get; set; }
public string AvatarUrl { get; set; }
public bool IsBot { get; set; }
public DateTimeOffset Joined { get; set; }
public List<string> UsedNames { get; set; }
}
}

View file

@ -1,14 +1,22 @@
using System; using System;
using System.Linq;
using System.Net; using System.Net;
using System.Reflection; using System.Reflection;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using CommandLine;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Geekbot.net.Lib.Clients;
using Geekbot.net.Lib.Converters;
using Geekbot.net.Lib.ErrorHandling;
using Geekbot.net.Lib.Levels;
using Geekbot.net.Lib.Localization;
using Geekbot.net.Lib.Logger;
using Geekbot.net.Lib.Media; using Geekbot.net.Lib.Media;
using Geekbot.net.Lib.ReactionListener;
using Geekbot.net.Lib.UserRepository;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Nancy.Hosting.Self; using Nancy.Hosting.Self;
using StackExchange.Redis; using StackExchange.Redis;
@ -24,13 +32,18 @@ namespace Geekbot.net
private IServiceCollection _services; private IServiceCollection _services;
private IServiceProvider _servicesProvider; private IServiceProvider _servicesProvider;
private RedisValue _token; private RedisValue _token;
private IGeekbotLogger _logger; private GeekbotLogger _logger;
private IUserRepository _userRepository; private IUserRepository _userRepository;
private string[] _args;
private bool _firstStart; private bool _firstStart;
private RunParameters _runParameters;
private static void Main(string[] args) private static void Main(string[] args)
{ {
RunParameters runParameters = null;
Parser.Default.ParseArguments<RunParameters>(args)
.WithParsed(e => runParameters = e)
.WithNotParsed(_ => Environment.Exit(1));
var logo = new StringBuilder(); var logo = new StringBuilder();
logo.AppendLine(@" ____ _____ _____ _ ______ ___ _____"); logo.AppendLine(@" ____ _____ _____ _ ______ ___ _____");
logo.AppendLine(@" / ___| ____| ____| |/ / __ ) / _ \\_ _|"); logo.AppendLine(@" / ___| ____| ____| |/ / __ ) / _ \\_ _|");
@ -40,11 +53,11 @@ namespace Geekbot.net
logo.AppendLine("========================================="); logo.AppendLine("=========================================");
Console.WriteLine(logo.ToString()); Console.WriteLine(logo.ToString());
var sumologicActive = !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("GEEKBOT_SUMO")); var sumologicActive = !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("GEEKBOT_SUMO"));
var logger = new GeekbotLogger(sumologicActive); var logger = new GeekbotLogger(runParameters, sumologicActive);
logger.Information("Geekbot", "Starting..."); logger.Information("Geekbot", "Starting...");
try try
{ {
new Program().MainAsync(args, logger).GetAwaiter().GetResult(); new Program().MainAsync(runParameters, logger).GetAwaiter().GetResult();
} }
catch (Exception e) catch (Exception e)
{ {
@ -52,18 +65,19 @@ namespace Geekbot.net
} }
} }
private async Task MainAsync(string[] args, IGeekbotLogger logger) private async Task MainAsync(RunParameters runParameters, GeekbotLogger logger)
{ {
_logger = logger; _logger = logger;
_args = args; _runParameters = runParameters;
logger.Information("Geekbot", "Initing Stuff"); logger.Information("Geekbot", "Initing Stuff");
var discordLogger = new DiscordLogger(logger);
_client = new DiscordSocketClient(new DiscordSocketConfig _client = new DiscordSocketClient(new DiscordSocketConfig
{ {
LogLevel = LogSeverity.Verbose, LogLevel = LogSeverity.Verbose,
MessageCacheSize = 1000 MessageCacheSize = 1000
}); });
_client.Log += DiscordLogger; _client.Log += discordLogger.Log;
_commands = new CommandService(); _commands = new CommandService();
try try
@ -78,7 +92,7 @@ namespace Geekbot.net
Environment.Exit(102); Environment.Exit(102);
} }
_token = _redis.StringGet("discordToken"); _token = runParameters.Token ??_redis.StringGet("discordToken");
if (_token.IsNullOrEmpty) if (_token.IsNullOrEmpty)
{ {
Console.Write("Your bot Token: "); Console.Write("Your bot Token: ");
@ -132,7 +146,7 @@ namespace Geekbot.net
_logger.Information("Geekbot", "Registering Stuff"); _logger.Information("Geekbot", "Registering Stuff");
var translationHandler = new TranslationHandler(_client.Guilds, _redis, _logger); var translationHandler = new TranslationHandler(_client.Guilds, _redis, _logger);
var errorHandler = new ErrorHandler(_logger, translationHandler, _args.Contains("--expose-errors")); var errorHandler = new ErrorHandler(_logger, translationHandler, _runParameters.ExposeErrors);
var reactionListener = new ReactionListener(_redis); var reactionListener = new ReactionListener(_redis);
await _commands.AddModulesAsync(Assembly.GetEntryAssembly()); await _commands.AddModulesAsync(Assembly.GetEntryAssembly());
_services.AddSingleton(_commands); _services.AddSingleton(_commands);
@ -153,13 +167,13 @@ namespace Geekbot.net
_client.ReactionAdded += handlers.ReactionAdded; _client.ReactionAdded += handlers.ReactionAdded;
_client.ReactionRemoved += handlers.ReactionRemoved; _client.ReactionRemoved += handlers.ReactionRemoved;
if (_firstStart || _args.Contains("--reset")) if (_firstStart || _runParameters.Reset)
{ {
_logger.Information("Geekbot", "Finishing setup"); _logger.Information("Geekbot", "Finishing setup");
await FinishSetup(); await FinishSetup();
_logger.Information("Geekbot", "Setup finished"); _logger.Information("Geekbot", "Setup finished");
} }
if (!_args.Contains("--disable-api")) if (!_runParameters.DisableApi)
{ {
StartWebApi(); StartWebApi();
} }
@ -213,30 +227,5 @@ namespace Geekbot.net
} }
return Task.CompletedTask; return Task.CompletedTask;
} }
private Task DiscordLogger(LogMessage message)
{
var logMessage = $"[{message.Source}] {message.Message}";
switch (message.Severity)
{
case LogSeverity.Verbose:
case LogSeverity.Debug:
_logger.Debug(message.Source, message.Message);
break;
case LogSeverity.Info:
_logger.Information(message.Source, message.Message);
break;
case LogSeverity.Critical:
case LogSeverity.Error:
case LogSeverity.Warning:
if (logMessage.Contains("VOICE_STATE_UPDATE")) break;
_logger.Error(message.Source, message.Message, message.Exception);
break;
default:
_logger.Information(message.Source, $"{logMessage} --- {message.Severity}");
break;
}
return Task.CompletedTask;
}
} }
} }

View file

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
namespace Geekbot.net.WebApi.Help
{
public class CommandDto
{
public string Name { get; set; }
public string Category { get; set; }
public string Summary { get; set; }
public bool IsAdminCommand { get; set; }
public Array Aliases { get; set; }
public List<CommandParamDto> Params { get; set; }
}
}

View file

@ -0,0 +1,9 @@
namespace Geekbot.net.WebApi.Help
{
public class CommandParamDto
{
public string Summary { get; set; }
public string Default { get; set; }
public string Type { get; set; }
}
}

View file

@ -1,13 +1,11 @@
using System; using System.Linq;
using System.Collections.Generic;
using System.Linq;
using System.Reflection; using System.Reflection;
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Nancy; using Nancy;
namespace Geekbot.net.WebApi namespace Geekbot.net.WebApi.Help
{ {
public class HelpController : NancyModule public class HelpController : NancyModule
{ {
@ -47,21 +45,4 @@ namespace Geekbot.net.WebApi
return commands; return commands;
} }
} }
public class CommandDto
{
public string Name { get; set; }
public string Category { get; set; }
public string Summary { get; set; }
public bool IsAdminCommand { get; set; }
public Array Aliases { get; set; }
public List<CommandParamDto> Params { get; set; }
}
public class CommandParamDto
{
public string Summary { get; set; }
public string Default { get; set; }
public string Type { get; set; }
}
} }

View file

@ -0,0 +1,9 @@
namespace Geekbot.net.WebApi.Status
{
public class ApiStatusDto
{
public string GeekbotVersion { get; set; }
public string ApiVersion { get; set; }
public string Status { get; set; }
}
}

Some files were not shown because too many files have changed in this diff Show more