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;
using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Discord.WebSocket; 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.ErrorHandling;
using Geekbot.net.Lib.Extensions;
using Geekbot.net.Lib.Localization; using Geekbot.net.Lib.Localization;
using StackExchange.Redis; using StackExchange.Redis;
@ -17,13 +20,13 @@ namespace Geekbot.net.Commands.Admin
{ {
private readonly DiscordSocketClient _client; private readonly DiscordSocketClient _client;
private readonly IErrorHandler _errorHandler; private readonly IErrorHandler _errorHandler;
private readonly IDatabase _redis; private readonly DatabaseContext _database;
private readonly ITranslationHandler _translation; private readonly ITranslationHandler _translation;
public Admin(IDatabase redis, DiscordSocketClient client, IErrorHandler errorHandler, public Admin(DatabaseContext database, DiscordSocketClient client, IErrorHandler errorHandler,
ITranslationHandler translationHandler) ITranslationHandler translationHandler)
{ {
_redis = redis; _database = database;
_client = client; _client = client;
_errorHandler = errorHandler; _errorHandler = errorHandler;
_translation = translationHandler; _translation = translationHandler;
@ -33,7 +36,11 @@ namespace Geekbot.net.Commands.Admin
[Summary("Set a Welcome Message (use '$user' to mention the new joined user).")] [Summary("Set a Welcome Message (use '$user' to mention the new joined user).")]
public async Task SetWelcomeMessage([Remainder] [Summary("message")] string welcomeMessage) public async Task SetWelcomeMessage([Remainder] [Summary("message")] string welcomeMessage)
{ {
_redis.HashSet($"{Context.Guild.Id}:Settings", new[] {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); 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}"); 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 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(); var sb = new StringBuilder();
sb.AppendLine("Successfully saved mod channel, you can now do the following"); 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 showleave` - send message to mod channel when someone leaves");
sb.AppendLine("- `!admin showdel true` - send message to mod channel when someone deletes a message"); sb.AppendLine("- `!admin showdel` - send message to mod channel when someone deletes a message");
await channel.SendMessageAsync(sb.ToString()); await m.ModifyAsync(e => e.Content = sb.ToString());
_redis.HashSet($"{Context.Guild.Id}:Settings",
new[] {new HashEntry("ModChannel", channel.Id.ToString())});
} }
catch (Exception e) catch (Exception e)
{ {
@ -59,56 +71,50 @@ namespace Geekbot.net.Commands.Admin
} }
[Command("showleave", RunMode = RunMode.Async)] [Command("showleave", RunMode = RunMode.Async)]
[Summary("Notify modchannel when someone leaves")] [Summary("Toggle - notify modchannel when someone leaves")]
public async Task ShowLeave([Summary("true/false")] bool enabled) public async Task ShowLeave()
{ {
var modChannelId = ulong.Parse(_redis.HashGet($"{Context.Guild.Id}:Settings", "ModChannel"));
try try
{ {
var modChannel = (ISocketMessageChannel) _client.GetChannel(modChannelId); var guild = GetGuildSettings(Context.Guild.Id);
if (enabled) var modChannel = await GetModChannel(guild.ModChannel.AsUlong());
{ if (modChannel == null) return;
await modChannel.SendMessageAsync("Saved - now sending messages here when someone leaves");
_redis.HashSet($"{Context.Guild.Id}:Settings", new[] {new HashEntry("ShowLeave", true)}); guild.ShowLeave = !guild.ShowLeave;
} _database.GuildSettings.Update(guild);
else _database.SaveChanges();
{ await modChannel.SendMessageAsync(guild.ShowLeave
await modChannel.SendMessageAsync("Saved - stopping sending messages here when someone leaves"); ? "Saved - now sending messages here when someone leaves"
_redis.HashSet($"{Context.Guild.Id}:Settings", new[] {new HashEntry("ShowLeave", false)}); : "Saved - stopping sending messages here when someone leaves"
} );
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context, _errorHandler.HandleCommandException(e, Context);
"Modchannel doesn't seem to exist, please set one with `!admin modchannel [channelId]`");
} }
} }
[Command("showdel", RunMode = RunMode.Async)] [Command("showdel", RunMode = RunMode.Async)]
[Summary("Notify modchannel when someone deletes a message")] [Summary("Toggle - notify modchannel when someone deletes a message")]
public async Task ShowDelete([Summary("true/false")] bool enabled) public async Task ShowDelete()
{ {
var modChannelId = ulong.Parse(_redis.HashGet($"{Context.Guild.Id}:Settings", "ModChannel"));
try try
{ {
var modChannel = (ISocketMessageChannel) _client.GetChannel(modChannelId); var guild = GetGuildSettings(Context.Guild.Id);
if (enabled) var modChannel = await GetModChannel(guild.ModChannel.AsUlong());
{ if (modChannel == null) return;
await modChannel.SendMessageAsync(
"Saved - now sending messages here when someone deletes a message"); guild.ShowDelete = !guild.ShowDelete;
_redis.HashSet($"{Context.Guild.Id}:Settings", new[] {new HashEntry("ShowDelete", true)}); _database.GuildSettings.Update(guild);
} _database.SaveChanges();
else await modChannel.SendMessageAsync(guild.ShowDelete
{ ? "Saved - now sending messages here when someone deletes a message"
await modChannel.SendMessageAsync( : "Saved - stopping sending messages here when someone deletes a message"
"Saved - stopping sending messages here when someone deletes a message"); );
_redis.HashSet($"{Context.Guild.Id}:Settings", new[] {new HashEntry("ShowDelete", false)});
}
} }
catch (Exception e) catch (Exception e)
{ {
_errorHandler.HandleCommandException(e, Context, _errorHandler.HandleCommandException(e, Context);
"Modchannel doesn't seem to exist, please set one with `!admin modchannel [channelId]`");
} }
} }
@ -122,6 +128,11 @@ namespace Geekbot.net.Commands.Admin
var success = _translation.SetLanguage(Context.Guild.Id, language); var success = _translation.SetLanguage(Context.Guild.Id, language);
if (success) if (success)
{ {
var guild = GetGuildSettings(Context.Guild.Id);
guild.Language = language;
_database.GuildSettings.Update(guild);
_database.SaveChanges();
var trans = _translation.GetDict(Context); var trans = _translation.GetDict(Context);
await ReplyAsync(trans["NewLanguageSet"]); await ReplyAsync(trans["NewLanguageSet"]);
return; return;
@ -143,7 +154,10 @@ namespace Geekbot.net.Commands.Admin
try try
{ {
var language = languageRaw.ToLower(); 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"); await ReplyAsync($"Now using the {language} wikipedia");
} }
@ -153,30 +167,17 @@ namespace Geekbot.net.Commands.Admin
} }
} }
[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)] [Command("ping", RunMode = RunMode.Async)]
[Summary("Enable the ping reply.")] [Summary("Enable the ping reply.")]
public async Task TogglePing() public async Task TogglePing()
{ {
try try
{ {
bool.TryParse(_redis.HashGet($"{Context.Guild.Id}:Settings", "ping"), out var current); var guild = GetGuildSettings(Context.Guild.Id);
_redis.HashSet($"{Context.Guild.Id}:Settings", new[] {new HashEntry("ping", current ? "false" : "true") }); guild.Ping = !guild.Ping;
await ReplyAsync(!current ? "i will reply to ping now" : "No more pongs..."); _database.GuildSettings.Update(guild);
_database.SaveChanges();
await ReplyAsync(guild.Ping ? "i will reply to ping now" : "No more pongs...");
} }
catch (Exception e) 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;
using Discord.Commands; using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
using Geekbot.net.Lib;
using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.ErrorHandling;
using Geekbot.net.Lib.UserRepository; using Geekbot.net.Lib.UserRepository;
using StackExchange.Redis;
namespace Geekbot.net.Commands.Admin namespace Geekbot.net.Commands.Admin
{ {
@ -19,15 +17,12 @@ namespace Geekbot.net.Commands.Admin
{ {
private readonly DiscordSocketClient _client; private readonly DiscordSocketClient _client;
private readonly IErrorHandler _errorHandler; private readonly IErrorHandler _errorHandler;
private readonly IDatabase _redis;
private readonly IUserRepository _userRepository; private readonly IUserRepository _userRepository;
public Mod(IUserRepository userRepositry, IErrorHandler errorHandler, IDatabase redis, public Mod(IUserRepository userRepositry, IErrorHandler errorHandler, DiscordSocketClient client)
DiscordSocketClient client)
{ {
_userRepository = userRepositry; _userRepository = userRepositry;
_errorHandler = errorHandler; _errorHandler = errorHandler;
_redis = redis;
_client = client; _client = client;
} }
@ -49,39 +44,5 @@ namespace Geekbot.net.Commands.Admin
$"I don't have enough permissions do that"); $"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;
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord;
using Discord.Commands; using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
using Geekbot.net.Database; using Geekbot.net.Database;
using Geekbot.net.Lib;
using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.ErrorHandling;
using Geekbot.net.Lib.GlobalSettings;
using Geekbot.net.Lib.Logger; using Geekbot.net.Lib.Logger;
using Geekbot.net.Lib.UserRepository; using Geekbot.net.Lib.UserRepository;
using StackExchange.Redis; using StackExchange.Redis;
@ -19,11 +18,12 @@ namespace Geekbot.net.Commands.Admin
private readonly DiscordSocketClient _client; private readonly DiscordSocketClient _client;
private readonly IErrorHandler _errorHandler; private readonly IErrorHandler _errorHandler;
private readonly DatabaseContext _database; private readonly DatabaseContext _database;
private readonly IGlobalSettings _globalSettings;
private readonly IGeekbotLogger _logger; private readonly IGeekbotLogger _logger;
private readonly IDatabase _redis; private readonly IDatabase _redis;
private readonly IUserRepository _userRepository; 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; _redis = redis;
_client = client; _client = client;
@ -31,6 +31,7 @@ namespace Geekbot.net.Commands.Admin
_userRepository = userRepositry; _userRepository = userRepositry;
_errorHandler = errorHandler; _errorHandler = errorHandler;
_database = database; _database = database;
_globalSettings = globalSettings;
} }
[Command("migrate", RunMode = RunMode.Async)] [Command("migrate", RunMode = RunMode.Async)]
@ -55,7 +56,7 @@ namespace Geekbot.net.Commands.Admin
[Summary("Set the youtube api key")] [Summary("Set the youtube api key")]
public async Task SetYoutubeKey([Summary("API Key")] string key) public async Task SetYoutubeKey([Summary("API Key")] string key)
{ {
_redis.StringSet("youtubeKey", key); _globalSettings.SetKey("YoutubeKey", key);
await ReplyAsync("Apikey has been set"); await ReplyAsync("Apikey has been set");
} }
@ -63,7 +64,7 @@ namespace Geekbot.net.Commands.Admin
[Summary("Set the game that the bot is playing")] [Summary("Set the game that the bot is playing")]
public async Task SetGame([Remainder] [Summary("Game")] string key) public async Task SetGame([Remainder] [Summary("Game")] string key)
{ {
_redis.StringSet("Game", key); _globalSettings.SetKey("Game", key);
await _client.SetGameAsync(key); await _client.SetGameAsync(key);
_logger.Information(LogSource.Geekbot, $"Changed game to {key}"); _logger.Information(LogSource.Geekbot, $"Changed game to {key}");
await ReplyAsync($"Now Playing {key}"); await ReplyAsync($"Now Playing {key}");

View file

@ -4,22 +4,21 @@ using System.Net;
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Lib;
using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.ErrorHandling;
using Geekbot.net.Lib.GlobalSettings;
using Newtonsoft.Json; using Newtonsoft.Json;
using StackExchange.Redis;
namespace Geekbot.net.Commands.Integrations.Google namespace Geekbot.net.Commands.Integrations.Google
{ {
public class Google : ModuleBase public class Google : ModuleBase
{ {
private readonly IErrorHandler _errorHandler; 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; _errorHandler = errorHandler;
_redis = redis; _globalSettings = globalSettings;
} }
[Command("google", RunMode = RunMode.Async)] [Command("google", RunMode = RunMode.Async)]
@ -30,8 +29,8 @@ namespace Geekbot.net.Commands.Integrations.Google
{ {
using (var client = new WebClient()) using (var client = new WebClient())
{ {
var apiKey = _redis.StringGet("googleGraphKey"); var apiKey = _globalSettings.GetKey("GoogleGraphKey");
if (!apiKey.HasValue) if (string.IsNullOrEmpty(apiKey))
{ {
await ReplyAsync("No Google API key has been set, please contact my owner"); await ReplyAsync("No Google API key has been set, please contact my owner");
return; return;
@ -48,8 +47,10 @@ namespace Geekbot.net.Commands.Integrations.Google
} }
var data = response.ItemListElement.First().Result; var data = response.ItemListElement.First().Result;
var eb = new EmbedBuilder(); var eb = new EmbedBuilder
eb.Title = data.Name; {
Title = data.Name
};
if(!string.IsNullOrEmpty(data.Description)) eb.WithDescription(data.Description); 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?.Url)) eb.WithUrl(data.DetailedDtoDescription.Url);
if(!string.IsNullOrEmpty(data.DetailedDtoDescription?.ArticleBody)) eb.AddField("Details", data.DetailedDtoDescription.ArticleBody); if(!string.IsNullOrEmpty(data.DetailedDtoDescription?.ArticleBody)) eb.AddField("Details", data.DetailedDtoDescription.ArticleBody);

View file

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

View file

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

View file

@ -1,9 +1,12 @@
using System; using System;
using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
using Geekbot.net.Database;
using Geekbot.net.Lib.Extensions;
using Geekbot.net.Lib.Logger; using Geekbot.net.Lib.Logger;
using Geekbot.net.Lib.ReactionListener; using Geekbot.net.Lib.ReactionListener;
using Geekbot.net.Lib.UserRepository; using Geekbot.net.Lib.UserRepository;
@ -13,6 +16,7 @@ namespace Geekbot.net
{ {
public class Handlers public class Handlers
{ {
private readonly DatabaseContext _database;
private readonly IDiscordClient _client; private readonly IDiscordClient _client;
private readonly IGeekbotLogger _logger; private readonly IGeekbotLogger _logger;
private readonly IDatabase _redis; private readonly IDatabase _redis;
@ -21,8 +25,9 @@ namespace Geekbot.net
private readonly IUserRepository _userRepository; private readonly IUserRepository _userRepository;
private readonly IReactionListener _reactionListener; private readonly IReactionListener _reactionListener;
public Handlers(IDiscordClient client, IGeekbotLogger logger, IDatabase redis, IServiceProvider servicesProvider, CommandService commands, IUserRepository userRepository, IReactionListener reactionListener) public Handlers(DatabaseContext database, IDiscordClient client, IGeekbotLogger logger, IDatabase redis, IServiceProvider servicesProvider, CommandService commands, IUserRepository userRepository, IReactionListener reactionListener)
{ {
_database = database;
_client = client; _client = client;
_logger = logger; _logger = logger;
_redis = redis; _redis = redis;
@ -45,14 +50,22 @@ namespace Geekbot.net
var argPos = 0; var argPos = 0;
var lowCaseMsg = message.ToString().ToLower(); var lowCaseMsg = message.ToString().ToLower();
if (lowCaseMsg.StartsWith("hui")) if (lowCaseMsg.StartsWith("hui"))
{
var hasPing = _database.GuildSettings.FirstOrDefault(guild =>
guild.GuildId.Equals(((SocketGuildChannel) message.Channel).Guild.Id.AsLong()))
?.Hui ?? false;
if (hasPing)
{ {
message.Channel.SendMessageAsync("hui!!!"); message.Channel.SendMessageAsync("hui!!!");
return Task.CompletedTask; return Task.CompletedTask;
} }
}
if (lowCaseMsg.StartsWith("ping ") || lowCaseMsg.Equals("ping")) if (lowCaseMsg.StartsWith("ping ") || lowCaseMsg.Equals("ping"))
{ {
bool.TryParse(_redis.HashGet($"{((SocketGuildChannel) message.Channel).Guild.Id}:Settings", "ping"), out var allowPings); var hasPing = _database.GuildSettings.FirstOrDefault(guild =>
if (allowPings) guild.GuildId.Equals(((SocketGuildChannel) message.Channel).Guild.Id.AsLong()))
?.Ping ?? false;
if (hasPing)
{ {
message.Channel.SendMessageAsync("pong"); message.Channel.SendMessageAsync("pong");
return Task.CompletedTask; return Task.CompletedTask;
@ -109,10 +122,12 @@ namespace Geekbot.net
{ {
if (!user.IsBot) if (!user.IsBot)
{ {
var message = _redis.HashGet($"{user.Guild.Id}:Settings", "WelcomeMsg"); var message = _database.GuildSettings.FirstOrDefault(guild =>
if (!message.IsNullOrEmpty) guild.GuildId.Equals(user.Guild.Id.AsLong()))
?.WelcomeMessage;
if (!string.IsNullOrEmpty(message))
{ {
message = message.ToString().Replace("$user", user.Mention); message = message.Replace("$user", user.Mention);
await user.Guild.DefaultChannel.SendMessageAsync(message); await user.Guild.DefaultChannel.SendMessageAsync(message);
} }
} }
@ -134,17 +149,14 @@ namespace Geekbot.net
{ {
try try
{ {
var sendLeftEnabled = _redis.HashGet($"{user.Guild.Id}:Settings", "ShowLeave"); var guild = _database.GuildSettings.FirstOrDefault(g =>
if (sendLeftEnabled.ToString() == "1") g.GuildId.Equals(user.Guild.Id.AsLong()));
if (guild?.ShowLeave ?? false)
{ {
var modChannel = ulong.Parse(_redis.HashGet($"{user.Guild.Id}:Settings", "ModChannel")); var modChannelSocket = (ISocketMessageChannel) await _client.GetChannelAsync(guild.ModChannel.AsUlong());
if (!string.IsNullOrEmpty(modChannel.ToString()))
{
var modChannelSocket = (ISocketMessageChannel) await _client.GetChannelAsync(modChannel);
await modChannelSocket.SendMessageAsync($"{user.Username}#{user.Discriminator} left the server"); await modChannelSocket.SendMessageAsync($"{user.Username}#{user.Discriminator} left the server");
} }
} }
}
catch (Exception e) catch (Exception e)
{ {
_logger.Error(LogSource.Geekbot, "Failed to send leave message", e); _logger.Error(LogSource.Geekbot, "Failed to send leave message", e);
@ -160,14 +172,12 @@ namespace Geekbot.net
{ {
try try
{ {
var guild = ((IGuildChannel) channel).Guild; var guildSocketData = ((IGuildChannel) channel).Guild;
var sendLeftEnabled = _redis.HashGet($"{guild.Id}:Settings", "ShowDelete"); var guild = _database.GuildSettings.FirstOrDefault(g =>
if (sendLeftEnabled.ToString() == "1") g.GuildId.Equals(guildSocketData.Id.AsLong()));
if (guild?.ShowDelete ?? false)
{ {
var modChannel = ulong.Parse(_redis.HashGet($"{guild.Id}:Settings", "ModChannel")); var modChannelSocket = (ISocketMessageChannel) await _client.GetChannelAsync(guild.ModChannel.AsUlong());
if (!string.IsNullOrEmpty(modChannel.ToString()) && modChannel != channel.Id)
{
var modChannelSocket = (ISocketMessageChannel) await _client.GetChannelAsync(modChannel);
var sb = new StringBuilder(); var sb = new StringBuilder();
if (message.Value != null) if (message.Value != null)
{ {
@ -182,7 +192,6 @@ namespace Geekbot.net
await modChannelSocket.SendMessageAsync(sb.ToString()); await modChannelSocket.SendMessageAsync(sb.ToString());
} }
} }
}
catch (Exception e) catch (Exception e)
{ {
_logger.Error(LogSource.Geekbot, "Failed to send delete message...", e); _logger.Error(LogSource.Geekbot, "Failed to send delete message...", e);

View file

@ -0,0 +1,55 @@
using System.Linq;
using Geekbot.net.Database;
using Geekbot.net.Database.Models;
namespace Geekbot.net.Lib.GlobalSettings
{
public class GlobalSettings : IGlobalSettings
{
private readonly DatabaseContext _database;
public GlobalSettings(DatabaseContext database)
{
_database = database;
}
public bool SetKey(string keyName, string value)
{
try
{
var key = GetKeyFull(keyName);
if (key == null)
{
_database.Globals.Add(new GlobalsModel()
{
Name = keyName,
Value = value
});
_database.SaveChanges();
return true;
}
key.Value = value;
_database.Globals.Update(key);
_database.SaveChanges();
return true;
}
catch
{
return false;
}
}
public string GetKey(string keyName)
{
var key = _database.Globals.FirstOrDefault(k => k.Name.Equals(keyName));
return key?.Value ?? string.Empty;
}
public GlobalsModel GetKeyFull(string keyName)
{
var key = _database.Globals.FirstOrDefault(k => k.Name.Equals(keyName));
return key;
}
}
}

View file

@ -0,0 +1,11 @@
using Geekbot.net.Database.Models;
namespace Geekbot.net.Lib.GlobalSettings
{
public interface IGlobalSettings
{
bool SetKey(string keyName, string value);
string GetKey(string keyName);
GlobalsModel GetKeyFull(string keyName);
}
}

View file

@ -1,6 +1,4 @@
using System; using System;
using System.Linq;
using System.Net;
using System.Reflection; using System.Reflection;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -14,13 +12,13 @@ using Geekbot.net.Lib.Audio;
using Geekbot.net.Lib.Clients; using Geekbot.net.Lib.Clients;
using Geekbot.net.Lib.Converters; using Geekbot.net.Lib.Converters;
using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.ErrorHandling;
using Geekbot.net.Lib.GlobalSettings;
using Geekbot.net.Lib.Levels; using Geekbot.net.Lib.Levels;
using Geekbot.net.Lib.Localization; using Geekbot.net.Lib.Localization;
using Geekbot.net.Lib.Logger; using Geekbot.net.Lib.Logger;
using Geekbot.net.Lib.Media; using Geekbot.net.Lib.Media;
using Geekbot.net.Lib.ReactionListener; using Geekbot.net.Lib.ReactionListener;
using Geekbot.net.Lib.UserRepository; using Geekbot.net.Lib.UserRepository;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Nancy.Hosting.Self; using Nancy.Hosting.Self;
using StackExchange.Redis; using StackExchange.Redis;
@ -33,6 +31,8 @@ namespace Geekbot.net
private DiscordSocketClient _client; private DiscordSocketClient _client;
private CommandService _commands; private CommandService _commands;
private IDatabase _redis; private IDatabase _redis;
private DatabaseContext _database;
private IGlobalSettings _globalSettings;
private IServiceCollection _services; private IServiceCollection _services;
private IServiceProvider _servicesProvider; private IServiceProvider _servicesProvider;
private RedisValue _token; private RedisValue _token;
@ -107,11 +107,12 @@ namespace Geekbot.net
_firstStart = true; _firstStart = true;
} }
var database = new DatabaseInitializer(runParameters, logger).Initzialize(); _database = new DatabaseInitializer(runParameters, logger).Initzialize();
_globalSettings = new GlobalSettings(_database);
_services = new ServiceCollection(); _services = new ServiceCollection();
_userRepository = new UserRepository(database, logger); _userRepository = new UserRepository(_database, logger);
var fortunes = new FortunesProvider(logger); var fortunes = new FortunesProvider(logger);
var mediaProvider = new MediaProvider(logger); var mediaProvider = new MediaProvider(logger);
var malClient = new MalClient(_redis, logger); var malClient = new MalClient(_redis, logger);
@ -132,7 +133,8 @@ namespace Geekbot.net
_services.AddSingleton<IMtgManaConverter>(mtgManaConverter); _services.AddSingleton<IMtgManaConverter>(mtgManaConverter);
_services.AddSingleton<IWikipediaClient>(wikipediaClient); _services.AddSingleton<IWikipediaClient>(wikipediaClient);
_services.AddSingleton<IAudioUtils>(audioUtils); _services.AddSingleton<IAudioUtils>(audioUtils);
_services.AddSingleton<DatabaseContext>(database); _services.AddSingleton<DatabaseContext>(_database);
_services.AddSingleton<IGlobalSettings>(_globalSettings);
logger.Information(LogSource.Geekbot, "Connecting to Discord"); logger.Information(LogSource.Geekbot, "Connecting to Discord");
@ -150,7 +152,7 @@ namespace Geekbot.net
var isConneted = await IsConnected(); var isConneted = await IsConnected();
if (isConneted) if (isConneted)
{ {
await _client.SetGameAsync(_redis.StringGet("Game")); await _client.SetGameAsync(_globalSettings.GetKey("Game"));
_logger.Information(LogSource.Geekbot, $"Now Connected as {_client.CurrentUser.Username} to {_client.Guilds.Count} Servers"); _logger.Information(LogSource.Geekbot, $"Now Connected as {_client.CurrentUser.Username} to {_client.Guilds.Count} Servers");
_logger.Information(LogSource.Geekbot, "Registering Stuff"); _logger.Information(LogSource.Geekbot, "Registering Stuff");
@ -165,7 +167,7 @@ namespace Geekbot.net
_services.AddSingleton<IReactionListener>(reactionListener); _services.AddSingleton<IReactionListener>(reactionListener);
_servicesProvider = _services.BuildServiceProvider(); _servicesProvider = _services.BuildServiceProvider();
var handlers = new Handlers(_client, _logger, _redis, _servicesProvider, _commands, _userRepository, reactionListener); var handlers = new Handlers(_database, _client, _logger, _redis, _servicesProvider, _commands, _userRepository, reactionListener);
_client.MessageReceived += handlers.RunCommand; _client.MessageReceived += handlers.RunCommand;
_client.MessageReceived += handlers.UpdateStats; _client.MessageReceived += handlers.UpdateStats;