Port !owner, !admin, !mod, handlers (partial) and add globals to the db

This commit is contained in:
runebaas 2018-05-13 17:49:13 +02:00
parent 37ac7f56a8
commit bb8aee1eda
No known key found for this signature in database
GPG key ID: 2677AF508D0300D6
10 changed files with 265 additions and 174 deletions

View file

@ -1,11 +1,14 @@
using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using Geekbot.net.Lib;
using Geekbot.net.Database;
using Geekbot.net.Database.Models;
using Geekbot.net.Lib.ErrorHandling;
using Geekbot.net.Lib.Extensions;
using Geekbot.net.Lib.Localization;
using StackExchange.Redis;
@ -17,13 +20,13 @@ namespace Geekbot.net.Commands.Admin
{
private readonly DiscordSocketClient _client;
private readonly IErrorHandler _errorHandler;
private readonly IDatabase _redis;
private readonly DatabaseContext _database;
private readonly ITranslationHandler _translation;
public Admin(IDatabase redis, DiscordSocketClient client, IErrorHandler errorHandler,
public Admin(DatabaseContext database, DiscordSocketClient client, IErrorHandler errorHandler,
ITranslationHandler translationHandler)
{
_redis = redis;
_database = database;
_client = client;
_errorHandler = errorHandler;
_translation = translationHandler;
@ -33,7 +36,11 @@ namespace Geekbot.net.Commands.Admin
[Summary("Set a Welcome Message (use '$user' to mention the new joined user).")]
public async Task SetWelcomeMessage([Remainder] [Summary("message")] string welcomeMessage)
{
_redis.HashSet($"{Context.Guild.Id}:Settings", new[] {new HashEntry("WelcomeMsg", welcomeMessage)});
var guild = GetGuildSettings(Context.Guild.Id);
guild.WelcomeMessage = welcomeMessage;
_database.GuildSettings.Update(guild);
_database.SaveChanges();
var formatedMessage = welcomeMessage.Replace("$user", Context.User.Mention);
await ReplyAsync($"Welcome message has been changed\r\nHere is an example of how it would look:\r\n{formatedMessage}");
}
@ -44,13 +51,18 @@ namespace Geekbot.net.Commands.Admin
{
try
{
var m = await channel.SendMessageAsync("verifying...");
var guild = GetGuildSettings(Context.Guild.Id);
guild.ModChannel = channel.Id.AsLong();
_database.GuildSettings.Update(guild);
_database.SaveChanges();
var sb = new StringBuilder();
sb.AppendLine("Successfully saved mod channel, you can now do the following");
sb.AppendLine("- `!admin showleave true` - send message to mod channel when someone leaves");
sb.AppendLine("- `!admin showdel true` - send message to mod channel when someone deletes a message");
await channel.SendMessageAsync(sb.ToString());
_redis.HashSet($"{Context.Guild.Id}:Settings",
new[] {new HashEntry("ModChannel", channel.Id.ToString())});
sb.AppendLine("- `!admin showleave` - send message to mod channel when someone leaves");
sb.AppendLine("- `!admin showdel` - send message to mod channel when someone deletes a message");
await m.ModifyAsync(e => e.Content = sb.ToString());
}
catch (Exception e)
{
@ -59,56 +71,50 @@ namespace Geekbot.net.Commands.Admin
}
[Command("showleave", RunMode = RunMode.Async)]
[Summary("Notify modchannel when someone leaves")]
public async Task ShowLeave([Summary("true/false")] bool enabled)
[Summary("Toggle - notify modchannel when someone leaves")]
public async Task ShowLeave()
{
var modChannelId = ulong.Parse(_redis.HashGet($"{Context.Guild.Id}:Settings", "ModChannel"));
try
{
var modChannel = (ISocketMessageChannel) _client.GetChannel(modChannelId);
if (enabled)
{
await modChannel.SendMessageAsync("Saved - now sending messages here when someone leaves");
_redis.HashSet($"{Context.Guild.Id}:Settings", new[] {new HashEntry("ShowLeave", true)});
}
else
{
await modChannel.SendMessageAsync("Saved - stopping sending messages here when someone leaves");
_redis.HashSet($"{Context.Guild.Id}:Settings", new[] {new HashEntry("ShowLeave", false)});
}
var guild = GetGuildSettings(Context.Guild.Id);
var modChannel = await GetModChannel(guild.ModChannel.AsUlong());
if (modChannel == null) return;
guild.ShowLeave = !guild.ShowLeave;
_database.GuildSettings.Update(guild);
_database.SaveChanges();
await modChannel.SendMessageAsync(guild.ShowLeave
? "Saved - now sending messages here when someone leaves"
: "Saved - stopping sending messages here when someone leaves"
);
}
catch (Exception e)
{
_errorHandler.HandleCommandException(e, Context,
"Modchannel doesn't seem to exist, please set one with `!admin modchannel [channelId]`");
_errorHandler.HandleCommandException(e, Context);
}
}
[Command("showdel", RunMode = RunMode.Async)]
[Summary("Notify modchannel when someone deletes a message")]
public async Task ShowDelete([Summary("true/false")] bool enabled)
[Summary("Toggle - notify modchannel when someone deletes a message")]
public async Task ShowDelete()
{
var modChannelId = ulong.Parse(_redis.HashGet($"{Context.Guild.Id}:Settings", "ModChannel"));
try
{
var modChannel = (ISocketMessageChannel) _client.GetChannel(modChannelId);
if (enabled)
{
await modChannel.SendMessageAsync(
"Saved - now sending messages here when someone deletes a message");
_redis.HashSet($"{Context.Guild.Id}:Settings", new[] {new HashEntry("ShowDelete", true)});
}
else
{
await modChannel.SendMessageAsync(
"Saved - stopping sending messages here when someone deletes a message");
_redis.HashSet($"{Context.Guild.Id}:Settings", new[] {new HashEntry("ShowDelete", false)});
}
var guild = GetGuildSettings(Context.Guild.Id);
var modChannel = await GetModChannel(guild.ModChannel.AsUlong());
if (modChannel == null) return;
guild.ShowDelete = !guild.ShowDelete;
_database.GuildSettings.Update(guild);
_database.SaveChanges();
await modChannel.SendMessageAsync(guild.ShowDelete
? "Saved - now sending messages here when someone deletes a message"
: "Saved - stopping sending messages here when someone deletes a message"
);
}
catch (Exception e)
{
_errorHandler.HandleCommandException(e, Context,
"Modchannel doesn't seem to exist, please set one with `!admin modchannel [channelId]`");
_errorHandler.HandleCommandException(e, Context);
}
}
@ -122,6 +128,11 @@ namespace Geekbot.net.Commands.Admin
var success = _translation.SetLanguage(Context.Guild.Id, language);
if (success)
{
var guild = GetGuildSettings(Context.Guild.Id);
guild.Language = language;
_database.GuildSettings.Update(guild);
_database.SaveChanges();
var trans = _translation.GetDict(Context);
await ReplyAsync(trans["NewLanguageSet"]);
return;
@ -143,8 +154,11 @@ namespace Geekbot.net.Commands.Admin
try
{
var language = languageRaw.ToLower();
_redis.HashSet($"{Context.Guild.Id}:Settings", new[] {new HashEntry("WikiLang", language) });
var guild = GetGuildSettings(Context.Guild.Id);
guild.WikiLang = language;
_database.GuildSettings.Update(guild);
_database.SaveChanges();
await ReplyAsync($"Now using the {language} wikipedia");
}
catch (Exception e)
@ -152,21 +166,6 @@ namespace Geekbot.net.Commands.Admin
_errorHandler.HandleCommandException(e, Context);
}
}
[Command("lang", RunMode = RunMode.Async)]
[Summary("Change the bots language")]
public async Task GetLanguage()
{
try
{
var trans = _translation.GetDict(Context);
await ReplyAsync(trans["GetLanguage"]);
}
catch (Exception e)
{
_errorHandler.HandleCommandException(e, Context);
}
}
[Command("ping", RunMode = RunMode.Async)]
[Summary("Enable the ping reply.")]
@ -174,9 +173,11 @@ namespace Geekbot.net.Commands.Admin
{
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") });
await ReplyAsync(!current ? "i will reply to ping now" : "No more pongs...");
var guild = GetGuildSettings(Context.Guild.Id);
guild.Ping = !guild.Ping;
_database.GuildSettings.Update(guild);
_database.SaveChanges();
await ReplyAsync(guild.Ping ? "i will reply to ping now" : "No more pongs...");
}
catch (Exception e)
{
@ -184,5 +185,59 @@ namespace Geekbot.net.Commands.Admin
}
}
[Command("hui", RunMode = RunMode.Async)]
[Summary("Enable the ping reply.")]
public async Task ToggleHui()
{
try
{
var guild = GetGuildSettings(Context.Guild.Id);
guild.Hui = !guild.Hui;
_database.GuildSettings.Update(guild);
_database.SaveChanges();
await ReplyAsync(guild.Hui ? "i will reply to hui now" : "No more hui's...");
}
catch (Exception e)
{
_errorHandler.HandleCommandException(e, Context);
}
}
private GuildSettingsModel GetGuildSettings(ulong guildId)
{
var guild = _database.GuildSettings.FirstOrDefault(g => g.GuildId.Equals(guildId.AsLong()));
if (guild != null) return guild;
Console.WriteLine("Adding non-exist Guild Settings to database");
_database.GuildSettings.Add(new GuildSettingsModel()
{
GuildId = guildId.AsLong(),
Hui = false,
Ping = false,
Language = "en",
ShowDelete = false,
ShowLeave = false,
WikiLang = "en"
});
_database.SaveChanges();
return _database.GuildSettings.FirstOrDefault(g => g.GuildId.Equals(guildId.AsLong()));
}
private async Task<ISocketMessageChannel> GetModChannel(ulong channelId)
{
try
{
if(channelId == ulong.MinValue) throw new Exception();
var modChannel = (ISocketMessageChannel) _client.GetChannel(channelId);
if(modChannel == null) throw new Exception();
return modChannel;
}
catch
{
await ReplyAsync(
"Modchannel doesn't seem to exist, please set one with `!admin modchannel [channelId]`");
return null;
}
}
}
}

