This commit is contained in:
Master Kwoth 2017-07-25 18:31:30 +02:00
parent e9cf57d46f
commit 263a95a6ad
18 changed files with 68 additions and 54 deletions

View File

@ -37,7 +37,7 @@ namespace NadekoBot.Modules.Administration
if (role == null) if (role == null)
{ {
conf.AutoAssignRoleId = 0; conf.AutoAssignRoleId = 0;
_service.AutoAssignedRoles.TryRemove(Context.Guild.Id, out ulong throwaway); _service.AutoAssignedRoles.TryRemove(Context.Guild.Id, out _);
} }
else else
{ {

View File

@ -61,8 +61,7 @@ namespace NadekoBot.Modules.Administration
return; return;
} }
AntiRaidStats throwaway; if (_service.AntiRaidGuilds.TryRemove(Context.Guild.Id, out _))
if (_service.AntiRaidGuilds.TryRemove(Context.Guild.Id, out throwaway))
{ {
using (var uow = _db.UnitOfWork) using (var uow = _db.UnitOfWork)
{ {
@ -118,10 +117,9 @@ namespace NadekoBot.Modules.Administration
if (messageCount < 2 || messageCount > 10) if (messageCount < 2 || messageCount > 10)
return; return;
AntiSpamStats throwaway; if (_service.AntiSpamGuilds.TryRemove(Context.Guild.Id, out var removed))
if (_service.AntiSpamGuilds.TryRemove(Context.Guild.Id, out throwaway))
{ {
throwaway.UserStats.ForEach(x => x.Value.Dispose()); removed.UserStats.ForEach(x => x.Value.Dispose());
using (var uow = _db.UnitOfWork) using (var uow = _db.UnitOfWork)
{ {
var gc = uow.GuildConfigs.For(Context.Guild.Id, set => set.Include(x => x.AntiSpamSetting) var gc = uow.GuildConfigs.For(Context.Guild.Id, set => set.Include(x => x.AntiSpamSetting)

View File

@ -30,9 +30,9 @@ namespace NadekoBot.Modules.Administration
[RequireUserPermission(GuildPermission.ManageMessages)] [RequireUserPermission(GuildPermission.ManageMessages)]
public async Task Slowmode() public async Task Slowmode()
{ {
if (_service.RatelimitingChannels.TryRemove(Context.Channel.Id, out Ratelimiter throwaway)) if (_service.RatelimitingChannels.TryRemove(Context.Channel.Id, out Ratelimiter removed))
{ {
throwaway.CancelSource.Cancel(); removed.CancelSource.Cancel();
await ReplyConfirmLocalized("slowmode_disabled").ConfigureAwait(false); await ReplyConfirmLocalized("slowmode_disabled").ConfigureAwait(false);
} }
} }

View File

@ -18,17 +18,19 @@ namespace NadekoBot.Modules.Administration.Services
private readonly Logger _log; private readonly Logger _log;
private readonly Replacer _rep; private readonly Replacer _rep;
private readonly DbService _db; private readonly DbService _db;
public BotConfig BotConfig { get; private set; } //todo load whole botconifg, not just for this service when you have the time private readonly IBotConfigProvider _bcp;
public BotConfig BotConfig => _bcp.BotConfig;
private class TimerState private class TimerState
{ {
public int Index { get; set; } public int Index { get; set; }
} }
public PlayingRotateService(DiscordSocketClient client, BotConfig bc, MusicService music, DbService db) public PlayingRotateService(DiscordSocketClient client, IBotConfigProvider bcp, MusicService music, DbService db)
{ {
_client = client; _client = client;
BotConfig = bc; _bcp = bcp;
_music = music; _music = music;
_db = db; _db = db;
_log = LogManager.GetCurrentClassLogger(); _log = LogManager.GetCurrentClassLogger();
@ -42,10 +44,8 @@ namespace NadekoBot.Modules.Administration.Services
{ {
try try
{ {
using (var uow = _db.UnitOfWork) bcp.Reload();
{
BotConfig = uow.BotConfig.GetOrCreate();
}
var state = (TimerState)objState; var state = (TimerState)objState;
if (!BotConfig.RotatingStatuses) if (!BotConfig.RotatingStatuses)
return; return;

View File

@ -15,7 +15,6 @@ namespace NadekoBot.Modules.Administration.Services
{ {
public class SelfService : ILateExecutor, INService public class SelfService : ILateExecutor, INService
{ {
//todo bot config
public bool ForwardDMs => _bc.BotConfig.ForwardMessages; public bool ForwardDMs => _bc.BotConfig.ForwardMessages;
public bool ForwardDMsToAllOwners => _bc.BotConfig.ForwardToAllOwners; public bool ForwardDMsToAllOwners => _bc.BotConfig.ForwardToAllOwners;

View File

@ -433,8 +433,7 @@ namespace NadekoBot.Modules.CustomReactions
} }
else else
{ {
uint throwaway; if (_service.ReactionStats.TryRemove(trigger, out _))
if (_service.ReactionStats.TryRemove(trigger, out throwaway))
{ {
await ReplyErrorLocalized("stats_cleared", Format.Bold(trigger)).ConfigureAwait(false); await ReplyErrorLocalized("stats_cleared", Format.Bold(trigger)).ConfigureAwait(false);
} }

View File

@ -158,8 +158,7 @@ namespace NadekoBot.Modules.Gambling
private void End() private void End()
{ {
AnimalRace throwaway; AnimalRaces.TryRemove(_serverId, out _);
AnimalRaces.TryRemove(_serverId, out throwaway);
} }
private async Task StartRace() private async Task StartRace()

View File

@ -28,7 +28,7 @@ namespace NadekoBot.Modules.Games
{ {
var channel = (ITextChannel)Context.Channel; var channel = (ITextChannel)Context.Channel;
if (_service.ChatterBotGuilds.TryRemove(channel.Guild.Id, out Lazy<IChatterBotSession> throwaway)) if (_service.ChatterBotGuilds.TryRemove(channel.Guild.Id, out _))
{ {
using (var uow = _db.UnitOfWork) using (var uow = _db.UnitOfWork)
{ {

View File

@ -11,6 +11,14 @@ using NadekoBot.Modules.Games.Services;
namespace NadekoBot.Modules.Games namespace NadekoBot.Modules.Games
{ {
/*todo more games
- Blackjack
- Shiritori
- Simple RPG adventure
- The nunchi game
- Wheel of fortune
- Connect 4
*/
public partial class Games : NadekoTopLevelModule<GamesService> public partial class Games : NadekoTopLevelModule<GamesService>
{ {
private readonly IImagesService _images; private readonly IImagesService _images;

View File

@ -45,7 +45,7 @@ namespace NadekoBot.Modules.Games
hm.OnEnded += g => hm.OnEnded += g =>
{ {
HangmanGames.TryRemove(g.GameChannel.Id, out HangmanGame throwaway); HangmanGames.TryRemove(g.GameChannel.Id, out _);
}; };
try try
{ {
@ -54,8 +54,8 @@ namespace NadekoBot.Modules.Games
catch (Exception ex) catch (Exception ex)
{ {
try { await Context.Channel.SendErrorAsync(GetText("hangman_start_errored") + " " + ex.Message).ConfigureAwait(false); } catch { } try { await Context.Channel.SendErrorAsync(GetText("hangman_start_errored") + " " + ex.Message).ConfigureAwait(false); } catch { }
HangmanGames.TryRemove(Context.Channel.Id, out HangmanGame throwaway); if(HangmanGames.TryRemove(Context.Channel.Id, out var removed))
throwaway.Dispose(); removed.Dispose();
return; return;
} }
@ -66,9 +66,9 @@ namespace NadekoBot.Modules.Games
[RequireContext(ContextType.Guild)] [RequireContext(ContextType.Guild)]
public async Task HangmanStop() public async Task HangmanStop()
{ {
if (HangmanGames.TryRemove(Context.Channel.Id, out HangmanGame throwaway)) if (HangmanGames.TryRemove(Context.Channel.Id, out var removed))
{ {
throwaway.Dispose(); removed.Dispose();
await ReplyConfirmLocalized("hangman_stopped").ConfigureAwait(false); await ReplyConfirmLocalized("hangman_stopped").ConfigureAwait(false);
} }
} }

View File

@ -74,8 +74,7 @@ namespace NadekoBot.Modules.Permissions
// else // else
// { // {
// bc.CommandCosts.RemoveAt(bc.CommandCosts.IndexOf(cmdPrice)); // bc.CommandCosts.RemoveAt(bc.CommandCosts.IndexOf(cmdPrice));
// int throwaway; // _commandCosts.TryRemove(cmdName, out _);
// _commandCosts.TryRemove(cmdName, out throwaway);
// } // }
// await uow.CompleteAsync().ConfigureAwait(false); // await uow.CompleteAsync().ConfigureAwait(false);

View File

@ -10,8 +10,15 @@ namespace NadekoBot.Modules.Utility
{ {
public partial class Utility public partial class Utility
{ {
public class BotConfigCommands : NadekoSubmodule<IBotConfigProvider> public class BotConfigCommands : NadekoSubmodule
{ {
private readonly IBotConfigProvider _service;
public BotConfigCommands(IBotConfigProvider service)
{
_service = service;
}
[NadekoCommand, Usage, Description, Aliases] [NadekoCommand, Usage, Description, Aliases]
[OwnerOnly] [OwnerOnly]
public async Task BotConfigEdit() public async Task BotConfigEdit()

View File

@ -42,10 +42,8 @@ namespace NadekoBot.Modules.Utility
if (string.IsNullOrWhiteSpace(mapping)) if (string.IsNullOrWhiteSpace(mapping))
{ {
ConcurrentDictionary<string, string> maps; if (!_service.AliasMaps.TryGetValue(Context.Guild.Id, out var maps) ||
string throwaway; !maps.TryRemove(trigger, out _))
if (!_service.AliasMaps.TryGetValue(Context.Guild.Id, out maps) ||
!maps.TryRemove(trigger, out throwaway))
{ {
await ReplyErrorLocalized("alias_remove_fail", Format.Code(trigger)).ConfigureAwait(false); await ReplyErrorLocalized("alias_remove_fail", Format.Code(trigger)).ConfigureAwait(false);
return; return;
@ -113,8 +111,7 @@ namespace NadekoBot.Modules.Utility
if (page < 0) if (page < 0)
return; return;
ConcurrentDictionary<string, string> maps; if (!_service.AliasMaps.TryGetValue(Context.Guild.Id, out var maps) || !maps.Any())
if (!_service.AliasMaps.TryGetValue(Context.Guild.Id, out maps) || !maps.Any())
{ {
await ReplyErrorLocalized("aliases_none").ConfigureAwait(false); await ReplyErrorLocalized("aliases_none").ConfigureAwait(false);
return; return;

View File

@ -32,7 +32,7 @@ namespace NadekoBot
public DiscordSocketClient Client { get; } public DiscordSocketClient Client { get; }
public CommandService CommandService { get; } public CommandService CommandService { get; }
public DbService Db { get; } private readonly DbService _db;
public ImmutableArray<GuildConfig> AllGuildConfigs { get; private set; } public ImmutableArray<GuildConfig> AllGuildConfigs { get; private set; }
/* I don't know how to make this not be static /* I don't know how to make this not be static
@ -64,7 +64,7 @@ namespace NadekoBot
TerribleElevatedPermissionCheck(); TerribleElevatedPermissionCheck();
Credentials = new BotCredentials(); Credentials = new BotCredentials();
Db = new DbService(Credentials); _db = new DbService(Credentials);
Client = new DiscordSocketClient(new DiscordSocketConfig Client = new DiscordSocketClient(new DiscordSocketConfig
{ {
MessageCacheSize = 10, MessageCacheSize = 10,
@ -83,7 +83,7 @@ namespace NadekoBot
port = port ?? Credentials.ShardRunPort; port = port ?? Credentials.ShardRunPort;
_comClient = new ShardComClient(port.Value); _comClient = new ShardComClient(port.Value);
using (var uow = Db.UnitOfWork) using (var uow = _db.UnitOfWork)
{ {
_botConfig = uow.BotConfig.GetOrCreate(); _botConfig = uow.BotConfig.GetOrCreate();
OkColor = new Color(Convert.ToUInt32(_botConfig.OkColor, 16)); OkColor = new Color(Convert.ToUInt32(_botConfig.OkColor, 16));
@ -120,20 +120,22 @@ namespace NadekoBot
var startingGuildIdList = Client.Guilds.Select(x => (long)x.Id).ToList(); var startingGuildIdList = Client.Guilds.Select(x => (long)x.Id).ToList();
//this unit of work will be used for initialization of all modules too, to prevent multiple queries from running //this unit of work will be used for initialization of all modules too, to prevent multiple queries from running
using (var uow = Db.UnitOfWork) using (var uow = _db.UnitOfWork)
{ {
AllGuildConfigs = uow.GuildConfigs.GetAllGuildConfigs(startingGuildIdList).ToImmutableArray(); AllGuildConfigs = uow.GuildConfigs.GetAllGuildConfigs(startingGuildIdList).ToImmutableArray();
var localization = new Localization(_botConfig.Locale, AllGuildConfigs.ToDictionary(x => x.GuildId, x => x.Locale), Db); IBotConfigProvider botConfigProvider = new BotConfigProvider(_db, _botConfig);
//var localization = new Localization(_botConfig.Locale, AllGuildConfigs.ToDictionary(x => x.GuildId, x => x.Locale), Db);
//initialize Services //initialize Services
Services = new NServiceProvider.ServiceProviderBuilder() Services = new NServiceProvider.ServiceProviderBuilder()
.AddManual<IBotCredentials>(Credentials) .AddManual<IBotCredentials>(Credentials)
.AddManual(Db) .AddManual(_db)
.AddManual(_botConfig)
.AddManual(Client) .AddManual(Client)
.AddManual(CommandService) .AddManual(CommandService)
.AddManual<ILocalization>(localization) .AddManual(botConfigProvider)
//.AddManual<ILocalization>(localization)
.AddManual<IEnumerable<GuildConfig>>(AllGuildConfigs) //todo wrap this .AddManual<IEnumerable<GuildConfig>>(AllGuildConfigs) //todo wrap this
.AddManual<NadekoBot>(this) .AddManual<NadekoBot>(this)
.AddManual<IUnitOfWork>(uow) .AddManual<IUnitOfWork>(uow)

View File

@ -261,10 +261,11 @@ namespace NadekoBot.Services
} }
} }
var prefix = GetPrefix(guild?.Id); var prefix = GetPrefix(guild?.Id);
var isPrefixCommand = messageContent == ".prefix";
// execute the command and measure the time it took // execute the command and measure the time it took
if (messageContent.StartsWith(prefix)) if (messageContent.StartsWith(prefix) || isPrefixCommand)
{ {
var result = await ExecuteCommandAsync(new CommandContext(_client, usrMsg), messageContent, prefix.Length, _services, MultiMatchHandling.Best); var result = await ExecuteCommandAsync(new CommandContext(_client, usrMsg), messageContent, isPrefixCommand ? 1 : prefix.Length, _services, MultiMatchHandling.Best);
execTime = Environment.TickCount - execTime; execTime = Environment.TickCount - execTime;
if (result.Success) if (result.Success)

View File

@ -3,7 +3,7 @@ using NadekoBot.Services.Database.Models;
namespace NadekoBot.Services namespace NadekoBot.Services
{ {
public interface IBotConfigProvider : INService public interface IBotConfigProvider
{ {
BotConfig BotConfig { get; } BotConfig BotConfig { get; }
void Reload(); void Reload();

View File

@ -4,7 +4,7 @@ using Discord;
namespace NadekoBot.Services namespace NadekoBot.Services
{ {
public interface ILocalization public interface ILocalization : INService
{ {
CultureInfo DefaultCultureInfo { get; } CultureInfo DefaultCultureInfo { get; }
ConcurrentDictionary<ulong, CultureInfo> GuildCultureInfos { get; } ConcurrentDictionary<ulong, CultureInfo> GuildCultureInfos { get; }

View File

@ -4,6 +4,7 @@ using System.Globalization;
using System.Linq; using System.Linq;
using Discord; using Discord;
using NLog; using NLog;
using NadekoBot.Services.Database.Models;
namespace NadekoBot.Services.Impl namespace NadekoBot.Services.Impl
{ {
@ -16,10 +17,15 @@ namespace NadekoBot.Services.Impl
public CultureInfo DefaultCultureInfo { get; private set; } = CultureInfo.CurrentCulture; public CultureInfo DefaultCultureInfo { get; private set; } = CultureInfo.CurrentCulture;
private Localization() { } private Localization() { }
public Localization(string defaultCulture, IDictionary<ulong, string> cultureInfoNames, DbService db) public Localization(IBotConfigProvider bcp, IEnumerable<GuildConfig> gcs, DbService db)
{ {
_log = LogManager.GetCurrentClassLogger(); _log = LogManager.GetCurrentClassLogger();
var cultureInfoNames = gcs.ToDictionary(x => x.GuildId, x => x.Locale);
var defaultCulture = bcp.BotConfig.Locale;
_db = db; _db = db;
if (string.IsNullOrWhiteSpace(defaultCulture)) if (string.IsNullOrWhiteSpace(defaultCulture))
DefaultCultureInfo = new CultureInfo("en-US"); DefaultCultureInfo = new CultureInfo("en-US");
else else
@ -74,8 +80,7 @@ namespace NadekoBot.Services.Impl
public void RemoveGuildCulture(ulong guildId) { public void RemoveGuildCulture(ulong guildId) {
CultureInfo throwaway; if (GuildCultureInfos.TryRemove(guildId, out var _))
if (GuildCultureInfos.TryRemove(guildId, out throwaway))
{ {
using (var uow = _db.UnitOfWork) using (var uow = _db.UnitOfWork)
{ {