Add GeekbotBase as an extension of ModuleBase

This commit is contained in:
runebaas 2019-05-23 23:23:16 +02:00
parent ced287e492
commit 8d9c436cfc
No known key found for this signature in database
GPG key ID: 2677AF508D0300D6
8 changed files with 113 additions and 11 deletions

View file

@ -6,12 +6,13 @@ using Discord;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Database; using Geekbot.net.Database;
using Geekbot.net.Database.Models; using Geekbot.net.Database.Models;
using Geekbot.net.Lib;
using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.ErrorHandling;
using Geekbot.net.Lib.Extensions; using Geekbot.net.Lib.Extensions;
namespace Geekbot.net.Commands.Randomness namespace Geekbot.net.Commands.Randomness
{ {
public class Slap : ModuleBase public class Slap : GeekbotBase
{ {
private readonly IErrorHandler _errorHandler; private readonly IErrorHandler _errorHandler;
private readonly DatabaseContext _database; private readonly DatabaseContext _database;
@ -24,7 +25,7 @@ namespace Geekbot.net.Commands.Randomness
[Command("slap", RunMode = RunMode.Async)] [Command("slap", RunMode = RunMode.Async)]
[Summary("slap someone")] [Summary("slap someone")]
public async Task Slapper([Summary("@someone")] IUser user) public async Task Slapper([Summary("@someone")] IGuildUser user)
{ {
try try
{ {
@ -79,7 +80,7 @@ namespace Geekbot.net.Commands.Randomness
"powerless banhammer" "powerless banhammer"
}; };
await ReplyAsync($"{Context.User.Username} slapped {user.Username} with a {things[new Random().Next(things.Count - 1)]}"); await ReplyAsync($"{Context.GuildUser.Nickname} slapped {user.Nickname} with a {things[new Random().Next(things.Count - 1)]}");
await UpdateRecieved(user.Id); await UpdateRecieved(user.Id);
await UpdateGiven(Context.User.Id); await UpdateGiven(Context.User.Id);

View file

@ -9,7 +9,9 @@ using Discord.WebSocket;
using Geekbot.net.Database; using Geekbot.net.Database;
using Geekbot.net.Database.Models; using Geekbot.net.Database.Models;
using Geekbot.net.Lib.AlmostRedis; using Geekbot.net.Lib.AlmostRedis;
using Geekbot.net.Lib.Context;
using Geekbot.net.Lib.Extensions; using Geekbot.net.Lib.Extensions;
using Geekbot.net.Lib.Localization;
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;
@ -27,11 +29,12 @@ namespace Geekbot.net
private readonly CommandService _commands; private readonly CommandService _commands;
private readonly IUserRepository _userRepository; private readonly IUserRepository _userRepository;
private readonly IReactionListener _reactionListener; private readonly IReactionListener _reactionListener;
private readonly ITranslationHandler _translationHandler;
private readonly DatabaseContext _messageCounterDatabaseContext; private readonly DatabaseContext _messageCounterDatabaseContext;
public Handlers(DatabaseInitializer databaseInitializer, IDiscordClient client, IGeekbotLogger logger, IAlmostRedis redis, public Handlers(DatabaseInitializer databaseInitializer, IDiscordClient client, IGeekbotLogger logger, IAlmostRedis redis,
IServiceProvider servicesProvider, CommandService commands, IUserRepository userRepository, IServiceProvider servicesProvider, CommandService commands, IUserRepository userRepository,
IReactionListener reactionListener) IReactionListener reactionListener, ITranslationHandler translationHandler)
{ {
_database = databaseInitializer.Initialize(); _database = databaseInitializer.Initialize();
_messageCounterDatabaseContext = databaseInitializer.Initialize(); _messageCounterDatabaseContext = databaseInitializer.Initialize();
@ -42,6 +45,7 @@ namespace Geekbot.net
_commands = commands; _commands = commands;
_userRepository = userRepository; _userRepository = userRepository;
_reactionListener = reactionListener; _reactionListener = reactionListener;
_translationHandler = translationHandler;
} }
// //
@ -79,7 +83,7 @@ namespace Geekbot.net
if (!(message.HasCharPrefix('!', ref argPos) || if (!(message.HasCharPrefix('!', ref argPos) ||
message.HasMentionPrefix(_client.CurrentUser, ref argPos))) return Task.CompletedTask; message.HasMentionPrefix(_client.CurrentUser, ref argPos))) return Task.CompletedTask;
var context = new CommandContext(_client, message); var context = new GeekbotContext(_client, message, _translationHandler);
var commandExec = _commands.ExecuteAsync(context, argPos, _servicesProvider); var commandExec = _commands.ExecuteAsync(context, argPos, _servicesProvider);
_logger.Information(LogSource.Command, _logger.Information(LogSource.Command,
context.Message.Content.Split(" ")[0].Replace("!", ""), context.Message.Content.Split(" ")[0].Replace("!", ""),

View file

@ -0,0 +1,56 @@
using Discord;
using Geekbot.net.Lib.Localization;
namespace Geekbot.net.Lib.Context
{
/// <summary> The context of a command which may contain the client, user, guild, channel, and message. </summary>
public class GeekbotContext : IGeekbotContext
{
/// <inheritdoc />
public IDiscordClient Client { get; }
/// <inheritdoc />
public IGuild Guild { get; }
/// <inheritdoc />
public IMessageChannel Channel { get; }
/// <inheritdoc />
public IUser User { get; }
/// <inheritdoc />
public IUserMessage Message { get; }
/// <inheritdoc />
public IGuildUser GuildUser { get; }
/// <inheritdoc />
public TranslationGuildContext Translations { get; }
/// <summary> Indicates whether the channel that the command is executed in is a private channel. </summary>
public bool IsPrivate
{
get
{
return this.Channel is IPrivateChannel;
}
}
/// <summary>
/// Initializes a new <see cref="T:Discord.Commands.CommandContext" /> class with the provided client and message.
/// </summary>
/// <param name="client">The underlying client.</param>
/// <param name="msg">The underlying message.</param>
/// <param name="translationHandler">the translation handler</param>
public GeekbotContext(IDiscordClient client, IUserMessage msg, ITranslationHandler translationHandler)
{
this.Client = client;
this.Guild = (msg.Channel as IGuildChannel)?.Guild;
this.Channel = msg.Channel;
this.User = msg.Author;
this.GuildUser = msg.Author as IGuildUser;
this.Message = msg;
this.Translations = translationHandler.GetGuildContext(this.Guild, this.Message).Result;
}
}
}

View file

@ -0,0 +1,19 @@
using Discord;
using Discord.Commands;
using Geekbot.net.Lib.Localization;
namespace Geekbot.net.Lib.Context
{
public interface IGeekbotContext : ICommandContext
{
/// <summary>
/// Gets the <see cref="T:Discord:IGuildUser"/> who executed the command.
/// </summary>
IGuildUser GuildUser { get; }
/// <summary>
/// Gets the <see cref="T:Geekbot:net:Lib:Localization:TranslationGuildContext"/> containing the necessary tools for command localization.
/// </summary>
TranslationGuildContext Translations { get; }
}
}

View file

@ -0,0 +1,9 @@
using Discord.Commands;
using Geekbot.net.Lib.Context;
namespace Geekbot.net.Lib
{
public abstract class GeekbotBase : ModuleBase<GeekbotContext>
{
}
}

View file

@ -1,5 +1,6 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord;
using Discord.Commands; using Discord.Commands;
namespace Geekbot.net.Lib.Localization namespace Geekbot.net.Lib.Localization
@ -10,6 +11,7 @@ namespace Geekbot.net.Lib.Localization
string GetString(string language, string command, string stringName); string GetString(string language, string command, string stringName);
Task<Dictionary<string, string>> GetDict(ICommandContext context, string command); Task<Dictionary<string, string>> GetDict(ICommandContext context, string command);
Task<TranslationGuildContext> GetGuildContext(ICommandContext context); Task<TranslationGuildContext> GetGuildContext(ICommandContext context);
Task<TranslationGuildContext> GetGuildContext(IGuild guild, IUserMessage message);
Task<bool> SetLanguage(ulong guildId, string language); Task<bool> SetLanguage(ulong guildId, string language);
List<string> SupportedLanguages { get; } List<string> SupportedLanguages { get; }
} }

View file

@ -3,13 +3,12 @@ using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Database; using Geekbot.net.Database;
using Geekbot.net.Database.Models; using Geekbot.net.Database.Models;
using Geekbot.net.Lib.Extensions; using Geekbot.net.Lib.Extensions;
using Geekbot.net.Lib.Logger; using Geekbot.net.Lib.Logger;
using Utf8Json;
using YamlDotNet.RepresentationModel;
using YamlDotNet.Serialization; using YamlDotNet.Serialization;
namespace Geekbot.net.Lib.Localization namespace Geekbot.net.Lib.Localization
@ -137,12 +136,17 @@ namespace Geekbot.net.Lib.Localization
return translation; return translation;
} }
private async Task<Dictionary<string, string>> GetDict(ICommandContext context) private Task<Dictionary<string, string>> GetDict(ICommandContext context)
{
return GetDict(context.Guild, context.Message);
}
private async Task<Dictionary<string, string>> GetDict(IGuild guild, IUserMessage message)
{ {
try try
{ {
var command = context.Message.Content.Split(' ').First().TrimStart('!').ToLower(); var command = message.Content.Split(' ').First().TrimStart('!').ToLower();
var serverLanguage = await GetServerLanguage(context.Guild?.Id ?? 0); var serverLanguage = await GetServerLanguage(guild?.Id ?? 0);
return _translations[serverLanguage][command]; return _translations[serverLanguage][command];
} }
catch (Exception e) catch (Exception e)
@ -159,6 +163,13 @@ namespace Geekbot.net.Lib.Localization
return new TranslationGuildContext(this, language, dict); return new TranslationGuildContext(this, language, dict);
} }
public async Task<TranslationGuildContext> GetGuildContext(IGuild guild, IUserMessage message)
{
var dict = await GetDict(guild, message);
var language = await GetServerLanguage(guild?.Id ?? 0);
return new TranslationGuildContext(this, language, dict);
}
public async Task<Dictionary<string, string>> GetDict(ICommandContext context, string command) public async Task<Dictionary<string, string>> GetDict(ICommandContext context, string command)
{ {
try try

View file

@ -170,7 +170,7 @@ namespace Geekbot.net
_servicesProvider = _services.BuildServiceProvider(); _servicesProvider = _services.BuildServiceProvider();
await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _servicesProvider); await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _servicesProvider);
var handlers = new Handlers(_databaseInitializer, _client, _logger, _redis, _servicesProvider, _commands, _userRepository, reactionListener); var handlers = new Handlers(_databaseInitializer, _client, _logger, _redis, _servicesProvider, _commands, _userRepository, reactionListener, translationHandler);
_client.MessageReceived += handlers.RunCommand; _client.MessageReceived += handlers.RunCommand;
_client.MessageDeleted += handlers.MessageDeleted; _client.MessageDeleted += handlers.MessageDeleted;