Refaction all files into component based folders

This commit is contained in:
runebaas 2018-05-03 00:56:06 +02:00
parent 55e152f4aa
commit e3adf55742
No known key found for this signature in database
GPG key ID: 2677AF508D0300D6
102 changed files with 816 additions and 709 deletions

View file

@ -0,0 +1,196 @@
using System;
using System.Text;
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.Localization;
using StackExchange.Redis;
namespace Geekbot.net.Commands.Admin
{
[Group("admin")]
[RequireUserPermission(GuildPermission.Administrator)]
public class Admin : ModuleBase
{
private readonly DiscordSocketClient _client;
private readonly IErrorHandler _errorHandler;
private readonly IDatabase _redis;
private readonly ITranslationHandler _translation;
public Admin(IDatabase redis, DiscordSocketClient client, IErrorHandler errorHandler,
ITranslationHandler translationHandler)
{
_redis = redis;
_client = client;
_errorHandler = errorHandler;
_translation = translationHandler;
}
[Command("welcome", RunMode = RunMode.Async)]
[Remarks(CommandCategories.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 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}");
}
[Command("modchannel", RunMode = RunMode.Async)]
[Remarks(CommandCategories.Admin)]
[Summary("Set a channel for moderation purposes")]
public async Task SelectModChannel([Summary("#Channel")] ISocketMessageChannel channel)
{
try
{
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())});
}
catch (Exception e)
{
_errorHandler.HandleCommandException(e, Context, "That channel doesn't seem to be valid");
}
}
[Command("showleave", RunMode = RunMode.Async)]
[Remarks(CommandCategories.Admin)]
[Summary("Notify modchannel when someone leaves")]
public async Task ShowLeave([Summary("true/false")] bool enabled)
{
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)});
}
}
catch (Exception e)
{
_errorHandler.HandleCommandException(e, Context,
"Modchannel doesn't seem to exist, please set one with `!admin modchannel [channelId]`");
}
}
[Command("showdel", RunMode = RunMode.Async)]
[Remarks(CommandCategories.Admin)]
[Summary("Notify modchannel when someone deletes a message")]
public async Task ShowDelete([Summary("true/false")] bool enabled)
{
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)});
}
}
catch (Exception e)
{
_errorHandler.HandleCommandException(e, Context,
"Modchannel doesn't seem to exist, please set one with `!admin modchannel [channelId]`");
}
}
[Command("setlang", RunMode = RunMode.Async)]
[Remarks(CommandCategories.Admin)]
[Summary("Change the bots language")]
public async Task SetLanguage([Summary("language")] string languageRaw)
{
try
{
var language = languageRaw.ToUpper();
var success = _translation.SetLanguage(Context.Guild.Id, language);
if (success)
{
var trans = _translation.GetDict(Context);
await ReplyAsync(trans["NewLanguageSet"]);
return;
}
await ReplyAsync(
$"That doesn't seem to be a supported language\r\nSupported Languages are {string.Join(", ", _translation.GetSupportedLanguages())}");
}
catch (Exception e)
{
_errorHandler.HandleCommandException(e, Context);
}
}
[Command("wiki", RunMode = RunMode.Async)]
[Remarks(CommandCategories.Admin)]
[Summary("Change the wikipedia instance (use lang code in xx.wikipedia.org)")]
public async Task SetWikiLanguage([Summary("language")] string languageRaw)
{
try
{
var language = languageRaw.ToLower();
_redis.HashSet($"{Context.Guild.Id}:Settings", new[] {new HashEntry("WikiLang", language) });
await ReplyAsync($"Now using the {language} wikipedia");
}
catch (Exception e)
{
_errorHandler.HandleCommandException(e, Context);
}
}
[Command("lang", RunMode = RunMode.Async)]
[Remarks(CommandCategories.Admin)]
[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)]
[Remarks(CommandCategories.Admin)]
[Summary("Enable the ping reply.")]
public async Task TogglePing()
{
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...");
}
catch (Exception e)
{
_errorHandler.HandleCommandException(e, Context);
}
}
}
}

View file

