Code Cleanup, thanks resharper

This commit is contained in:
runebaas 2017-12-29 01:53:50 +01:00
parent 00035ac4b1
commit 813698394a
No known key found for this signature in database
GPG key ID: 2677AF508D0300D6
34 changed files with 298 additions and 325 deletions

View file

@ -13,12 +13,13 @@ namespace Geekbot.net.Commands
[RequireUserPermission(GuildPermission.Administrator)] [RequireUserPermission(GuildPermission.Administrator)]
public class Admin : ModuleBase public class Admin : ModuleBase
{ {
private readonly IDatabase _redis;
private readonly DiscordSocketClient _client; private readonly DiscordSocketClient _client;
private readonly IErrorHandler _errorHandler; private readonly IErrorHandler _errorHandler;
private readonly IDatabase _redis;
private readonly ITranslationHandler _translation; private readonly ITranslationHandler _translation;
public Admin(IDatabase redis, DiscordSocketClient client, IErrorHandler errorHandler, ITranslationHandler translationHandler) public Admin(IDatabase redis, DiscordSocketClient client, IErrorHandler errorHandler,
ITranslationHandler translationHandler)
{ {
_redis = redis; _redis = redis;
_client = client; _client = client;
@ -31,7 +32,7 @@ namespace Geekbot.net.Commands
[Summary("Set a Welcome Message (use '$user' to mention the new joined user).")] [Summary("Set a Welcome Message (use '$user' to mention the new joined user).")]
public async Task SetWelcomeMessage([Remainder] [Summary("message")] string welcomeMessage) public async Task SetWelcomeMessage([Remainder] [Summary("message")] string welcomeMessage)
{ {
_redis.HashSet($"{Context.Guild.Id}:Settings", new HashEntry[] { new HashEntry("WelcomeMsg", welcomeMessage) }); _redis.HashSet($"{Context.Guild.Id}:Settings", new[] {new HashEntry("WelcomeMsg", welcomeMessage)});
var formatedMessage = welcomeMessage.Replace("$user", Context.User.Mention); var formatedMessage = welcomeMessage.Replace("$user", Context.User.Mention);
await ReplyAsync("Welcome message has been changed\r\nHere is an example of how it would look:\r\n" + await ReplyAsync("Welcome message has been changed\r\nHere is an example of how it would look:\r\n" +
formatedMessage); formatedMessage);
@ -49,7 +50,8 @@ namespace Geekbot.net.Commands
sb.AppendLine("- `!admin showleave true` - send message to mod channel when someone leaves"); sb.AppendLine("- `!admin showleave true` - send message to mod channel when someone leaves");
sb.AppendLine("- `!admin showdel true` - send message to mod channel when someone deletes a message"); sb.AppendLine("- `!admin showdel true` - send message to mod channel when someone deletes a message");
await channel.SendMessageAsync(sb.ToString()); await channel.SendMessageAsync(sb.ToString());
_redis.HashSet($"{Context.Guild.Id}:Settings", new HashEntry[] {new HashEntry("ModChannel", channel.Id.ToString())}); _redis.HashSet($"{Context.Guild.Id}:Settings",
new[] {new HashEntry("ModChannel", channel.Id.ToString())});
} }
catch (Exception e) catch (Exception e)
{ {
@ -69,20 +71,21 @@ namespace Geekbot.net.Commands
if (enabled) if (enabled)
{ {
await modChannel.SendMessageAsync("Saved - now sending messages here when someone leaves"); await modChannel.SendMessageAsync("Saved - now sending messages here when someone leaves");
_redis.HashSet($"{Context.Guild.Id}:Settings", new HashEntry[] {new HashEntry("ShowLeave", true)}); _redis.HashSet($"{Context.Guild.Id}:Settings", new[] {new HashEntry("ShowLeave", true)});
} }
else else
{ {
await modChannel.SendMessageAsync("Saved - stopping sending messages here when someone leaves"); await modChannel.SendMessageAsync("Saved - stopping sending messages here when someone leaves");
_redis.HashSet($"{Context.Guild.Id}:Settings", new HashEntry[] {new HashEntry("ShowLeave", false)}); _redis.HashSet($"{Context.Guild.Id}:Settings", new[] {new HashEntry("ShowLeave", false)});
} }
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context, "Modchannel doesn't seem to exist, please set one with `!admin modchannel [channelId]`"); _errorHandler.HandleCommandException(e, Context,
"Modchannel doesn't seem to exist, please set one with `!admin modchannel [channelId]`");
} }
} }
[Command("showdel", RunMode = RunMode.Async)] [Command("showdel", RunMode = RunMode.Async)]
[Remarks(CommandCategories.Admin)] [Remarks(CommandCategories.Admin)]
[Summary("Notify modchannel when someone deletes a message")] [Summary("Notify modchannel when someone deletes a message")]
@ -94,21 +97,24 @@ namespace Geekbot.net.Commands
var modChannel = (ISocketMessageChannel) _client.GetChannel(modChannelId); var modChannel = (ISocketMessageChannel) _client.GetChannel(modChannelId);
if (enabled) if (enabled)
{ {
await modChannel.SendMessageAsync("Saved - now sending messages here when someone deletes a message"); await modChannel.SendMessageAsync(
_redis.HashSet($"{Context.Guild.Id}:Settings", new HashEntry[] {new HashEntry("ShowDelete", true)}); "Saved - now sending messages here when someone deletes a message");
_redis.HashSet($"{Context.Guild.Id}:Settings", new[] {new HashEntry("ShowDelete", true)});
} }
else else
{ {
await modChannel.SendMessageAsync("Saved - stopping sending messages here when someone deletes a message"); await modChannel.SendMessageAsync(
_redis.HashSet($"{Context.Guild.Id}:Settings", new HashEntry[] {new HashEntry("ShowDelete", false)}); "Saved - stopping sending messages here when someone deletes a message");
_redis.HashSet($"{Context.Guild.Id}:Settings", new[] {new HashEntry("ShowDelete", false)});
} }
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context, "Modchannel doesn't seem to exist, please set one with `!admin modchannel [channelId]`"); _errorHandler.HandleCommandException(e, Context,
"Modchannel doesn't seem to exist, please set one with `!admin modchannel [channelId]`");
} }
} }
[Command("setlang", RunMode = RunMode.Async)] [Command("setlang", RunMode = RunMode.Async)]
[Remarks(CommandCategories.Admin)] [Remarks(CommandCategories.Admin)]
[Summary("Change the bots language")] [Summary("Change the bots language")]
@ -124,6 +130,7 @@ namespace Geekbot.net.Commands
await ReplyAsync(trans["NewLanguageSet"]); await ReplyAsync(trans["NewLanguageSet"]);
return; return;
} }
await ReplyAsync( await ReplyAsync(
$"That doesn't seem to be a supported language\r\nSupported Languages are {string.Join(", ", _translation.GetSupportedLanguages())}"); $"That doesn't seem to be a supported language\r\nSupported Languages are {string.Join(", ", _translation.GetSupportedLanguages())}");
} }
@ -132,7 +139,7 @@ namespace Geekbot.net.Commands
_errorHandler.HandleCommandException(e, Context); _errorHandler.HandleCommandException(e, Context);
} }
} }
[Command("lang", RunMode = RunMode.Async)] [Command("lang", RunMode = RunMode.Async)]
[Remarks(CommandCategories.Admin)] [Remarks(CommandCategories.Admin)]
[Summary("Change the bots language")] [Summary("Change the bots language")]

View file

