utility done

This commit is contained in:
Kwoth 2016-12-17 01:21:05 +01:00
parent 14876012f5
commit 091ea0fd32
5 changed files with 250 additions and 235 deletions

View File

@ -11,55 +11,60 @@ namespace NadekoBot.Modules.Utility
{
public partial class Utility
{
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task Calculate([Remainder] string expression)
[Group]
public class CalcCommands : ModuleBase
{
var expr = new NCalc.Expression(expression, NCalc.EvaluateOptions.IgnoreCase);
expr.EvaluateParameter += Expr_EvaluateParameter;
var result = expr.Evaluate();
if (expr.Error == null)
await Context.Channel.SendConfirmAsync("Result", $"{result}");
else
await Context.Channel.SendErrorAsync($"⚙ Error", expr.Error);
}
private static void Expr_EvaluateParameter(string name, NCalc.ParameterArgs args)
{
switch (name.ToLowerInvariant()) {
case "pi": args.Result= Math.PI;
break;
case "e": args.Result = Math.E;
break;
}
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task CalcOps()
{
var selection = typeof(Math).GetTypeInfo().GetMethods().Except(typeof(object).GetTypeInfo().GetMethods()).Distinct(new MethodInfoEqualityComparer()).Select(x =>
[NadekoCommand, Usage, Description, Aliases]
public async Task Calculate([Remainder] string expression)
{
return x.Name;
})
.Except(new[] { "ToString",
var expr = new NCalc.Expression(expression, NCalc.EvaluateOptions.IgnoreCase);
expr.EvaluateParameter += Expr_EvaluateParameter;
var result = expr.Evaluate();
if (expr.Error == null)
await Context.Channel.SendConfirmAsync("Result", $"{result}");
else
await Context.Channel.SendErrorAsync($"⚙ Error", expr.Error);
}
private static void Expr_EvaluateParameter(string name, NCalc.ParameterArgs args)
{
switch (name.ToLowerInvariant())
{
case "pi":
args.Result = Math.PI;
break;
case "e":
args.Result = Math.E;
break;
}
}
[NadekoCommand, Usage, Description, Aliases]
public async Task CalcOps()
{
var selection = typeof(Math).GetTypeInfo().GetMethods().Except(typeof(object).GetTypeInfo().GetMethods()).Distinct(new MethodInfoEqualityComparer()).Select(x =>
{
return x.Name;
})
.Except(new[] { "ToString",
"Equals",
"GetHashCode",
"GetType"});
await Context.Channel.SendConfirmAsync(string.Join(", ",selection));
await Context.Channel.SendConfirmAsync(string.Join(", ", selection));
}
}
class MethodInfoEqualityComparer : IEqualityComparer<MethodInfo>
{
public bool Equals(MethodInfo x, MethodInfo y) => x.Name == y.Name;
public int GetHashCode(MethodInfo obj) => obj.Name.GetHashCode();
}
class ExpressionContext
{
public double Pi { get; set; } = Math.PI;
}
}
class MethodInfoEqualityComparer : IEqualityComparer<MethodInfo>
{
public bool Equals(MethodInfo x, MethodInfo y) => x.Name == y.Name;
public int GetHashCode(MethodInfo obj) => obj.Name.GetHashCode();
}
class ExpressionContext
{
public double Pi { get; set; } = Math.PI;
}
}
}

View File

@ -11,88 +11,93 @@ namespace NadekoBot.Modules.Utility
{
public partial class Utility
{
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task ServerInfo(string guildName = null)
[Group]
public class InfoCommands : ModuleBase
{
var channel = (ITextChannel)Context.Channel;
guildName = guildName?.ToUpperInvariant();
IGuild guild;
if (string.IsNullOrWhiteSpace(guildName))
guild = channel.Guild;
else
guild = NadekoBot.Client.GetGuilds().Where(g => g.Name.ToUpperInvariant() == guildName.ToUpperInvariant()).FirstOrDefault();
if (guild == null)
return;
var ownername = await guild.GetUserAsync(guild.OwnerId);
var textchn = (await guild.GetTextChannelsAsync()).Count();
var voicechn = (await guild.GetVoiceChannelsAsync()).Count();
var createdAt = new DateTime(2015, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(guild.Id >> 22);
var sb = new StringBuilder();
var users = await guild.GetUsersAsync().ConfigureAwait(false);
var embed = new EmbedBuilder()
.WithAuthor(eab => eab.WithName("Server Info"))
.WithTitle(guild.Name)
.AddField(fb => fb.WithName("**ID**").WithValue(guild.Id.ToString()).WithIsInline(true))
.AddField(fb => fb.WithName("**Owner**").WithValue(ownername.ToString()).WithIsInline(true))
.AddField(fb => fb.WithName("**Members**").WithValue(users.Count.ToString()).WithIsInline(true))
.AddField(fb => fb.WithName("**Text Channels**").WithValue(textchn.ToString()).WithIsInline(true))
.AddField(fb => fb.WithName("**Voice Channels**").WithValue(voicechn.ToString()).WithIsInline(true))
.AddField(fb => fb.WithName("**Created At**").WithValue($"{createdAt.ToString("dd.MM.yyyy HH:mm")}").WithIsInline(true))
.AddField(fb => fb.WithName("**Region**").WithValue(guild.VoiceRegionId.ToString()).WithIsInline(true))
.AddField(fb => fb.WithName("**Roles**").WithValue(guild.Roles.Count().ToString()).WithIsInline(true))
.WithImageUrl(guild.IconUrl)
.WithColor(NadekoBot.OkColor);
if (guild.Emojis.Count() > 0)
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task ServerInfo(string guildName = null)
{
embed.AddField(fb => fb.WithName("**Custom Emojis**").WithValue(Format.Italics(string.Join(", ", guild.Emojis))).WithIsInline(true));
var channel = (ITextChannel)Context.Channel;
guildName = guildName?.ToUpperInvariant();
IGuild guild;
if (string.IsNullOrWhiteSpace(guildName))
guild = channel.Guild;
else
guild = NadekoBot.Client.GetGuilds().Where(g => g.Name.ToUpperInvariant() == guildName.ToUpperInvariant()).FirstOrDefault();
if (guild == null)
return;
var ownername = await guild.GetUserAsync(guild.OwnerId);
var textchn = (await guild.GetTextChannelsAsync()).Count();
var voicechn = (await guild.GetVoiceChannelsAsync()).Count();
var createdAt = new DateTime(2015, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(guild.Id >> 22);
var sb = new StringBuilder();
var users = await guild.GetUsersAsync().ConfigureAwait(false);
var embed = new EmbedBuilder()
.WithAuthor(eab => eab.WithName("Server Info"))
.WithTitle(guild.Name)
.AddField(fb => fb.WithName("**ID**").WithValue(guild.Id.ToString()).WithIsInline(true))
.AddField(fb => fb.WithName("**Owner**").WithValue(ownername.ToString()).WithIsInline(true))
.AddField(fb => fb.WithName("**Members**").WithValue(users.Count.ToString()).WithIsInline(true))
.AddField(fb => fb.WithName("**Text Channels**").WithValue(textchn.ToString()).WithIsInline(true))
.AddField(fb => fb.WithName("**Voice Channels**").WithValue(voicechn.ToString()).WithIsInline(true))
.AddField(fb => fb.WithName("**Created At**").WithValue($"{createdAt.ToString("dd.MM.yyyy HH:mm")}").WithIsInline(true))
.AddField(fb => fb.WithName("**Region**").WithValue(guild.VoiceRegionId.ToString()).WithIsInline(true))
.AddField(fb => fb.WithName("**Roles**").WithValue(guild.Roles.Count().ToString()).WithIsInline(true))
.WithImageUrl(guild.IconUrl)
.WithColor(NadekoBot.OkColor);
if (guild.Emojis.Count() > 0)
{
embed.AddField(fb => fb.WithName("**Custom Emojis**").WithValue(Format.Italics(string.Join(", ", guild.Emojis))).WithIsInline(true));
}
await Context.Channel.EmbedAsync(embed).ConfigureAwait(false);
}
await Context.Channel.EmbedAsync(embed).ConfigureAwait(false);
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task ChannelInfo(ITextChannel channel = null)
{
var ch = channel ?? (ITextChannel)Context.Channel;
if (ch == null)
return;
var createdAt = new DateTime(2015, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(ch.Id >> 22);
var usercount = (await ch.GetUsersAsync().Flatten()).Count();
var embed = new EmbedBuilder()
.WithTitle(ch.Name)
.WithDescription(ch.Topic?.SanitizeMentions())
.AddField(fb => fb.WithName("**ID**").WithValue(ch.Id.ToString()).WithIsInline(true))
.AddField(fb => fb.WithName("**Created At**").WithValue($"{createdAt.ToString("dd.MM.yyyy HH:mm")}").WithIsInline(true))
.AddField(fb => fb.WithName("**Users**").WithValue(usercount.ToString()).WithIsInline(true))
.WithColor(NadekoBot.OkColor);
await Context.Channel.EmbedAsync(embed).ConfigureAwait(false);
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task UserInfo(IGuildUser usr = null)
{
var channel = (ITextChannel)Context.Channel;
var user = usr ?? Context.User as IGuildUser;
if (user == null)
return;
var embed = new EmbedBuilder()
.AddField(fb => fb.WithName("**Name**").WithValue($"**{user.Username}**#{user.Discriminator}").WithIsInline(true));
if (!string.IsNullOrWhiteSpace(user.Nickname)) {
embed.AddField(fb => fb.WithName("**Nickname**").WithValue(user.Nickname).WithIsInline(true));
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task ChannelInfo(ITextChannel channel = null)
{
var ch = channel ?? (ITextChannel)Context.Channel;
if (ch == null)
return;
var createdAt = new DateTime(2015, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(ch.Id >> 22);
var usercount = (await ch.GetUsersAsync().Flatten()).Count();
var embed = new EmbedBuilder()
.WithTitle(ch.Name)
.WithDescription(ch.Topic?.SanitizeMentions())
.AddField(fb => fb.WithName("**ID**").WithValue(ch.Id.ToString()).WithIsInline(true))
.AddField(fb => fb.WithName("**Created At**").WithValue($"{createdAt.ToString("dd.MM.yyyy HH:mm")}").WithIsInline(true))
.AddField(fb => fb.WithName("**Users**").WithValue(usercount.ToString()).WithIsInline(true))
.WithColor(NadekoBot.OkColor);
await Context.Channel.EmbedAsync(embed).ConfigureAwait(false);
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task UserInfo(IGuildUser usr = null)
{
var channel = (ITextChannel)Context.Channel;
var user = usr ?? Context.User as IGuildUser;
if (user == null)
return;
var embed = new EmbedBuilder()
.AddField(fb => fb.WithName("**Name**").WithValue($"**{user.Username}**#{user.Discriminator}").WithIsInline(true));
if (!string.IsNullOrWhiteSpace(user.Nickname))
{
embed.AddField(fb => fb.WithName("**Nickname**").WithValue(user.Nickname).WithIsInline(true));
}
embed.AddField(fb => fb.WithName("**ID**").WithValue(user.Id.ToString()).WithIsInline(true))
.AddField(fb => fb.WithName("**Joined Server**").WithValue($"{user.JoinedAt?.ToString("dd.MM.yyyy HH:mm")}").WithIsInline(true))
.AddField(fb => fb.WithName("**Joined Discord**").WithValue($"{user.CreatedAt.ToString("dd.MM.yyyy HH:mm")}").WithIsInline(true))
.AddField(fb => fb.WithName("**Current Game**").WithValue($"{(user.Game?.Name == null ? "-" : user.Game.Value.Name)}").WithIsInline(true))
.AddField(fb => fb.WithName("**Roles**").WithValue($"**({user.RoleIds.Count})** - {string.Join(", ", user.Roles.Select(r => r.Name)).SanitizeMentions()}").WithIsInline(true))
.WithThumbnail(tn => tn.WithUrl(user.AvatarUrl))
.WithColor(NadekoBot.OkColor);
await Context.Channel.EmbedAsync(embed).ConfigureAwait(false);
}
embed.AddField(fb => fb.WithName("**ID**").WithValue(user.Id.ToString()).WithIsInline(true))
.AddField(fb => fb.WithName("**Joined Server**").WithValue($"{user.JoinedAt?.ToString("dd.MM.yyyy HH:mm")}").WithIsInline(true))
.AddField(fb => fb.WithName("**Joined Discord**").WithValue($"{user.CreatedAt.ToString("dd.MM.yyyy HH:mm")}").WithIsInline(true))
.AddField(fb => fb.WithName("**Current Game**").WithValue($"{(user.Game?.Name == null ? "-" : user.Game.Value.Name)}").WithIsInline(true))
.AddField(fb => fb.WithName("**Roles**").WithValue($"**({user.RoleIds.Count})** - {string.Join(", ", user.Roles.Select(r => r.Name)).SanitizeMentions()}").WithIsInline(true))
.WithThumbnail(tn => tn.WithUrl(user.AvatarUrl))
.WithColor(NadekoBot.OkColor);
await Context.Channel.EmbedAsync(embed).ConfigureAwait(false);
}
}
}
}

View File

@ -13,123 +13,127 @@ namespace NadekoBot.Modules.Utility
{
public partial class Utility
{
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task ListQuotes(int page = 1)
[Group]
public class QuoteCommands : ModuleBase
{
page -= 1;
if (page < 0)
return;
IEnumerable<Quote> quotes;
using (var uow = DbHandler.UnitOfWork())
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task ListQuotes(int page = 1)
{
quotes = uow.Quotes.GetGroup(Context.Guild.Id, page * 16, 16);
}
page -= 1;
if (quotes.Any())
await Context.Channel.SendConfirmAsync($"💬 **Page {page + 1} of quotes:**\n```xl\n" + String.Join("\n", quotes.Select((q) => $"{q.Keyword,-20} by {q.AuthorName}")) + "\n```")
.ConfigureAwait(false);
else
await Context.Channel.SendErrorAsync("No quotes on this page.").ConfigureAwait(false);
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task ShowQuote([Remainder] string keyword)
{
if (string.IsNullOrWhiteSpace(keyword))
return;
keyword = keyword.ToUpperInvariant();
Quote quote;
using (var uow = DbHandler.Instance.GetUnitOfWork())
{
quote = await uow.Quotes.GetRandomQuoteByKeywordAsync(Context.Guild.Id, keyword).ConfigureAwait(false);
}
if (quote == null)
return;
await Context.Channel.SendMessageAsync("📣 " + quote.Text.SanitizeMentions());
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task AddQuote(string keyword, [Remainder] string text)
{
if (string.IsNullOrWhiteSpace(keyword) || string.IsNullOrWhiteSpace(text))
return;
keyword = keyword.ToUpperInvariant();
using (var uow = DbHandler.UnitOfWork())
{
uow.Quotes.Add(new Quote
{
AuthorId = Context.Message.Author.Id,
AuthorName = Context.Message.Author.Username,
GuildId = Context.Guild.Id,
Keyword = keyword,
Text = text,
});
await uow.CompleteAsync().ConfigureAwait(false);
}
await Context.Channel.SendConfirmAsync("✅ Quote added.").ConfigureAwait(false);
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task DeleteQuote([Remainder] string keyword)
{
if (string.IsNullOrWhiteSpace(keyword))
return;
var isAdmin = ((IGuildUser)Context.Message.Author).GuildPermissions.Administrator;
keyword = keyword.ToUpperInvariant();
string response;
using (var uow = DbHandler.UnitOfWork())
{
var qs = uow.Quotes.GetAllQuotesByKeyword(Context.Guild.Id, keyword);
if (qs==null || !qs.Any())
{
await Context.Channel.SendErrorAsync("No quotes found.").ConfigureAwait(false);
if (page < 0)
return;
IEnumerable<Quote> quotes;
using (var uow = DbHandler.UnitOfWork())
{
quotes = uow.Quotes.GetGroup(Context.Guild.Id, page * 16, 16);
}
var q = qs.Shuffle().FirstOrDefault(elem => isAdmin || elem.AuthorId == Context.Message.Author.Id);
uow.Quotes.Remove(q);
await uow.CompleteAsync().ConfigureAwait(false);
response = "🗑 **Deleted a random quote.**";
if (quotes.Any())
await Context.Channel.SendConfirmAsync($"💬 **Page {page + 1} of quotes:**\n```xl\n" + String.Join("\n", quotes.Select((q) => $"{q.Keyword,-20} by {q.AuthorName}")) + "\n```")
.ConfigureAwait(false);
else
await Context.Channel.SendErrorAsync("No quotes on this page.").ConfigureAwait(false);
}
await Context.Channel.SendConfirmAsync(response);
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
[RequireUserPermission(GuildPermission.Administrator)]
public async Task DelAllQuotes([Remainder] string keyword)
{
if (string.IsNullOrWhiteSpace(keyword))
return;
keyword = keyword.ToUpperInvariant();
using (var uow = DbHandler.UnitOfWork())
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task ShowQuote([Remainder] string keyword)
{
var quotes = uow.Quotes.GetAllQuotesByKeyword(Context.Guild.Id, keyword);
if (string.IsNullOrWhiteSpace(keyword))
return;
uow.Quotes.RemoveRange(quotes.ToArray());//wtf?!
keyword = keyword.ToUpperInvariant();
await uow.CompleteAsync();
Quote quote;
using (var uow = DbHandler.Instance.GetUnitOfWork())
{
quote = await uow.Quotes.GetRandomQuoteByKeywordAsync(Context.Guild.Id, keyword).ConfigureAwait(false);
}
if (quote == null)
return;
await Context.Channel.SendMessageAsync("📣 " + quote.Text.SanitizeMentions());
}
await Context.Channel.SendConfirmAsync($"🗑 **Deleted all quotes** with **{keyword}** keyword.");
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task AddQuote(string keyword, [Remainder] string text)
{
if (string.IsNullOrWhiteSpace(keyword) || string.IsNullOrWhiteSpace(text))
return;
keyword = keyword.ToUpperInvariant();
using (var uow = DbHandler.UnitOfWork())
{
uow.Quotes.Add(new Quote
{
AuthorId = Context.Message.Author.Id,
AuthorName = Context.Message.Author.Username,
GuildId = Context.Guild.Id,
Keyword = keyword,
Text = text,
});
await uow.CompleteAsync().ConfigureAwait(false);
}
await Context.Channel.SendConfirmAsync("✅ Quote added.").ConfigureAwait(false);
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task DeleteQuote([Remainder] string keyword)
{
if (string.IsNullOrWhiteSpace(keyword))
return;
var isAdmin = ((IGuildUser)Context.Message.Author).GuildPermissions.Administrator;
keyword = keyword.ToUpperInvariant();
string response;
using (var uow = DbHandler.UnitOfWork())
{
var qs = uow.Quotes.GetAllQuotesByKeyword(Context.Guild.Id, keyword);
if (qs == null || !qs.Any())
{
await Context.Channel.SendErrorAsync("No quotes found.").ConfigureAwait(false);
return;
}
var q = qs.Shuffle().FirstOrDefault(elem => isAdmin || elem.AuthorId == Context.Message.Author.Id);
uow.Quotes.Remove(q);
await uow.CompleteAsync().ConfigureAwait(false);
response = "🗑 **Deleted a random quote.**";
}
await Context.Channel.SendConfirmAsync(response);
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
[RequireUserPermission(GuildPermission.Administrator)]
public async Task DelAllQuotes([Remainder] string keyword)
{
if (string.IsNullOrWhiteSpace(keyword))
return;
keyword = keyword.ToUpperInvariant();
using (var uow = DbHandler.UnitOfWork())
{
var quotes = uow.Quotes.GetAllQuotesByKeyword(Context.Guild.Id, keyword);
uow.Quotes.RemoveRange(quotes.ToArray());//wtf?!
await uow.CompleteAsync();
}
await Context.Channel.SendConfirmAsync($"🗑 **Deleted all quotes** with **{keyword}** keyword.");
}
}
}
}
}

View File

@ -22,7 +22,6 @@ namespace NadekoBot.Modules.Utility
[Group]
public class UnitConverterCommands : ModuleBase
{
public static List<ConvertUnit> Units { get; set; } = new List<ConvertUnit>();
private static Logger _log { get; }
private static Timer _timer;
@ -42,7 +41,7 @@ namespace NadekoBot.Modules.Utility
}).ToArray();
using (var uow = DbHandler.UnitOfWork())
{
{
if (uow.ConverterUnits.Empty())
{
uow.ConverterUnits.AddRange(data);
@ -64,7 +63,8 @@ namespace NadekoBot.Modules.Utility
}
public async Task UpdateCurrency()
{try
{
try
{
var currencyRates = await UpdateCurrencyRates();
var unitTypeString = "currency";
@ -95,18 +95,19 @@ namespace NadekoBot.Modules.Utility
Units.AddRange(range);
_log.Info("Updated Currency");
}
catch {
catch
{
_log.Warn("Failed updating currency.");
}
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task ConvertList()
{
var res = Units.GroupBy(x => x.UnitType)
.Aggregate(new EmbedBuilder().WithTitle("__Units which can be used by the converter__")
.WithColor(NadekoBot.OkColor),
(embed, g) => embed.AddField(efb =>
(embed, g) => embed.AddField(efb =>
efb.WithName(g.Key.ToTitleCase())
.WithValue(String.Join(", ", g.Select(x => x.Triggers.FirstOrDefault())
.OrderBy(x => x)))));

View File

@ -211,7 +211,7 @@ namespace NadekoBot.Modules.Utility
await channel.EmbedAsync(guilds.Aggregate(new EmbedBuilder().WithColor(NadekoBot.OkColor),
(embed, g) => embed.AddField(efb => efb.WithName(g.Name)
.WithValue($"```css\nID: {g.Id}\nMembers: {(g.GetUsersAsync().GetAwaiter().GetResult()).Count}\nOwnerID: {g.OwnerId} ```")
.WithValue($"```css\nID: {g.Id}\nMembers: {g.Users.Count}\nOwnerID: {g.OwnerId} ```")
.WithIsInline(false))))
.ConfigureAwait(false);
}