@ -0,0 +1,89 @@
using System;
using System.Text;
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
{
[Group("mod")]
[RequireUserPermission(GuildPermission.KickMembers)]
[RequireUserPermission(GuildPermission.ManageMessages)]
[RequireUserPermission(GuildPermission.ManageRoles)]
public class Mod : ModuleBase
{
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)
{
_userRepository = userRepositry;
_errorHandler = errorHandler;
_redis = redis;
_client = client;
}
[Command("namehistory", RunMode = RunMode.Async)]
[Remarks(CommandCategories.Admin)]
[Summary("See past usernames of an user")]
public async Task UsernameHistory([Summary("@user")] IUser user)
{
try
{
var userRepo = _userRepository.Get(user.Id);
var sb = new StringBuilder();
sb.AppendLine($":bust_in_silhouette: {user.Username} has been known as:");
foreach (var name in userRepo.UsedNames) sb.AppendLine($"- `{name}`");
await ReplyAsync(sb.ToString());
}
catch (Exception e)
{
_errorHandler.HandleCommandException(e, Context,
$"I don't have enough permissions to give {user.Username} that role");
}
}
[Command("kick", RunMode = RunMode.Async)]
[Remarks(CommandCategories.Admin)]
[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

@ -0,0 +1,118 @@
using System;
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.Logger;
using Geekbot.net.Lib.UserRepository;
using StackExchange.Redis;
namespace Geekbot.net.Commands.Admin
{
[Group("owner")]
[RequireUserPermission(GuildPermission.Administrator)]
public class Owner : ModuleBase
{
private readonly DiscordSocketClient _client;
private readonly IErrorHandler _errorHandler;
private readonly IGeekbotLogger _logger;
private readonly IDatabase _redis;
private readonly IUserRepository _userRepository;
public Owner(IDatabase redis, DiscordSocketClient client, IGeekbotLogger logger, IUserRepository userRepositry,
IErrorHandler errorHandler)
{
_redis = redis;
_client = client;
_logger = logger;
_userRepository = userRepositry;
_errorHandler = errorHandler;
}
[Command("youtubekey", RunMode = RunMode.Async)]
[Remarks(CommandCategories.Admin)]
[Summary("Set the youtube api key")]
public async Task SetYoutubeKey([Summary("API Key")] string key)
{
var botOwner = Context.Guild.GetUserAsync(ulong.Parse(_redis.StringGet("botOwner"))).Result;
if (!Context.User.Id.ToString().Equals(botOwner.Id.ToString()))
{
await ReplyAsync(
$"Sorry, only the botowner can do this ({botOwner.Username}#{botOwner.Discriminator})");
return;
}
_redis.StringSet("youtubeKey", key);
await ReplyAsync("Apikey has been set");
}
[Command("game", RunMode = RunMode.Async)]
[Remarks(CommandCategories.Admin)]
[Summary("Set the game that the bot is playing")]
public async Task SetGame([Remainder] [Summary("Game")] string key)
{
var botOwner = Context.Guild.GetUserAsync(ulong.Parse(_redis.StringGet("botOwner"))).Result;
if (!Context.User.Id.ToString().Equals(botOwner.Id.ToString()))
{
await ReplyAsync(
$"Sorry, only the botowner can do this ({botOwner.Username}#{botOwner.Discriminator})");
return;
}
_redis.StringSet("Game", key);
await _client.SetGameAsync(key);
_logger.Information("Geekbot", $"Changed game to {key}");
await ReplyAsync($"Now Playing {key}");
}
[Command("popuserrepo", RunMode = RunMode.Async)]
[Remarks(CommandCategories.Admin)]
[Summary("Populate user cache")]
public async Task PopUserRepoCommand()
{
try
{
var botOwner = Context.Guild.GetUserAsync(ulong.Parse(_redis.StringGet("botOwner"))).Result;
if (!Context.User.Id.ToString().Equals(botOwner.Id.ToString()))
{
await ReplyAsync(
$"Sorry, only the botowner can do this ({botOwner.Username}#{botOwner.Discriminator})");
return;
}
}
catch (Exception)
{
await ReplyAsync("Sorry, only the botowner can do this");
return;
}
var success = 0;
var failed = 0;
try
{
_logger.Warning("UserRepository", "Populating User Repositry");
await ReplyAsync("Starting Population of User Repository");
foreach (var guild in _client.Guilds)
{
_logger.Information("UserRepository", $"Populating users from {guild.Name}");
foreach (var user in guild.Users)
{
var succeded = await _userRepository.Update(user);
var inc = succeded ? success++ : failed++;
}
}
_logger.Warning("UserRepository", "Finished Updating User Repositry");
await ReplyAsync(
$"Successfully Populated User Repository with {success} Users in {_client.Guilds.Count} Guilds (Failed: {failed})");
}
catch (Exception e)
{
_errorHandler.HandleCommandException(e, Context,
"Couldn't complete User Repository, see console for more info");
}
}
}
}

View file

@ -0,0 +1,193 @@
using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using Discord.Net;
using Geekbot.net.Lib;
using Geekbot.net.Lib.ErrorHandling;
using Geekbot.net.Lib.ReactionListener;
using StackExchange.Redis;
namespace Geekbot.net.Commands.Admin
{
[Group("role")]
public class Role : ModuleBase
{
private readonly IErrorHandler _errorHandler;
private readonly IDatabase _redis;
private readonly IReactionListener _reactionListener;
public Role(IErrorHandler errorHandler, IDatabase redis, IReactionListener reactionListener)
{
_errorHandler = errorHandler;
_redis = redis;
_reactionListener = reactionListener;
}
[Command(RunMode = RunMode.Async)]
[Remarks(CommandCategories.Helpers)]
[Summary("Get a list of all available roles.")]
public async Task GetAllRoles()
{
try
{
var roles = _redis.HashGetAll($"{Context.Guild.Id}:RoleWhitelist");
if (roles.Length == 0)
{
await ReplyAsync("There are no roles configured for this server");
return;
}
var sb = new StringBuilder();
sb.AppendLine($"**Self Service Roles on {Context.Guild.Name}**");
sb.AppendLine("To get a role, use `!role name`");
foreach (var role in roles) sb.AppendLine($"- {role.Name}");
await ReplyAsync(sb.ToString());
}
catch (Exception e)
{
_errorHandler.HandleCommandException(e, Context);
}
}
[Command(RunMode = RunMode.Async)]
[Remarks(CommandCategories.Helpers)]
[Summary("Get a role by mentioning it.")]
public async Task GiveRole([Summary("roleNickname")] string roleNameRaw)
{
try
{
var roleName = roleNameRaw.ToLower();
if (_redis.HashExists($"{Context.Guild.Id}:RoleWhitelist", roleName))
{
var guildUser = (IGuildUser) Context.User;
var roleId = ulong.Parse(_redis.HashGet($"{Context.Guild.Id}:RoleWhitelist", roleName));
var role = Context.Guild.Roles.First(r => r.Id == roleId);
if (role == null)
{
await ReplyAsync("That role doesn't seem to exist");
return;
}
if (guildUser.RoleIds.Contains(roleId))
{
await guildUser.RemoveRoleAsync(role);
await ReplyAsync($"Removed you from {role.Name}");
return;
}
await guildUser.AddRoleAsync(role);
await ReplyAsync($"Added you to {role.Name}");
return;
}
await ReplyAsync("That role doesn't seem to exist");
}
catch (HttpException e)
{
_errorHandler.HandleHttpException(e, Context);
}
catch (Exception e)
{
_errorHandler.HandleCommandException(e, Context);
}
}
[RequireUserPermission(GuildPermission.ManageRoles)]
[Command("add", RunMode = RunMode.Async)]
[Remarks(CommandCategories.Admin)]
[Summary("Add a role to the whitelist.")]
public async Task AddRole([Summary("@role")] IRole role, [Summary("alias")] string roleName)
{
try
{
if (role.IsManaged)
{
await ReplyAsync("You can't add a role that is managed by discord");
return;
}
if (role.Permissions.ManageRoles
|| role.Permissions.Administrator
|| role.Permissions.ManageGuild
|| role.Permissions.BanMembers
|| role.Permissions.KickMembers)
{
await ReplyAsync(
"Woah, i don't think you want to add that role to self service as it contains some dangerous permissions");
return;
}
_redis.HashSet($"{Context.Guild.Id}:RoleWhitelist",
new[] {new HashEntry(roleName.ToLower(), role.Id.ToString())});
await ReplyAsync($"Added {role.Name} to the whitelist");
}
catch (Exception e)
{
_errorHandler.HandleCommandException(e, Context);
}
}
[RequireUserPermission(GuildPermission.ManageRoles)]
[Command("remove", RunMode = RunMode.Async)]
[Remarks(CommandCategories.Admin)]
[Summary("Remove a role from the whitelist.")]
public async Task RemoveRole([Summary("roleNickname")] string roleName)
{
try
{
var success = _redis.HashDelete($"{Context.Guild.Id}:RoleWhitelist", roleName.ToLower());
if (success)
{
await ReplyAsync($"Removed {roleName} from the whitelist");
return;
}
await ReplyAsync("There is not whitelisted role with that name...");
}
catch (Exception e)
{
_errorHandler.HandleCommandException(e, Context);
}
}
[RequireUserPermission(GuildPermission.ManageRoles)]
[Remarks(CommandCategories.Admin)]
[Summary("Give a role by clicking on an emoji")]
[Command("listen", RunMode = RunMode.Async)]
public async Task AddListener([Summary("messageID")] string messageId, [Summary("Emoji")] string emoji, [Summary("@role")] IRole role)
{
try
{
var message = (IUserMessage) await Context.Channel.GetMessageAsync(ulong.Parse(messageId));
IEmote emote;
if (!emoji.StartsWith('<'))
{
var emo = new Emoji(emoji);
emote = emo;
}
else
{
emote = Emote.Parse(emoji);
}
await message.AddReactionAsync(emote);
await _reactionListener.AddRoleToListener(messageId, emote, role);
await Context.Message.DeleteAsync();
}
catch (HttpException e)
{
await Context.Channel.SendMessageAsync("Custom emojis from other servers are not supported");
Console.WriteLine(e);
}
catch (Exception e)
{
await Context.Channel.SendMessageAsync("Something went wrong... please try again on a new message");
Console.WriteLine(e);
}
}
}
}

View file

@ -0,0 +1,36 @@
using System;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using Geekbot.net.Lib;
using Geekbot.net.Lib.ErrorHandling;
namespace Geekbot.net.Commands.Admin
{
public class Say : ModuleBase
{
private readonly IErrorHandler _errorHandler;
public Say(IErrorHandler errorHandler)
{
_errorHandler = errorHandler;
}
[RequireUserPermission(GuildPermission.Administrator)]
[Command("say", RunMode = RunMode.Async)]
[Remarks(CommandCategories.Admin)]
[Summary("Say Something.")]
public async Task Echo([Remainder] [Summary("What?")] string echo)
{
try
{
await Context.Message.DeleteAsync();
await ReplyAsync(echo);
}
catch (Exception e)
{
_errorHandler.HandleCommandException(e, Context);
}
}
}
}