@ -9,7 +9,7 @@ namespace Geekbot.net.Commands
public class AvatarGetter : ModuleBase public class AvatarGetter : ModuleBase
{ {
private readonly IErrorHandler _errorHandler; private readonly IErrorHandler _errorHandler;
public AvatarGetter(IErrorHandler errorHandler) public AvatarGetter(IErrorHandler errorHandler)
{ {
_errorHandler = errorHandler; _errorHandler = errorHandler;
@ -18,14 +18,11 @@ namespace Geekbot.net.Commands
[Command("avatar", RunMode = RunMode.Async)] [Command("avatar", RunMode = RunMode.Async)]
[Remarks(CommandCategories.Helpers)] [Remarks(CommandCategories.Helpers)]
[Summary("Get someones avatar")] [Summary("Get someones avatar")]
public async Task getAvatar([Remainder, Summary("user")] IUser user = null) public async Task getAvatar([Remainder] [Summary("user")] IUser user = null)
{ {
try try
{ {
if (user == null) if (user == null) user = Context.User;
{
user = Context.User;
}
var url = user.GetAvatarUrl().Replace("128", "1024"); var url = user.GetAvatarUrl().Replace("128", "1024");
await ReplyAsync(url); await ReplyAsync(url);
} }

View file

@ -2,7 +2,6 @@
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using StackExchange.Redis;
namespace Geekbot.net.Commands namespace Geekbot.net.Commands
{ {
@ -10,13 +9,11 @@ namespace Geekbot.net.Commands
public class BattleTag : ModuleBase public class BattleTag : ModuleBase
{ {
private readonly IErrorHandler _errorHandler; private readonly IErrorHandler _errorHandler;
private readonly IDatabase _redis;
private readonly IUserRepository _userRepository; private readonly IUserRepository _userRepository;
public BattleTag(IErrorHandler errorHandler, IDatabase redis, IUserRepository userRepository) public BattleTag(IErrorHandler errorHandler, IUserRepository userRepository)
{ {
_errorHandler = errorHandler; _errorHandler = errorHandler;
_redis = redis;
_userRepository = userRepository; _userRepository = userRepository;
} }
@ -29,21 +26,16 @@ namespace Geekbot.net.Commands
{ {
var tag = _userRepository.getUserSetting(Context.User.Id, "BattleTag"); var tag = _userRepository.getUserSetting(Context.User.Id, "BattleTag");
if (!string.IsNullOrEmpty(tag)) if (!string.IsNullOrEmpty(tag))
{
await ReplyAsync($"Your BattleTag is {tag}"); await ReplyAsync($"Your BattleTag is {tag}");
}
else else
{
await ReplyAsync("You haven't set your BattleTag, set it with `!battletag user#1234`"); await ReplyAsync("You haven't set your BattleTag, set it with `!battletag user#1234`");
}
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); _errorHandler.HandleCommandException(e, Context);
} }
} }
[Command(RunMode = RunMode.Async)] [Command(RunMode = RunMode.Async)]
[Remarks(CommandCategories.Games)] [Remarks(CommandCategories.Games)]
[Summary("Save your battletag")] [Summary("Save your battletag")]
@ -71,7 +63,7 @@ namespace Geekbot.net.Commands
{ {
var splited = tag.Split("#"); var splited = tag.Split("#");
if (splited.Length != 2) return false; if (splited.Length != 2) return false;
if (!int.TryParse(splited[1], out int discriminator)) return false; if (!int.TryParse(splited[1], out var discriminator)) return false;
if (splited[1].Length == 4 || splited[1].Length == 5) return true; if (splited[1].Length == 4 || splited[1].Length == 5) return true;
return false; return false;
} }

View file

@ -11,12 +11,12 @@ namespace Geekbot.net.Commands
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)] [Command("cat", RunMode = RunMode.Async)]
[Remarks(CommandCategories.Randomness)] [Remarks(CommandCategories.Randomness)]
[Summary("Return a random image of a cat.")] [Summary("Return a random image of a cat.")]
@ -49,7 +49,7 @@ namespace Geekbot.net.Commands
_errorHandler.HandleCommandException(e, Context); _errorHandler.HandleCommandException(e, Context);
} }
} }
private class CatResponse private class CatResponse
{ {
public string file { get; set; } public string file { get; set; }

View file

@ -3,7 +3,6 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Net.Http; using System.Net.Http;
using System.Text; using System.Text;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
@ -15,15 +14,15 @@ namespace Geekbot.net.Commands
{ {
public class Changelog : ModuleBase public class Changelog : ModuleBase
{ {
private readonly IErrorHandler _errorHandler;
private readonly DiscordSocketClient _client; private readonly DiscordSocketClient _client;
private readonly IErrorHandler _errorHandler;
public Changelog(IErrorHandler errorHandler, DiscordSocketClient client) public Changelog(IErrorHandler errorHandler, DiscordSocketClient client)
{ {
_errorHandler = errorHandler; _errorHandler = errorHandler;
_client = client; _client = client;
} }
[Command("changelog", RunMode = RunMode.Async)] [Command("changelog", RunMode = RunMode.Async)]
[Alias("updates")] [Alias("updates")]
[Remarks(CommandCategories.Helpers)] [Remarks(CommandCategories.Helpers)]
@ -35,7 +34,8 @@ namespace Geekbot.net.Commands
using (var client = new HttpClient()) using (var client = new HttpClient())
{ {
client.BaseAddress = new Uri("https://api.github.com"); client.BaseAddress = new Uri("https://api.github.com");
client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "http://developer.github.com/v3/#user-agent-required"); client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent",
"http://developer.github.com/v3/#user-agent-required");
var response = await client.GetAsync("/repos/pizzaandcoffee/geekbot.net/commits"); var response = await client.GetAsync("/repos/pizzaandcoffee/geekbot.net/commits");
response.EnsureSuccessStatusCode(); response.EnsureSuccessStatusCode();
@ -43,7 +43,7 @@ namespace Geekbot.net.Commands
var commits = JsonConvert.DeserializeObject<List<Commit>>(stringResponse); var commits = JsonConvert.DeserializeObject<List<Commit>>(stringResponse);
var eb = new EmbedBuilder(); var eb = new EmbedBuilder();
eb.WithColor(new Color(143, 165, 102)); eb.WithColor(new Color(143, 165, 102));
eb.WithAuthor(new EmbedAuthorBuilder() eb.WithAuthor(new EmbedAuthorBuilder
{ {
IconUrl = _client.CurrentUser.GetAvatarUrl(), IconUrl = _client.CurrentUser.GetAvatarUrl(),
Name = "Latest Updates", Name = "Latest Updates",
@ -51,11 +51,9 @@ 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.author.date:yyyy-MM-dd})");
}
eb.Description = sb.ToString(); eb.Description = sb.ToString();
eb.WithFooter(new EmbedFooterBuilder() eb.WithFooter(new EmbedFooterBuilder
{ {
Text = $"List generated from github commits on {DateTime.Now:yyyy-MM-dd}" Text = $"List generated from github commits on {DateTime.Now:yyyy-MM-dd}"
}); });
@ -67,14 +65,14 @@ namespace Geekbot.net.Commands
_errorHandler.HandleCommandException(e, Context); _errorHandler.HandleCommandException(e, Context);
} }
} }
private class Commit private class Commit
{ {
public string sha { get; set; } public string sha { get; set; }
public CommitInfo commit { get; set; } public CommitInfo commit { get; set; }
public Uri html_url { get; set; } public Uri html_url { get; set; }
} }
private class CommitInfo private class CommitInfo
{ {
public commitAuthor author { get; set; } public commitAuthor author { get; set; }

View file

@ -11,8 +11,8 @@ namespace Geekbot.net.Commands
public class CheckEm : ModuleBase public class CheckEm : ModuleBase
{ {
private readonly IMediaProvider _checkEmImages; private readonly IMediaProvider _checkEmImages;
private readonly Random _rnd;
private readonly IErrorHandler _errorHandler; private readonly IErrorHandler _errorHandler;
private readonly Random _rnd;
public CheckEm(Random RandomClient, IMediaProvider mediaProvider, IErrorHandler errorHandler) public CheckEm(Random RandomClient, IMediaProvider mediaProvider, IErrorHandler errorHandler)
{ {
@ -66,6 +66,7 @@ namespace Geekbot.net.Commands
listOfInts.Add(num % 10); listOfInts.Add(num % 10);
num = num / 10; num = num / 10;
} }
listOfInts.Reverse(); listOfInts.Reverse();
return listOfInts.ToArray(); return listOfInts.ToArray();
} }

View file

@ -7,8 +7,8 @@ namespace Geekbot.net.Commands
{ {
public class Choose : ModuleBase public class Choose : ModuleBase
{ {
private readonly Random _rnd;
private readonly IErrorHandler _errorHandler; private readonly IErrorHandler _errorHandler;
private readonly Random _rnd;
private readonly ITranslationHandler _translation; private readonly ITranslationHandler _translation;
public Choose(Random RandomClient, IErrorHandler errorHandler, ITranslationHandler translation) public Choose(Random RandomClient, IErrorHandler errorHandler, ITranslationHandler translation)
@ -21,7 +21,8 @@ namespace Geekbot.net.Commands
[Command("choose", RunMode = RunMode.Async)] [Command("choose", RunMode = RunMode.Async)]
[Remarks(CommandCategories.Helpers)] [Remarks(CommandCategories.Helpers)]
[Summary("Let the bot choose for you, seperate options with a semicolon.")] [Summary("Let the bot choose for you, seperate options with a semicolon.")]
public async Task Command([Remainder] [Summary("option1;option2")] string choices) public async Task Command([Remainder] [Summary("option1;option2")]
string choices)
{ {
try try
{ {

View file

@ -10,11 +10,11 @@ namespace Geekbot.net.Commands
{ {
public class Dice : ModuleBase public class Dice : ModuleBase
{ {
private readonly Random rnd; private readonly Random _rnd;
public Dice(Random RandomClient) public Dice(Random RandomClient)
{ {
rnd = RandomClient; _rnd = RandomClient;
} }
[Command("dice", RunMode = RunMode.Async)] [Command("dice", RunMode = RunMode.Async)]
@ -39,6 +39,7 @@ namespace Geekbot.net.Commands
await ReplyAsync("You can only have one mod"); await ReplyAsync("You can only have one mod");
return; return;
} }
mod = dice.mod; mod = dice.mod;
} }
} }
@ -56,6 +57,7 @@ namespace Geekbot.net.Commands
await ReplyAsync("You can't throw more than 20 dices"); await ReplyAsync("You can't throw more than 20 dices");
return; return;
} }
if (dices.Any(d => d.sides > 120)) if (dices.Any(d => d.sides > 120))
{ {
await ReplyAsync("A dice can't have more than 120 sides"); await ReplyAsync("A dice can't have more than 120 sides");
@ -73,32 +75,26 @@ namespace Geekbot.net.Commands
var results = new List<int>(); var results = new List<int>();
for (var i = 0; i < dice.times; i++) for (var i = 0; i < dice.times; i++)
{ {
var roll = rnd.Next(1, dice.sides); var roll = _rnd.Next(1, dice.sides);
total += roll; total += roll;
results.Add(roll); results.Add(roll);
if (roll == dice.sides) if (roll == dice.sides) extraText = "**Critical Hit!**";
{ if (roll == 1) extraText = "**Critical Fail!**";
extraText = "**Critical Hit!**";
}
if (roll == 1)
{
extraText = "**Critical Fail!**";
}
} }
resultStrings.Add($"{dice.diceType} ({string.Join(",", results)})"); resultStrings.Add($"{dice.diceType} ({string.Join(",", results)})");
} }
rep.Append(string.Join(" + ", resultStrings)); rep.Append(string.Join(" + ", resultStrings));
if (mod != 0) if (mod != 0)
{ {
rep.Append($" + {mod}"); rep.Append($" + {mod}");
total += mod; total += mod;
} }
rep.AppendLine(); rep.AppendLine();
rep.AppendLine($"**Total:** {total}"); rep.AppendLine($"**Total:** {total}");
if (extraText != "") if (extraText != "") rep.AppendLine(extraText);
{
rep.AppendLine(extraText);
}
await ReplyAsync(rep.ToString()); await ReplyAsync(rep.ToString());
} }
@ -106,29 +102,25 @@ namespace Geekbot.net.Commands
{ {
var diceParts = dice.Split('d'); var diceParts = dice.Split('d');
if (diceParts.Length == 2 if (diceParts.Length == 2
&& int.TryParse(diceParts[0], out int times) && int.TryParse(diceParts[0], out var times)
&& int.TryParse(diceParts[1], out int max)) && int.TryParse(diceParts[1], out var max))
{ return new DiceTypeDto
return new DiceTypeDto()
{ {
diceType = dice, diceType = dice,
times = times, times = times,
sides = max sides = max
}; };
}
if (dice.Length == 1 if (dice.Length == 1
&& int.TryParse(diceParts[0], out int mod)) && int.TryParse(diceParts[0], out var mod))
{ return new DiceTypeDto
return new DiceTypeDto()
{ {
mod = mod mod = mod
}; };
}
return new DiceTypeDto(); return new DiceTypeDto();
} }
} }
class DiceTypeDto internal class DiceTypeDto
{ {
public string diceType { get; set; } public string diceType { get; set; }
public int times { get; set; } public int times { get; set; }

View file

@ -11,12 +11,12 @@ namespace Geekbot.net.Commands
public class Dog : ModuleBase public class Dog : ModuleBase
{ {
private readonly IErrorHandler _errorHandler; private readonly IErrorHandler _errorHandler;
public Dog(IErrorHandler errorHandler) public Dog(IErrorHandler errorHandler)
{ {
_errorHandler = errorHandler; _errorHandler = errorHandler;
} }
[Command("dog", RunMode = RunMode.Async)] [Command("dog", RunMode = RunMode.Async)]
[Remarks(CommandCategories.Randomness)] [Remarks(CommandCategories.Randomness)]
[Summary("Return a random image of a dog.")] [Summary("Return a random image of a dog.")]
@ -49,7 +49,7 @@ namespace Geekbot.net.Commands
_errorHandler.HandleCommandException(e, Context); _errorHandler.HandleCommandException(e, Context);
} }
} }
private class DogResponse private class DogResponse
{ {
public string url { get; set; } public string url { get; set; }

View file

@ -8,8 +8,8 @@ namespace Geekbot.net.Commands
{ {
public class EightBall : ModuleBase public class EightBall : ModuleBase
{ {
private readonly Random _rnd;
private readonly IErrorHandler _errorHandler; private readonly IErrorHandler _errorHandler;
private readonly Random _rnd;
public EightBall(Random RandomClient, IErrorHandler errorHandler) public EightBall(Random RandomClient, IErrorHandler errorHandler)
{ {

View file

@ -1,7 +1,5 @@
using System; using System;
using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Lib; using Geekbot.net.Lib;
@ -9,38 +7,31 @@ namespace Geekbot.net.Commands
{ {
public class Emojify : ModuleBase public class Emojify : ModuleBase
{ {
private readonly IErrorHandler _errorHandler;
private readonly IEmojiConverter _emojiConverter; private readonly IEmojiConverter _emojiConverter;
private readonly IErrorHandler _errorHandler;
public Emojify(IErrorHandler errorHandler, IEmojiConverter emojiConverter) public Emojify(IErrorHandler errorHandler, IEmojiConverter emojiConverter)
{ {
_errorHandler = errorHandler; _errorHandler = errorHandler;
_emojiConverter = emojiConverter; _emojiConverter = emojiConverter;
} }
[Command("emojify", RunMode = RunMode.Async)] [Command("emojify", RunMode = RunMode.Async)]
[Remarks(CommandCategories.Helpers)] [Remarks(CommandCategories.Helpers)]
[Summary("Emojify text")] [Summary("Emojify text")]
public async Task Dflt([Remainder, Summary("text")] string text) public async Task Dflt([Remainder] [Summary("text")] string text)
{ {
try try
{ {
var sb = new StringBuilder();
var emojis = _emojiConverter.textToEmoji(text); var emojis = _emojiConverter.textToEmoji(text);
if (emojis.Length > 1999) if (emojis.Length > 1999)
{ {
await ReplyAsync("I can't take that much at once!"); await ReplyAsync("I can't take that much at once!");
return; return;
} }
var eb = new EmbedBuilder();
eb.WithAuthor(new EmbedAuthorBuilder() await ReplyAsync($"{Context.User.Username}#{Context.User.Discriminator} said:");
{ await ReplyAsync(emojis);
IconUrl = Context.User.GetAvatarUrl(),
Name = $"{Context.User.Username}#{Context.User.Discriminator}"
});
eb.WithColor(new Color(59, 136, 195));
eb.Description = emojis;
await ReplyAsync("", false, eb.Build());
} }
catch (Exception e) catch (Exception e)
{ {

View file

@ -7,11 +7,11 @@ namespace Geekbot.net.Commands
{ {
public class Fortune : ModuleBase public class Fortune : ModuleBase
{ {
private readonly IFortunesProvider fortunes; private readonly IFortunesProvider _fortunes;
public Fortune(IFortunesProvider fortunes) public Fortune(IFortunesProvider fortunes)
{ {
this.fortunes = fortunes; _fortunes = fortunes;
} }
[Command("fortune", RunMode = RunMode.Async)] [Command("fortune", RunMode = RunMode.Async)]
@ -19,7 +19,7 @@ namespace Geekbot.net.Commands
[Summary("Get a random fortune")] [Summary("Get a random fortune")]
public async Task GetAFortune() public async Task GetAFortune()
{ {
await ReplyAsync(fortunes.GetRandomFortune()); await ReplyAsync(_fortunes.GetRandomFortune());
} }
} }
} }

View file

@ -1,19 +0,0 @@
using System.Threading.Tasks;
using Discord.Commands;
using Geekbot.net.Lib;
namespace Geekbot.net.Commands
{
public class Google : ModuleBase
{
[Command("google", RunMode = RunMode.Async)]
[Remarks(CommandCategories.Fun)]
[Summary("Google Something.")]
public async Task Eyes([Remainder, Summary("SearchText")] string searchText)
{
var url = $"http://lmgtfy.com/?q={searchText.Replace(' ', '+')}";
await ReplyAsync($"Please click here :unamused:\r\n{url}");
}
}
}

View file

@ -10,9 +10,9 @@ namespace Geekbot.net.Commands
{ {
public class GuildInfo : ModuleBase public class GuildInfo : ModuleBase
{ {
private readonly IDatabase _redis;
private readonly ILevelCalc _levelCalc;
private readonly IErrorHandler _errorHandler; private readonly IErrorHandler _errorHandler;
private readonly ILevelCalc _levelCalc;
private readonly IDatabase _redis;
public GuildInfo(IDatabase redis, ILevelCalc levelCalc, IErrorHandler errorHandler) public GuildInfo(IDatabase redis, ILevelCalc levelCalc, IErrorHandler errorHandler)
{ {

View file

@ -12,10 +12,10 @@ namespace Geekbot.net.Commands
{ {
public class Info : ModuleBase public class Info : ModuleBase
{ {
private readonly IDatabase _redis;
private readonly IErrorHandler _errorHandler;
private readonly DiscordSocketClient _client; private readonly DiscordSocketClient _client;
private readonly CommandService _commands; private readonly CommandService _commands;
private readonly IErrorHandler _errorHandler;
private readonly IDatabase _redis;
public Info(IDatabase redis, IErrorHandler errorHandler, DiscordSocketClient client, CommandService commands) public Info(IDatabase redis, IErrorHandler errorHandler, DiscordSocketClient client, CommandService commands)
{ {
@ -33,30 +33,30 @@ namespace Geekbot.net.Commands
try try
{ {
var eb = new EmbedBuilder(); var eb = new EmbedBuilder();
eb.WithAuthor(new EmbedAuthorBuilder() eb.WithAuthor(new EmbedAuthorBuilder()
.WithIconUrl(_client.CurrentUser.GetAvatarUrl()) .WithIconUrl(_client.CurrentUser.GetAvatarUrl())
.WithName($"{Constants.Name} V{Constants.BotVersion}")); .WithName($"{Constants.Name} V{Constants.BotVersion}"));
var botOwner = await Context.Guild.GetUserAsync(ulong.Parse(_redis.StringGet("botOwner"))); var botOwner = await Context.Guild.GetUserAsync(ulong.Parse(_redis.StringGet("botOwner")));
var uptime = (DateTime.Now.Subtract(Process.GetCurrentProcess().StartTime)); var uptime = DateTime.Now.Subtract(Process.GetCurrentProcess().StartTime);
eb.AddInlineField("Bot Name", _client.CurrentUser.Username); eb.AddInlineField("Bot Name", _client.CurrentUser.Username);
eb.AddInlineField("Bot Owner", $"{botOwner.Username}#{botOwner.Discriminator}"); eb.AddInlineField("Bot Owner", $"{botOwner.Username}#{botOwner.Discriminator}");
eb.AddInlineField("Library", "Discord.NET V1.0.2"); eb.AddInlineField("Library", "Discord.NET V1.0.2");
eb.AddInlineField("Uptime", $"{uptime.Days}D {uptime.Hours}H {uptime.Minutes}M {uptime.Seconds}S"); eb.AddInlineField("Uptime", $"{uptime.Days}D {uptime.Hours}H {uptime.Minutes}M {uptime.Seconds}S");
eb.AddInlineField("Servers", Context.Client.GetGuildsAsync().Result.Count); eb.AddInlineField("Servers", Context.Client.GetGuildsAsync().Result.Count);
eb.AddInlineField("Total Commands", _commands.Commands.Count()); eb.AddInlineField("Total Commands", _commands.Commands.Count());
eb.AddField("Website", "https://geekbot.pizzaandcoffee.rocks/"); eb.AddField("Website", "https://geekbot.pizzaandcoffee.rocks/");
await ReplyAsync("", false, eb.Build()); await ReplyAsync("", false, eb.Build());
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); _errorHandler.HandleCommandException(e, Context);
} }
} }
[Command("uptime", RunMode = RunMode.Async)] [Command("uptime", RunMode = RunMode.Async)]
[Remarks(CommandCategories.Helpers)] [Remarks(CommandCategories.Helpers)]
[Summary("Get the Bot Uptime")] [Summary("Get the Bot Uptime")]
@ -64,12 +64,12 @@ namespace Geekbot.net.Commands
{ {
try try
{ {
var uptime = (DateTime.Now.Subtract(Process.GetCurrentProcess().StartTime)); var uptime = DateTime.Now.Subtract(Process.GetCurrentProcess().StartTime);
await ReplyAsync($"{uptime.Days}D {uptime.Hours}H {uptime.Minutes}M {uptime.Seconds}S"); await ReplyAsync($"{uptime.Days}D {uptime.Hours}H {uptime.Minutes}M {uptime.Seconds}S");
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); _errorHandler.HandleCommandException(e, Context);
} }
} }
} }

View file

@ -3,18 +3,17 @@ using System.Threading.Tasks;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Serilog;
using StackExchange.Redis; using StackExchange.Redis;
namespace Geekbot.net.Commands namespace Geekbot.net.Commands
{ {
public class Counters : ModuleBase public class Karma : ModuleBase
{ {
private readonly IDatabase _redis;
private readonly IErrorHandler _errorHandler; private readonly IErrorHandler _errorHandler;
private readonly IDatabase _redis;
private readonly ITranslationHandler _translation; private readonly ITranslationHandler _translation;
public Counters(IDatabase redis, IErrorHandler errorHandler, ITranslationHandler translation) public Karma(IDatabase redis, IErrorHandler errorHandler, ITranslationHandler translation)
{ {
_redis = redis; _redis = redis;
_errorHandler = errorHandler; _errorHandler = errorHandler;
@ -37,13 +36,14 @@ namespace Geekbot.net.Commands
} }
else if (TimeoutFinished(lastKarma)) else if (TimeoutFinished(lastKarma))
{ {
await ReplyAsync(string.Format(transDict["WaitUntill"], Context.User.Username, GetTimeLeft(lastKarma))); await ReplyAsync(string.Format(transDict["WaitUntill"], Context.User.Username,
GetTimeLeft(lastKarma)));
} }
else else
{ {
var newKarma = _redis.HashIncrement($"{Context.Guild.Id}:Karma", user.Id.ToString()); var newKarma = _redis.HashIncrement($"{Context.Guild.Id}:Karma", user.Id.ToString());
_redis.HashSet($"{Context.Guild.Id}:KarmaTimeout", _redis.HashSet($"{Context.Guild.Id}:KarmaTimeout",
new HashEntry[] {new HashEntry(Context.User.Id.ToString(), DateTimeOffset.Now.ToString("u"))}); new[] {new HashEntry(Context.User.Id.ToString(), DateTimeOffset.Now.ToString("u"))});
var eb = new EmbedBuilder(); var eb = new EmbedBuilder();
eb.WithAuthor(new EmbedAuthorBuilder() eb.WithAuthor(new EmbedAuthorBuilder()
@ -80,13 +80,14 @@ namespace Geekbot.net.Commands
} }
else if (TimeoutFinished(lastKarma)) else if (TimeoutFinished(lastKarma))
{ {
await ReplyAsync(string.Format(transDict["WaitUntill"], Context.User.Username, GetTimeLeft(lastKarma))); await ReplyAsync(string.Format(transDict["WaitUntill"], Context.User.Username,
GetTimeLeft(lastKarma)));
} }
else else
{ {
var newKarma = _redis.HashDecrement($"{Context.Guild.Id}:Karma", user.Id.ToString()); var newKarma = _redis.HashDecrement($"{Context.Guild.Id}:Karma", user.Id.ToString());
_redis.HashSet($"{Context.Guild.Id}:KarmaTimeout", _redis.HashSet($"{Context.Guild.Id}:KarmaTimeout",
new HashEntry[] {new HashEntry(Context.User.Id.ToString(), DateTimeOffset.Now.ToString())}); new[] {new HashEntry(Context.User.Id.ToString(), DateTimeOffset.Now.ToString())});
var eb = new EmbedBuilder(); var eb = new EmbedBuilder();
eb.WithAuthor(new EmbedAuthorBuilder() eb.WithAuthor(new EmbedAuthorBuilder()
@ -109,15 +110,16 @@ namespace Geekbot.net.Commands
private DateTimeOffset ConvertToDateTimeOffset(string dateTimeOffsetString) private DateTimeOffset ConvertToDateTimeOffset(string dateTimeOffsetString)
{ {
if(string.IsNullOrEmpty(dateTimeOffsetString)) return DateTimeOffset.Now.Subtract(new TimeSpan(7, 18, 0, 0)); if (string.IsNullOrEmpty(dateTimeOffsetString))
return DateTimeOffset.Now.Subtract(new TimeSpan(7, 18, 0, 0));
return DateTimeOffset.Parse(dateTimeOffsetString); return DateTimeOffset.Parse(dateTimeOffsetString);
} }
private bool TimeoutFinished(DateTimeOffset lastKarma) private bool TimeoutFinished(DateTimeOffset lastKarma)
{ {
return lastKarma.AddMinutes(3) > DateTimeOffset.Now; return lastKarma.AddMinutes(3) > DateTimeOffset.Now;
} }
private string GetTimeLeft(DateTimeOffset lastKarma) private string GetTimeLeft(DateTimeOffset lastKarma)
{ {
var dt = lastKarma.AddMinutes(3).Subtract(DateTimeOffset.Now); var dt = lastKarma.AddMinutes(3).Subtract(DateTimeOffset.Now);

View file

@ -1,24 +1,20 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq; using System.Linq;
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 MtgApiManager.Lib.Service; using MtgApiManager.Lib.Service;
using Serilog;
namespace Geekbot.net.Commands namespace Geekbot.net.Commands
{ {
public class Magicthegathering : ModuleBase public class Magicthegathering : ModuleBase
{ {
private ILogger _logger; private readonly IErrorHandler _errorHandler;
private IErrorHandler _errorHandler;
public Magicthegathering(ILogger logger, IErrorHandler errorHandler) public Magicthegathering(IErrorHandler errorHandler)
{ {
_logger = logger;
_errorHandler = errorHandler; _errorHandler = errorHandler;
} }
@ -38,26 +34,28 @@ namespace Geekbot.net.Commands
await ReplyAsync("I couldn't find that card..."); await ReplyAsync("I couldn't find that card...");
return; return;
} }
var eb = new EmbedBuilder(); var eb = new EmbedBuilder();
eb.Title = card.Name; eb.Title = card.Name;
eb.Description = card.Type; eb.Description = card.Type;
if (card.Colors != null) eb.WithColor(GetColor(card.Colors)); if (card.Colors != null) eb.WithColor(GetColor(card.Colors));
if (card.ImageUrl != null) eb.ImageUrl = card.ImageUrl.ToString(); if (card.ImageUrl != null) eb.ImageUrl = card.ImageUrl.ToString();
if (!string.IsNullOrEmpty(card.Text)) eb.AddField("Text", card.Text); if (!string.IsNullOrEmpty(card.Text)) eb.AddField("Text", card.Text);
if (!string.IsNullOrEmpty(card.Flavor)) eb.AddField("Flavor", card.Flavor); if (!string.IsNullOrEmpty(card.Flavor)) eb.AddField("Flavor", card.Flavor);
if (!string.IsNullOrEmpty(card.SetName)) eb.AddInlineField("Set", card.SetName); if (!string.IsNullOrEmpty(card.SetName)) eb.AddInlineField("Set", card.SetName);
if (!string.IsNullOrEmpty(card.Power)) eb.AddInlineField("Power", card.Power); if (!string.IsNullOrEmpty(card.Power)) eb.AddInlineField("Power", card.Power);
if (!string.IsNullOrEmpty(card.Loyalty)) eb.AddInlineField("Loyality", card.Loyalty); if (!string.IsNullOrEmpty(card.Loyalty)) eb.AddInlineField("Loyality", card.Loyalty);
if (!string.IsNullOrEmpty(card.Toughness)) eb.AddInlineField("Thoughness", card.Toughness); if (!string.IsNullOrEmpty(card.Toughness)) eb.AddInlineField("Thoughness", card.Toughness);
if (!string.IsNullOrEmpty(card.ManaCost)) eb.AddInlineField("Cost", card.ManaCost); if (!string.IsNullOrEmpty(card.ManaCost)) eb.AddInlineField("Cost", card.ManaCost);
if (!string.IsNullOrEmpty(card.Rarity)) eb.AddInlineField("Rarity", card.Rarity); if (!string.IsNullOrEmpty(card.Rarity)) eb.AddInlineField("Rarity", card.Rarity);
if (card.Legalities != null) eb.AddField("Legality", string.Join(", ", card.Legalities.Select(e => e.Format))); if (card.Legalities != null)
eb.AddField("Legality", string.Join(", ", card.Legalities.Select(e => e.Format)));
await ReplyAsync("", false, eb.Build()); await ReplyAsync("", false, eb.Build());
} }

View file

@ -15,19 +15,20 @@ namespace Geekbot.net.Commands
[RequireUserPermission(GuildPermission.ManageRoles)] [RequireUserPermission(GuildPermission.ManageRoles)]
public class Mod : ModuleBase public class Mod : ModuleBase
{ {
private readonly IUserRepository _userRepository; private readonly DiscordSocketClient _client;
private readonly IErrorHandler _errorHandler; private readonly IErrorHandler _errorHandler;
private readonly IDatabase _redis; private readonly IDatabase _redis;
private readonly DiscordSocketClient _client; private readonly IUserRepository _userRepository;
public Mod(IUserRepository userRepositry, IErrorHandler errorHandler, IDatabase redis, DiscordSocketClient client) public Mod(IUserRepository userRepositry, IErrorHandler errorHandler, IDatabase redis,
DiscordSocketClient client)
{ {
_userRepository = userRepositry; _userRepository = userRepositry;
_errorHandler = errorHandler; _errorHandler = errorHandler;
_redis = redis; _redis = redis;
_client = client; _client = client;
} }
[Command("namehistory", RunMode = RunMode.Async)] [Command("namehistory", RunMode = RunMode.Async)]
[Remarks(CommandCategories.Admin)] [Remarks(CommandCategories.Admin)]
[Summary("See past usernames of an user")] [Summary("See past usernames of an user")]
@ -38,30 +39,26 @@ namespace Geekbot.net.Commands
var userRepo = _userRepository.Get(user.Id); var userRepo = _userRepository.Get(user.Id);
var sb = new StringBuilder(); var sb = new StringBuilder();
sb.AppendLine($":bust_in_silhouette: {user.Username} has been known as:"); sb.AppendLine($":bust_in_silhouette: {user.Username} has been known as:");
foreach (var name in userRepo.UsedNames) foreach (var name in userRepo.UsedNames) sb.AppendLine($"- `{name}`");
{
sb.AppendLine($"- `{name}`");
}
await ReplyAsync(sb.ToString()); await ReplyAsync(sb.ToString());
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context, $"I don't have enough permissions to give {user.Username} that role"); _errorHandler.HandleCommandException(e, Context,
$"I don't have enough permissions to give {user.Username} that role");
} }
} }
[Command("kick", RunMode = RunMode.Async)] [Command("kick", RunMode = RunMode.Async)]
[Remarks(CommandCategories.Admin)] [Remarks(CommandCategories.Admin)]
[Summary("Ban a user")] [Summary("Ban a user")]
public async Task kick([Summary("@user")] IUser userNormal, [Summary("reason"), Remainder] string reason = "none") public async Task kick([Summary("@user")] IUser userNormal,
[Summary("reason")] [Remainder] string reason = "none")
{ {
try try
{ {
var user = (IGuildUser)userNormal; var user = (IGuildUser) userNormal;
if (reason == "none") if (reason == "none") reason = "No reason provided";
{
reason = "No reason provided";
}
await user.GetOrCreateDMChannelAsync().Result.SendMessageAsync( await user.GetOrCreateDMChannelAsync().Result.SendMessageAsync(
$"You have been kicked from {Context.Guild.Name} for the following reason: \"{reason}\""); $"You have been kicked from {Context.Guild.Name} for the following reason: \"{reason}\"");
await user.KickAsync(); await user.KickAsync();

View file

@ -3,7 +3,6 @@ using System.Threading.Tasks;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Google.Apis.Util;
using OverwatchAPI; using OverwatchAPI;
using OverwatchAPI.Config; using OverwatchAPI.Config;
using Serilog; using Serilog;
@ -17,7 +16,7 @@ namespace Geekbot.net.Commands
private readonly IErrorHandler _errorHandler; private readonly IErrorHandler _errorHandler;
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IUserRepository _userRepository; private readonly IUserRepository _userRepository;
public Overwatch(IErrorHandler errorHandler, ILogger logger, IDatabase redis, IUserRepository userRepository) public Overwatch(IErrorHandler errorHandler, ILogger logger, IDatabase redis, IUserRepository userRepository)
{ {
_errorHandler = errorHandler; _errorHandler = errorHandler;
@ -38,21 +37,22 @@ namespace Geekbot.net.Commands
await ReplyAsync("You have no battle Tag saved, use `!battletag`"); await ReplyAsync("You have no battle Tag saved, use `!battletag`");
return; return;
} }
var profile = await createProfile(tag); var profile = await createProfile(tag);
if (profile == null) if (profile == null)
{ {
await ReplyAsync("That player doesn't seem to exist"); await ReplyAsync("That player doesn't seem to exist");
return; return;
} }
await ReplyAsync("", false, profile.Build());
await ReplyAsync("", false, profile.Build());
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); _errorHandler.HandleCommandException(e, Context);
} }
} }
[Command("profile", RunMode = RunMode.Async)] [Command("profile", RunMode = RunMode.Async)]
[Summary("Get someones overwatch profile. EU on PC only. Default battletag is your own (if set).")] [Summary("Get someones overwatch profile. EU on PC only. Default battletag is your own (if set).")]
[Remarks(CommandCategories.Games)] [Remarks(CommandCategories.Games)]
@ -65,12 +65,14 @@ namespace Geekbot.net.Commands
await ReplyAsync("That doesn't seem to be a valid battletag..."); await ReplyAsync("That doesn't seem to be a valid battletag...");
return; return;
} }
var profile = await createProfile(tag); var profile = await createProfile(tag);
if (profile == null) if (profile == null)
{ {
await ReplyAsync("That player doesn't seem to exist"); await ReplyAsync("That player doesn't seem to exist");
return; return;
} }
await ReplyAsync("", false, profile.Build()); await ReplyAsync("", false, profile.Build());
} }
catch (Exception e) catch (Exception e)
@ -92,12 +94,14 @@ namespace Geekbot.net.Commands
await ReplyAsync("This user didn't set a battletag"); await ReplyAsync("This user didn't set a battletag");
return; return;
} }
var profile = await createProfile(tag); var profile = await createProfile(tag);
if (profile == null) if (profile == null)
{ {
await ReplyAsync("That player doesn't seem to exist"); await ReplyAsync("That player doesn't seem to exist");
return; return;
} }
await ReplyAsync("", false, profile.Build()); await ReplyAsync("", false, profile.Build());
} }
catch (Exception e) catch (Exception e)
@ -112,10 +116,7 @@ namespace Geekbot.net.Commands
using (var owClient = new OverwatchClient(owConfig)) using (var owClient = new OverwatchClient(owConfig))
{ {
var player = await owClient.GetPlayerAsync(battletag); var player = await owClient.GetPlayerAsync(battletag);
if (player.Username == null) if (player.Username == null) return null;
{
return null;
}
_logger.Debug($"[OW] Username = {player.Username}"); _logger.Debug($"[OW] Username = {player.Username}");
var eb = new EmbedBuilder(); var eb = new EmbedBuilder();
eb.WithAuthor(new EmbedAuthorBuilder() eb.WithAuthor(new EmbedAuthorBuilder()
@ -123,10 +124,11 @@ namespace Geekbot.net.Commands
.WithName(player.Username)); .WithName(player.Username));
eb.Url = player.ProfileUrl; eb.Url = player.ProfileUrl;
eb.AddInlineField("Level", player.PlayerLevel); eb.AddInlineField("Level", player.PlayerLevel);
eb.AddInlineField("Current Rank", player.CompetitiveRank > 0 ? player.CompetitiveRank.ToString() : "Unranked"); eb.AddInlineField("Current Rank",
player.CompetitiveRank > 0 ? player.CompetitiveRank.ToString() : "Unranked");
return eb; return eb;
} }
} }
} }
} }

View file

@ -13,13 +13,14 @@ namespace Geekbot.net.Commands
[RequireUserPermission(GuildPermission.Administrator)] [RequireUserPermission(GuildPermission.Administrator)]
public class Owner : ModuleBase public class Owner : ModuleBase
{ {
private readonly IDatabase _redis;
private readonly DiscordSocketClient _client; private readonly DiscordSocketClient _client;
private readonly ILogger _logger;
private readonly IUserRepository _userRepository;
private readonly IErrorHandler _errorHandler; private readonly IErrorHandler _errorHandler;
private readonly ILogger _logger;
public Owner(IDatabase redis, DiscordSocketClient client, ILogger logger, IUserRepository userRepositry, IErrorHandler errorHandler) private readonly IDatabase _redis;
private readonly IUserRepository _userRepository;
public Owner(IDatabase redis, DiscordSocketClient client, ILogger logger, IUserRepository userRepositry,
IErrorHandler errorHandler)
{ {
_redis = redis; _redis = redis;
_client = client; _client = client;
@ -27,7 +28,7 @@ namespace Geekbot.net.Commands
_userRepository = userRepositry; _userRepository = userRepositry;
_errorHandler = errorHandler; _errorHandler = errorHandler;
} }
[Command("youtubekey", RunMode = RunMode.Async)] [Command("youtubekey", RunMode = RunMode.Async)]
[Remarks(CommandCategories.Admin)] [Remarks(CommandCategories.Admin)]
[Summary("Set the youtube api key")] [Summary("Set the youtube api key")]
@ -36,14 +37,15 @@ namespace Geekbot.net.Commands
var botOwner = Context.Guild.GetUserAsync(ulong.Parse(_redis.StringGet("botOwner"))).Result; var botOwner = Context.Guild.GetUserAsync(ulong.Parse(_redis.StringGet("botOwner"))).Result;
if (!Context.User.Id.ToString().Equals(botOwner.Id.ToString())) if (!Context.User.Id.ToString().Equals(botOwner.Id.ToString()))
{ {
await ReplyAsync($"Sorry, only the botowner can do this ({botOwner.Username}#{botOwner.Discriminator})"); await ReplyAsync(
$"Sorry, only the botowner can do this ({botOwner.Username}#{botOwner.Discriminator})");
return; return;
} }
_redis.StringSet("youtubeKey", key); _redis.StringSet("youtubeKey", key);
await ReplyAsync("Apikey has been set"); await ReplyAsync("Apikey has been set");
} }
[Command("game", RunMode = RunMode.Async)] [Command("game", RunMode = RunMode.Async)]
[Remarks(CommandCategories.Admin)] [Remarks(CommandCategories.Admin)]
[Summary("Set the game that the bot is playing")] [Summary("Set the game that the bot is playing")]
@ -52,7 +54,8 @@ namespace Geekbot.net.Commands
var botOwner = Context.Guild.GetUserAsync(ulong.Parse(_redis.StringGet("botOwner"))).Result; var botOwner = Context.Guild.GetUserAsync(ulong.Parse(_redis.StringGet("botOwner"))).Result;
if (!Context.User.Id.ToString().Equals(botOwner.Id.ToString())) if (!Context.User.Id.ToString().Equals(botOwner.Id.ToString()))
{ {
await ReplyAsync($"Sorry, only the botowner can do this ({botOwner.Username}#{botOwner.Discriminator})"); await ReplyAsync(
$"Sorry, only the botowner can do this ({botOwner.Username}#{botOwner.Discriminator})");
return; return;
} }
@ -61,7 +64,7 @@ namespace Geekbot.net.Commands
_logger.Information($"[Geekbot] Changed game to {key}"); _logger.Information($"[Geekbot] Changed game to {key}");
await ReplyAsync($"Now Playing {key}"); await ReplyAsync($"Now Playing {key}");
} }
[Command("popuserrepo", RunMode = RunMode.Async)] [Command("popuserrepo", RunMode = RunMode.Async)]
[Remarks(CommandCategories.Admin)] [Remarks(CommandCategories.Admin)]
[Summary("Populate user cache")] [Summary("Populate user cache")]
@ -83,6 +86,7 @@ namespace Geekbot.net.Commands
$"Sorry, only the botowner can do this"); $"Sorry, only the botowner can do this");
return; return;
} }
var success = 0; var success = 0;
var failed = 0; var failed = 0;
try try
@ -98,12 +102,15 @@ namespace Geekbot.net.Commands
var inc = succeded ? success++ : failed++; var inc = succeded ? success++ : failed++;
} }
} }
_logger.Warning("[UserRepository] Finished Updating User Repositry"); _logger.Warning("[UserRepository] Finished Updating User Repositry");
await ReplyAsync($"Successfully Populated User Repository with {success} Users in {_client.Guilds.Count} Guilds (Failed: {failed})"); await ReplyAsync(
$"Successfully Populated User Repository with {success} Users in {_client.Guilds.Count} Guilds (Failed: {failed})");
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context, "Couldn't complete User Repository, see console for more info"); _errorHandler.HandleCommandException(e, Context,
"Couldn't complete User Repository, see console for more info");
} }
} }
} }

View file

@ -5,14 +5,13 @@ using Discord;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using PokeAPI; using PokeAPI;
using Serilog;
namespace Geekbot.net.Commands namespace Geekbot.net.Commands
{ {
public class Pokedex : ModuleBase public class Pokedex : ModuleBase
{ {
private readonly IErrorHandler _errorHandler; private readonly IErrorHandler _errorHandler;
public Pokedex(IErrorHandler errorHandler) public Pokedex(IErrorHandler errorHandler)
{ {
_errorHandler = errorHandler; _errorHandler = errorHandler;
@ -36,6 +35,7 @@ namespace Geekbot.net.Commands
await ReplyAsync("I couldn't find that pokemon :confused:"); await ReplyAsync("I couldn't find that pokemon :confused:");
return; return;
} }
var embed = await pokemonEmbedBuilder(pokemon); var embed = await pokemonEmbedBuilder(pokemon);
await ReplyAsync("", false, embed.Build()); await ReplyAsync("", false, embed.Build());
} }
@ -52,8 +52,10 @@ namespace Geekbot.net.Commands
eb.Title = $"#{pokemon.ID} {toUpper(pokemon.Name)}"; eb.Title = $"#{pokemon.ID} {toUpper(pokemon.Name)}";
eb.Description = species.FlavorTexts[1].FlavorText; eb.Description = species.FlavorTexts[1].FlavorText;
eb.ThumbnailUrl = pokemon.Sprites.FrontMale ?? pokemon.Sprites.FrontFemale; eb.ThumbnailUrl = pokemon.Sprites.FrontMale ?? pokemon.Sprites.FrontFemale;
eb.AddInlineField(getSingularOrPlural(pokemon.Types.Length, "Type"), string.Join(", ", pokemon.Types.Select(t => toUpper(t.Type.Name)))); eb.AddInlineField(getSingularOrPlural(pokemon.Types.Length, "Type"),
eb.AddInlineField(getSingularOrPlural(pokemon.Abilities.Length, "Ability"), string.Join(", ", pokemon.Abilities.Select(t => toUpper(t.Ability.Name)))); string.Join(", ", pokemon.Types.Select(t => toUpper(t.Type.Name))));
eb.AddInlineField(getSingularOrPlural(pokemon.Abilities.Length, "Ability"),
string.Join(", ", pokemon.Abilities.Select(t => toUpper(t.Ability.Name))));
eb.AddInlineField("Height", pokemon.Height); eb.AddInlineField("Height", pokemon.Height);
eb.AddInlineField("Weight", pokemon.Mass); eb.AddInlineField("Weight", pokemon.Mass);
return eb; return eb;
@ -61,22 +63,14 @@ namespace Geekbot.net.Commands
private string getSingularOrPlural(int lenght, string word) private string getSingularOrPlural(int lenght, string word)
{ {
if (lenght == 1) if (lenght == 1) return word;
{ return word.EndsWith("y") ? $"{word.Remove(word.Length - 1)}ies" : $"{word}s";
return word;
}
return word.EndsWith("y") ? $"{word.Remove(word.Length-1)}ies" : $"{word}s";
} }
private string toUpper(string s) private string toUpper(string s)
{ {
if (string.IsNullOrEmpty(s)) if (string.IsNullOrEmpty(s)) return string.Empty;
{
return string.Empty;
}
return char.ToUpper(s[0]) + s.Substring(1); return char.ToUpper(s[0]) + s.Substring(1);
} }
} }
} }

View file

@ -14,12 +14,13 @@ namespace Geekbot.net.Commands
[Group("poll")] [Group("poll")]
public class Poll : ModuleBase public class Poll : ModuleBase
{ {
private readonly IEmojiConverter _emojiConverter;
private readonly IErrorHandler _errorHandler; private readonly IErrorHandler _errorHandler;
private readonly IDatabase _redis; private readonly IDatabase _redis;
private readonly IEmojiConverter _emojiConverter;
private readonly IUserRepository _userRepository; private readonly IUserRepository _userRepository;
public Poll(IErrorHandler errorHandler, IDatabase redis, IEmojiConverter emojiConverter, IUserRepository userRepository) public Poll(IErrorHandler errorHandler, IDatabase redis, IEmojiConverter emojiConverter,
IUserRepository userRepository)
{ {
_errorHandler = errorHandler; _errorHandler = errorHandler;
_redis = redis; _redis = redis;
@ -41,6 +42,7 @@ namespace Geekbot.net.Commands
"There is no poll in this channel ongoing at the moment\r\nYou can create one with `!poll create question;option1;option2;option3`"); "There is no poll in this channel ongoing at the moment\r\nYou can create one with `!poll create question;option1;option2;option3`");
return; return;
} }
await ReplyAsync("There is a poll running at the moment"); await ReplyAsync("There is a poll running at the moment");
} }
catch (Exception e) catch (Exception e)
@ -48,11 +50,12 @@ namespace Geekbot.net.Commands
_errorHandler.HandleCommandException(e, Context); _errorHandler.HandleCommandException(e, Context);
} }
} }
[Command("create", RunMode = RunMode.Async)] [Command("create", RunMode = RunMode.Async)]
[Remarks(CommandCategories.Helpers)] [Remarks(CommandCategories.Helpers)]
[Summary("Create a poll")] [Summary("Create a poll")]
public async Task Create([Remainder, Summary("question;option1;option2")] string rawPollString) public async Task Create([Remainder] [Summary("question;option1;option2")]
string rawPollString)
{ {
try try
{ {
@ -62,6 +65,7 @@ namespace Geekbot.net.Commands
await ReplyAsync("You have not finished you last poll yet. To finish it use `!poll end`"); await ReplyAsync("You have not finished you last poll yet. To finish it use `!poll end`");
return; return;
} }
var pollList = rawPollString.Split(';').ToList(); var pollList = rawPollString.Split(';').ToList();
if (pollList.Count <= 2) if (pollList.Count <= 2)
{ {
@ -88,7 +92,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 PollData
{ {
Creator = Context.User.Id, Creator = Context.User.Id,
MessageId = pollMessage.Id, MessageId = pollMessage.Id,
@ -97,14 +101,14 @@ namespace Geekbot.net.Commands
Options = pollList Options = pollList
}; };
var pollJson = JsonConvert.SerializeObject(poll); var pollJson = JsonConvert.SerializeObject(poll);
_redis.HashSet($"{Context.Guild.Id}:Polls", new HashEntry[] {new HashEntry(Context.Channel.Id, pollJson)}); _redis.HashSet($"{Context.Guild.Id}:Polls", new[] {new HashEntry(Context.Channel.Id, pollJson)});
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context); _errorHandler.HandleCommandException(e, Context);
} }
} }
[Command("end", RunMode = RunMode.Async)] [Command("end", RunMode = RunMode.Async)]
[Remarks(CommandCategories.Helpers)] [Remarks(CommandCategories.Helpers)]
[Summary("End the current poll")] [Summary("End the current poll")]
@ -118,18 +122,16 @@ namespace Geekbot.net.Commands
await ReplyAsync("There is no ongoing poll at the moment"); await ReplyAsync("There is no ongoing poll at the moment");
return; return;
} }
var results = await getPollResults(currentPoll); var results = await getPollResults(currentPoll);
var sb = new StringBuilder(); var sb = new StringBuilder();
sb.AppendLine("**Poll Results**"); sb.AppendLine("**Poll Results**");
sb.AppendLine(currentPoll.Question); sb.AppendLine(currentPoll.Question);
foreach (var result in results) foreach (var result in results) sb.AppendLine($"{result.VoteCount} - {result.Option}");
{
sb.AppendLine($"{result.VoteCount} - {result.Option}");
}
await ReplyAsync(sb.ToString()); await ReplyAsync(sb.ToString());
currentPoll.IsFinshed = true; currentPoll.IsFinshed = true;
var pollJson = JsonConvert.SerializeObject(currentPoll); var pollJson = JsonConvert.SerializeObject(currentPoll);
_redis.HashSet($"{Context.Guild.Id}:Polls", new HashEntry[] {new HashEntry(Context.Channel.Id, pollJson)}); _redis.HashSet($"{Context.Guild.Id}:Polls", new[] {new HashEntry(Context.Channel.Id, pollJson)});
} }
catch (Exception e) catch (Exception e)
{ {
@ -144,7 +146,7 @@ namespace Geekbot.net.Commands
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<PollData>(currentPoll.ToString());
} }
catch catch
{ {
return new PollData(); return new PollData();
} }
@ -152,14 +154,13 @@ namespace Geekbot.net.Commands
private async Task<List<PollResult>> getPollResults(PollData poll) private async Task<List<PollResult>> getPollResults(PollData 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<PollResult>();
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 PollResult
{ {
Option = poll.Options[option - 1], Option = poll.Options[option - 1],
VoteCount = r.Value.ReactionCount VoteCount = r.Value.ReactionCount
@ -167,8 +168,8 @@ namespace Geekbot.net.Commands
results.Add(result); results.Add(result);
} }
catch {} catch {}
}
results.Sort((x,y) => y.VoteCount.CompareTo(x.VoteCount)); results.Sort((x, y) => y.VoteCount.CompareTo(x.VoteCount));
return results; return results;
} }
@ -180,7 +181,7 @@ namespace Geekbot.net.Commands
public string Question { get; set; } public string Question { get; set; }
public List<string> Options { get; set; } public List<string> Options { get; set; }
} }
private class PollResult private class PollResult
{ {
public string Option { get; set; } public string Option { get; set; }

View file

@ -1,12 +1,10 @@
using System; using System;
using System.Collections.Generic;
using System.Linq; using System.Linq;
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 Newtonsoft.Json;
using Serilog;
using StackExchange.Redis; using StackExchange.Redis;
namespace Geekbot.net.Commands namespace Geekbot.net.Commands
@ -14,23 +12,21 @@ namespace Geekbot.net.Commands
[Group("quote")] [Group("quote")]
public class Quote : ModuleBase public class Quote : ModuleBase
{ {
private readonly IDatabase redis;
private readonly ILogger logger;
private readonly IErrorHandler errorHandler; private readonly IErrorHandler errorHandler;
private readonly IDatabase redis;
public Quote(IDatabase redis, ILogger logger, IErrorHandler errorHandler)
public Quote(IDatabase redis, IErrorHandler errorHandler)
{ {
this.redis = redis; this.redis = redis;
this.logger = logger;
this.errorHandler = errorHandler; this.errorHandler = errorHandler;
} }
[Command()] [Command]
[Remarks(CommandCategories.Quotes)] [Remarks(CommandCategories.Quotes)]
[Summary("Return a random quoute from the database")] [Summary("Return a random quoute from the database")]
public async Task getRandomQuote() public async Task getRandomQuote()
{ {
var randomQuote = redis.SetRandomMember($"{Context.Guild.Id}:Quotes"); var randomQuote = redis.SetRandomMember($"{Context.Guild.Id}:Quotes");
try try
{ {
var quote = JsonConvert.DeserializeObject<QuoteObject>(randomQuote); var quote = JsonConvert.DeserializeObject<QuoteObject>(randomQuote);
@ -42,7 +38,7 @@ namespace Geekbot.net.Commands
errorHandler.HandleCommandException(e, Context, "Whoops, seems like the quote was to edgy to return"); errorHandler.HandleCommandException(e, Context, "Whoops, seems like the quote was to edgy to return");
} }
} }
[Command("save")] [Command("save")]
[Remarks(CommandCategories.Quotes)] [Remarks(CommandCategories.Quotes)]
[Summary("Save a quote from the last sent message by @user")] [Summary("Save a quote from the last sent message by @user")]
@ -55,11 +51,13 @@ namespace Geekbot.net.Commands
await ReplyAsync("You can't save your own quotes..."); await ReplyAsync("You can't save your own quotes...");
return; return;
} }
if (user.IsBot) if (user.IsBot)
{ {
await ReplyAsync("You can't save quotes by a bot..."); await ReplyAsync("You can't save quotes by a bot...");
return; return;
} }
var lastMessage = await getLastMessageByUser(user); var lastMessage = await getLastMessageByUser(user);
var quote = createQuoteObject(lastMessage); var quote = createQuoteObject(lastMessage);
var quoteStore = JsonConvert.SerializeObject(quote); var quoteStore = JsonConvert.SerializeObject(quote);
@ -69,10 +67,11 @@ namespace Geekbot.net.Commands
} }
catch (Exception e) catch (Exception e)
{ {
errorHandler.HandleCommandException(e, Context, "I counldn't find a quote from that user :disappointed:"); errorHandler.HandleCommandException(e, Context,
"I counldn't find a quote from that user :disappointed:");
} }
} }
[Command("save")] [Command("save")]
[Remarks(CommandCategories.Quotes)] [Remarks(CommandCategories.Quotes)]
[Summary("Save a quote from a message id")] [Summary("Save a quote from a message id")]
@ -86,24 +85,26 @@ namespace Geekbot.net.Commands
await ReplyAsync("You can't save your own quotes..."); await ReplyAsync("You can't save your own quotes...");
return; return;
} }
if (message.Author.IsBot) if (message.Author.IsBot)
{ {
await ReplyAsync("You can't save quotes by a bot..."); await ReplyAsync("You can't save quotes by a bot...");
return; return;
} }
var quote = createQuoteObject(message); var quote = createQuoteObject(message);
var quoteStore = JsonConvert.SerializeObject(quote); var quoteStore = JsonConvert.SerializeObject(quote);
redis.SetAdd($"{Context.Guild.Id}:Quotes", quoteStore); redis.SetAdd($"{Context.Guild.Id}:Quotes", quoteStore);
var embed = quoteBuilder(quote); var embed = quoteBuilder(quote);
await ReplyAsync("**Quote Added**", false, embed.Build()); await ReplyAsync("**Quote Added**", false, embed.Build());
} }
catch (Exception e) catch (Exception e)
{ {
errorHandler.HandleCommandException(e, Context, "I couldn't find a message with that id :disappointed:"); errorHandler.HandleCommandException(e, Context,
"I couldn't find a message with that id :disappointed:");
} }
} }
[Command("make")] [Command("make")]
[Remarks(CommandCategories.Quotes)] [Remarks(CommandCategories.Quotes)]
[Summary("Create a quote from the last sent message by @user")] [Summary("Create a quote from the last sent message by @user")]
@ -118,10 +119,11 @@ namespace Geekbot.net.Commands
} }
catch (Exception e) catch (Exception e)
{ {
errorHandler.HandleCommandException(e, Context, "I counldn't find a quote from that user :disappointed:"); errorHandler.HandleCommandException(e, Context,
"I counldn't find a quote from that user :disappointed:");
} }
} }
[Command("make")] [Command("make")]
[Remarks(CommandCategories.Quotes)] [Remarks(CommandCategories.Quotes)]
[Summary("Create a quote from a message id")] [Summary("Create a quote from a message id")]
@ -136,21 +138,22 @@ namespace Geekbot.net.Commands
} }
catch (Exception e) catch (Exception e)
{ {
errorHandler.HandleCommandException(e, Context, "I couldn't find a message with that id :disappointed:"); errorHandler.HandleCommandException(e, Context,
"I couldn't find a message with that id :disappointed:");
} }
} }
private async Task<IMessage> getLastMessageByUser(IUser user) private async Task<IMessage> getLastMessageByUser(IUser user)
{ {
Task<IEnumerable<IMessage>> list = Context.Channel.GetMessagesAsync().Flatten(); var list = Context.Channel.GetMessagesAsync().Flatten();
await list; await list;
return list.Result return list.Result
.First(msg => msg.Author.Id == user.Id .First(msg => msg.Author.Id == user.Id
&& msg.Embeds.Count == 0 && msg.Embeds.Count == 0
&& msg.Id != Context.Message.Id && msg.Id != Context.Message.Id
&& !msg.Content.ToLower().StartsWith("!")); && !msg.Content.ToLower().StartsWith("!"));
} }
private EmbedBuilder quoteBuilder(QuoteObject quote) private EmbedBuilder quoteBuilder(QuoteObject quote)
{ {
var user = Context.Client.GetUserAsync(quote.userId).Result; var user = Context.Client.GetUserAsync(quote.userId).Result;
@ -159,10 +162,7 @@ namespace Geekbot.net.Commands
eb.Title = $"{user.Username} @ {quote.time.Day}.{quote.time.Month}.{quote.time.Year}"; eb.Title = $"{user.Username} @ {quote.time.Day}.{quote.time.Month}.{quote.time.Year}";
eb.Description = quote.quote; eb.Description = quote.quote;
eb.ThumbnailUrl = user.GetAvatarUrl(); eb.ThumbnailUrl = user.GetAvatarUrl();
if (quote.image != null) if (quote.image != null) eb.ImageUrl = quote.image;
{
eb.ImageUrl = quote.image;
}
return eb; return eb;
} }
@ -177,7 +177,8 @@ namespace Geekbot.net.Commands
{ {
image = null; image = null;
} }
return new QuoteObject()
return new QuoteObject
{ {
userId = message.Author.Id, userId = message.Author.Id,
time = message.Timestamp.DateTime, time = message.Timestamp.DateTime,
@ -186,8 +187,9 @@ namespace Geekbot.net.Commands
}; };
} }
} }
public class QuoteObject { public class QuoteObject
{
public ulong userId { get; set; } public ulong userId { get; set; }
public string quote { get; set; } public string quote { get; set; }
public DateTime time { get; set; } public DateTime time { get; set; }

View file

@ -8,12 +8,12 @@ namespace Geekbot.net.Commands
public class RandomAnimals : ModuleBase public class RandomAnimals : ModuleBase
{ {
private readonly IMediaProvider _mediaProvider; private readonly IMediaProvider _mediaProvider;
public RandomAnimals(IMediaProvider mediaProvider) public RandomAnimals(IMediaProvider mediaProvider)
{ {
_mediaProvider = mediaProvider; _mediaProvider = mediaProvider;
} }
[Command("panda", RunMode = RunMode.Async)] [Command("panda", RunMode = RunMode.Async)]
[Remarks(CommandCategories.Randomness)] [Remarks(CommandCategories.Randomness)]
[Summary("Get a random panda image")] [Summary("Get a random panda image")]
@ -21,7 +21,7 @@ namespace Geekbot.net.Commands
{ {
await ReplyAsync(_mediaProvider.getPanda()); await ReplyAsync(_mediaProvider.getPanda());
} }
[Command("croissant", RunMode = RunMode.Async)] [Command("croissant", RunMode = RunMode.Async)]
[Alias("gipfeli")] [Alias("gipfeli")]
[Remarks(CommandCategories.Randomness)] [Remarks(CommandCategories.Randomness)]
@ -30,7 +30,7 @@ namespace Geekbot.net.Commands
{ {
await ReplyAsync(_mediaProvider.getCrossant()); await ReplyAsync(_mediaProvider.getCrossant());
} }
[Command("pumpkin", RunMode = RunMode.Async)] [Command("pumpkin", RunMode = RunMode.Async)]
[Remarks(CommandCategories.Randomness)] [Remarks(CommandCategories.Randomness)]
[Summary("Get a random pumpkin image")] [Summary("Get a random pumpkin image")]
@ -38,7 +38,7 @@ namespace Geekbot.net.Commands
{ {
await ReplyAsync(_mediaProvider.getPumpkin()); await ReplyAsync(_mediaProvider.getPumpkin());
} }
[Command("squirrel", RunMode = RunMode.Async)] [Command("squirrel", RunMode = RunMode.Async)]
[Remarks(CommandCategories.Randomness)] [Remarks(CommandCategories.Randomness)]
[Summary("Get a random squirrel image")] [Summary("Get a random squirrel image")]
@ -46,7 +46,7 @@ namespace Geekbot.net.Commands
{ {
await ReplyAsync(_mediaProvider.getSquirrel()); await ReplyAsync(_mediaProvider.getSquirrel());
} }
[Command("turtle", RunMode = RunMode.Async)] [Command("turtle", RunMode = RunMode.Async)]
[Remarks(CommandCategories.Randomness)] [Remarks(CommandCategories.Randomness)]
[Summary("Get a random turtle image")] [Summary("Get a random turtle image")]

View file

@ -3,7 +3,6 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Serilog; using Serilog;
@ -13,13 +12,14 @@ namespace Geekbot.net.Commands
{ {
public class Rank : ModuleBase public class Rank : ModuleBase
{ {
private readonly IDatabase _redis; private readonly IEmojiConverter _emojiConverter;
private readonly IErrorHandler _errorHandler; private readonly IErrorHandler _errorHandler;
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IDatabase _redis;
private readonly IUserRepository _userRepository; private readonly IUserRepository _userRepository;
private readonly IEmojiConverter _emojiConverter;
public Rank(IDatabase redis, IErrorHandler errorHandler, ILogger logger, IUserRepository userRepository,
public Rank(IDatabase redis, IErrorHandler errorHandler, ILogger logger, IUserRepository userRepository, IEmojiConverter emojiConverter) IEmojiConverter emojiConverter)
{ {
_redis = redis; _redis = redis;
_errorHandler = errorHandler; _errorHandler = errorHandler;
@ -27,11 +27,12 @@ namespace Geekbot.net.Commands
_userRepository = userRepository; _userRepository = userRepository;
_emojiConverter = emojiConverter; _emojiConverter = emojiConverter;
} }
[Command("rank", RunMode = RunMode.Async)] [Command("rank", RunMode = RunMode.Async)]
[Remarks(CommandCategories.Statistics)] [Remarks(CommandCategories.Statistics)]
[Summary("get user top 10 in messages or karma")] [Summary("get user top 10 in messages or karma")]
public async Task RankCmd([Summary("type")] string typeUnformated = "messages", [Summary("amount")] int amount = 10) public async Task RankCmd([Summary("type")] string typeUnformated = "messages",
[Summary("amount")] int amount = 10)
{ {
try try
{ {
@ -42,7 +43,7 @@ namespace Geekbot.net.Commands
await ReplyAsync("Valid types are '`messages`' '`karma`', '`rolls`'"); await ReplyAsync("Valid types are '`messages`' '`karma`', '`rolls`'");
return; return;
} }
var replyBuilder = new StringBuilder(); var replyBuilder = new StringBuilder();
if (amount > 20) if (amount > 20)
@ -50,7 +51,7 @@ namespace Geekbot.net.Commands
replyBuilder.AppendLine(":warning: Limiting to 20"); replyBuilder.AppendLine(":warning: Limiting to 20");
amount = 20; amount = 20;
} }
var messageList = _redis.HashGetAll($"{Context.Guild.Id}:{type}"); var messageList = _redis.HashGetAll($"{Context.Guild.Id}:{type}");
var sortedList = messageList.OrderByDescending(e => e.Value).ToList(); var sortedList = messageList.OrderByDescending(e => e.Value).ToList();
var guildMessages = (int) sortedList.First().Value; var guildMessages = (int) sortedList.First().Value;
@ -64,10 +65,10 @@ namespace Geekbot.net.Commands
if (listLimiter > amount) break; if (listLimiter > amount) break;
try try
{ {
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 RankUserPolyfill
{ {
Username = guildUser.Username, Username = guildUser.Username,
Discriminator = guildUser.Discriminator Discriminator = guildUser.Discriminator
@ -75,21 +76,21 @@ namespace Geekbot.net.Commands
} }
else else
{ {
highscoreUsers.Add(new RankUserPolyfill() highscoreUsers.Add(new RankUserPolyfill
{ {
Id = user.Name Id = user.Name
}, (int) user.Value); }, (int) user.Value);
failedToRetrieveUser = true; failedToRetrieveUser = true;
} }
listLimiter++; listLimiter++;
} }
catch (Exception e) catch (Exception e)
{ {
_logger.Warning(e, $"Could not retrieve user {user.Name}"); _logger.Warning(e, $"Could not retrieve user {user.Name}");
} }
} }
if (failedToRetrieveUser) replyBuilder.AppendLine(":warning: Couldn't get all userdata\n"); if (failedToRetrieveUser) replyBuilder.AppendLine(":warning: Couldn't get all userdata\n");
replyBuilder.AppendLine($":bar_chart: **{type} Highscore for {Context.Guild.Name}**"); replyBuilder.AppendLine($":bar_chart: **{type} Highscore for {Context.Guild.Name}**");
var highscorePlace = 1; var highscorePlace = 1;
@ -114,13 +115,14 @@ namespace Geekbot.net.Commands
break; break;
case "Rolls": case "Rolls":
replyBuilder.Append($" - {user.Value} Guessed"); replyBuilder.Append($" - {user.Value} Guessed");
break; break;
} }
replyBuilder.Append("\n"); replyBuilder.Append("\n");
highscorePlace++; highscorePlace++;
} }
await ReplyAsync(replyBuilder.ToString()); await ReplyAsync(replyBuilder.ToString());
} }
catch (Exception e) catch (Exception e)
@ -129,8 +131,8 @@ namespace Geekbot.net.Commands
} }
} }
} }
class RankUserPolyfill internal class RankUserPolyfill
{ {
public string Username { get; set; } public string Username { get; set; }
public string Discriminator { get; set; } public string Discriminator { get; set; }

View file

@ -2,7 +2,6 @@
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using AngleSharp;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Discord.Net; using Discord.Net;
@ -16,13 +15,13 @@ namespace Geekbot.net.Commands
{ {
private readonly IErrorHandler _errorHandler; private readonly IErrorHandler _errorHandler;
private readonly IDatabase _redis; private readonly IDatabase _redis;
public Role(IErrorHandler errorHandler, IDatabase redis) public Role(IErrorHandler errorHandler, IDatabase redis)
{ {
_errorHandler = errorHandler; _errorHandler = errorHandler;
_redis = redis; _redis = redis;
} }
[Command(RunMode = RunMode.Async)] [Command(RunMode = RunMode.Async)]
[Remarks(CommandCategories.Helpers)] [Remarks(CommandCategories.Helpers)]
[Summary("Get a list of all available roles.")] [Summary("Get a list of all available roles.")]
@ -36,13 +35,11 @@ namespace Geekbot.net.Commands
await ReplyAsync("There are no roles configured for this server"); await ReplyAsync("There are no roles configured for this server");
return; return;
} }
var sb = new StringBuilder(); var sb = new StringBuilder();
sb.AppendLine($"**Self Service Roles on {Context.Guild.Name}**"); sb.AppendLine($"**Self Service Roles on {Context.Guild.Name}**");
sb.AppendLine("To get a role, use `!role name`"); sb.AppendLine("To get a role, use `!role name`");
foreach (var role in roles) foreach (var role in roles) sb.AppendLine($"- {role.Name}");
{
sb.AppendLine($"- {role.Name}");
}
await ReplyAsync(sb.ToString()); await ReplyAsync(sb.ToString());
} }
catch (Exception e) catch (Exception e)
@ -69,16 +66,19 @@ namespace Geekbot.net.Commands
await ReplyAsync("That role doesn't seem to exist"); await ReplyAsync("That role doesn't seem to exist");
return; return;
} }
if (guildUser.RoleIds.Contains(roleId)) if (guildUser.RoleIds.Contains(roleId))
{ {
await guildUser.RemoveRoleAsync(role); await guildUser.RemoveRoleAsync(role);
await ReplyAsync($"Removed you from {role.Name}"); await ReplyAsync($"Removed you from {role.Name}");
return; return;
} }
await guildUser.AddRoleAsync(role); await guildUser.AddRoleAsync(role);
await ReplyAsync($"Added you to {role.Name}"); await ReplyAsync($"Added you to {role.Name}");
return; return;
} }
await ReplyAsync("That role doesn't seem to exist"); await ReplyAsync("That role doesn't seem to exist");
} }
catch (HttpException e) catch (HttpException e)
@ -104,16 +104,20 @@ namespace Geekbot.net.Commands
await ReplyAsync("You can't add a role that is managed by discord"); await ReplyAsync("You can't add a role that is managed by discord");
return; return;
} }
if (role.Permissions.ManageRoles if (role.Permissions.ManageRoles
|| role.Permissions.Administrator || role.Permissions.Administrator
|| role.Permissions.ManageGuild || role.Permissions.ManageGuild
|| role.Permissions.BanMembers || role.Permissions.BanMembers
|| role.Permissions.KickMembers) || role.Permissions.KickMembers)
{ {
await ReplyAsync("Woah, i don't think you want to add that role to self service as it contains some dangerous permissions"); await ReplyAsync(
"Woah, i don't think you want to add that role to self service as it contains some dangerous permissions");
return; return;
} }
_redis.HashSet($"{Context.Guild.Id}:RoleWhitelist", new HashEntry[] { new HashEntry(roleName.ToLower(), role.Id.ToString()) });
_redis.HashSet($"{Context.Guild.Id}:RoleWhitelist",
new[] {new HashEntry(roleName.ToLower(), role.Id.ToString())});
await ReplyAsync($"Added {role.Name} to the whitelist"); await ReplyAsync($"Added {role.Name} to the whitelist");
} }
catch (Exception e) catch (Exception e)

