Resharper suggestions
This commit is contained in:
parent
b81284bfe7
commit
cdb104cacc
55 changed files with 382 additions and 550 deletions
|
@ -40,7 +40,7 @@ namespace Geekbot.net.Commands
|
|||
[Command("modchannel", RunMode = RunMode.Async)]
|
||||
[Remarks(CommandCategories.Admin)]
|
||||
[Summary("Set a channel for moderation purposes")]
|
||||
public async Task selectModChannel([Summary("#Channel")] ISocketMessageChannel channel)
|
||||
public async Task SelectModChannel([Summary("#Channel")] ISocketMessageChannel channel)
|
||||
{
|
||||
try
|
||||
{
|
||||
|
@ -61,7 +61,7 @@ namespace Geekbot.net.Commands
|
|||
[Command("showleave", RunMode = RunMode.Async)]
|
||||
[Remarks(CommandCategories.Admin)]
|
||||
[Summary("Notify modchannel when someone leaves")]
|
||||
public async Task showLeave([Summary("true/false")] bool enabled)
|
||||
public async Task ShowLeave([Summary("true/false")] bool enabled)
|
||||
{
|
||||
var modChannelId = ulong.Parse(_redis.HashGet($"{Context.Guild.Id}:Settings", "ModChannel"));
|
||||
try
|
||||
|
@ -88,7 +88,7 @@ namespace Geekbot.net.Commands
|
|||
[Command("showdel", RunMode = RunMode.Async)]
|
||||
[Remarks(CommandCategories.Admin)]
|
||||
[Summary("Notify modchannel when someone deletes a message")]
|
||||
public async Task showDelete([Summary("true/false")] bool enabled)
|
||||
public async Task ShowDelete([Summary("true/false")] bool enabled)
|
||||
{
|
||||
var modChannelId = ulong.Parse(_redis.HashGet($"{Context.Guild.Id}:Settings", "ModChannel"));
|
||||
try
|
||||
|
@ -117,7 +117,7 @@ namespace Geekbot.net.Commands
|
|||
[Command("setlang", RunMode = RunMode.Async)]
|
||||
[Remarks(CommandCategories.Admin)]
|
||||
[Summary("Change the bots language")]
|
||||
public async Task setLanguage([Summary("language")] string languageRaw)
|
||||
public async Task SetLanguage([Summary("language")] string languageRaw)
|
||||
{
|
||||
try
|
||||
{
|
||||
|
@ -142,7 +142,7 @@ namespace Geekbot.net.Commands
|
|||
[Command("wiki", RunMode = RunMode.Async)]
|
||||
[Remarks(CommandCategories.Admin)]
|
||||
[Summary("Change the wikipedia instance (use lang code in xx.wikipedia.org)")]
|
||||
public async Task setWikiLanguage([Summary("language")] string languageRaw)
|
||||
public async Task SetWikiLanguage([Summary("language")] string languageRaw)
|
||||
{
|
||||
try
|
||||
{
|
||||
|
@ -160,7 +160,7 @@ namespace Geekbot.net.Commands
|
|||
[Command("lang", RunMode = RunMode.Async)]
|
||||
[Remarks(CommandCategories.Admin)]
|
||||
[Summary("Change the bots language")]
|
||||
public async Task getLanguage()
|
||||
public async Task GetLanguage()
|
||||
{
|
||||
try
|
||||
{
|
||||
|
@ -176,12 +176,12 @@ namespace Geekbot.net.Commands
|
|||
[Command("ping", RunMode = RunMode.Async)]
|
||||
[Remarks(CommandCategories.Admin)]
|
||||
[Summary("Enable the ping reply.")]
|
||||
public async Task togglePing()
|
||||
public async Task TogglePing()
|
||||
{
|
||||
try
|
||||
{
|
||||
bool.TryParse(_redis.HashGet($"{Context.Guild.Id}:Settings", "ping"), out var current);
|
||||
_redis.HashSet($"{Context.Guild.Id}:Settings", new[] {new HashEntry("ping", current ? "false" : "true"), });
|
||||
_redis.HashSet($"{Context.Guild.Id}:Settings", new[] {new HashEntry("ping", current ? "false" : "true") });
|
||||
await ReplyAsync(!current ? "i will reply to ping now" : "No more pongs...");
|
||||
}
|
||||
catch (Exception e)
|
||||
|
|
|
@ -18,7 +18,7 @@ namespace Geekbot.net.Commands
|
|||
[Command("avatar", RunMode = RunMode.Async)]
|
||||
[Remarks(CommandCategories.Helpers)]
|
||||
[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
|
||||
{
|
||||
|
|
|
@ -24,7 +24,7 @@ namespace Geekbot.net.Commands
|
|||
{
|
||||
try
|
||||
{
|
||||
var tag = _userRepository.getUserSetting(Context.User.Id, "BattleTag");
|
||||
var tag = _userRepository.GetUserSetting(Context.User.Id, "BattleTag");
|
||||
if (!string.IsNullOrEmpty(tag))
|
||||
await ReplyAsync($"Your BattleTag is {tag}");
|
||||
else
|
||||
|
@ -43,9 +43,9 @@ namespace Geekbot.net.Commands
|
|||
{
|
||||
try
|
||||
{
|
||||
if (isValidTag(tag))
|
||||
if (IsValidTag(tag))
|
||||
{
|
||||
_userRepository.saveUserSetting(Context.User.Id, "BattleTag", tag);
|
||||
_userRepository.SaveUserSetting(Context.User.Id, "BattleTag", tag);
|
||||
await ReplyAsync("Saved!");
|
||||
}
|
||||
else
|
||||
|
@ -59,13 +59,12 @@ namespace Geekbot.net.Commands
|
|||
}
|
||||
}
|
||||
|
||||
public static bool isValidTag(string tag)
|
||||
public static bool IsValidTag(string tag)
|
||||
{
|
||||
var splited = tag.Split("#");
|
||||
if (splited.Length != 2) return false;
|
||||
if (!int.TryParse(splited[1], out var discriminator)) return false;
|
||||
if (splited[1].Length == 4 || splited[1].Length == 5) return true;
|
||||
return false;
|
||||
return splited[1].Length == 4 || splited[1].Length == 5;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -35,7 +35,7 @@ namespace Geekbot.net.Commands
|
|||
var stringResponse = await response.Content.ReadAsStringAsync();
|
||||
var catFile = JsonConvert.DeserializeObject<CatResponse>(stringResponse);
|
||||
var eb = new EmbedBuilder();
|
||||
eb.ImageUrl = catFile.file;
|
||||
eb.ImageUrl = catFile.File;
|
||||
await ReplyAsync("", false, eb.Build());
|
||||
}
|
||||
catch
|
||||
|
@ -52,7 +52,7 @@ namespace Geekbot.net.Commands
|
|||
|
||||
private class CatResponse
|
||||
{
|
||||
public string file { get; set; }
|
||||
public string File { get; set; }
|
||||
}
|
||||
}
|
||||
}
|
|
@ -27,7 +27,7 @@ namespace Geekbot.net.Commands
|
|||
[Alias("updates")]
|
||||
[Remarks(CommandCategories.Helpers)]
|
||||
[Summary("Show the latest 5 updates")]
|
||||
public async Task getChangelog()
|
||||
public async Task GetChangelog()
|
||||
{
|
||||
try
|
||||
{
|
||||
|
@ -40,7 +40,7 @@ namespace Geekbot.net.Commands
|
|||
response.EnsureSuccessStatusCode();
|
||||
|
||||
var stringResponse = await response.Content.ReadAsStringAsync();
|
||||
var commits = JsonConvert.DeserializeObject<List<Commit>>(stringResponse);
|
||||
var commits = JsonConvert.DeserializeObject<List<CommitDto>>(stringResponse);
|
||||
var eb = new EmbedBuilder();
|
||||
eb.WithColor(new Color(143, 165, 102));
|
||||
eb.WithAuthor(new EmbedAuthorBuilder
|
||||
|
@ -51,7 +51,7 @@ namespace Geekbot.net.Commands
|
|||
});
|
||||
var sb = new StringBuilder();
|
||||
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.WithFooter(new EmbedFooterBuilder
|
||||
{
|
||||
|
@ -66,24 +66,20 @@ namespace Geekbot.net.Commands
|
|||
}
|
||||
}
|
||||
|
||||
private class Commit
|
||||
private class CommitDto
|
||||
{
|
||||
public string sha { get; set; }
|
||||
public CommitInfo commit { get; set; }
|
||||
public Uri html_url { get; set; }
|
||||
public CommitInfo Commit { get; set; }
|
||||
}
|
||||
|
||||
private class CommitInfo
|
||||
{
|
||||
public commitAuthor author { get; set; }
|
||||
public string message { get; set; }
|
||||
public CommitAuthor Author { get; set; }
|
||||
public string Message { get; set; }
|
||||
}
|
||||
|
||||
private class commitAuthor
|
||||
private class CommitAuthor
|
||||
{
|
||||
public string name { get; set; }
|
||||
public string email { get; set; }
|
||||
public DateTimeOffset date { get; set; }
|
||||
public DateTimeOffset Date { get; set; }
|
||||
}
|
||||
}
|
||||
}
|
|
@ -46,7 +46,7 @@ namespace Geekbot.net.Commands
|
|||
sb.AppendLine($"**{number}**");
|
||||
if (!string.IsNullOrEmpty(dubtriqua))
|
||||
sb.AppendLine($":tada: {dubtriqua} :tada:");
|
||||
sb.AppendLine(_checkEmImages.getCheckem());
|
||||
sb.AppendLine(_checkEmImages.GetCheckem());
|
||||
|
||||
await ReplyAsync(sb.ToString());
|
||||
}
|
||||
|
|
|
@ -35,7 +35,7 @@ namespace Geekbot.net.Commands
|
|||
|
||||
var stringResponse = await response.Content.ReadAsStringAsync();
|
||||
var data = JsonConvert.DeserializeObject<ChuckNorrisJokeResponse>(stringResponse);
|
||||
await ReplyAsync(data.value);
|
||||
await ReplyAsync(data.Value);
|
||||
}
|
||||
catch (HttpRequestException)
|
||||
{
|
||||
|
@ -51,11 +51,7 @@ namespace Geekbot.net.Commands
|
|||
|
||||
private class ChuckNorrisJokeResponse
|
||||
{
|
||||
public string category { get; set; }
|
||||
public string icon_url { get; set; }
|
||||
public string id { get; set; }
|
||||
public string url { get; set; }
|
||||
public string value { get; set; }
|
||||
public string Value { get; set; }
|
||||
}
|
||||
}
|
||||
}
|
|
@ -2,7 +2,6 @@
|
|||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Threading.Tasks;
|
||||
using Discord;
|
||||
using Discord.Commands;
|
||||
using Geekbot.net.Lib;
|
||||
using Newtonsoft.Json;
|
||||
|
@ -36,7 +35,7 @@ namespace Geekbot.net.Commands
|
|||
|
||||
var stringResponse = await response.Content.ReadAsStringAsync();
|
||||
var data = JsonConvert.DeserializeObject<DadJokeResponse>(stringResponse);
|
||||
await ReplyAsync(data.joke);
|
||||
await ReplyAsync(data.Joke);
|
||||
}
|
||||
catch (HttpRequestException)
|
||||
{
|
||||
|
@ -52,9 +51,7 @@ namespace Geekbot.net.Commands
|
|||
|
||||
private class DadJokeResponse
|
||||
{
|
||||
public string id { get; set; }
|
||||
public string joke { get; set; }
|
||||
public string status { get; set; }
|
||||
public string Joke { get; set; }
|
||||
}
|
||||
}
|
||||
}
|
|
@ -20,12 +20,12 @@ namespace Geekbot.net.Commands
|
|||
var mod = 0;
|
||||
foreach (var i in splitedDices)
|
||||
{
|
||||
var dice = toDice(i);
|
||||
if (dice.sides != 0 && dice.times != 0)
|
||||
var dice = ToDice(i);
|
||||
if (dice.Sides != 0 && dice.Times != 0)
|
||||
{
|
||||
dices.Add(dice);
|
||||
}
|
||||
else if (dice.mod != 0)
|
||||
else if (dice.Mod != 0)
|
||||
{
|
||||
if (mod != 0)
|
||||
{
|
||||
|
@ -33,7 +33,7 @@ namespace Geekbot.net.Commands
|
|||
return;
|
||||
}
|
||||
|
||||
mod = dice.mod;
|
||||
mod = dice.Mod;
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -45,13 +45,13 @@ namespace Geekbot.net.Commands
|
|||
}
|
||||
|
||||
|
||||
if (dices.Any(d => d.times > 20))
|
||||
if (dices.Any(d => d.Times > 20))
|
||||
{
|
||||
await ReplyAsync("You can't throw more than 20 dices");
|
||||
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");
|
||||
return;
|
||||
|
@ -66,16 +66,16 @@ namespace Geekbot.net.Commands
|
|||
foreach (var dice in dices)
|
||||
{
|
||||
var results = new List<int>();
|
||||
for (var i = 0; i < dice.times; i++)
|
||||
for (var i = 0; i < dice.Times; i++)
|
||||
{
|
||||
var roll = new Random().Next(1, dice.sides);
|
||||
var roll = new Random().Next(1, dice.Sides);
|
||||
total += roll;
|
||||
results.Add(roll);
|
||||
if (roll == dice.sides) extraText = "**Critical Hit!**";
|
||||
if (roll == dice.Sides) 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));
|
||||
|
@ -91,7 +91,7 @@ namespace Geekbot.net.Commands
|
|||
await ReplyAsync(rep.ToString());
|
||||
}
|
||||
|
||||
private DiceTypeDto toDice(string dice)
|
||||
private DiceTypeDto ToDice(string dice)
|
||||
{
|
||||
var diceParts = dice.Split('d');
|
||||
if (diceParts.Length == 2
|
||||
|
@ -99,15 +99,15 @@ namespace Geekbot.net.Commands
|
|||
&& int.TryParse(diceParts[1], out var max))
|
||||
return new DiceTypeDto
|
||||
{
|
||||
diceType = dice,
|
||||
times = times,
|
||||
sides = max
|
||||
DiceType = dice,
|
||||
Times = times,
|
||||
Sides = max
|
||||
};
|
||||
if (dice.Length == 1
|
||||
&& int.TryParse(diceParts[0], out var mod))
|
||||
return new DiceTypeDto
|
||||
{
|
||||
mod = mod
|
||||
Mod = mod
|
||||
};
|
||||
return new DiceTypeDto();
|
||||
}
|
||||
|
@ -115,9 +115,9 @@ namespace Geekbot.net.Commands
|
|||
|
||||
internal class DiceTypeDto
|
||||
{
|
||||
public string diceType { get; set; }
|
||||
public int times { get; set; }
|
||||
public int sides { get; set; }
|
||||
public int mod { get; set; }
|
||||
public string DiceType { get; set; }
|
||||
public int Times { get; set; }
|
||||
public int Sides { get; set; }
|
||||
public int Mod { get; set; }
|
||||
}
|
||||
}
|
|
@ -35,7 +35,7 @@ namespace Geekbot.net.Commands
|
|||
var stringResponse = await response.Content.ReadAsStringAsync();
|
||||
var dogFile = JsonConvert.DeserializeObject<DogResponse>(stringResponse);
|
||||
var eb = new EmbedBuilder();
|
||||
eb.ImageUrl = dogFile.url;
|
||||
eb.ImageUrl = dogFile.Url;
|
||||
await ReplyAsync("", false, eb.Build());
|
||||
}
|
||||
catch (HttpRequestException e)
|
||||
|
@ -52,7 +52,7 @@ namespace Geekbot.net.Commands
|
|||
|
||||
private class DogResponse
|
||||
{
|
||||
public string url { get; set; }
|
||||
public string Url { get; set; }
|
||||
}
|
||||
}
|
||||
}
|
|
@ -23,7 +23,7 @@ namespace Geekbot.net.Commands
|
|||
{
|
||||
try
|
||||
{
|
||||
var emojis = _emojiConverter.textToEmoji(text);
|
||||
var emojis = _emojiConverter.TextToEmoji(text);
|
||||
if (emojis.Length > 1999)
|
||||
{
|
||||
await ReplyAsync("I can't take that much at once!");
|
||||
|
|
|
@ -1,8 +1,6 @@
|
|||
using System;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Threading.Tasks;
|
||||
using Discord;
|
||||
using Discord.Commands;
|
||||
using Geekbot.net.Lib;
|
||||
|
||||
|
@ -20,7 +18,7 @@ namespace Geekbot.net.Commands
|
|||
[Command("gdq", RunMode = RunMode.Async)]
|
||||
[Remarks(CommandCategories.Games)]
|
||||
[Summary("Get a quote from the GDQ donation generator.")]
|
||||
public async Task getQuote()
|
||||
public async Task GetQuote()
|
||||
{
|
||||
try
|
||||
{
|
||||
|
|
|
@ -2,14 +2,12 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
using Discord;
|
||||
using Discord.Commands;
|
||||
using Discord.Net;
|
||||
using Geekbot.net.Lib;
|
||||
using Newtonsoft.Json;
|
||||
using StackExchange.Redis;
|
||||
using Utf8Json;
|
||||
|
||||
namespace Geekbot.net.Commands
|
||||
{
|
||||
|
@ -27,7 +25,7 @@ namespace Geekbot.net.Commands
|
|||
[Command("google", RunMode = RunMode.Async)]
|
||||
[Remarks(CommandCategories.Helpers)]
|
||||
[Summary("Google Something.")]
|
||||
public async Task askGoogle([Remainder, Summary("SearchText")] string searchText)
|
||||
public async Task AskGoogle([Remainder, Summary("SearchText")] string searchText)
|
||||
{
|
||||
try
|
||||
{
|
||||
|
@ -42,21 +40,21 @@ namespace Geekbot.net.Commands
|
|||
|
||||
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 response = Utf8Json.JsonSerializer.Deserialize<GoogleKGApiResponse>(responseString);
|
||||
var response = JsonSerializer.Deserialize<GoogleKgApiResponse>(responseString);
|
||||
|
||||
if (!response.itemListElement.Any())
|
||||
if (!response.ItemListElement.Any())
|
||||
{
|
||||
await ReplyAsync("No results were found...");
|
||||
return;
|
||||
}
|
||||
|
||||
var data = response.itemListElement.First().result;
|
||||
var data = response.ItemListElement.First().Result;
|
||||
var eb = new EmbedBuilder();
|
||||
eb.Title = data.name;
|
||||
if(!string.IsNullOrEmpty(data.description)) eb.WithDescription(data.description);
|
||||
if(!string.IsNullOrEmpty(data.detailedDescription?.url)) eb.WithUrl(data.detailedDescription.url);
|
||||
if(!string.IsNullOrEmpty(data.detailedDescription?.articleBody)) eb.AddField("Details", data.detailedDescription.articleBody);
|
||||
if(!string.IsNullOrEmpty(data.image?.contentUrl)) eb.WithThumbnailUrl(data.image.contentUrl);
|
||||
eb.Title = data.Name;
|
||||
if(!string.IsNullOrEmpty(data.Description)) eb.WithDescription(data.Description);
|
||||
if(!string.IsNullOrEmpty(data.DetailedDescription?.Url)) eb.WithUrl(data.DetailedDescription.Url);
|
||||
if(!string.IsNullOrEmpty(data.DetailedDescription?.ArticleBody)) eb.AddField("Details", data.DetailedDescription.ArticleBody);
|
||||
if(!string.IsNullOrEmpty(data.Image?.ContentUrl)) eb.WithThumbnailUrl(data.Image.ContentUrl);
|
||||
|
||||
await ReplyAsync("", false, eb.Build());
|
||||
}
|
||||
|
@ -67,35 +65,35 @@ namespace Geekbot.net.Commands
|
|||
}
|
||||
}
|
||||
|
||||
public class GoogleKGApiResponse
|
||||
public class GoogleKgApiResponse
|
||||
{
|
||||
public List<GoogleKGApiElement> itemListElement { get; set; }
|
||||
public List<GoogleKgApiElement> ItemListElement { get; set; }
|
||||
|
||||
public class GoogleKGApiElement
|
||||
public class GoogleKgApiElement
|
||||
{
|
||||
public GoogleKGApiResult result { get; set; }
|
||||
public double resultScore { get; set; }
|
||||
public GoogleKgApiResult Result { get; set; }
|
||||
public double ResultScore { get; set; }
|
||||
}
|
||||
|
||||
public class GoogleKGApiResult
|
||||
public class GoogleKgApiResult
|
||||
{
|
||||
public string name { get; set; }
|
||||
public string description { get; set; }
|
||||
public GoogleKGApiImage image { get; set; }
|
||||
public GoogleKGApiDetailed detailedDescription { get; set; }
|
||||
public string Name { get; set; }
|
||||
public string Description { get; set; }
|
||||
public GoogleKgApiImage Image { get; set; }
|
||||
public GoogleKgApiDetailed DetailedDescription { get; set; }
|
||||
}
|
||||
|
||||
public class GoogleKGApiImage
|
||||
public class GoogleKgApiImage
|
||||
{
|
||||
public string contentUrl { get; set; }
|
||||
public string url { get; set; }
|
||||
public string ContentUrl { get; set; }
|
||||
public string Url { get; set; }
|
||||
}
|
||||
|
||||
public class GoogleKGApiDetailed
|
||||
public class GoogleKgApiDetailed
|
||||
{
|
||||
public string articleBody { get; set; }
|
||||
public string url { get; set; }
|
||||
public string license { get; set; }
|
||||
public string ArticleBody { get; set; }
|
||||
public string Url { get; set; }
|
||||
public string License { get; set; }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -24,7 +24,7 @@ namespace Geekbot.net.Commands
|
|||
[Command("serverstats", RunMode = RunMode.Async)]
|
||||
[Remarks(CommandCategories.Statistics)]
|
||||
[Summary("Show some info about the bot.")]
|
||||
public async Task getInfo()
|
||||
public async Task GetInfo()
|
||||
{
|
||||
try
|
||||
{
|
||||
|
|
|
@ -110,9 +110,7 @@ namespace Geekbot.net.Commands
|
|||
|
||||
private DateTimeOffset ConvertToDateTimeOffset(string dateTimeOffsetString)
|
||||
{
|
||||
if (string.IsNullOrEmpty(dateTimeOffsetString))
|
||||
return DateTimeOffset.Now.Subtract(new TimeSpan(7, 18, 0, 0));
|
||||
return DateTimeOffset.Parse(dateTimeOffsetString);
|
||||
return string.IsNullOrEmpty(dateTimeOffsetString) ? DateTimeOffset.Now.Subtract(new TimeSpan(7, 18, 0, 0)) : DateTimeOffset.Parse(dateTimeOffsetString);
|
||||
}
|
||||
|
||||
private bool TimeoutFinished(DateTimeOffset lastKarma)
|
||||
|
|
|
@ -1,7 +1,6 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading.Tasks;
|
||||
using Discord;
|
||||
using Discord.Commands;
|
||||
|
@ -24,7 +23,7 @@ namespace Geekbot.net.Commands
|
|||
[Command("mtg", RunMode = RunMode.Async)]
|
||||
[Remarks(CommandCategories.Games)]
|
||||
[Summary("Find a Magic The Gathering Card.")]
|
||||
public async Task getCard([Remainder] [Summary("name")] string cardName)
|
||||
public async Task GetCard([Remainder] [Summary("name")] string cardName)
|
||||
{
|
||||
try
|
||||
{
|
||||
|
|
|
@ -32,7 +32,7 @@ namespace Geekbot.net.Commands
|
|||
[Command("namehistory", RunMode = RunMode.Async)]
|
||||
[Remarks(CommandCategories.Admin)]
|
||||
[Summary("See past usernames of an user")]
|
||||
public async Task usernameHistory([Summary("@user")] IUser user)
|
||||
public async Task UsernameHistory([Summary("@user")] IUser user)
|
||||
{
|
||||
try
|
||||
{
|
||||
|
@ -52,7 +52,7 @@ namespace Geekbot.net.Commands
|
|||
[Command("kick", RunMode = RunMode.Async)]
|
||||
[Remarks(CommandCategories.Admin)]
|
||||
[Summary("Ban a user")]
|
||||
public async Task kick([Summary("@user")] IUser userNormal,
|
||||
public async Task Kick([Summary("@user")] IUser userNormal,
|
||||
[Summary("reason")] [Remainder] string reason = "none")
|
||||
{
|
||||
try
|
||||
|
|
|
@ -5,7 +5,6 @@ using Discord.Commands;
|
|||
using Geekbot.net.Lib;
|
||||
using OverwatchAPI;
|
||||
using OverwatchAPI.Config;
|
||||
using Serilog;
|
||||
using StackExchange.Redis;
|
||||
|
||||
namespace Geekbot.net.Commands
|
||||
|
@ -16,7 +15,7 @@ namespace Geekbot.net.Commands
|
|||
private readonly IErrorHandler _errorHandler;
|
||||
private readonly IUserRepository _userRepository;
|
||||
|
||||
public Overwatch(IErrorHandler errorHandler, IDatabase redis, IUserRepository userRepository)
|
||||
public Overwatch(IErrorHandler errorHandler, IUserRepository userRepository)
|
||||
{
|
||||
_errorHandler = errorHandler;
|
||||
_userRepository = userRepository;
|
||||
|
@ -25,18 +24,18 @@ namespace Geekbot.net.Commands
|
|||
[Command("profile", RunMode = RunMode.Async)]
|
||||
[Summary("Get someones overwatch profile. EU on PC only. Default battletag is your own (if set).")]
|
||||
[Remarks(CommandCategories.Games)]
|
||||
public async Task owProfile()
|
||||
public async Task OwProfile()
|
||||
{
|
||||
try
|
||||
{
|
||||
var tag = _userRepository.getUserSetting(Context.User.Id, "BattleTag");
|
||||
var tag = _userRepository.GetUserSetting(Context.User.Id, "BattleTag");
|
||||
if (string.IsNullOrEmpty(tag))
|
||||
{
|
||||
await ReplyAsync("You have no battle Tag saved, use `!battletag`");
|
||||
return;
|
||||
}
|
||||
|
||||
var profile = await createProfile(tag);
|
||||
var profile = await CreateProfile(tag);
|
||||
if (profile == null)
|
||||
{
|
||||
await ReplyAsync("That player doesn't seem to exist");
|
||||
|
@ -54,17 +53,17 @@ namespace Geekbot.net.Commands
|
|||
[Command("profile", RunMode = RunMode.Async)]
|
||||
[Summary("Get someones overwatch profile. EU on PC only. Default battletag is your own (if set).")]
|
||||
[Remarks(CommandCategories.Games)]
|
||||
public async Task owProfile([Summary("BattleTag")] string tag)
|
||||
public async Task OwProfile([Summary("BattleTag")] string tag)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!BattleTag.isValidTag(tag))
|
||||
if (!BattleTag.IsValidTag(tag))
|
||||
{
|
||||
await ReplyAsync("That doesn't seem to be a valid battletag...");
|
||||
return;
|
||||
}
|
||||
|
||||
var profile = await createProfile(tag);
|
||||
var profile = await CreateProfile(tag);
|
||||
if (profile == null)
|
||||
{
|
||||
await ReplyAsync("That player doesn't seem to exist");
|
||||
|
@ -82,18 +81,18 @@ namespace Geekbot.net.Commands
|
|||
[Command("profile", RunMode = RunMode.Async)]
|
||||
[Summary("Get someones overwatch profile. EU on PC only.")]
|
||||
[Remarks(CommandCategories.Games)]
|
||||
public async Task owProfile([Summary("@someone")] IUser user)
|
||||
public async Task OwProfile([Summary("@someone")] IUser user)
|
||||
{
|
||||
try
|
||||
{
|
||||
var tag = _userRepository.getUserSetting(user.Id, "BattleTag");
|
||||
var tag = _userRepository.GetUserSetting(user.Id, "BattleTag");
|
||||
if (string.IsNullOrEmpty(tag))
|
||||
{
|
||||
await ReplyAsync("This user didn't set a battletag");
|
||||
return;
|
||||
}
|
||||
|
||||
var profile = await createProfile(tag);
|
||||
var profile = await CreateProfile(tag);
|
||||
if (profile == null)
|
||||
{
|
||||
await ReplyAsync("That player doesn't seem to exist");
|
||||
|
@ -108,7 +107,7 @@ namespace Geekbot.net.Commands
|
|||
}
|
||||
}
|
||||
|
||||
private async Task<EmbedBuilder> createProfile(string battletag)
|
||||
private async Task<EmbedBuilder> CreateProfile(string battletag)
|
||||
{
|
||||
var owConfig = new OverwatchConfig.Builder().WithPlatforms(Platform.Pc);
|
||||
using (var owClient = new OverwatchClient(owConfig))
|
||||
|
|
|
@ -4,7 +4,6 @@ using Discord;
|
|||
using Discord.Commands;
|
||||
using Discord.WebSocket;
|
||||
using Geekbot.net.Lib;
|
||||
using Serilog;
|
||||
using StackExchange.Redis;
|
||||
|
||||
namespace Geekbot.net.Commands
|
||||
|
@ -68,7 +67,7 @@ namespace Geekbot.net.Commands
|
|||
[Command("popuserrepo", RunMode = RunMode.Async)]
|
||||
[Remarks(CommandCategories.Admin)]
|
||||
[Summary("Populate user cache")]
|
||||
public async Task popUserRepoCommand()
|
||||
public async Task PopUserRepoCommand()
|
||||
{
|
||||
try
|
||||
{
|
||||
|
@ -82,8 +81,7 @@ namespace Geekbot.net.Commands
|
|||
}
|
||||
catch (Exception)
|
||||
{
|
||||
await ReplyAsync(
|
||||
$"Sorry, only the botowner can do this");
|
||||
await ReplyAsync("Sorry, only the botowner can do this");
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
|
@ -36,7 +36,7 @@ namespace Geekbot.net.Commands
|
|||
return;
|
||||
}
|
||||
|
||||
var embed = await pokemonEmbedBuilder(pokemon);
|
||||
var embed = await PokemonEmbedBuilder(pokemon);
|
||||
await ReplyAsync("", false, embed.Build());
|
||||
}
|
||||
catch (Exception e)
|
||||
|
@ -45,29 +45,29 @@ namespace Geekbot.net.Commands
|
|||
}
|
||||
}
|
||||
|
||||
private async Task<EmbedBuilder> pokemonEmbedBuilder(Pokemon pokemon)
|
||||
private async Task<EmbedBuilder> PokemonEmbedBuilder(Pokemon pokemon)
|
||||
{
|
||||
var eb = new EmbedBuilder();
|
||||
var species = await DataFetcher.GetApiObject<PokemonSpecies>(pokemon.ID);
|
||||
eb.Title = $"#{pokemon.ID} {toUpper(pokemon.Name)}";
|
||||
eb.Title = $"#{pokemon.ID} {ToUpper(pokemon.Name)}";
|
||||
eb.Description = species.FlavorTexts[1].FlavorText;
|
||||
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.Abilities.Length, "Ability"),
|
||||
string.Join(", ", pokemon.Abilities.Select(t => toUpper(t.Ability.Name))));
|
||||
eb.AddInlineField(GetSingularOrPlural(pokemon.Types.Length, "Type"),
|
||||
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("Weight", pokemon.Mass);
|
||||
return eb;
|
||||
}
|
||||
|
||||
private string getSingularOrPlural(int lenght, string word)
|
||||
private string GetSingularOrPlural(int lenght, string word)
|
||||
{
|
||||
if (lenght == 1) 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)) return string.Empty;
|
||||
return char.ToUpper(s[0]) + s.Substring(1);
|
||||
|
|
|
@ -82,14 +82,14 @@ namespace Geekbot.net.Commands
|
|||
var i = 1;
|
||||
pollList.ForEach(option =>
|
||||
{
|
||||
eb.AddInlineField($"Option {_emojiConverter.numberToEmoji(i)}", option);
|
||||
eb.AddInlineField($"Option {_emojiConverter.NumberToEmoji(i)}", option);
|
||||
i++;
|
||||
});
|
||||
var pollMessage = await ReplyAsync("", false, eb.Build());
|
||||
i = 1;
|
||||
pollList.ForEach(option =>
|
||||
{
|
||||
pollMessage.AddReactionAsync(new Emoji(_emojiConverter.numberToEmoji(i)));
|
||||
pollMessage.AddReactionAsync(new Emoji(_emojiConverter.NumberToEmoji(i)));
|
||||
i++;
|
||||
});
|
||||
var poll = new PollData
|
||||
|
@ -123,7 +123,7 @@ namespace Geekbot.net.Commands
|
|||
return;
|
||||
}
|
||||
|
||||
var results = await getPollResults(currentPoll);
|
||||
var results = await GetPollResults(currentPoll);
|
||||
var sb = new StringBuilder();
|
||||
sb.AppendLine("**Poll Results**");
|
||||
sb.AppendLine(currentPoll.Question);
|
||||
|
@ -152,7 +152,7 @@ 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 results = new List<PollResult>();
|
||||
|
|
|
@ -24,7 +24,7 @@ namespace Geekbot.net.Commands
|
|||
[Command]
|
||||
[Remarks(CommandCategories.Quotes)]
|
||||
[Summary("Return a random quoute from the database")]
|
||||
public async Task getRandomQuote()
|
||||
public async Task GetRandomQuote()
|
||||
{
|
||||
try
|
||||
{
|
||||
|
@ -32,7 +32,7 @@ namespace Geekbot.net.Commands
|
|||
var randomNumber = new Random().Next(randomQuotes.Length - 1);
|
||||
var randomQuote = randomQuotes[randomNumber];
|
||||
var quote = JsonConvert.DeserializeObject<QuoteObject>(randomQuote);
|
||||
var embed = quoteBuilder(quote, randomNumber + 1);
|
||||
var embed = QuoteBuilder(quote, randomNumber + 1);
|
||||
await ReplyAsync("", false, embed.Build());
|
||||
}
|
||||
catch (Exception e)
|
||||
|
@ -44,7 +44,7 @@ namespace Geekbot.net.Commands
|
|||
[Command("save")]
|
||||
[Remarks(CommandCategories.Quotes)]
|
||||
[Summary("Save a quote from the last sent message by @user")]
|
||||
public async Task saveQuote([Summary("@user")] IUser user)
|
||||
public async Task SaveQuote([Summary("@user")] IUser user)
|
||||
{
|
||||
try
|
||||
{
|
||||
|
@ -60,11 +60,11 @@ namespace Geekbot.net.Commands
|
|||
return;
|
||||
}
|
||||
|
||||
var lastMessage = await getLastMessageByUser(user);
|
||||
var quote = createQuoteObject(lastMessage);
|
||||
var lastMessage = await GetLastMessageByUser(user);
|
||||
var quote = CreateQuoteObject(lastMessage);
|
||||
var quoteStore = JsonConvert.SerializeObject(quote);
|
||||
_redis.SetAdd($"{Context.Guild.Id}:Quotes", quoteStore);
|
||||
var embed = quoteBuilder(quote);
|
||||
var embed = QuoteBuilder(quote);
|
||||
await ReplyAsync("**Quote Added**", false, embed.Build());
|
||||
}
|
||||
catch (Exception e)
|
||||
|
@ -77,7 +77,7 @@ namespace Geekbot.net.Commands
|
|||
[Command("save")]
|
||||
[Remarks(CommandCategories.Quotes)]
|
||||
[Summary("Save a quote from a message id")]
|
||||
public async Task saveQuote([Summary("messageId")] ulong messageId)
|
||||
public async Task SaveQuote([Summary("messageId")] ulong messageId)
|
||||
{
|
||||
try
|
||||
{
|
||||
|
@ -94,10 +94,10 @@ namespace Geekbot.net.Commands
|
|||
return;
|
||||
}
|
||||
|
||||
var quote = createQuoteObject(message);
|
||||
var quote = CreateQuoteObject(message);
|
||||
var quoteStore = JsonConvert.SerializeObject(quote);
|
||||
_redis.SetAdd($"{Context.Guild.Id}:Quotes", quoteStore);
|
||||
var embed = quoteBuilder(quote);
|
||||
var embed = QuoteBuilder(quote);
|
||||
await ReplyAsync("**Quote Added**", false, embed.Build());
|
||||
}
|
||||
catch (Exception e)
|
||||
|
@ -110,13 +110,13 @@ namespace Geekbot.net.Commands
|
|||
[Command("make")]
|
||||
[Remarks(CommandCategories.Quotes)]
|
||||
[Summary("Create a quote from the last sent message by @user")]
|
||||
public async Task returnSpecifiedQuote([Summary("@user")] IUser user)
|
||||
public async Task ReturnSpecifiedQuote([Summary("@user")] IUser user)
|
||||
{
|
||||
try
|
||||
{
|
||||
var lastMessage = await getLastMessageByUser(user);
|
||||
var quote = createQuoteObject(lastMessage);
|
||||
var embed = quoteBuilder(quote);
|
||||
var lastMessage = await GetLastMessageByUser(user);
|
||||
var quote = CreateQuoteObject(lastMessage);
|
||||
var embed = QuoteBuilder(quote);
|
||||
await ReplyAsync("", false, embed.Build());
|
||||
}
|
||||
catch (Exception e)
|
||||
|
@ -129,13 +129,13 @@ namespace Geekbot.net.Commands
|
|||
[Command("make")]
|
||||
[Remarks(CommandCategories.Quotes)]
|
||||
[Summary("Create a quote from a message id")]
|
||||
public async Task returnSpecifiedQuote([Summary("messageId")] ulong messageId)
|
||||
public async Task ReturnSpecifiedQuote([Summary("messageId")] ulong messageId)
|
||||
{
|
||||
try
|
||||
{
|
||||
var message = await Context.Channel.GetMessageAsync(messageId);
|
||||
var quote = createQuoteObject(message);
|
||||
var embed = quoteBuilder(quote);
|
||||
var quote = CreateQuoteObject(message);
|
||||
var embed = QuoteBuilder(quote);
|
||||
await ReplyAsync("", false, embed.Build());
|
||||
}
|
||||
catch (Exception e)
|
||||
|
@ -151,7 +151,7 @@ namespace Geekbot.net.Commands
|
|||
[RequireUserPermission(GuildPermission.ManageRoles)]
|
||||
[Remarks(CommandCategories.Quotes)]
|
||||
[Summary("Remove a quote (required mod permissions)")]
|
||||
public async Task removeQuote([Summary("quoteId")] int id)
|
||||
public async Task RemoveQuote([Summary("quoteId")] int id)
|
||||
{
|
||||
try
|
||||
{
|
||||
|
@ -160,12 +160,12 @@ namespace Geekbot.net.Commands
|
|||
if (success)
|
||||
{
|
||||
var quote = JsonConvert.DeserializeObject<QuoteObject>(quotes[id - 1]);
|
||||
var embed = quoteBuilder(quote);
|
||||
var embed = QuoteBuilder(quote);
|
||||
await ReplyAsync($"**Removed #{id}**", false, embed.Build());
|
||||
}
|
||||
else
|
||||
{
|
||||
await ReplyAsync($"I couldn't find a quote with that id :disappointed:");
|
||||
await ReplyAsync("I couldn't find a quote with that id :disappointed:");
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
|
@ -175,7 +175,7 @@ namespace Geekbot.net.Commands
|
|||
}
|
||||
}
|
||||
|
||||
private async Task<IMessage> getLastMessageByUser(IUser user)
|
||||
private async Task<IMessage> GetLastMessageByUser(IUser user)
|
||||
{
|
||||
var list = Context.Channel.GetMessagesAsync().Flatten();
|
||||
await list;
|
||||
|
@ -186,20 +186,20 @@ namespace Geekbot.net.Commands
|
|||
&& !msg.Content.ToLower().StartsWith("!"));
|
||||
}
|
||||
|
||||
private EmbedBuilder quoteBuilder(QuoteObject quote, int id = 0)
|
||||
private EmbedBuilder QuoteBuilder(QuoteObject quote, int id = 0)
|
||||
{
|
||||
var user = Context.Client.GetUserAsync(quote.userId).Result;
|
||||
var user = Context.Client.GetUserAsync(quote.UserId).Result;
|
||||
var eb = new EmbedBuilder();
|
||||
eb.WithColor(new Color(143, 167, 232));
|
||||
eb.Title = id == 0 ? "" : $"#{id} | ";
|
||||
eb.Title += $"{user.Username} @ {quote.time.Day}.{quote.time.Month}.{quote.time.Year}";
|
||||
eb.Description = quote.quote;
|
||||
eb.Title += $"{user.Username} @ {quote.Time.Day}.{quote.Time.Month}.{quote.Time.Year}";
|
||||
eb.Description = quote.Quote;
|
||||
eb.ThumbnailUrl = user.GetAvatarUrl();
|
||||
if (quote.image != null) eb.ImageUrl = quote.image;
|
||||
if (quote.Image != null) eb.ImageUrl = quote.Image;
|
||||
return eb;
|
||||
}
|
||||
|
||||
private QuoteObject createQuoteObject(IMessage message)
|
||||
private QuoteObject CreateQuoteObject(IMessage message)
|
||||
{
|
||||
string image;
|
||||
try
|
||||
|
@ -213,19 +213,19 @@ namespace Geekbot.net.Commands
|
|||
|
||||
return new QuoteObject
|
||||
{
|
||||
userId = message.Author.Id,
|
||||
time = message.Timestamp.DateTime,
|
||||
quote = message.Content,
|
||||
image = image
|
||||
UserId = message.Author.Id,
|
||||
Time = message.Timestamp.DateTime,
|
||||
Quote = message.Content,
|
||||
Image = image
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
public class QuoteObject
|
||||
{
|
||||
public ulong userId { get; set; }
|
||||
public string quote { get; set; }
|
||||
public DateTime time { get; set; }
|
||||
public string image { get; set; }
|
||||
public ulong UserId { get; set; }
|
||||
public string Quote { get; set; }
|
||||
public DateTime Time { get; set; }
|
||||
public string Image { get; set; }
|
||||
}
|
||||
}
|
|
@ -18,62 +18,62 @@ namespace Geekbot.net.Commands
|
|||
[Command("panda", RunMode = RunMode.Async)]
|
||||
[Remarks(CommandCategories.Randomness)]
|
||||
[Summary("Get a random panda image")]
|
||||
public async Task panda()
|
||||
public async Task Panda()
|
||||
{
|
||||
await ReplyAsync("", false, eb(_mediaProvider.getPanda()));
|
||||
await ReplyAsync("", false, Eb(_mediaProvider.GetPanda()));
|
||||
}
|
||||
|
||||
[Command("croissant", RunMode = RunMode.Async)]
|
||||
[Alias("gipfeli")]
|
||||
[Remarks(CommandCategories.Randomness)]
|
||||
[Summary("Get a random croissant image")]
|
||||
public async Task croissant()
|
||||
public async Task Croissant()
|
||||
{
|
||||
await ReplyAsync("", false, eb(_mediaProvider.getCrossant()));
|
||||
await ReplyAsync("", false, Eb(_mediaProvider.GetCrossant()));
|
||||
}
|
||||
|
||||
[Command("pumpkin", RunMode = RunMode.Async)]
|
||||
[Remarks(CommandCategories.Randomness)]
|
||||
[Summary("Get a random pumpkin image")]
|
||||
public async Task pumpkin()
|
||||
public async Task Pumpkin()
|
||||
{
|
||||
await ReplyAsync("", false, eb(_mediaProvider.getPumpkin()));
|
||||
await ReplyAsync("", false, Eb(_mediaProvider.GetPumpkin()));
|
||||
}
|
||||
|
||||
[Command("squirrel", RunMode = RunMode.Async)]
|
||||
[Remarks(CommandCategories.Randomness)]
|
||||
[Summary("Get a random squirrel image")]
|
||||
public async Task squirrel()
|
||||
public async Task Squirrel()
|
||||
{
|
||||
await ReplyAsync("", false, eb(_mediaProvider.getSquirrel()));
|
||||
await ReplyAsync("", false, Eb(_mediaProvider.GetSquirrel()));
|
||||
}
|
||||
|
||||
[Command("turtle", RunMode = RunMode.Async)]
|
||||
[Remarks(CommandCategories.Randomness)]
|
||||
[Summary("Get a random turtle image")]
|
||||
public async Task turtle()
|
||||
public async Task Turtle()
|
||||
{
|
||||
await ReplyAsync("", false, eb(_mediaProvider.getTurtle()));
|
||||
await ReplyAsync("", false, Eb(_mediaProvider.GetTurtle()));
|
||||
}
|
||||
|
||||
[Command("pinguin", RunMode = RunMode.Async)]
|
||||
[Alias("pingu")]
|
||||
[Remarks(CommandCategories.Randomness)]
|
||||
[Summary("Get a random turtle image")]
|
||||
public async Task pinguin()
|
||||
public async Task Pinguin()
|
||||
{
|
||||
await ReplyAsync("", false, eb(_mediaProvider.getPinguin()));
|
||||
await ReplyAsync("", false, Eb(_mediaProvider.GetPinguin()));
|
||||
}
|
||||
|
||||
[Command("fox", RunMode = RunMode.Async)]
|
||||
[Remarks(CommandCategories.Randomness)]
|
||||
[Summary("Get a random turtle image")]
|
||||
public async Task fox()
|
||||
public async Task Fox()
|
||||
{
|
||||
await ReplyAsync("", false, eb(_mediaProvider.getFox()));
|
||||
await ReplyAsync("", false, Eb(_mediaProvider.GetFox()));
|
||||
}
|
||||
|
||||
private EmbedBuilder eb(string image)
|
||||
private EmbedBuilder Eb(string image)
|
||||
{
|
||||
var eb = new EmbedBuilder();
|
||||
eb.ImageUrl = image;
|
||||
|
|
|
@ -6,7 +6,6 @@ using System.Threading.Tasks;
|
|||
using Discord.Commands;
|
||||
using Discord.WebSocket;
|
||||
using Geekbot.net.Lib;
|
||||
using Serilog;
|
||||
using StackExchange.Redis;
|
||||
|
||||
namespace Geekbot.net.Commands
|
||||
|
@ -110,7 +109,7 @@ namespace Geekbot.net.Commands
|
|||
foreach (var user in highscoreUsers)
|
||||
{
|
||||
replyBuilder.Append(highscorePlace < 11
|
||||
? $"{_emojiConverter.numberToEmoji(highscorePlace)} "
|
||||
? $"{_emojiConverter.NumberToEmoji(highscorePlace)} "
|
||||
: $"`{highscorePlace}.` ");
|
||||
|
||||
replyBuilder.Append(user.Key.Username != null
|
||||
|
|
|
@ -27,7 +27,7 @@ namespace Geekbot.net.Commands
|
|||
[Command(RunMode = RunMode.Async)]
|
||||
[Remarks(CommandCategories.Helpers)]
|
||||
[Summary("Get a list of all available roles.")]
|
||||
public async Task getAllRoles()
|
||||
public async Task GetAllRoles()
|
||||
{
|
||||
try
|
||||
{
|
||||
|
@ -53,7 +53,7 @@ namespace Geekbot.net.Commands
|
|||
[Command(RunMode = RunMode.Async)]
|
||||
[Remarks(CommandCategories.Helpers)]
|
||||
[Summary("Get a role by mentioning it.")]
|
||||
public async Task giveRole([Summary("roleNickname")] string roleNameRaw)
|
||||
public async Task GiveRole([Summary("roleNickname")] string roleNameRaw)
|
||||
{
|
||||
try
|
||||
{
|
||||
|
@ -97,7 +97,7 @@ namespace Geekbot.net.Commands
|
|||
[Command("add", RunMode = RunMode.Async)]
|
||||
[Remarks(CommandCategories.Admin)]
|
||||
[Summary("Add a role to the whitelist.")]
|
||||
public async Task addRole([Summary("@role")] IRole role, [Summary("alias")] string roleName)
|
||||
public async Task AddRole([Summary("@role")] IRole role, [Summary("alias")] string roleName)
|
||||
{
|
||||
try
|
||||
{
|
||||
|
@ -132,7 +132,7 @@ namespace Geekbot.net.Commands
|
|||
[Command("remove", RunMode = RunMode.Async)]
|
||||
[Remarks(CommandCategories.Admin)]
|
||||
[Summary("Remove a role from the whitelist.")]
|
||||
public async Task removeRole([Summary("roleNickname")] string roleName)
|
||||
public async Task RemoveRole([Summary("roleNickname")] string roleName)
|
||||
{
|
||||
try
|
||||
{
|
||||
|
@ -166,7 +166,7 @@ namespace Geekbot.net.Commands
|
|||
if (!emoji.StartsWith('<'))
|
||||
{
|
||||
var emo = new Emoji(emoji);
|
||||
emote = (IEmote) emo;
|
||||
emote = emo;
|
||||
}
|
||||
else
|
||||
{
|
||||
|
|
|
@ -64,9 +64,7 @@ namespace Geekbot.net.Commands
|
|||
return "There might be a chance";
|
||||
if (rate >= 60 && rate < 80)
|
||||
return "Almost a match, but could work";
|
||||
if (rate >= 80)
|
||||
return "It's a match";
|
||||
return "a";
|
||||
return rate >= 80 ? "It's a match" : "a";
|
||||
}
|
||||
|
||||
private string BlockCounter(int rate)
|
||||
|
|
|
@ -32,7 +32,7 @@ namespace Geekbot.net.Commands
|
|||
return;
|
||||
}
|
||||
|
||||
var things = new List<string>()
|
||||
var things = new List<string>
|
||||
{
|
||||
"thing",
|
||||
"rubber chicken",
|
||||
|
|
|
@ -22,7 +22,7 @@ namespace Geekbot.net.Commands
|
|||
[Command("urban", RunMode = RunMode.Async)]
|
||||
[Remarks(CommandCategories.Helpers)]
|
||||
[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
|
||||
{
|
||||
|
@ -34,26 +34,26 @@ namespace Geekbot.net.Commands
|
|||
|
||||
var stringResponse = await response.Content.ReadAsStringAsync();
|
||||
var definitions = JsonConvert.DeserializeObject<UrbanResponse>(stringResponse);
|
||||
if (definitions.list.Count == 0)
|
||||
if (definitions.List.Count == 0)
|
||||
{
|
||||
await ReplyAsync("That word hasn't been defined...");
|
||||
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();
|
||||
eb.WithAuthor(new EmbedAuthorBuilder
|
||||
{
|
||||
Name = definition.word,
|
||||
Url = definition.permalink
|
||||
Name = definition.Word,
|
||||
Url = definition.Permalink
|
||||
});
|
||||
eb.WithColor(new Color(239, 255, 0));
|
||||
eb.Description = definition.definition;
|
||||
eb.AddField("Example", definition.example ?? "(no example given...)");
|
||||
eb.AddInlineField("Upvotes", definition.thumbs_up);
|
||||
eb.AddInlineField("Downvotes", definition.thumbs_down);
|
||||
if (definitions.tags.Length > 0) eb.AddField("Tags", string.Join(", ", definitions.tags));
|
||||
eb.Description = definition.Definition;
|
||||
eb.AddField("Example", definition.Example ?? "(no example given...)");
|
||||
eb.AddInlineField("Upvotes", definition.ThumbsUp);
|
||||
eb.AddInlineField("Downvotes", definition.ThumbsDown);
|
||||
if (definitions.Tags.Length > 0) eb.AddField("Tags", string.Join(", ", definitions.Tags));
|
||||
|
||||
await ReplyAsync("", false, eb.Build());
|
||||
}
|
||||
|
@ -66,22 +66,18 @@ namespace Geekbot.net.Commands
|
|||
|
||||
private class UrbanResponse
|
||||
{
|
||||
public string[] tags { get; set; }
|
||||
public string result_type { get; set; }
|
||||
public List<UrbanListItem> list { get; set; }
|
||||
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 thumbs_up { get; set; }
|
||||
public string author { get; set; }
|
||||
public string word { get; set; }
|
||||
public string defid { get; set; }
|
||||
public string current_vote { get; set; }
|
||||
public string example { get; set; }
|
||||
public string thumbs_down { get; set; }
|
||||
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; }
|
||||
}
|
||||
}
|
||||
}
|
|
@ -78,7 +78,7 @@ namespace Geekbot.net.Commands
|
|||
};
|
||||
|
||||
eb.AddField("Description", article.Extract);
|
||||
if (article.Coordinates != null) eb.AddField("Coordinates", $"{article.Coordinates.lat} Lat {article.Coordinates.lon} Lon");
|
||||
if (article.Coordinates != null) eb.AddField("Coordinates", $"{article.Coordinates.Lat} Lat {article.Coordinates.Lon} Lon");
|
||||
await ReplyAsync("", false, eb.Build());
|
||||
}
|
||||
catch (HttpRequestException)
|
||||
|
|
|
@ -7,12 +7,12 @@ using Geekbot.net.Lib;
|
|||
|
||||
namespace Geekbot.net.Commands
|
||||
{
|
||||
public class mal : ModuleBase
|
||||
public class Mal : ModuleBase
|
||||
{
|
||||
private readonly IErrorHandler _errorHandler;
|
||||
private readonly IMalClient _malClient;
|
||||
|
||||
public mal(IMalClient malClient, IErrorHandler errorHandler)
|
||||
public Mal(IMalClient malClient, IErrorHandler errorHandler)
|
||||
{
|
||||
_malClient = malClient;
|
||||
_errorHandler = errorHandler;
|
||||
|
@ -21,13 +21,13 @@ namespace Geekbot.net.Commands
|
|||
[Command("anime", RunMode = RunMode.Async)]
|
||||
[Remarks(CommandCategories.Helpers)]
|
||||
[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
|
||||
{
|
||||
if (_malClient.isLoggedIn())
|
||||
if (_malClient.IsLoggedIn())
|
||||
{
|
||||
var anime = await _malClient.getAnime(animeName);
|
||||
var anime = await _malClient.GetAnime(animeName);
|
||||
if (anime != null)
|
||||
{
|
||||
var eb = new EmbedBuilder();
|
||||
|
@ -70,13 +70,13 @@ namespace Geekbot.net.Commands
|
|||
[Command("manga", RunMode = RunMode.Async)]
|
||||
[Remarks(CommandCategories.Helpers)]
|
||||
[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
|
||||
{
|
||||
if (_malClient.isLoggedIn())
|
||||
if (_malClient.IsLoggedIn())
|
||||
{
|
||||
var manga = await _malClient.getManga(mangaName);
|
||||
var manga = await _malClient.GetManga(mangaName);
|
||||
if (manga != null)
|
||||
{
|
||||
var eb = new EmbedBuilder();
|
||||
|
|
|
@ -1,12 +1,10 @@
|
|||
using System;
|
||||
using System.Collections;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Discord;
|
||||
using Discord.Commands;
|
||||
using Discord.WebSocket;
|
||||
using Geekbot.net.Lib;
|
||||
using Serilog;
|
||||
using StackExchange.Redis;
|
||||
|
||||
namespace Geekbot.net
|
||||
|
|
|
@ -1,106 +0,0 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Security.Cryptography;
|
||||
using Discord.Audio;
|
||||
using Discord.Net;
|
||||
|
||||
namespace Geekbot.net.Lib
|
||||
{
|
||||
public class AudioUtils : IAudioUtils
|
||||
{
|
||||
private string _tempFolderPath;
|
||||
private Dictionary<ulong, IAudioClient> _audioClients;
|
||||
|
||||
public AudioUtils()
|
||||
{
|
||||
_audioClients = new Dictionary<ulong, IAudioClient>();
|
||||
_tempFolderPath = Path.GetFullPath("./tmp/");
|
||||
if (Directory.Exists(_tempFolderPath))
|
||||
{
|
||||
Directory.Delete(_tempFolderPath, true);
|
||||
}
|
||||
Directory.CreateDirectory(_tempFolderPath);
|
||||
}
|
||||
|
||||
public IAudioClient GetAudioClient(ulong guildId)
|
||||
{
|
||||
return _audioClients[guildId];
|
||||
}
|
||||
|
||||
public void StoreAudioClient(ulong guildId, IAudioClient client)
|
||||
{
|
||||
_audioClients[guildId] = client;
|
||||
}
|
||||
|
||||
public Process CreateStreamFromFile(string path)
|
||||
{
|
||||
var ffmpeg = new ProcessStartInfo
|
||||
{
|
||||
FileName = "ffmpeg",
|
||||
Arguments = $"-i {path} -ac 2 -f s16le -ar 48000 pipe:1",
|
||||
UseShellExecute = false,
|
||||
RedirectStandardOutput = true,
|
||||
};
|
||||
return Process.Start(ffmpeg);
|
||||
}
|
||||
|
||||
public Process CreateStreamFromYoutube(string url, ulong guildId)
|
||||
{
|
||||
var ytdlMediaUrl = GetYoutubeMediaUrl(url);
|
||||
DownloadMediaUrl(ytdlMediaUrl, guildId);
|
||||
return CreateStreamFromFile($"{_tempFolderPath}{guildId}");
|
||||
}
|
||||
|
||||
public void Cleanup(ulong guildId)
|
||||
{
|
||||
File.Delete($"{_tempFolderPath}{guildId}");
|
||||
}
|
||||
|
||||
private string GetYoutubeMediaUrl(string url)
|
||||
{
|
||||
var ytdl = new ProcessStartInfo()
|
||||
{
|
||||
FileName = "youtube-dl",
|
||||
Arguments = $"-f bestaudio -g {url}",
|
||||
UseShellExecute = false,
|
||||
RedirectStandardOutput = true
|
||||
};
|
||||
var output = Process.Start(ytdl).StandardOutput.ReadToEnd();
|
||||
if (string.IsNullOrWhiteSpace(output))
|
||||
{
|
||||
throw new Exception("Could not get Youtube Media URL");
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
private void DownloadMediaUrl(string url, ulong guildId)
|
||||
{
|
||||
using (var web = new WebClient())
|
||||
{
|
||||
web.DownloadFile(url, $"{_tempFolderPath}{guildId}");
|
||||
}
|
||||
// var ffmpeg = new ProcessStartInfo
|
||||
// {
|
||||
// FileName = "ffmpeg",
|
||||
// Arguments = $"-i \"{_tempFolderPath}{guildId}\" -c:a mp3 -b:a 256k {_tempFolderPath}{guildId}.mp3",
|
||||
// UseShellExecute = false,
|
||||
// RedirectStandardOutput = true,
|
||||
// };
|
||||
// Process.Start(ffmpeg).WaitForExit();
|
||||
// File.Delete($"{_tempFolderPath}{guildId}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
public interface IAudioUtils
|
||||
{
|
||||
IAudioClient GetAudioClient(ulong guildId);
|
||||
void StoreAudioClient(ulong guildId, IAudioClient client);
|
||||
Process CreateStreamFromFile(string path);
|
||||
Process CreateStreamFromYoutube(string url, ulong guildId);
|
||||
void Cleanup(ulong guildId);
|
||||
}
|
||||
}
|
|
@ -1,6 +1,6 @@
|
|||
namespace Geekbot.net.Lib
|
||||
{
|
||||
public class CommandCategories
|
||||
public static class CommandCategories
|
||||
{
|
||||
public const string Randomness = "Randomness";
|
||||
public const string Karma = "Karma";
|
||||
|
|
|
@ -3,7 +3,7 @@
|
|||
public class Constants
|
||||
{
|
||||
public const string Name = "Geekbot";
|
||||
public const double BotVersion = 3.5;
|
||||
public const double BotVersion = 3.6;
|
||||
public const double ApiVersion = 1;
|
||||
}
|
||||
}
|
|
@ -5,13 +5,13 @@ namespace Geekbot.net.Lib
|
|||
{
|
||||
public class EmojiConverter : IEmojiConverter
|
||||
{
|
||||
public string numberToEmoji(int number)
|
||||
public string NumberToEmoji(int number)
|
||||
{
|
||||
if (number == 10)
|
||||
{
|
||||
return "🔟";
|
||||
}
|
||||
var emojiMap = new string[]
|
||||
var emojiMap = new[]
|
||||
{
|
||||
":zero:",
|
||||
":one:",
|
||||
|
@ -22,7 +22,7 @@ namespace Geekbot.net.Lib
|
|||
":six:",
|
||||
":seven:",
|
||||
":eight:",
|
||||
":nine:",
|
||||
":nine:"
|
||||
};
|
||||
var numbers = number.ToString().ToCharArray();
|
||||
var returnString = new StringBuilder();
|
||||
|
@ -33,7 +33,7 @@ namespace Geekbot.net.Lib
|
|||
return returnString.ToString();
|
||||
}
|
||||
|
||||
public string textToEmoji(string text)
|
||||
public string TextToEmoji(string text)
|
||||
{
|
||||
var emojiMap = new Hashtable
|
||||
{
|
||||
|
@ -93,7 +93,7 @@ namespace Geekbot.net.Lib
|
|||
|
||||
public interface IEmojiConverter
|
||||
{
|
||||
string numberToEmoji(int number);
|
||||
string textToEmoji(string text);
|
||||
string NumberToEmoji(int number);
|
||||
string TextToEmoji(string text);
|
||||
}
|
||||
}
|
|
@ -1,6 +1,4 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Net;
|
||||
using Discord.Commands;
|
||||
using Discord.Net;
|
||||
|
@ -34,12 +32,12 @@ namespace Geekbot.net.Lib
|
|||
}
|
||||
}
|
||||
|
||||
public void HandleCommandException(Exception e, ICommandContext Context, string errorMessage = "def")
|
||||
public void HandleCommandException(Exception e, ICommandContext context, string errorMessage = "def")
|
||||
{
|
||||
try
|
||||
{
|
||||
var errorString = errorMessage == "def" ? _translation.GetString(Context.Guild.Id, "errorHandler", "SomethingWentWrong") : errorMessage;
|
||||
var errorObj = SimpleConextConverter.ConvertContext(Context);
|
||||
var errorString = errorMessage == "def" ? _translation.GetString(context.Guild.Id, "errorHandler", "SomethingWentWrong") : errorMessage;
|
||||
var errorObj = SimpleConextConverter.ConvertContext(context);
|
||||
if (e.Message.Contains("50007")) return;
|
||||
if (e.Message.Contains("50013")) return;
|
||||
_logger.Error("Geekbot", "An error ocured", e, errorObj);
|
||||
|
@ -49,11 +47,11 @@ namespace Geekbot.net.Lib
|
|||
{
|
||||
var resStackTrace = string.IsNullOrEmpty(e.InnerException?.ToString()) ? e.StackTrace : e.InnerException.ToString();
|
||||
var maxLen = Math.Min(resStackTrace.Length, 1850);
|
||||
Context.Channel.SendMessageAsync($"{e.Message}\r\n```\r\n{resStackTrace?.Substring(0, maxLen)}\r\n```");
|
||||
context.Channel.SendMessageAsync($"{e.Message}\r\n```\r\n{resStackTrace.Substring(0, maxLen)}\r\n```");
|
||||
}
|
||||
else
|
||||
{
|
||||
Context.Channel.SendMessageAsync(errorString);
|
||||
context.Channel.SendMessageAsync(errorString);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -74,18 +72,18 @@ namespace Geekbot.net.Lib
|
|||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Context.Channel.SendMessageAsync("Something went really really wrong here");
|
||||
context.Channel.SendMessageAsync("Something went really really wrong here");
|
||||
_logger.Error("Geekbot", "Errorception", ex);
|
||||
}
|
||||
}
|
||||
|
||||
public async void HandleHttpException(HttpException e, ICommandContext Context)
|
||||
public async void HandleHttpException(HttpException e, ICommandContext context)
|
||||
{
|
||||
var errorStrings = _translation.GetDict(Context, "httpErrors");
|
||||
var errorStrings = _translation.GetDict(context, "httpErrors");
|
||||
switch(e.HttpCode)
|
||||
{
|
||||
case HttpStatusCode.Forbidden:
|
||||
await Context.Channel.SendMessageAsync(errorStrings["403"]);
|
||||
await context.Channel.SendMessageAsync(errorStrings["403"]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
@ -95,7 +93,7 @@ namespace Geekbot.net.Lib
|
|||
|
||||
public interface IErrorHandler
|
||||
{
|
||||
void HandleCommandException(Exception e, ICommandContext Context, string errorMessage = "def");
|
||||
void HandleHttpException(HttpException e, ICommandContext Context);
|
||||
void HandleCommandException(Exception e, ICommandContext context, string errorMessage = "def");
|
||||
void HandleHttpException(HttpException e, ICommandContext context);
|
||||
}
|
||||
}
|
|
@ -10,7 +10,7 @@ namespace Geekbot.net.Lib
|
|||
private readonly ILogger _serilog;
|
||||
public GeekbotLogger()
|
||||
{
|
||||
_serilog = LoggerFactory.createLogger();
|
||||
_serilog = LoggerFactory.CreateLogger();
|
||||
//JsonSerializer.SetDefaultResolver(StandardResolver.AllowPrivateExcludeNullSnakeCase);
|
||||
Information("Geekbot", "Using GeekbotLogger");
|
||||
}
|
||||
|
@ -45,7 +45,7 @@ namespace Geekbot.net.Lib
|
|||
|
||||
private string CreateLogObject(string type, string source, string message, Exception stackTrace = null, object extra = null)
|
||||
{
|
||||
var logObject = new GeekbotLoggerObject()
|
||||
var logObject = new GeekbotLoggerObject
|
||||
{
|
||||
Timestamp = DateTime.Now,
|
||||
Type = type,
|
||||
|
|
|
@ -1,6 +1,5 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace Geekbot.net.Lib
|
||||
{
|
||||
|
|
|
@ -1,13 +1,12 @@
|
|||
using System;
|
||||
using Serilog;
|
||||
using Serilog.Formatting.Json;
|
||||
using Serilog.Sinks.SumoLogic;
|
||||
|
||||
namespace Geekbot.net.Lib
|
||||
{
|
||||
public class LoggerFactory
|
||||
{
|
||||
public static ILogger createLogger()
|
||||
public static ILogger CreateLogger()
|
||||
{
|
||||
var loggerCreation = new LoggerConfiguration();
|
||||
var template = "{Message}{NewLine}";
|
||||
|
|
|
@ -2,7 +2,6 @@
|
|||
using MyAnimeListSharp.Auth;
|
||||
using MyAnimeListSharp.Core;
|
||||
using MyAnimeListSharp.Facade.Async;
|
||||
using Serilog;
|
||||
using StackExchange.Redis;
|
||||
|
||||
namespace Geekbot.net.Lib
|
||||
|
@ -19,10 +18,10 @@ namespace Geekbot.net.Lib
|
|||
{
|
||||
_redis = redis;
|
||||
_logger = logger;
|
||||
reloadClient();
|
||||
ReloadClient();
|
||||
}
|
||||
|
||||
public bool reloadClient()
|
||||
public bool ReloadClient()
|
||||
{
|
||||
var malCredentials = _redis.HashGetAll("malCredentials");
|
||||
if (malCredentials.Length != 0)
|
||||
|
@ -50,18 +49,18 @@ namespace Geekbot.net.Lib
|
|||
|
||||
}
|
||||
|
||||
public bool isLoggedIn()
|
||||
public bool IsLoggedIn()
|
||||
{
|
||||
return _credentials != null;
|
||||
}
|
||||
|
||||
public async Task<AnimeEntry> getAnime(string query)
|
||||
public async Task<AnimeEntry> GetAnime(string query)
|
||||
{
|
||||
var response = await _animeSearch.SearchDeserializedAsync(query);
|
||||
return response.Entries.Count == 0 ? null : response.Entries[0];
|
||||
}
|
||||
|
||||
public async Task<MangaEntry> getManga(string query)
|
||||
public async Task<MangaEntry> GetManga(string query)
|
||||
{
|
||||
var response = await _mangaSearch.SearchDeserializedAsync(query);
|
||||
return response.Entries.Count == 0 ? null : response.Entries[0];
|
||||
|
@ -70,9 +69,8 @@ namespace Geekbot.net.Lib
|
|||
|
||||
public interface IMalClient
|
||||
{
|
||||
bool reloadClient();
|
||||
bool isLoggedIn();
|
||||
Task<AnimeEntry> getAnime(string query);
|
||||
Task<MangaEntry> getManga(string query);
|
||||
bool IsLoggedIn();
|
||||
Task<AnimeEntry> GetAnime(string query);
|
||||
Task<MangaEntry> GetManga(string query);
|
||||
}
|
||||
}
|
|
@ -1,13 +1,12 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using Serilog;
|
||||
|
||||
namespace Geekbot.net.Lib.Media
|
||||
{
|
||||
internal class FortunesProvider : IFortunesProvider
|
||||
{
|
||||
private readonly string[] fortuneArray;
|
||||
private readonly int totalFortunes;
|
||||
private readonly string[] _fortuneArray;
|
||||
private readonly int _totalFortunes;
|
||||
|
||||
public FortunesProvider(IGeekbotLogger logger)
|
||||
{
|
||||
|
@ -15,8 +14,8 @@ namespace Geekbot.net.Lib.Media
|
|||
if (File.Exists(path))
|
||||
{
|
||||
var rawFortunes = File.ReadAllText(path);
|
||||
fortuneArray = rawFortunes.Split("%");
|
||||
totalFortunes = fortuneArray.Length;
|
||||
_fortuneArray = rawFortunes.Split("%");
|
||||
_totalFortunes = _fortuneArray.Length;
|
||||
logger.Debug("Geekbot", "Loaded {totalFortunes} Fortunes");
|
||||
}
|
||||
else
|
||||
|
@ -27,7 +26,7 @@ namespace Geekbot.net.Lib.Media
|
|||
|
||||
public string GetRandomFortune()
|
||||
{
|
||||
return fortuneArray[new Random().Next(0, totalFortunes)];
|
||||
return _fortuneArray[new Random().Next(0, _totalFortunes)];
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -1,8 +1,5 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading.Tasks;
|
||||
using Serilog;
|
||||
|
||||
namespace Geekbot.net.Lib.Media
|
||||
{
|
||||
|
@ -92,42 +89,42 @@ namespace Geekbot.net.Lib.Media
|
|||
_logger.Debug("Geekbot", $"Loaded {_foxImages.Length} Foxes Images");
|
||||
}
|
||||
|
||||
public string getCheckem()
|
||||
public string GetCheckem()
|
||||
{
|
||||
return _checkemImages[_random.Next(0, _checkemImages.Length)];
|
||||
}
|
||||
|
||||
public string getPanda()
|
||||
public string GetPanda()
|
||||
{
|
||||
return _pandaImages[_random.Next(0, _pandaImages.Length)];
|
||||
}
|
||||
|
||||
public string getCrossant()
|
||||
public string GetCrossant()
|
||||
{
|
||||
return _croissantImages[_random.Next(0, _croissantImages.Length)];
|
||||
}
|
||||
|
||||
public string getSquirrel()
|
||||
public string GetSquirrel()
|
||||
{
|
||||
return _squirrelImages[_random.Next(0, _squirrelImages.Length)];
|
||||
}
|
||||
|
||||
public string getPumpkin()
|
||||
public string GetPumpkin()
|
||||
{
|
||||
return _pumpkinImages[_random.Next(0, _pumpkinImages.Length)];
|
||||
}
|
||||
|
||||
public string getTurtle()
|
||||
public string GetTurtle()
|
||||
{
|
||||
return _turtlesImages[_random.Next(0, _turtlesImages.Length)];
|
||||
}
|
||||
|
||||
public string getPinguin()
|
||||
public string GetPinguin()
|
||||
{
|
||||
return _pinguinImages[_random.Next(0, _pinguinImages.Length)];
|
||||
}
|
||||
|
||||
public string getFox()
|
||||
public string GetFox()
|
||||
{
|
||||
return _foxImages[_random.Next(0, _foxImages.Length)];
|
||||
}
|
||||
|
@ -135,13 +132,13 @@ namespace Geekbot.net.Lib.Media
|
|||
|
||||
public interface IMediaProvider
|
||||
{
|
||||
string getCheckem();
|
||||
string getPanda();
|
||||
string getCrossant();
|
||||
string getSquirrel();
|
||||
string getPumpkin();
|
||||
string getTurtle();
|
||||
string getPinguin();
|
||||
string getFox();
|
||||
string GetCheckem();
|
||||
string GetPanda();
|
||||
string GetCrossant();
|
||||
string GetSquirrel();
|
||||
string GetPumpkin();
|
||||
string GetTurtle();
|
||||
string GetPinguin();
|
||||
string GetFox();
|
||||
}
|
||||
}
|
|
@ -1,5 +1,4 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Geekbot.net.Lib
|
||||
|
|
|
@ -33,7 +33,7 @@ namespace Geekbot.net.Lib
|
|||
if (!r.Name.ToString().StartsWith('<'))
|
||||
{
|
||||
var emo = new Emoji(r.Name);
|
||||
emote = (IEmote) emo;
|
||||
emote = emo;
|
||||
}
|
||||
else
|
||||
{
|
||||
|
|
|
@ -1,5 +1,4 @@
|
|||
using System;
|
||||
using Discord.Commands;
|
||||
using Discord.Commands;
|
||||
using Discord.WebSocket;
|
||||
|
||||
namespace Geekbot.net.Lib
|
||||
|
@ -8,9 +7,9 @@ namespace Geekbot.net.Lib
|
|||
{
|
||||
public static MessageDto ConvertContext(ICommandContext context)
|
||||
{
|
||||
return new MessageDto()
|
||||
return new MessageDto
|
||||
{
|
||||
Message = new MessageDto.MessageContent()
|
||||
Message = new MessageDto.MessageContent
|
||||
{
|
||||
Content = context.Message.Content,
|
||||
Id = context.Message.Id.ToString(),
|
||||
|
@ -19,17 +18,17 @@ namespace Geekbot.net.Lib
|
|||
UserMentions = context.Message.MentionedUserIds.Count,
|
||||
RoleMentions = context.Message.MentionedRoleIds.Count
|
||||
},
|
||||
User = new MessageDto.IdAndName()
|
||||
User = new MessageDto.IdAndName
|
||||
{
|
||||
Id = context.User.Id.ToString(),
|
||||
Name = $"{context.User.Username}#{context.User.Discriminator}"
|
||||
},
|
||||
Guild = new MessageDto.IdAndName()
|
||||
Guild = new MessageDto.IdAndName
|
||||
{
|
||||
Id = context.Guild.Id.ToString(),
|
||||
Name = context.Guild.Name
|
||||
},
|
||||
Channel = new MessageDto.IdAndName()
|
||||
Channel = new MessageDto.IdAndName
|
||||
{
|
||||
Id = context.Channel.Id.ToString(),
|
||||
Name = context.Channel.Name
|
||||
|
@ -39,9 +38,9 @@ namespace Geekbot.net.Lib
|
|||
public static MessageDto ConvertSocketMessage(SocketMessage message)
|
||||
{
|
||||
var channel = (SocketGuildChannel) message.Channel;
|
||||
return new MessageDto()
|
||||
return new MessageDto
|
||||
{
|
||||
Message = new MessageDto.MessageContent()
|
||||
Message = new MessageDto.MessageContent
|
||||
{
|
||||
Content = message.Content,
|
||||
Id = message.Id.ToString(),
|
||||
|
@ -50,21 +49,21 @@ namespace Geekbot.net.Lib
|
|||
UserMentions = message.MentionedUsers.Count,
|
||||
RoleMentions = message.MentionedRoles.Count
|
||||
},
|
||||
User = new MessageDto.IdAndName()
|
||||
User = new MessageDto.IdAndName
|
||||
{
|
||||
Id = message.Author.Id.ToString(),
|
||||
Name = $"{message.Author.Username}#{message.Author.Discriminator}"
|
||||
},
|
||||
Guild = new MessageDto.IdAndName()
|
||||
Guild = new MessageDto.IdAndName
|
||||
{
|
||||
Id = channel.Guild.Id.ToString(),
|
||||
Name = channel.Guild.Name
|
||||
},
|
||||
Channel = new MessageDto.IdAndName()
|
||||
Channel = new MessageDto.IdAndName
|
||||
{
|
||||
Id = channel.Id.ToString(),
|
||||
Name = channel.Name
|
||||
},
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
@ -4,8 +4,8 @@ using System.IO;
|
|||
using System.Linq;
|
||||
using Discord.Commands;
|
||||
using Discord.WebSocket;
|
||||
using Serilog;
|
||||
using StackExchange.Redis;
|
||||
using Utf8Json;
|
||||
|
||||
namespace Geekbot.net.Lib
|
||||
{
|
||||
|
@ -31,7 +31,7 @@ namespace Geekbot.net.Lib
|
|||
try
|
||||
{
|
||||
var translationFile = File.ReadAllText(Path.GetFullPath("./Storage/Translations.json"));
|
||||
var rawTranslations = Utf8Json.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>>>();
|
||||
foreach (var command in rawTranslations)
|
||||
{
|
||||
|
@ -136,7 +136,7 @@ namespace Geekbot.net.Lib
|
|||
try
|
||||
{
|
||||
if (!_supportedLanguages.Contains(language)) return false;
|
||||
_redis.HashSet($"{guildId}:Settings", new HashEntry[]{ new HashEntry("Language", language), });
|
||||
_redis.HashSet($"{guildId}:Settings", new[]{ new HashEntry("Language", language) });
|
||||
_serverLanguages[guildId] = language;
|
||||
return true;
|
||||
}
|
||||
|
|
|
@ -1,10 +1,7 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Discord.WebSocket;
|
||||
using Serilog;
|
||||
using StackExchange.Redis;
|
||||
using Utf8Json;
|
||||
|
||||
|
@ -50,7 +47,7 @@ namespace Geekbot.net.Lib
|
|||
|
||||
private void Store(UserRepositoryUser user)
|
||||
{
|
||||
_redis.HashSetAsync($"Users:{user.Id.ToString()}", new HashEntry[]
|
||||
_redis.HashSetAsync($"Users:{user.Id.ToString()}", new[]
|
||||
{
|
||||
new HashEntry("Id", user.Id.ToString()),
|
||||
new HashEntry("Username", user.Username),
|
||||
|
@ -58,7 +55,7 @@ namespace Geekbot.net.Lib
|
|||
new HashEntry("AvatarUrl", user.AvatarUrl),
|
||||
new HashEntry("IsBot", user.IsBot),
|
||||
new HashEntry("Joined", user.Joined.ToString()),
|
||||
new HashEntry("UsedNames", JsonSerializer.Serialize(user.UsedNames)),
|
||||
new HashEntry("UsedNames", JsonSerializer.Serialize(user.UsedNames))
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -67,7 +64,7 @@ namespace Geekbot.net.Lib
|
|||
try
|
||||
{
|
||||
var user = _redis.HashGetAll($"Users:{userId.ToString()}");
|
||||
for (int i = 1; i < 11; i++)
|
||||
for (var i = 1; i < 11; i++)
|
||||
{
|
||||
if (user.Length != 0) break;
|
||||
user = _redis.HashGetAll($"Users:{(userId + (ulong) i).ToString()}");
|
||||
|
@ -88,7 +85,7 @@ namespace Geekbot.net.Lib
|
|||
dto.Discriminator = a.Value.ToString();
|
||||
break;
|
||||
case "AvatarUrl":
|
||||
dto.AvatarUrl = (a.Value != "0") ? a.Value.ToString() : null;
|
||||
dto.AvatarUrl = a.Value != "0" ? a.Value.ToString() : null;
|
||||
break;
|
||||
case "IsBot":
|
||||
dto.IsBot = a.Value == 1;
|
||||
|
@ -110,14 +107,14 @@ namespace Geekbot.net.Lib
|
|||
}
|
||||
}
|
||||
|
||||
public string getUserSetting(ulong userId, string setting)
|
||||
public string GetUserSetting(ulong userId, string setting)
|
||||
{
|
||||
return _redis.HashGet($"Users:{userId}", setting);
|
||||
}
|
||||
|
||||
public bool saveUserSetting(ulong userId, string setting, string value)
|
||||
public bool SaveUserSetting(ulong userId, string setting, string value)
|
||||
{
|
||||
_redis.HashSet($"Users:{userId}", new HashEntry[]
|
||||
_redis.HashSet($"Users:{userId}", new[]
|
||||
{
|
||||
new HashEntry(setting, value)
|
||||
});
|
||||
|
@ -140,7 +137,7 @@ namespace Geekbot.net.Lib
|
|||
{
|
||||
Task<bool> Update(SocketUser user);
|
||||
UserRepositoryUser Get(ulong userId);
|
||||
string getUserSetting(ulong userId, string setting);
|
||||
bool saveUserSetting(ulong userId, string setting, string value);
|
||||
string GetUserSetting(ulong userId, string setting);
|
||||
bool SaveUserSetting(ulong userId, string setting, string value);
|
||||
}
|
||||
}
|
|
@ -18,16 +18,16 @@ namespace Geekbot.net
|
|||
{
|
||||
internal class Program
|
||||
{
|
||||
private DiscordSocketClient client;
|
||||
private CommandService commands;
|
||||
private IDatabase redis;
|
||||
private IServiceCollection services;
|
||||
private IServiceProvider servicesProvider;
|
||||
private RedisValue token;
|
||||
private IGeekbotLogger logger;
|
||||
private IUserRepository userRepository;
|
||||
private string[] args;
|
||||
private bool firstStart = false;
|
||||
private DiscordSocketClient _client;
|
||||
private CommandService _commands;
|
||||
private IDatabase _redis;
|
||||
private IServiceCollection _services;
|
||||
private IServiceProvider _servicesProvider;
|
||||
private RedisValue _token;
|
||||
private IGeekbotLogger _logger;
|
||||
private IUserRepository _userRepository;
|
||||
private string[] _args;
|
||||
private bool _firstStart;
|
||||
|
||||
private static void Main(string[] args)
|
||||
{
|
||||
|
@ -53,23 +53,23 @@ namespace Geekbot.net
|
|||
|
||||
private async Task MainAsync(string[] args, IGeekbotLogger logger)
|
||||
{
|
||||
this.logger = logger;
|
||||
this.args = args;
|
||||
_logger = logger;
|
||||
_args = args;
|
||||
logger.Information("Geekbot", "Initing Stuff");
|
||||
|
||||
client = new DiscordSocketClient(new DiscordSocketConfig
|
||||
_client = new DiscordSocketClient(new DiscordSocketConfig
|
||||
{
|
||||
LogLevel = LogSeverity.Verbose,
|
||||
MessageCacheSize = 1000
|
||||
});
|
||||
client.Log += DiscordLogger;
|
||||
commands = new CommandService();
|
||||
_client.Log += DiscordLogger;
|
||||
_commands = new CommandService();
|
||||
|
||||
try
|
||||
{
|
||||
var redisMultiplexer = ConnectionMultiplexer.Connect("127.0.0.1:6379");
|
||||
redis = redisMultiplexer.GetDatabase(6);
|
||||
logger.Information("Redis", $"Connected to db {redis.Database}");
|
||||
_redis = redisMultiplexer.GetDatabase(6);
|
||||
logger.Information("Redis", $"Connected to db {_redis.Database}");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
|
@ -77,40 +77,38 @@ namespace Geekbot.net
|
|||
Environment.Exit(102);
|
||||
}
|
||||
|
||||
token = redis.StringGet("discordToken");
|
||||
if (token.IsNullOrEmpty)
|
||||
_token = _redis.StringGet("discordToken");
|
||||
if (_token.IsNullOrEmpty)
|
||||
{
|
||||
Console.Write("Your bot Token: ");
|
||||
var newToken = Console.ReadLine();
|
||||
redis.StringSet("discordToken", newToken);
|
||||
redis.StringSet("Game", "Ping Pong");
|
||||
token = newToken;
|
||||
firstStart = true;
|
||||
_redis.StringSet("discordToken", newToken);
|
||||
_redis.StringSet("Game", "Ping Pong");
|
||||
_token = newToken;
|
||||
_firstStart = true;
|
||||
}
|
||||
|
||||
services = new ServiceCollection();
|
||||
_services = new ServiceCollection();
|
||||
|
||||
userRepository = new UserRepository(redis, logger);
|
||||
_userRepository = new UserRepository(_redis, logger);
|
||||
var fortunes = new FortunesProvider(logger);
|
||||
var mediaProvider = new MediaProvider(logger);
|
||||
var malClient = new MalClient(redis, logger);
|
||||
var malClient = new MalClient(_redis, logger);
|
||||
var levelCalc = new LevelCalc();
|
||||
var emojiConverter = new EmojiConverter();
|
||||
var audioUtils = new AudioUtils();
|
||||
var mtgManaConverter = new MtgManaConverter();
|
||||
var wikipediaClient = new WikipediaClient();
|
||||
|
||||
services.AddSingleton(redis);
|
||||
services.AddSingleton<IGeekbotLogger>(logger);
|
||||
services.AddSingleton<IUserRepository>(userRepository);
|
||||
services.AddSingleton<ILevelCalc>(levelCalc);
|
||||
services.AddSingleton<IEmojiConverter>(emojiConverter);
|
||||
services.AddSingleton<IAudioUtils>(audioUtils);
|
||||
services.AddSingleton<IFortunesProvider>(fortunes);
|
||||
services.AddSingleton<IMediaProvider>(mediaProvider);
|
||||
services.AddSingleton<IMalClient>(malClient);
|
||||
services.AddSingleton<IMtgManaConverter>(mtgManaConverter);
|
||||
services.AddSingleton<IWikipediaClient>(wikipediaClient);
|
||||
_services.AddSingleton(_redis);
|
||||
_services.AddSingleton(logger);
|
||||
_services.AddSingleton(_userRepository);
|
||||
_services.AddSingleton<ILevelCalc>(levelCalc);
|
||||
_services.AddSingleton<IEmojiConverter>(emojiConverter);
|
||||
_services.AddSingleton<IFortunesProvider>(fortunes);
|
||||
_services.AddSingleton<IMediaProvider>(mediaProvider);
|
||||
_services.AddSingleton<IMalClient>(malClient);
|
||||
_services.AddSingleton<IMtgManaConverter>(mtgManaConverter);
|
||||
_services.AddSingleton<IWikipediaClient>(wikipediaClient);
|
||||
|
||||
logger.Information("Geekbot", "Connecting to Discord");
|
||||
|
||||
|
@ -123,94 +121,94 @@ namespace Geekbot.net
|
|||
{
|
||||
try
|
||||
{
|
||||
await client.LoginAsync(TokenType.Bot, token);
|
||||
await client.StartAsync();
|
||||
var isConneted = await isConnected();
|
||||
await _client.LoginAsync(TokenType.Bot, _token);
|
||||
await _client.StartAsync();
|
||||
var isConneted = await IsConnected();
|
||||
if (isConneted)
|
||||
{
|
||||
await client.SetGameAsync(redis.StringGet("Game"));
|
||||
logger.Information("Geekbot", $"Now Connected as {client.CurrentUser.Username} to {client.Guilds.Count} Servers");
|
||||
await _client.SetGameAsync(_redis.StringGet("Game"));
|
||||
_logger.Information("Geekbot", $"Now Connected as {_client.CurrentUser.Username} to {_client.Guilds.Count} Servers");
|
||||
|
||||
logger.Information("Geekbot", "Registering Stuff");
|
||||
var translationHandler = new TranslationHandler(client.Guilds, redis, logger);
|
||||
var errorHandler = new ErrorHandler(logger, translationHandler, args.Contains("--expose-errors"));
|
||||
var reactionListener = new ReactionListener(redis);
|
||||
await commands.AddModulesAsync(Assembly.GetEntryAssembly());
|
||||
services.AddSingleton(commands);
|
||||
services.AddSingleton<IErrorHandler>(errorHandler);
|
||||
services.AddSingleton<ITranslationHandler>(translationHandler);
|
||||
services.AddSingleton<DiscordSocketClient>(client);
|
||||
services.AddSingleton<IReactionListener>(reactionListener);
|
||||
servicesProvider = services.BuildServiceProvider();
|
||||
_logger.Information("Geekbot", "Registering Stuff");
|
||||
var translationHandler = new TranslationHandler(_client.Guilds, _redis, _logger);
|
||||
var errorHandler = new ErrorHandler(_logger, translationHandler, _args.Contains("--expose-errors"));
|
||||
var reactionListener = new ReactionListener(_redis);
|
||||
await _commands.AddModulesAsync(Assembly.GetEntryAssembly());
|
||||
_services.AddSingleton(_commands);
|
||||
_services.AddSingleton<IErrorHandler>(errorHandler);
|
||||
_services.AddSingleton<ITranslationHandler>(translationHandler);
|
||||
_services.AddSingleton(_client);
|
||||
_services.AddSingleton<IReactionListener>(reactionListener);
|
||||
_servicesProvider = _services.BuildServiceProvider();
|
||||
|
||||
var handlers = new Handlers(client, logger, redis, servicesProvider, commands, userRepository, reactionListener);
|
||||
var handlers = new Handlers(_client, _logger, _redis, _servicesProvider, _commands, _userRepository, reactionListener);
|
||||
|
||||
client.MessageReceived += handlers.RunCommand;
|
||||
client.MessageReceived += handlers.UpdateStats;
|
||||
client.MessageDeleted += handlers.MessageDeleted;
|
||||
client.UserJoined += handlers.UserJoined;
|
||||
client.UserUpdated += handlers.UserUpdated;
|
||||
client.UserLeft += handlers.UserLeft;
|
||||
client.ReactionAdded += handlers.ReactionAdded;
|
||||
client.ReactionRemoved += handlers.ReactionRemoved;
|
||||
_client.MessageReceived += handlers.RunCommand;
|
||||
_client.MessageReceived += handlers.UpdateStats;
|
||||
_client.MessageDeleted += handlers.MessageDeleted;
|
||||
_client.UserJoined += handlers.UserJoined;
|
||||
_client.UserUpdated += handlers.UserUpdated;
|
||||
_client.UserLeft += handlers.UserLeft;
|
||||
_client.ReactionAdded += handlers.ReactionAdded;
|
||||
_client.ReactionRemoved += handlers.ReactionRemoved;
|
||||
|
||||
if (firstStart || args.Contains("--reset"))
|
||||
if (_firstStart || _args.Contains("--reset"))
|
||||
{
|
||||
logger.Information("Geekbot", "Finishing setup");
|
||||
_logger.Information("Geekbot", "Finishing setup");
|
||||
await FinishSetup();
|
||||
logger.Information("Geekbot", "Setup finished");
|
||||
_logger.Information("Geekbot", "Setup finished");
|
||||
}
|
||||
if (!args.Contains("--disable-api"))
|
||||
if (!_args.Contains("--disable-api"))
|
||||
{
|
||||
startWebApi();
|
||||
StartWebApi();
|
||||
}
|
||||
|
||||
logger.Information("Geekbot", "Done and ready for use");
|
||||
_logger.Information("Geekbot", "Done and ready for use");
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.Error("Discord", "Could not connect...", e);
|
||||
_logger.Error("Discord", "Could not connect...", e);
|
||||
Environment.Exit(103);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<bool> isConnected()
|
||||
private async Task<bool> IsConnected()
|
||||
{
|
||||
while (!client.ConnectionState.Equals(ConnectionState.Connected))
|
||||
while (!_client.ConnectionState.Equals(ConnectionState.Connected))
|
||||
await Task.Delay(25);
|
||||
return true;
|
||||
}
|
||||
|
||||
private void startWebApi()
|
||||
private void StartWebApi()
|
||||
{
|
||||
logger.Information("API", "Starting Webserver");
|
||||
_logger.Information("API", "Starting Webserver");
|
||||
var webApiUrl = new Uri("http://localhost:12995");
|
||||
new NancyHost(webApiUrl).Start();
|
||||
logger.Information("API", $"Webserver now running on {webApiUrl}");
|
||||
_logger.Information("API", $"Webserver now running on {webApiUrl}");
|
||||
}
|
||||
|
||||
private async Task<Task> FinishSetup()
|
||||
{
|
||||
var appInfo = await client.GetApplicationInfoAsync();
|
||||
logger.Information("Setup", $"Just a moment while i setup everything {appInfo.Owner.Username}");
|
||||
var appInfo = await _client.GetApplicationInfoAsync();
|
||||
_logger.Information("Setup", $"Just a moment while i setup everything {appInfo.Owner.Username}");
|
||||
try
|
||||
{
|
||||
redis.StringSet("botOwner", appInfo.Owner.Id);
|
||||
var req = HttpWebRequest.Create(appInfo.IconUrl);
|
||||
_redis.StringSet("botOwner", appInfo.Owner.Id);
|
||||
var req = WebRequest.Create(appInfo.IconUrl);
|
||||
using (var stream = req.GetResponse().GetResponseStream())
|
||||
{
|
||||
await client.CurrentUser.ModifyAsync(User =>
|
||||
await _client.CurrentUser.ModifyAsync(user =>
|
||||
{
|
||||
User.Avatar = new Image(stream);
|
||||
User.Username = appInfo.Name.ToString();
|
||||
user.Avatar = new Image(stream);
|
||||
user.Username = appInfo.Name.ToString();
|
||||
});
|
||||
}
|
||||
logger.Information("Setup", "Everything done, enjoy!");
|
||||
_logger.Information("Setup", "Everything done, enjoy!");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.Warning("Setup", "Oha, it seems like something went wrong while running the setup, geekbot will work never the less though", e);
|
||||
_logger.Warning("Setup", "Oha, it seems like something went wrong while running the setup, geekbot will work never the less though", e);
|
||||
}
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
@ -222,19 +220,19 @@ namespace Geekbot.net
|
|||
{
|
||||
case LogSeverity.Verbose:
|
||||
case LogSeverity.Debug:
|
||||
logger.Debug(message.Source, message.Message);
|
||||
_logger.Debug(message.Source, message.Message);
|
||||
break;
|
||||
case LogSeverity.Info:
|
||||
logger.Information(message.Source, message.Message);
|
||||
_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);
|
||||
_logger.Error(message.Source, message.Message, message.Exception);
|
||||
break;
|
||||
default:
|
||||
logger.Information(message.Source, $"{logMessage} --- {message.Severity}");
|
||||
_logger.Information(message.Source, $"{logMessage} --- {message.Severity}");
|
||||
break;
|
||||
}
|
||||
return Task.CompletedTask;
|
||||
|
|
|
@ -3,10 +3,9 @@ using System.Collections.Generic;
|
|||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Threading.Tasks;
|
||||
using Discord;
|
||||
using Discord.Commands;
|
||||
using Nancy;
|
||||
using Geekbot.net.Lib;
|
||||
using Nancy;
|
||||
|
||||
namespace Geekbot.net.WebApi
|
||||
{
|
||||
|
@ -16,25 +15,18 @@ namespace Geekbot.net.WebApi
|
|||
{
|
||||
Get("/v1/commands", args =>
|
||||
{
|
||||
var commands = getCommands().Result;
|
||||
var commands = GetCommands().Result;
|
||||
|
||||
var commandList = new List<CommandDto>();
|
||||
foreach (var cmd in commands.Commands)
|
||||
{
|
||||
var cmdParamsObj = new List<CommandParamDto>();
|
||||
foreach (var cmdParam in cmd.Parameters)
|
||||
{
|
||||
var singleParamObj = new CommandParamDto()
|
||||
var commandList = (from cmd in commands.Commands
|
||||
let cmdParamsObj = cmd.Parameters.Select(cmdParam => new CommandParamDto
|
||||
{
|
||||
Summary = cmdParam.Summary,
|
||||
Default = cmdParam?.DefaultValue?.ToString() ?? null,
|
||||
Type = cmdParam?.Type?.ToString()
|
||||
};
|
||||
cmdParamsObj.Add(singleParamObj);
|
||||
}
|
||||
|
||||
var param = string.Join(", !", cmd.Aliases);
|
||||
var cmdObj = new CommandDto()
|
||||
Default = cmdParam.DefaultValue?.ToString() ?? null,
|
||||
Type = cmdParam.Type?.ToString()
|
||||
})
|
||||
.ToList()
|
||||
let param = string.Join(", !", cmd.Aliases)
|
||||
select new CommandDto
|
||||
{
|
||||
Name = cmd.Name,
|
||||
Summary = cmd.Summary,
|
||||
|
@ -42,15 +34,13 @@ namespace Geekbot.net.WebApi
|
|||
IsAdminCommand = (param.Contains("admin")),
|
||||
Aliases = cmd.Aliases.ToArray(),
|
||||
Params = cmdParamsObj
|
||||
};
|
||||
commandList.Add(cmdObj);
|
||||
}
|
||||
}).ToList();
|
||||
return Response.AsJson(commandList);
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
private async Task<CommandService> getCommands()
|
||||
private async Task<CommandService> GetCommands()
|
||||
{
|
||||
var commands = new CommandService();
|
||||
await commands.AddModulesAsync(Assembly.GetEntryAssembly());
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
using Nancy;
|
||||
using Geekbot.net.Lib;
|
||||
using Geekbot.net.Lib;
|
||||
using Nancy;
|
||||
|
||||
namespace Geekbot.net.WebApi
|
||||
{
|
||||
|
@ -9,7 +9,7 @@ namespace Geekbot.net.WebApi
|
|||
{
|
||||
Get("/", args =>
|
||||
{
|
||||
var responseBody = new ApiStatusDto()
|
||||
var responseBody = new ApiStatusDto
|
||||
{
|
||||
GeekbotVersion = Constants.BotVersion.ToString(),
|
||||
ApiVersion = Constants.ApiVersion.ToString(),
|
||||
|
|
|
@ -1,11 +1,10 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using Geekbot.net.Lib;
|
||||
using Xunit;
|
||||
|
||||
namespace Tests.Lib
|
||||
{
|
||||
public class EmojiConverter_test
|
||||
public class EmojiConverterTest
|
||||
{
|
||||
public static IEnumerable<object[]> NumberToEmojiTestData
|
||||
{
|
||||
|
@ -42,11 +41,11 @@ namespace Tests.Lib
|
|||
public void NumberToEmoji(int number, string expectedResult)
|
||||
{
|
||||
var emojiConverter = new EmojiConverter();
|
||||
var result = emojiConverter.numberToEmoji(number);
|
||||
var result = emojiConverter.NumberToEmoji(number);
|
||||
Assert.Equal(result, expectedResult);
|
||||
}
|
||||
|
||||
public static IEnumerable<object[]> textToEmojiTestData
|
||||
public static IEnumerable<object[]> TextToEmojiTestData
|
||||
{
|
||||
get
|
||||
{
|
||||
|
@ -64,11 +63,11 @@ namespace Tests.Lib
|
|||
}
|
||||
|
||||
|
||||
[Theory, MemberData(nameof(textToEmojiTestData))]
|
||||
[Theory, MemberData(nameof(TextToEmojiTestData))]
|
||||
public void TextToEmoji(string text, string expectedResult)
|
||||
{
|
||||
var emojiConverter = new EmojiConverter();
|
||||
var result = emojiConverter.textToEmoji(text);
|
||||
var result = emojiConverter.TextToEmoji(text);
|
||||
Assert.Equal(result, expectedResult);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,11 +1,10 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using Geekbot.net.Lib;
|
||||
using Xunit;
|
||||
|
||||
namespace Tests.Lib
|
||||
{
|
||||
public class LevelCalc_test
|
||||
public class LevelCalcTest
|
||||
{
|
||||
public static IEnumerable<object[]> LevelCalcTestData
|
||||
{
|
||||
|
|
|
@ -2,7 +2,7 @@
|
|||
{
|
||||
public class PageCoordinates
|
||||
{
|
||||
public float lat { get; set; }
|
||||
public float lon { get; set; }
|
||||
public float Lat { get; set; }
|
||||
public float Lon { get; set; }
|
||||
}
|
||||
}
|
|
@ -1,5 +1,4 @@
|
|||
using System;
|
||||
using System.Runtime.Serialization;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Converters;
|
||||
|
||||
|
@ -18,7 +17,7 @@ namespace WikipediaApi.Page
|
|||
public string Displaytitle { get; set; }
|
||||
|
||||
[JsonProperty("namespace")]
|
||||
public PageNamespace @Namespace { get; set; }
|
||||
public PageNamespace Namespace { get; set; }
|
||||
|
||||
[JsonProperty("titles")]
|
||||
public PageTitles Titles { get; set; }
|
||||
|
|
|
@ -1,5 +1,4 @@
|
|||
using System;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
using Newtonsoft.Json;
|
||||
using WikipediaApi.Page;
|
||||
|
|
Loading…
Reference in a new issue