View file

@ -4,10 +4,8 @@ using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using Geekbot.net.Lib;
using Geekbot.net.Lib.ErrorHandling;
using Geekbot.net.Lib.UserRepository;
using StackExchange.Redis;
namespace Geekbot.net.Commands.Admin
{
@ -19,15 +17,12 @@ namespace Geekbot.net.Commands.Admin
{
private readonly DiscordSocketClient _client;
private readonly IErrorHandler _errorHandler;
private readonly IDatabase _redis;
private readonly IUserRepository _userRepository;
public Mod(IUserRepository userRepositry, IErrorHandler errorHandler, IDatabase redis,
DiscordSocketClient client)
public Mod(IUserRepository userRepositry, IErrorHandler errorHandler, DiscordSocketClient client)
{
_userRepository = userRepositry;
_errorHandler = errorHandler;
_redis = redis;
_client = client;
}
@ -49,39 +44,5 @@ namespace Geekbot.net.Commands.Admin
$"I don't have enough permissions do that");
}
}
[Command("kick", RunMode = RunMode.Async)]
[Summary("Ban a user")]
public async Task Kick([Summary("@user")] IUser userNormal,
[Summary("reason")] [Remainder] string reason = "none")
{
try
{
var user = (IGuildUser) userNormal;
if (reason == "none") reason = "No reason provided";
await user.GetOrCreateDMChannelAsync().Result.SendMessageAsync(
$"You have been kicked from {Context.Guild.Name} for the following reason: \"{reason}\"");
await user.KickAsync();
try
{
var modChannelId = ulong.Parse(_redis.HashGet($"{Context.Guild.Id}:Settings", "ModChannel"));
var modChannel = (ISocketMessageChannel) _client.GetChannel(modChannelId);
var eb = new EmbedBuilder();
eb.Title = ":x: User Kicked";
eb.AddInlineField("User", user.Username);
eb.AddInlineField("By Mod", Context.User.Username);
eb.AddField("Reason", reason);
await modChannel.SendMessageAsync("", false, eb.Build());
}
catch
{
await ReplyAsync($"{user.Username} was kicked for the following reason: \"{reason}\"");
}
}
catch (Exception e)
{
_errorHandler.HandleCommandException(e, Context, "I don't have enough permissions to kick someone");
}
}
}
}