View file

@ -8,10 +8,10 @@ namespace Geekbot.net.Commands
{ {
public class Roll : ModuleBase public class Roll : ModuleBase
{ {
private readonly IErrorHandler _errorHandler;
private readonly IDatabase _redis; private readonly IDatabase _redis;
private readonly Random _rnd; private readonly Random _rnd;
private readonly ITranslationHandler _translation; private readonly ITranslationHandler _translation;
private readonly IErrorHandler _errorHandler;
public Roll(IDatabase redis, Random RandomClient, IErrorHandler errorHandler, ITranslationHandler translation) public Roll(IDatabase redis, Random RandomClient, IErrorHandler errorHandler, ITranslationHandler translation)
{ {
@ -40,7 +40,9 @@ namespace Geekbot.net.Commands
await ReplyAsync(string.Format(transDict["NoPrevGuess"], Context.Message.Author.Mention)); await ReplyAsync(string.Format(transDict["NoPrevGuess"], Context.Message.Author.Mention));
return; return;
} }
_redis.HashSet($"{Context.Guild.Id}:RollsPrevious", new HashEntry[]{ new HashEntry(Context.Message.Author.Id, guess), });
_redis.HashSet($"{Context.Guild.Id}:RollsPrevious",
new[] {new HashEntry(Context.Message.Author.Id, guess)});
await ReplyAsync(string.Format(transDict["Rolled"], Context.Message.Author.Mention, number, guess)); await ReplyAsync(string.Format(transDict["Rolled"], Context.Message.Author.Mention, number, guess));
if (guess == number) if (guess == number)
{ {

View file

@ -14,7 +14,7 @@ namespace Geekbot.net.Commands
{ {
_errorHandler = errorHandler; _errorHandler = errorHandler;
} }
[RequireUserPermission(GuildPermission.Administrator)] [RequireUserPermission(GuildPermission.Administrator)]
[Command("say", RunMode = RunMode.Async)] [Command("say", RunMode = RunMode.Async)]
[Remarks(CommandCategories.Admin)] [Remarks(CommandCategories.Admin)]

View file

@ -9,9 +9,9 @@ namespace Geekbot.net.Commands
{ {
public class Ship : ModuleBase public class Ship : ModuleBase
{ {
private readonly IErrorHandler _errorHandler;
private readonly IDatabase _redis; private readonly IDatabase _redis;
private readonly Random _rnd; private readonly Random _rnd;
private readonly IErrorHandler _errorHandler;
public Ship(IDatabase redis, Random randomClient, IErrorHandler errorHandler) public Ship(IDatabase redis, Random randomClient, IErrorHandler errorHandler)
{ {
@ -87,6 +87,7 @@ namespace Geekbot.net.Commands
{ {
blocks = blocks + ":black_medium_small_square:"; blocks = blocks + ":black_medium_small_square:";
} }
return blocks; return blocks;
} }
} }

View file

@ -9,10 +9,10 @@ namespace Geekbot.net.Commands
{ {
public class Stats : ModuleBase public class Stats : ModuleBase
{ {
private readonly IDatabase _redis;
private readonly IErrorHandler _errorHandler; private readonly IErrorHandler _errorHandler;
private readonly ILevelCalc _levelCalc; private readonly ILevelCalc _levelCalc;
private readonly IDatabase _redis;
public Stats(IDatabase redis, IErrorHandler errorHandler, ILevelCalc levelCalc) public Stats(IDatabase redis, IErrorHandler errorHandler, ILevelCalc levelCalc)
{ {
_redis = redis; _redis = redis;
@ -45,12 +45,14 @@ namespace Geekbot.net.Commands
.WithIconUrl(userInfo.GetAvatarUrl()) .WithIconUrl(userInfo.GetAvatarUrl())
.WithName(userInfo.Username)); .WithName(userInfo.Username));
eb.WithColor(new Color(221, 255, 119)); eb.WithColor(new Color(221, 255, 119));
var karma = _redis.HashGet($"{Context.Guild.Id}:Karma", userInfo.Id.ToString()); var karma = _redis.HashGet($"{Context.Guild.Id}:Karma", userInfo.Id.ToString());
var correctRolls = _redis.HashGet($"{Context.Guild.Id}:Rolls", userInfo.Id.ToString()); var correctRolls = _redis.HashGet($"{Context.Guild.Id}:Rolls", userInfo.Id.ToString());
eb.AddInlineField("Discordian Since", $"{createdAt.Day}.{createdAt.Month}.{createdAt.Year} ({age} days)") eb.AddInlineField("Discordian Since",
.AddInlineField("Joined Server", $"{joinedAt.Day}.{joinedAt.Month}.{joinedAt.Year} ({joinedDayAgo} days)") $"{createdAt.Day}.{createdAt.Month}.{createdAt.Year} ({age} days)")
.AddInlineField("Joined Server",
$"{joinedAt.Day}.{joinedAt.Month}.{joinedAt.Year} ({joinedDayAgo} days)")
.AddInlineField("Karma", karma.ToString() ?? "0") .AddInlineField("Karma", karma.ToString() ?? "0")
.AddInlineField("Level", level) .AddInlineField("Level", level)
.AddInlineField("Messages Sent", messages) .AddInlineField("Messages Sent", messages)

View file

@ -13,16 +13,16 @@ namespace Geekbot.net.Commands
public class UrbanDictionary : ModuleBase public class UrbanDictionary : ModuleBase
{ {
private readonly IErrorHandler _errorHandler; private readonly IErrorHandler _errorHandler;
public UrbanDictionary(IErrorHandler errorHandler) public UrbanDictionary(IErrorHandler errorHandler)
{ {
_errorHandler = errorHandler; _errorHandler = errorHandler;
} }
[Command("urban", RunMode = RunMode.Async)] [Command("urban", RunMode = RunMode.Async)]
[Remarks(CommandCategories.Helpers)] [Remarks(CommandCategories.Helpers)]
[Summary("Lookup something on urban dictionary")] [Summary("Lookup something on urban dictionary")]
public async Task urbanDefine([Remainder, Summary("word")] string word) public async Task urbanDefine([Remainder] [Summary("word")] string word)
{ {
try try
{ {
@ -39,23 +39,21 @@ namespace Geekbot.net.Commands
await ReplyAsync("That word hasn't been defined..."); await ReplyAsync("That word hasn't been defined...");
return; return;
} }
var definition = definitions.list.First(e => !string.IsNullOrWhiteSpace(e.example)); var definition = definitions.list.First(e => !string.IsNullOrWhiteSpace(e.example));
var eb = new EmbedBuilder(); var eb = new EmbedBuilder();
eb.WithAuthor(new EmbedAuthorBuilder() eb.WithAuthor(new EmbedAuthorBuilder
{ {
Name = definition.word, Name = definition.word,
Url = definition.permalink Url = definition.permalink
}); });
eb.WithColor(new Color(239,255,0)); eb.WithColor(new Color(239, 255, 0));
eb.Description = definition.definition; eb.Description = definition.definition;
eb.AddField("Example", definition.example ?? "(no example given...)"); eb.AddField("Example", definition.example ?? "(no example given...)");
eb.AddInlineField("Upvotes", definition.thumbs_up); eb.AddInlineField("Upvotes", definition.thumbs_up);
eb.AddInlineField("Downvotes", definition.thumbs_down); eb.AddInlineField("Downvotes", definition.thumbs_down);
if (definitions.tags.Length > 0) if (definitions.tags.Length > 0) eb.AddField("Tags", string.Join(", ", definitions.tags));
{
eb.AddField("Tags", string.Join(", ", definitions.tags));
}
await ReplyAsync("", false, eb.Build()); await ReplyAsync("", false, eb.Build());
} }
@ -65,14 +63,14 @@ namespace Geekbot.net.Commands
_errorHandler.HandleCommandException(e, Context); _errorHandler.HandleCommandException(e, Context);
} }
} }
private class UrbanResponse private class UrbanResponse
{ {
public string[] tags { get; set; } public string[] tags { get; set; }
public string result_type { get; set; } public string result_type { get; set; }
public List<UrbanListItem> list { get; set; } public List<UrbanListItem> list { get; set; }
} }
private class UrbanListItem private class UrbanListItem
{ {
public string definition { get; set; } public string definition { get; set; }

View file

@ -1,7 +1,6 @@
using System; using System;
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord; using Discord;
using Discord.Audio;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Lib; using Geekbot.net.Lib;
@ -9,8 +8,8 @@ namespace Geekbot.net.Commands
{ {
public class Voice : ModuleBase public class Voice : ModuleBase
{ {
private readonly IErrorHandler _errorHandler;
private readonly IAudioUtils _audioUtils; private readonly IAudioUtils _audioUtils;
private readonly IErrorHandler _errorHandler;
public Voice(IErrorHandler errorHandler, IAudioUtils audioUtils) public Voice(IErrorHandler errorHandler, IAudioUtils audioUtils)
{ {
@ -42,7 +41,7 @@ namespace Geekbot.net.Commands
_errorHandler.HandleCommandException(e, Context); _errorHandler.HandleCommandException(e, Context);
} }
} }
[Command("disconnect")] [Command("disconnect")]
public async Task DisconnectChannel() public async Task DisconnectChannel()
{ {
@ -54,6 +53,7 @@ namespace Geekbot.net.Commands
await Context.Channel.SendMessageAsync("I'm not in a voice channel at the moment"); await Context.Channel.SendMessageAsync("I'm not in a voice channel at the moment");
return; return;
} }
await audioClient.StopAsync(); await audioClient.StopAsync();
await ReplyAsync("Disconnected from channel!"); await ReplyAsync("Disconnected from channel!");
} }
@ -62,7 +62,7 @@ namespace Geekbot.net.Commands
_errorHandler.HandleCommandException(e, Context); _errorHandler.HandleCommandException(e, Context);
} }
} }
// [Command("play")] // [Command("play")]
// public async Task play(IVoiceChannel channel = null) // public async Task play(IVoiceChannel channel = null)
// { // {

View file

@ -10,8 +10,8 @@ namespace Geekbot.net.Commands
{ {
public class Youtube : ModuleBase public class Youtube : ModuleBase
{ {
private readonly IDatabase _redis;
private readonly IErrorHandler _errorHandler; private readonly IErrorHandler _errorHandler;
private readonly IDatabase _redis;
public Youtube(IDatabase redis, IErrorHandler errorHandler) public Youtube(IDatabase redis, IErrorHandler errorHandler)
{ {

View file

@ -1,5 +1,6 @@
using System; using System;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Web;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Lib; using Geekbot.net.Lib;
@ -8,19 +9,19 @@ namespace Geekbot.net.Commands
{ {
public class mal : ModuleBase public class mal : ModuleBase
{ {
private readonly IMalClient _malClient;
private readonly IErrorHandler _errorHandler; private readonly IErrorHandler _errorHandler;
private readonly IMalClient _malClient;
public mal(IMalClient malClient, IErrorHandler errorHandler) public mal(IMalClient malClient, IErrorHandler errorHandler)
{ {
_malClient = malClient; _malClient = malClient;
_errorHandler = errorHandler; _errorHandler = errorHandler;
} }
[Command("anime", RunMode = RunMode.Async)] [Command("anime", RunMode = RunMode.Async)]
[Remarks(CommandCategories.Helpers)] [Remarks(CommandCategories.Helpers)]
[Summary("Show Info about an Anime.")] [Summary("Show Info about an Anime.")]
public async Task searchAnime([Remainder, Summary("AnimeName")] string animeName) public async Task searchAnime([Remainder] [Summary("AnimeName")] string animeName)
{ {
try try
{ {
@ -31,11 +32,11 @@ namespace Geekbot.net.Commands
{ {
var eb = new EmbedBuilder(); var eb = new EmbedBuilder();
var description = System.Web.HttpUtility.HtmlDecode(anime.Synopsis) var description = HttpUtility.HtmlDecode(anime.Synopsis)
.Replace("<br />", "") .Replace("<br />", "")
.Replace("[i]", "*") .Replace("[i]", "*")
.Replace("[/i]", "*"); .Replace("[/i]", "*");
eb.Title = anime.Title; eb.Title = anime.Title;
eb.Description = description; eb.Description = description;
eb.ImageUrl = anime.Image; eb.ImageUrl = anime.Image;
@ -65,11 +66,11 @@ namespace Geekbot.net.Commands
_errorHandler.HandleCommandException(e, Context); _errorHandler.HandleCommandException(e, Context);
} }
} }
[Command("manga", RunMode = RunMode.Async)] [Command("manga", RunMode = RunMode.Async)]
[Remarks(CommandCategories.Helpers)] [Remarks(CommandCategories.Helpers)]
[Summary("Show Info about a Manga.")] [Summary("Show Info about a Manga.")]
public async Task searchManga([Remainder, Summary("MangaName")] string mangaName) public async Task searchManga([Remainder] [Summary("MangaName")] string mangaName)
{ {
try try
{ {
@ -80,11 +81,11 @@ namespace Geekbot.net.Commands
{ {
var eb = new EmbedBuilder(); var eb = new EmbedBuilder();
var description = System.Web.HttpUtility.HtmlDecode(manga.Synopsis) var description = HttpUtility.HtmlDecode(manga.Synopsis)
.Replace("<br />", "") .Replace("<br />", "")
.Replace("[i]", "*") .Replace("[i]", "*")
.Replace("[/i]", "*"); .Replace("[/i]", "*");
eb.Title = manga.Title; eb.Title = manga.Title;
eb.Description = description; eb.Description = description;
eb.ImageUrl = manga.Image; eb.ImageUrl = manga.Image;