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 public partial class Utility
{ {
[NadekoCommand, Usage, Description, Aliases] [Group]
[RequireContext(ContextType.Guild)] public class CalcCommands : ModuleBase
public async Task Calculate([Remainder] string expression)
{ {
var expr = new NCalc.Expression(expression, NCalc.EvaluateOptions.IgnoreCase); [NadekoCommand, Usage, Description, Aliases]
expr.EvaluateParameter += Expr_EvaluateParameter; public async Task Calculate([Remainder] string expression)
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 =>
{ {
return x.Name; var expr = new NCalc.Expression(expression, NCalc.EvaluateOptions.IgnoreCase);
}) expr.EvaluateParameter += Expr_EvaluateParameter;
.Except(new[] { "ToString", 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", "Equals",
"GetHashCode", "GetHashCode",
"GetType"}); "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 public partial class Utility
{ {
[NadekoCommand, Usage, Description, Aliases] [Group]
[RequireContext(ContextType.Guild)] public class InfoCommands : ModuleBase
public async Task ServerInfo(string guildName = null)
{ {
var channel = (ITextChannel)Context.Channel; [NadekoCommand, Usage, Description, Aliases]
guildName = guildName?.ToUpperInvariant(); [RequireContext(ContextType.Guild)]
IGuild guild; public async Task ServerInfo(string guildName = null)
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)); 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] [NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)] [RequireContext(ContextType.Guild)]
public async Task ChannelInfo(ITextChannel channel = null) public async Task ChannelInfo(ITextChannel channel = null)
{ {
var ch = channel ?? (ITextChannel)Context.Channel; var ch = channel ?? (ITextChannel)Context.Channel;
if (ch == null) if (ch == null)
return; return;
var createdAt = new DateTime(2015, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(ch.Id >> 22); 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 usercount = (await ch.GetUsersAsync().Flatten()).Count();
var embed = new EmbedBuilder() var embed = new EmbedBuilder()
.WithTitle(ch.Name) .WithTitle(ch.Name)
.WithDescription(ch.Topic?.SanitizeMentions()) .WithDescription(ch.Topic?.SanitizeMentions())
.AddField(fb => fb.WithName("**ID**").WithValue(ch.Id.ToString()).WithIsInline(true)) .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("**Created At**").WithValue($"{createdAt.ToString("dd.MM.yyyy HH:mm")}").WithIsInline(true))
.AddField(fb => fb.WithName("**Users**").WithValue(usercount.ToString()).WithIsInline(true)) .AddField(fb => fb.WithName("**Users**").WithValue(usercount.ToString()).WithIsInline(true))
.WithColor(NadekoBot.OkColor); .WithColor(NadekoBot.OkColor);
await Context.Channel.EmbedAsync(embed).ConfigureAwait(false); await Context.Channel.EmbedAsync(embed).ConfigureAwait(false);
} }
[NadekoCommand, Usage, Description, Aliases] [NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)] [RequireContext(ContextType.Guild)]
public async Task UserInfo(IGuildUser usr = null) public async Task UserInfo(IGuildUser usr = null)
{ {
var channel = (ITextChannel)Context.Channel; var channel = (ITextChannel)Context.Channel;
var user = usr ?? Context.User as IGuildUser; var user = usr ?? Context.User as IGuildUser;
if (user == null) if (user == null)
return; return;
var embed = new EmbedBuilder() var embed = new EmbedBuilder()
.AddField(fb => fb.WithName("**Name**").WithValue($"**{user.Username}**#{user.Discriminator}").WithIsInline(true)); .AddField(fb => fb.WithName("**Name**").WithValue($"**{user.Username}**#{user.Discriminator}").WithIsInline(true));
if (!string.IsNullOrWhiteSpace(user.Nickname)) { if (!string.IsNullOrWhiteSpace(user.Nickname))
embed.AddField(fb => fb.WithName("**Nickname**").WithValue(user.Nickname).WithIsInline(true)); {
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 public partial class Utility
{ {
[NadekoCommand, Usage, Description, Aliases] [Group]
[RequireContext(ContextType.Guild)] public class QuoteCommands : ModuleBase
public async Task ListQuotes(int page = 1)
{ {
page -= 1; [NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
if (page < 0) public async Task ListQuotes(int page = 1)
return;
IEnumerable<Quote> quotes;
using (var uow = DbHandler.UnitOfWork())
{ {
quotes = uow.Quotes.GetGroup(Context.Guild.Id, page * 16, 16); page -= 1;
}
if (quotes.Any()) if (page < 0)
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);
return; 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); 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```")
uow.Quotes.Remove(q); .ConfigureAwait(false);
await uow.CompleteAsync().ConfigureAwait(false); else
response = "🗑 **Deleted a random quote.**"; await Context.Channel.SendErrorAsync("No quotes on this page.").ConfigureAwait(false);
} }
await Context.Channel.SendConfirmAsync(response);
}
[NadekoCommand, Usage, Description, Aliases] [NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)] [RequireContext(ContextType.Guild)]
[RequireUserPermission(GuildPermission.Administrator)] public async Task ShowQuote([Remainder] string keyword)
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); 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] [Group]
public class UnitConverterCommands : ModuleBase public class UnitConverterCommands : ModuleBase
{ {
public static List<ConvertUnit> Units { get; set; } = new List<ConvertUnit>(); public static List<ConvertUnit> Units { get; set; } = new List<ConvertUnit>();
private static Logger _log { get; } private static Logger _log { get; }
private static Timer _timer; private static Timer _timer;
@ -64,7 +63,8 @@ namespace NadekoBot.Modules.Utility
} }
public async Task UpdateCurrency() public async Task UpdateCurrency()
{try {
try
{ {
var currencyRates = await UpdateCurrencyRates(); var currencyRates = await UpdateCurrencyRates();
var unitTypeString = "currency"; var unitTypeString = "currency";
@ -95,12 +95,13 @@ namespace NadekoBot.Modules.Utility
Units.AddRange(range); Units.AddRange(range);
_log.Info("Updated Currency"); _log.Info("Updated Currency");
} }
catch { catch
{
_log.Warn("Failed updating currency."); _log.Warn("Failed updating currency.");
} }
} }
[NadekoCommand, Usage, Description, Aliases] [NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task ConvertList() public async Task ConvertList()
{ {
var res = Units.GroupBy(x => x.UnitType) var res = Units.GroupBy(x => x.UnitType)

View File

@ -211,7 +211,7 @@ namespace NadekoBot.Modules.Utility
await channel.EmbedAsync(guilds.Aggregate(new EmbedBuilder().WithColor(NadekoBot.OkColor), await channel.EmbedAsync(guilds.Aggregate(new EmbedBuilder().WithColor(NadekoBot.OkColor),
(embed, g) => embed.AddField(efb => efb.WithName(g.Name) (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)))) .WithIsInline(false))))
.ConfigureAwait(false); .ConfigureAwait(false);
} }