View file

@ -1,11 +1,10 @@
using System;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using Geekbot.net.Database;
using Geekbot.net.Lib;
using Geekbot.net.Lib.ErrorHandling;
using Geekbot.net.Lib.GlobalSettings;
using Geekbot.net.Lib.Logger;
using Geekbot.net.Lib.UserRepository;
using StackExchange.Redis;
@ -19,11 +18,12 @@ namespace Geekbot.net.Commands.Admin
private readonly DiscordSocketClient _client;
private readonly IErrorHandler _errorHandler;
private readonly DatabaseContext _database;
private readonly IGlobalSettings _globalSettings;
private readonly IGeekbotLogger _logger;
private readonly IDatabase _redis;
private readonly IUserRepository _userRepository;
public Owner(IDatabase redis, DiscordSocketClient client, IGeekbotLogger logger, IUserRepository userRepositry, IErrorHandler errorHandler, DatabaseContext database)
public Owner(IDatabase redis, DiscordSocketClient client, IGeekbotLogger logger, IUserRepository userRepositry, IErrorHandler errorHandler, DatabaseContext database, IGlobalSettings globalSettings)
{
_redis = redis;
_client = client;
@ -31,6 +31,7 @@ namespace Geekbot.net.Commands.Admin
_userRepository = userRepositry;
_errorHandler = errorHandler;
_database = database;
_globalSettings = globalSettings;
}
[Command("migrate", RunMode = RunMode.Async)]
@ -55,7 +56,7 @@ namespace Geekbot.net.Commands.Admin
[Summary("Set the youtube api key")]
public async Task SetYoutubeKey([Summary("API Key")] string key)
{
_redis.StringSet("youtubeKey", key);
_globalSettings.SetKey("YoutubeKey", key);
await ReplyAsync("Apikey has been set");
}
@ -63,7 +64,7 @@ namespace Geekbot.net.Commands.Admin
[Summary("Set the game that the bot is playing")]
public async Task SetGame([Remainder] [Summary("Game")] string key)
{
_redis.StringSet("Game", key);
_globalSettings.SetKey("Game", key);
await _client.SetGameAsync(key);
_logger.Information(LogSource.Geekbot, $"Changed game to {key}");
await ReplyAsync($"Now Playing {key}");

View file

@ -4,22 +4,21 @@ using System.Net;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using Geekbot.net.Lib;
using Geekbot.net.Lib.ErrorHandling;
using Geekbot.net.Lib.GlobalSettings;
using Newtonsoft.Json;
using StackExchange.Redis;
namespace Geekbot.net.Commands.Integrations.Google
{
public class Google : ModuleBase
{
private readonly IErrorHandler _errorHandler;
private readonly IDatabase _redis;
private readonly IGlobalSettings _globalSettings;
public Google(IErrorHandler errorHandler, IDatabase redis)
public Google(IErrorHandler errorHandler, IGlobalSettings globalSettings)
{
_errorHandler = errorHandler;
_redis = redis;
_globalSettings = globalSettings;
}
[Command("google", RunMode = RunMode.Async)]
@ -30,12 +29,12 @@ namespace Geekbot.net.Commands.Integrations.Google
{
using (var client = new WebClient())
{
var apiKey = _redis.StringGet("googleGraphKey");
if (!apiKey.HasValue)
var apiKey = _globalSettings.GetKey("GoogleGraphKey");
if (string.IsNullOrEmpty(apiKey))
{
await ReplyAsync("No Google API key has been set, please contact my owner");
return;
}
}
var url = new Uri($"https://kgsearch.googleapis.com/v1/entities:search?languages=en&limit=1&query={searchText}&key={apiKey}");
var responseString = client.DownloadString(url);
@ -48,8 +47,10 @@ namespace Geekbot.net.Commands.Integrations.Google
}
var data = response.ItemListElement.First().Result;
var eb = new EmbedBuilder();
eb.Title = data.Name;
var eb = new EmbedBuilder
{
Title = data.Name
};
if(!string.IsNullOrEmpty(data.Description)) eb.WithDescription(data.Description);
if(!string.IsNullOrEmpty(data.DetailedDtoDescription?.Url)) eb.WithUrl(data.DetailedDtoDescription.Url);
if(!string.IsNullOrEmpty(data.DetailedDtoDescription?.ArticleBody)) eb.AddField("Details", data.DetailedDtoDescription.ArticleBody);

View file

@ -1,22 +1,21 @@
using System;
using System.Threading.Tasks;
using Discord.Commands;
using Geekbot.net.Lib;
using Geekbot.net.Lib.ErrorHandling;
using Geekbot.net.Lib.GlobalSettings;
using Google.Apis.Services;
using Google.Apis.YouTube.v3;
using StackExchange.Redis;
namespace Geekbot.net.Commands.Integrations
{
public class Youtube : ModuleBase
{
private readonly IGlobalSettings _globalSettings;
private readonly IErrorHandler _errorHandler;
private readonly IDatabase _redis;
public Youtube(IDatabase redis, IErrorHandler errorHandler)
public Youtube(IGlobalSettings globalSettings, IErrorHandler errorHandler)
{
_redis = redis;
_globalSettings = globalSettings;
_errorHandler = errorHandler;
}
@ -24,8 +23,8 @@ namespace Geekbot.net.Commands.Integrations
[Summary("Search for something on youtube.")]
public async Task Yt([Remainder] [Summary("Title")] string searchQuery)
{
var key = _redis.StringGet("youtubeKey");
if (key.IsNullOrEmpty)
var key = _globalSettings.GetKey("YoutubeKey");
if (string.IsNullOrEmpty(key))
{
await ReplyAsync("No youtube key set, please tell my senpai to set one");
return;
@ -35,7 +34,7 @@ namespace Geekbot.net.Commands.Integrations
{
var youtubeService = new YouTubeService(new BaseClientService.Initializer
{
ApiKey = key.ToString(),
ApiKey = key,
ApplicationName = GetType().ToString()
});

View file

@ -7,7 +7,6 @@ using Discord.Commands;
using Discord.WebSocket;
using Geekbot.net.Lib;
using Geekbot.net.Lib.ErrorHandling;
using StackExchange.Redis;
namespace Geekbot.net.Commands.Utils
{
@ -16,11 +15,9 @@ namespace Geekbot.net.Commands.Utils
private readonly DiscordSocketClient _client;
private readonly CommandService _commands;
private readonly IErrorHandler _errorHandler;
private readonly IDatabase _redis;
public Info(IDatabase redis, IErrorHandler errorHandler, DiscordSocketClient client, CommandService commands)
public Info(IErrorHandler errorHandler, DiscordSocketClient client, CommandService commands)
{
_redis = redis;
_errorHandler = errorHandler;
_client = client;
_commands = commands;
@ -37,7 +34,7 @@ namespace Geekbot.net.Commands.Utils
eb.WithAuthor(new EmbedAuthorBuilder()
.WithIconUrl(_client.CurrentUser.GetAvatarUrl())
.WithName($"{Constants.Name} V{Constants.BotVersion()}"));
var botOwner = await Context.Guild.GetUserAsync(ulong.Parse(_redis.StringGet("botOwner")));
var botOwner = (await _client.GetApplicationInfoAsync()).Owner;
var uptime = DateTime.Now.Subtract(Process.GetCurrentProcess().StartTime);
eb.AddInlineField("Bot Name", _client.CurrentUser.Username);