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);

View file

@ -1,9 +1,12 @@
using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using Geekbot.net.Database;
using Geekbot.net.Lib.Extensions;
using Geekbot.net.Lib.Logger;
using Geekbot.net.Lib.ReactionListener;
using Geekbot.net.Lib.UserRepository;
@ -13,6 +16,7 @@ namespace Geekbot.net
{
public class Handlers
{
private readonly DatabaseContext _database;
private readonly IDiscordClient _client;
private readonly IGeekbotLogger _logger;
private readonly IDatabase _redis;
@ -21,8 +25,9 @@ namespace Geekbot.net
private readonly IUserRepository _userRepository;
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;
_logger = logger;
_redis = redis;
@ -46,13 +51,21 @@ namespace Geekbot.net
var lowCaseMsg = message.ToString().ToLower();
if (lowCaseMsg.StartsWith("hui"))
{
message.Channel.SendMessageAsync("hui!!!");
return Task.CompletedTask;
var hasPing = _database.GuildSettings.FirstOrDefault(guild =>
guild.GuildId.Equals(((SocketGuildChannel) message.Channel).Guild.Id.AsLong()))
?.Hui ?? false;
if (hasPing)
{
message.Channel.SendMessageAsync("hui!!!");
return Task.CompletedTask;
}
}
if (lowCaseMsg.StartsWith("ping ") || lowCaseMsg.Equals("ping"))
{
bool.TryParse(_redis.HashGet($"{((SocketGuildChannel) message.Channel).Guild.Id}:Settings", "ping"), out var allowPings);
if (allowPings)
var hasPing = _database.GuildSettings.FirstOrDefault(guild =>
guild.GuildId.Equals(((SocketGuildChannel) message.Channel).Guild.Id.AsLong()))
?.Ping ?? false;
if (hasPing)
{
message.Channel.SendMessageAsync("pong");
return Task.CompletedTask;
@ -109,10 +122,12 @@ namespace Geekbot.net
{
if (!user.IsBot)
{
var message = _redis.HashGet($"{user.Guild.Id}:Settings", "WelcomeMsg");
if (!message.IsNullOrEmpty)
var message = _database.GuildSettings.FirstOrDefault(guild =>
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);
}
}
@ -134,15 +149,12 @@ namespace Geekbot.net
{
try
{
var sendLeftEnabled = _redis.HashGet($"{user.Guild.Id}:Settings", "ShowLeave");
if (sendLeftEnabled.ToString() == "1")
var guild = _database.GuildSettings.FirstOrDefault(g =>
g.GuildId.Equals(user.Guild.Id.AsLong()));
if (guild?.ShowLeave ?? false)
{
var modChannel = ulong.Parse(_redis.HashGet($"{user.Guild.Id}:Settings", "ModChannel"));
if (!string.IsNullOrEmpty(modChannel.ToString()))
{
var modChannelSocket = (ISocketMessageChannel) await _client.GetChannelAsync(modChannel);
await modChannelSocket.SendMessageAsync($"{user.Username}#{user.Discriminator} left the server");
}
var modChannelSocket = (ISocketMessageChannel) await _client.GetChannelAsync(guild.ModChannel.AsUlong());
await modChannelSocket.SendMessageAsync($"{user.Username}#{user.Discriminator} left the server");
}
}
catch (Exception e)
@ -160,27 +172,24 @@ namespace Geekbot.net
{
try
{
var guild = ((IGuildChannel) channel).Guild;
var sendLeftEnabled = _redis.HashGet($"{guild.Id}:Settings", "ShowDelete");
if (sendLeftEnabled.ToString() == "1")
var guildSocketData = ((IGuildChannel) channel).Guild;
var guild = _database.GuildSettings.FirstOrDefault(g =>
g.GuildId.Equals(guildSocketData.Id.AsLong()));
if (guild?.ShowDelete ?? false)
{
var modChannel = ulong.Parse(_redis.HashGet($"{guild.Id}:Settings", "ModChannel"));
if (!string.IsNullOrEmpty(modChannel.ToString()) && modChannel != channel.Id)
var modChannelSocket = (ISocketMessageChannel) await _client.GetChannelAsync(guild.ModChannel.AsUlong());
var sb = new StringBuilder();
if (message.Value != null)
{
var modChannelSocket = (ISocketMessageChannel) await _client.GetChannelAsync(modChannel);
var sb = new StringBuilder();
if (message.Value != null)
{
sb.AppendLine(
$"The following message from {message.Value.Author.Username}#{message.Value.Author.Discriminator} was deleted in <#{channel.Id}>");
sb.AppendLine(message.Value.Content);
}
else
{
sb.AppendLine("Someone deleted a message, the message was not cached...");
}
await modChannelSocket.SendMessageAsync(sb.ToString());
sb.AppendLine(
$"The following message from {message.Value.Author.Username}#{message.Value.Author.Discriminator} was deleted in <#{channel.Id}>");
sb.AppendLine(message.Value.Content);
}
else
{
sb.AppendLine("Someone deleted a message, the message was not cached...");
}
await modChannelSocket.SendMessageAsync(sb.ToString());
}
}
catch (Exception 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.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
@ -14,13 +12,13 @@ using Geekbot.net.Lib.Audio;
using Geekbot.net.Lib.Clients;
using Geekbot.net.Lib.Converters;
using Geekbot.net.Lib.ErrorHandling;
using Geekbot.net.Lib.GlobalSettings;
using Geekbot.net.Lib.Levels;
using Geekbot.net.Lib.Localization;
using Geekbot.net.Lib.Logger;
using Geekbot.net.Lib.Media;
using Geekbot.net.Lib.ReactionListener;
using Geekbot.net.Lib.UserRepository;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Nancy.Hosting.Self;
using StackExchange.Redis;
@ -33,6 +31,8 @@ namespace Geekbot.net
private DiscordSocketClient _client;
private CommandService _commands;
private IDatabase _redis;
private DatabaseContext _database;
private IGlobalSettings _globalSettings;
private IServiceCollection _services;
private IServiceProvider _servicesProvider;
private RedisValue _token;
@ -107,11 +107,12 @@ namespace Geekbot.net
_firstStart = true;
}
var database = new DatabaseInitializer(runParameters, logger).Initzialize();
_database = new DatabaseInitializer(runParameters, logger).Initzialize();
_globalSettings = new GlobalSettings(_database);
_services = new ServiceCollection();
_userRepository = new UserRepository(database, logger);
_userRepository = new UserRepository(_database, logger);
var fortunes = new FortunesProvider(logger);
var mediaProvider = new MediaProvider(logger);
var malClient = new MalClient(_redis, logger);
@ -132,7 +133,8 @@ namespace Geekbot.net
_services.AddSingleton<IMtgManaConverter>(mtgManaConverter);
_services.AddSingleton<IWikipediaClient>(wikipediaClient);
_services.AddSingleton<IAudioUtils>(audioUtils);
_services.AddSingleton<DatabaseContext>(database);
_services.AddSingleton<DatabaseContext>(_database);
_services.AddSingleton<IGlobalSettings>(_globalSettings);
logger.Information(LogSource.Geekbot, "Connecting to Discord");
@ -150,7 +152,7 @@ namespace Geekbot.net
var isConneted = await IsConnected();
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, "Registering Stuff");
@ -165,7 +167,7 @@ namespace Geekbot.net
_services.AddSingleton<IReactionListener>(reactionListener);
_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.UpdateStats;