massive cleanup

This commit is contained in:
Kwoth 2016-12-08 18:35:34 +01:00
parent 9c989804e8
commit 3a60df9539
36 changed files with 135 additions and 222 deletions

View File

@ -15,6 +15,7 @@ using System.Net.Http;
using System.IO;
using static NadekoBot.Modules.Permissions.Permissions;
using System.Collections.Concurrent;
using NLog;
namespace NadekoBot.Modules.Administration
{
@ -24,13 +25,17 @@ namespace NadekoBot.Modules.Administration
private static ConcurrentDictionary<ulong, string> GuildMuteRoles { get; } = new ConcurrentDictionary<ulong, string>();
public Administration(ILocalization loc, CommandService cmds, ShardedDiscordClient client) : base(loc, cmds, client)
private static Logger _log { get; }
public Administration() : base()
{
NadekoBot.CommandHandler.CommandExecuted += DelMsgOnCmd_Handler;
}
static Administration()
{
_log = LogManager.GetCurrentClassLogger();
NadekoBot.CommandHandler.CommandExecuted += DelMsgOnCmd_Handler;
using (var uow = DbHandler.UnitOfWork())
{
var configs = NadekoBot.AllGuildConfigs;
@ -40,7 +45,7 @@ namespace NadekoBot.Modules.Administration
}
}
private async Task DelMsgOnCmd_Handler(IUserMessage msg, Command cmd)
private static async Task DelMsgOnCmd_Handler(IUserMessage msg, Command cmd)
{
try
{
@ -802,7 +807,7 @@ namespace NadekoBot.Modules.Administration
{
var channel = (ITextChannel)umsg.Channel;
var channels = await Task.WhenAll(_client.GetGuilds().Select(g =>
var channels = await Task.WhenAll(NadekoBot.Client.GetGuilds().Select(g =>
g.GetDefaultChannelAsync()
)).ConfigureAwait(false);

View File

@ -74,13 +74,13 @@ namespace NadekoBot.Modules.Administration
private static ConcurrentDictionary<ulong, AntiSpamSetting> antiSpamGuilds =
new ConcurrentDictionary<ulong, AntiSpamSetting>();
private Logger _log { get; }
private static Logger _log { get; }
public AntiRaidCommands(ShardedDiscordClient client)
static AntiRaidCommands()
{
_log = LogManager.GetCurrentClassLogger();
client.MessageReceived += (imsg) =>
NadekoBot.Client.MessageReceived += (imsg) =>
{
var msg = imsg as IUserMessage;
if (msg == null || msg.Author.IsBot)
@ -115,7 +115,7 @@ namespace NadekoBot.Modules.Administration
return Task.CompletedTask;
};
client.UserJoined += (usr) =>
NadekoBot.Client.UserJoined += (usr) =>
{
if (usr.IsBot)
return Task.CompletedTask;
@ -148,7 +148,7 @@ namespace NadekoBot.Modules.Administration
};
}
private async Task PunishUsers(PunishmentAction action, IRole muteRole, ProtectionType pt, params IGuildUser[] gus)
private static async Task PunishUsers(PunishmentAction action, IRole muteRole, ProtectionType pt, params IGuildUser[] gus)
{
foreach (var gu in gus)
{

View File

@ -15,13 +15,12 @@ namespace NadekoBot.Modules.Administration
[Group]
public class AutoAssignRoleCommands
{
private Logger _log { get; }
private static Logger _log { get; }
public AutoAssignRoleCommands()
static AutoAssignRoleCommands()
{
var _client = NadekoBot.Client;
this._log = LogManager.GetCurrentClassLogger();
_client.UserJoined += (user) =>
_log = LogManager.GetCurrentClassLogger();
NadekoBot.Client.UserJoined += (user) =>
{
var t = Task.Run(async () =>
{

View File

@ -16,7 +16,7 @@ namespace NadekoBot.Modules.Administration
[Group]
public class CrossServerTextChannel
{
public CrossServerTextChannel()
static CrossServerTextChannel()
{
_log = LogManager.GetCurrentClassLogger();
NadekoBot.Client.MessageReceived += (imsg) =>
@ -50,11 +50,11 @@ namespace NadekoBot.Modules.Administration
};
}
private string GetText(IGuild server, ITextChannel channel, IGuildUser user, IUserMessage message) =>
private static string GetText(IGuild server, ITextChannel channel, IGuildUser user, IUserMessage message) =>
$"**{server.Name} | {channel.Name}** `{user.Username}`: " + message.Content;
public static readonly ConcurrentDictionary<int, ConcurrentHashSet<ITextChannel>> Subscribers = new ConcurrentDictionary<int, ConcurrentHashSet<ITextChannel>>();
private Logger _log { get; }
private static Logger _log { get; }
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]

View File

@ -18,7 +18,7 @@ namespace NadekoBot.Modules.Administration
[Group]
public class RepeatCommands
{
public ConcurrentDictionary<ulong, RepeatRunner> repeaters;
public static ConcurrentDictionary<ulong, RepeatRunner> repeaters { get; }
public class RepeatRunner
{
@ -70,7 +70,7 @@ namespace NadekoBot.Modules.Administration
}
}
public RepeatCommands()
static RepeatCommands()
{
using (var uow = DbHandler.UnitOfWork())
{

View File

@ -18,7 +18,7 @@ namespace NadekoBot.Modules.Administration
[Group]
public class PlayingRotateCommands
{
private Logger _log { get; }
private static Logger _log { get; }
public static List<PlayingStatus> RotatingStatusMessages { get; }
public static bool RotatingStatuses { get; private set; } = false;
@ -30,12 +30,9 @@ namespace NadekoBot.Modules.Administration
RotatingStatusMessages = conf.RotatingStatusMessages;
RotatingStatuses = conf.RotatingStatuses;
}
}
public PlayingRotateCommands()
{
_log = LogManager.GetCurrentClassLogger();
Task.Run(async () =>
var t = Task.Run(async () =>
{
var index = 0;
do

View File

@ -16,9 +16,7 @@ namespace NadekoBot.Modules.Administration
public class RatelimitCommand
{
public static ConcurrentDictionary<ulong, Ratelimiter> RatelimitingChannels = new ConcurrentDictionary<ulong, Ratelimiter>();
private Logger _log { get; }
private ShardedDiscordClient _client { get; }
private static Logger _log { get; }
public class Ratelimiter
{
@ -61,12 +59,11 @@ namespace NadekoBot.Modules.Administration
}
}
public RatelimitCommand()
static RatelimitCommand()
{
this._client = NadekoBot.Client;
this._log = LogManager.GetCurrentClassLogger();
_log = LogManager.GetCurrentClassLogger();
_client.MessageReceived += (umsg) =>
NadekoBot.Client.MessageReceived += (umsg) =>
{
var t = Task.Run(async () =>
{

View File

@ -17,17 +17,16 @@ namespace NadekoBot.Modules.Administration
[Group]
public class ServerGreetCommands
{
public static long Greeted = 0;
private Logger _log;
private static Logger _log { get; }
public ServerGreetCommands()
static ServerGreetCommands()
{
NadekoBot.Client.UserJoined += UserJoined;
NadekoBot.Client.UserLeft += UserLeft;
_log = LogManager.GetCurrentClassLogger();
}
private Task UserLeft(IGuildUser user)
private static Task UserLeft(IGuildUser user)
{
var leftTask = Task.Run(async () =>
{
@ -67,7 +66,7 @@ namespace NadekoBot.Modules.Administration
return Task.CompletedTask;
}
private Task UserJoined(IGuildUser user)
private static Task UserJoined(IGuildUser user)
{
var joinedTask = Task.Run(async () =>
{

View File

@ -17,10 +17,10 @@ namespace NadekoBot.Modules.Administration
[Group]
public class VoicePlusTextCommands
{
Regex channelNameRegex = new Regex(@"[^a-zA-Z0-9 -]", RegexOptions.Compiled);
private static Regex channelNameRegex = new Regex(@"[^a-zA-Z0-9 -]", RegexOptions.Compiled);
private ConcurrentHashSet<ulong> voicePlusTextCache;
public VoicePlusTextCommands()
private static ConcurrentHashSet<ulong> voicePlusTextCache { get; }
static VoicePlusTextCommands()
{
using (var uow = DbHandler.UnitOfWork())
{
@ -29,7 +29,7 @@ namespace NadekoBot.Modules.Administration
NadekoBot.Client.UserVoiceStateUpdated += UserUpdatedEventHandler;
}
private Task UserUpdatedEventHandler(IUser iuser, IVoiceState before, IVoiceState after)
private static Task UserUpdatedEventHandler(IUser iuser, IVoiceState before, IVoiceState after)
{
var user = (iuser as IGuildUser);
var guild = user?.Guild;
@ -101,7 +101,7 @@ namespace NadekoBot.Modules.Administration
return Task.CompletedTask;
}
private string GetChannelName(string voiceName) =>
private static string GetChannelName(string voiceName) =>
channelNameRegex.Replace(voiceName, "").Trim().Replace(" ", "-").TrimTo(90, true) + "-voice";
[NadekoCommand, Usage, Description, Aliases]

View File

@ -36,7 +36,7 @@ namespace NadekoBot.Modules.ClashOfClans
.ToDictionary(g => g.Key, g => g.ToList()));
}
}
public ClashOfClans(ILocalization loc, CommandService cmds, ShardedDiscordClient client) : base(loc, cmds, client)
public ClashOfClans() : base()
{
}

View File

@ -25,7 +25,7 @@ namespace NadekoBot.Modules.CustomReactions
GlobalReactions = new ConcurrentHashSet<CustomReaction>(items.Where(g => g.GuildId == null || g.GuildId == 0));
}
}
public CustomReactions(ILocalization loc, CommandService cmds, ShardedDiscordClient client) : base(loc, cmds, client)
public CustomReactions() : base()
{
}

View File

@ -6,12 +6,10 @@ namespace NadekoBot.Modules
{
public class DiscordModule
{
protected CommandService _commands { get; }
protected ShardedDiscordClient _client { get; }
protected Logger _log { get; }
protected string _prefix { get; }
public DiscordModule(ILocalization loc, CommandService cmds, ShardedDiscordClient client)
public DiscordModule()
{
string prefix;
if (NadekoBot.ModulePrefixes.TryGetValue(this.GetType().Name, out prefix))
@ -19,8 +17,6 @@ namespace NadekoBot.Modules
else
_prefix = "?missing_prefix?";
_commands = cmds;
_client = client;
_log = LogManager.GetCurrentClassLogger();
}
}

View File

@ -18,11 +18,7 @@ namespace NadekoBot.Modules.Gambling
[Group]
public class AnimalRacing
{
public AnimalRacing()
{
}
public static ConcurrentDictionary<ulong, AnimalRace> AnimalRaces = new ConcurrentDictionary<ulong, AnimalRace>();
public static ConcurrentDictionary<ulong, AnimalRace> AnimalRaces { get; } = new ConcurrentDictionary<ulong, AnimalRace>();
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
@ -119,7 +115,7 @@ namespace NadekoBot.Modules.Gambling
await Task.Run(StartRace);
End();
}
catch { }
catch { try { End(); } catch { } }
});
}

View File

@ -15,10 +15,9 @@ namespace NadekoBot.Modules.Gambling
[Group]
public class FlipCoinCommands
{
NadekoRandom rng { get; } = new NadekoRandom();
private static NadekoRandom rng { get; } = new NadekoRandom();
private const string headsPath = "data/images/coins/heads.png";
private const string tailsPath = "data/images/coins/tails.png";
public FlipCoinCommands() { }
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]

View File

@ -20,7 +20,7 @@ namespace NadekoBot.Modules.Gambling
public static string CurrencyPluralName { get; set; }
public static string CurrencySign { get; set; }
public Gambling(ILocalization loc, CommandService cmds, ShardedDiscordClient client) : base(loc, cmds, client)
public Gambling() : base()
{
using (var uow = DbHandler.UnitOfWork())
{

View File

@ -31,23 +31,20 @@ namespace NadekoBot.Modules.Games
[Group]
public class PlantPickCommands
{
private Random rng;
private ConcurrentHashSet<ulong> generationChannels = new ConcurrentHashSet<ulong>();
private static ConcurrentHashSet<ulong> generationChannels { get; } = new ConcurrentHashSet<ulong>();
//channelid/message
private ConcurrentDictionary<ulong, List<IUserMessage>> plantedFlowers = new ConcurrentDictionary<ulong, List<IUserMessage>>();
private static ConcurrentDictionary<ulong, List<IUserMessage>> plantedFlowers { get; } = new ConcurrentDictionary<ulong, List<IUserMessage>>();
//channelId/last generation
private ConcurrentDictionary<ulong, DateTime> lastGenerations = new ConcurrentDictionary<ulong, DateTime>();
private static ConcurrentDictionary<ulong, DateTime> lastGenerations { get; } = new ConcurrentDictionary<ulong, DateTime>();
private float chance;
private int cooldown;
private Logger _log { get; }
private static float chance { get; }
private static int cooldown { get; }
private static Logger _log { get; }
public PlantPickCommands()
static PlantPickCommands()
{
_log = LogManager.GetCurrentClassLogger();
NadekoBot.Client.MessageReceived += PotentialFlowerGeneration;
rng = new NadekoRandom();
using (var uow = DbHandler.UnitOfWork())
{
@ -60,7 +57,7 @@ namespace NadekoBot.Modules.Games
}
}
private Task PotentialFlowerGeneration(IMessage imsg)
private static Task PotentialFlowerGeneration(IMessage imsg)
{
var msg = imsg as IUserMessage;
if (msg == null || msg.IsAuthor() || msg.Author.IsBot)
@ -76,6 +73,7 @@ namespace NadekoBot.Modules.Games
var t = Task.Run(async () =>
{
var lastGeneration = lastGenerations.GetOrAdd(channel.Id, DateTime.MinValue);
var rng = new NadekoRandom();
if (DateTime.Now - TimeSpan.FromSeconds(cooldown) < lastGeneration) //recently generated in this channel, don't generate again
return;
@ -194,8 +192,11 @@ namespace NadekoBot.Modules.Games
}
}
private string GetRandomCurrencyImagePath() =>
Directory.GetFiles("data/currency_images").OrderBy(s => rng.Next()).FirstOrDefault();
private static string GetRandomCurrencyImagePath()
{
var rng = new NadekoRandom();
return Directory.GetFiles("data/currency_images").OrderBy(s => rng.Next()).FirstOrDefault();
}
int GetRandomNumber()
{

View File

@ -21,7 +21,7 @@ namespace NadekoBot.Modules.Games
}
}
}
public Games(ILocalization loc, CommandService cmds, ShardedDiscordClient client) : base(loc, cmds, client)
public Games() : base()
{
}

View File

@ -30,7 +30,7 @@ namespace NadekoBot.Modules.Help
}
}
public Help(ILocalization loc, CommandService cmds, ShardedDiscordClient client) : base(loc, cmds, client)
public Help() : base()
{
}
@ -38,7 +38,7 @@ namespace NadekoBot.Modules.Help
public async Task Modules(IUserMessage umsg)
{
await umsg.Channel.SendMessageAsync("📜 **List of modules:** ```css\n• " + string.Join("\n• ", _commands.Modules.Select(m => m.Name)) + $"\n``` **Type** `-commands module_name` **to get a list of commands in that module.** ***e.g.*** `-commands games`")
await umsg.Channel.SendMessageAsync("📜 **List of modules:** ```css\n• " + string.Join("\n• ", NadekoBot.CommandService.Modules.Select(m => m.Name)) + $"\n``` **Type** `-commands module_name` **to get a list of commands in that module.** ***e.g.*** `-commands games`")
.ConfigureAwait(false);
}
@ -50,7 +50,7 @@ namespace NadekoBot.Modules.Help
module = module?.Trim().ToUpperInvariant();
if (string.IsNullOrWhiteSpace(module))
return;
var cmds = _commands.Commands.Where(c => c.Module.Name.ToUpperInvariant().StartsWith(module))
var cmds = NadekoBot.CommandService.Commands.Where(c => c.Module.Name.ToUpperInvariant().StartsWith(module))
.OrderBy(c => c.Text)
.Distinct(new CommandTextEqualityComparer())
.AsEnumerable();
@ -84,7 +84,7 @@ namespace NadekoBot.Modules.Help
await ch.SendMessageAsync(HelpString).ConfigureAwait(false);
return;
}
var com = _commands.Commands.FirstOrDefault(c => c.Text.ToLowerInvariant() == comToFind || c.Aliases.Select(a=>a.ToLowerInvariant()).Contains(comToFind));
var com = NadekoBot.CommandService.Commands.FirstOrDefault(c => c.Text.ToLowerInvariant() == comToFind || c.Aliases.Select(a=>a.ToLowerInvariant()).Contains(comToFind));
if (com == null)
{
@ -129,7 +129,7 @@ namespace NadekoBot.Modules.Help
helpstr.AppendLine(string.Join("\n", NadekoBot.CommandService.Modules.Where(m => m.Name.ToLowerInvariant() != "help").OrderBy(m => m.Name).Prepend(NadekoBot.CommandService.Modules.FirstOrDefault(m=>m.Name.ToLowerInvariant()=="help")).Select(m => $"- [{m.Name}](#{m.Name.ToLowerInvariant()})")));
helpstr.AppendLine();
string lastModule = null;
foreach (var com in _commands.Commands.OrderBy(com=>com.Module.Name).GroupBy(c=>c.Text).Select(g=>g.First()))
foreach (var com in NadekoBot.CommandService.Commands.OrderBy(com=>com.Module.Name).GroupBy(c=>c.Text).Select(g=>g.First()))
{
if (com.Module.Name != lastModule)
{

View File

@ -25,7 +25,7 @@ namespace NadekoBot.Modules.Music
public const string MusicDataPath = "data/musicdata";
private IGoogleApiService _google;
public Music(ILocalization loc, CommandService cmds, ShardedDiscordClient client, IGoogleApiService google) : base(loc, cmds, client)
public Music(ILocalization loc, CommandService cmds, ShardedDiscordClient client, IGoogleApiService google) : base()
{
//it can fail if its currenctly opened or doesn't exist. Either way i don't care
try { Directory.Delete(MusicDataPath, true); } catch { }

View File

@ -16,7 +16,7 @@ namespace NadekoBot.Modules.NSFW
[NadekoModule("NSFW", "~")]
public class NSFW : DiscordModule
{
public NSFW(ILocalization loc, CommandService cmds, ShardedDiscordClient client) : base(loc, cmds, client)
public NSFW() : base()
{
}

View File

@ -24,7 +24,7 @@ namespace NadekoBot.Modules.Permissions
public class CmdCdsCommands
{
public static ConcurrentDictionary<ulong, ConcurrentHashSet<CommandCooldown>> commandCooldowns { get; }
private static ConcurrentDictionary<ulong, ConcurrentHashSet<ActiveCooldown>> activeCooldowns = new ConcurrentDictionary<ulong, ConcurrentHashSet<ActiveCooldown>>();
private static ConcurrentDictionary<ulong, ConcurrentHashSet<ActiveCooldown>> activeCooldowns { get; } = new ConcurrentDictionary<ulong, ConcurrentHashSet<ActiveCooldown>>();
static CmdCdsCommands()
{

View File

@ -14,14 +14,14 @@ namespace NadekoBot.Modules.Permissions
[Group]
public class FilterCommands
{
public static ConcurrentHashSet<ulong> InviteFilteringChannels { get; set; }
public static ConcurrentHashSet<ulong> InviteFilteringServers { get; set; }
public static ConcurrentHashSet<ulong> InviteFilteringChannels { get; }
public static ConcurrentHashSet<ulong> InviteFilteringServers { get; }
//serverid, filteredwords
private static ConcurrentDictionary<ulong, ConcurrentHashSet<string>> ServerFilteredWords { get; set; }
private static ConcurrentDictionary<ulong, ConcurrentHashSet<string>> ServerFilteredWords { get; }
public static ConcurrentHashSet<ulong> WordFilteringChannels { get; set; }
public static ConcurrentHashSet<ulong> WordFilteringServers { get; set; }
public static ConcurrentHashSet<ulong> WordFilteringChannels { get; }
public static ConcurrentHashSet<ulong> WordFilteringServers { get; }
public static ConcurrentHashSet<string> FilteredWordsForChannel(ulong channelId, ulong guildId)
{

View File

@ -21,7 +21,7 @@ namespace NadekoBot.Modules.Permissions
}
//guildid, root permission
public static ConcurrentDictionary<ulong, PermissionCache> Cache;
public static ConcurrentDictionary<ulong, PermissionCache> Cache { get; }
static Permissions()
{
@ -39,7 +39,7 @@ namespace NadekoBot.Modules.Permissions
}
}
public Permissions(ILocalization loc, CommandService cmds, ShardedDiscordClient client) : base(loc, cmds, client)
public Permissions() : base()
{
}

View File

@ -27,7 +27,7 @@ namespace NadekoBot.Modules.Pokemon
private Logger _pokelog { get; }
public Pokemon(ILocalization loc, CommandService cmds, ShardedDiscordClient client) : base(loc, cmds, client)
public Pokemon() : base()
{
_pokelog = LogManager.GetCurrentClassLogger();
if (File.Exists(PokemonTypesFile))

View File

@ -10,6 +10,7 @@ using NLog;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace NadekoBot.Modules.Searches
@ -19,14 +20,30 @@ namespace NadekoBot.Modules.Searches
[Group]
public class AnimeSearchCommands
{
private Logger _log;
private static Timer anilistTokenRefresher { get; }
private static Logger _log { get; }
private static string anilistToken { get; set; }
private string anilistToken { get; set; }
private DateTime lastRefresh { get; set; }
public AnimeSearchCommands()
static AnimeSearchCommands()
{
_log = LogManager.GetCurrentClassLogger();
anilistTokenRefresher = new Timer(async (state) =>
{
var headers = new Dictionary<string, string> {
{"grant_type", "client_credentials"},
{"client_id", "kwoth-w0ki9"},
{"client_secret", "Qd6j4FIAi1ZK6Pc7N7V4Z"},
};
using (var http = new HttpClient())
{
http.AddFakeHeaders();
var formContent = new FormUrlEncodedContent(headers);
var response = await http.PostAsync("http://anilist.co/api/auth/access_token", formContent).ConfigureAwait(false);
var stringContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
anilistToken = JObject.Parse(stringContent)["access_token"].ToString();
}
}, null, TimeSpan.FromSeconds(0), TimeSpan.FromMinutes(29));
}
[NadekoCommand, Usage, Description, Aliases]
@ -119,7 +136,6 @@ namespace NadekoBot.Modules.Searches
throw new ArgumentNullException(nameof(query));
try
{
await RefreshAnilistToken().ConfigureAwait(false);
var link = "http://anilist.co/api/anime/search/" + Uri.EscapeUriString(query);
using (var http = new HttpClient())
@ -137,37 +153,12 @@ namespace NadekoBot.Modules.Searches
}
}
private async Task RefreshAnilistToken()
{
if (DateTime.Now - lastRefresh > TimeSpan.FromMinutes(29))
lastRefresh = DateTime.Now;
else
{
return;
}
var headers = new Dictionary<string, string> {
{"grant_type", "client_credentials"},
{"client_id", "kwoth-w0ki9"},
{"client_secret", "Qd6j4FIAi1ZK6Pc7N7V4Z"},
};
using (var http = new HttpClient())
{
http.AddFakeHeaders();
var formContent = new FormUrlEncodedContent(headers);
var response = await http.PostAsync("http://anilist.co/api/auth/access_token", formContent).ConfigureAwait(false);
var stringContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
anilistToken = JObject.Parse(stringContent)["access_token"].ToString();
}
}
private async Task<MangaResult> GetMangaData(string query)
{
if (string.IsNullOrWhiteSpace(query))
throw new ArgumentNullException(nameof(query));
try
{
await RefreshAnilistToken().ConfigureAwait(false);
using (var http = new HttpClient())
{
var res = await http.GetStringAsync("http://anilist.co/api/manga/search/" + Uri.EscapeUriString(query) + $"?access_token={anilistToken}").ConfigureAwait(false);

View File

@ -19,11 +19,11 @@ namespace NadekoBot.Modules.Searches
[Group]
public class JokeCommands
{
private List<WoWJoke> wowJokes = new List<WoWJoke>();
private List<MagicItem> magicItems;
private Logger _log;
private static List<WoWJoke> wowJokes = new List<WoWJoke>();
private static List<MagicItem> magicItems;
private static Logger _log;
public JokeCommands()
static JokeCommands()
{
_log = LogManager.GetCurrentClassLogger();
if (File.Exists("data/wowjokes.json"))

View File

@ -23,7 +23,7 @@ namespace NadekoBot.Modules.Searches
obj["name"].GetHashCode();
}
private string[] trashTalk { get; } = { "Better ban your counters. You are going to carry the game anyway.",
private static string[] trashTalk { get; } = { "Better ban your counters. You are going to carry the game anyway.",
"Go with the flow. Don't think. Just ban one of these.",
"DONT READ BELOW! Ban Urgot mid OP 100%. Im smurf Diamond 1.",
"Ask your teammates what would they like to play, and ban that.",

View File

@ -18,9 +18,9 @@ namespace NadekoBot.Modules.Searches
[Group]
public class OsuCommands
{
private Logger _log;
private static Logger _log;
public OsuCommands()
static OsuCommands()
{
_log = LogManager.GetCurrentClassLogger();
}

View File

@ -21,9 +21,9 @@ namespace NadekoBot.Modules.Searches
public const string PokemonAbilitiesFile = "data/pokemon/pokemon_abilities.json";
public const string PokemonListFile = "data/pokemon/pokemon_list.json";
private Logger _log;
private static Logger _log;
public PokemonSearchCommands()
static PokemonSearchCommands()
{
_log = LogManager.GetCurrentClassLogger();
if (File.Exists(PokemonListFile))

View File

@ -69,14 +69,14 @@ namespace NadekoBot.Modules.Searches
[Group]
public class StreamNotificationCommands
{
private Timer checkTimer { get; }
private ConcurrentDictionary<string, StreamStatus> oldCachedStatuses = new ConcurrentDictionary<string, StreamStatus>();
private ConcurrentDictionary<string, StreamStatus> cachedStatuses = new ConcurrentDictionary<string, StreamStatus>();
private Logger _log { get; }
private static Timer checkTimer { get; }
private static ConcurrentDictionary<string, StreamStatus> oldCachedStatuses = new ConcurrentDictionary<string, StreamStatus>();
private static ConcurrentDictionary<string, StreamStatus> cachedStatuses = new ConcurrentDictionary<string, StreamStatus>();
private static Logger _log { get; }
private bool FirstPass { get; set; } = true;
private static bool FirstPass { get; set; } = true;
public StreamNotificationCommands()
static StreamNotificationCommands()
{
_log = NLog.LogManager.GetCurrentClassLogger();
@ -118,7 +118,7 @@ namespace NadekoBot.Modules.Searches
}, null, TimeSpan.Zero, TimeSpan.FromSeconds(60));
}
private async Task<StreamStatus> GetStreamStatus(FollowedStream stream, bool checkCache = true)
private static async Task<StreamStatus> GetStreamStatus(FollowedStream stream, bool checkCache = true)
{
string response;
StreamStatus result;

View File

@ -25,7 +25,7 @@ namespace NadekoBot.Modules.Searches
{
private IGoogleApiService _google { get; }
public Searches(ILocalization loc, CommandService cmds, ShardedDiscordClient client, IGoogleApiService youtube) : base(loc, cmds, client)
public Searches(ILocalization loc, CommandService cmds, ShardedDiscordClient client, IGoogleApiService youtube) : base()
{
_google = youtube;
}

View File

@ -22,7 +22,7 @@ namespace NadekoBot.Modules.Utility
if (guild == null)
server = channel.Guild;
else
server = _client.GetGuilds().Where(g => g.Name.ToUpperInvariant() == guild.ToUpperInvariant()).FirstOrDefault();
server = NadekoBot.Client.GetGuilds().Where(g => g.Name.ToUpperInvariant() == guild.ToUpperInvariant()).FirstOrDefault();
if (server == null)
return;

View File

@ -22,7 +22,7 @@ namespace NadekoBot.Modules.Utility
[NadekoModule("Utility", ".")]
public partial class Utility : DiscordModule
{
public Utility(ILocalization loc, CommandService cmds, ShardedDiscordClient client) : base(loc, cmds, client)
public Utility() : base()
{
}
@ -236,8 +236,11 @@ namespace NadekoBot.Modules.Utility
var result = string.Join("\n", matches.Cast<Match>()
.Select(m => $"**Name:** {m.Groups["name"]} **Link:** http://discordapp.com/api/emojis/{m.Groups["id"]}.png"));
await msg.Channel.SendMessageAsync(result).ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(result))
await msg.Channel.SendErrorAsync("No special emojis found.");
else
await msg.Channel.SendMessageAsync(result).ConfigureAwait(false);
}
[NadekoCommand, Usage, Description, Aliases]

View File

@ -75,12 +75,12 @@ namespace NadekoBot
CommandHandler = new CommandHandler(Client, CommandService);
Stats = new StatsService(Client, CommandHandler);
//setup DI
var depMap = new DependencyMap();
depMap.Add<ILocalization>(Localizer);
depMap.Add<ShardedDiscordClient>(Client);
depMap.Add<CommandService>(CommandService);
depMap.Add<IGoogleApiService>(Google);
////setup DI
//var depMap = new DependencyMap();
//depMap.Add<ILocalization>(Localizer);
//depMap.Add<ShardedDiscordClient>(Client);
//depMap.Add<CommandService>(CommandService);
//depMap.Add<IGoogleApiService>(Google);
//setup typereaders
@ -104,7 +104,7 @@ namespace NadekoBot
// start handling messages received in commandhandler
await CommandHandler.StartHandling().ConfigureAwait(false);
await CommandService.LoadAssembly(this.GetType().GetTypeInfo().Assembly, depMap).ConfigureAwait(false);
await CommandService.LoadAssembly(this.GetType().GetTypeInfo().Assembly).ConfigureAwait(false);
#if !GLOBAL_NADEKO
await CommandService.Load(new Music(Localizer, CommandService, Client, Google)).ConfigureAwait(false);
#endif

View File

@ -79,80 +79,7 @@ namespace NadekoBot.Extensions
public static IEnumerable<IUser> Members(this IRole role) =>
NadekoBot.Client.GetGuild(role.GuildId)?.GetUsers().Where(u => u.Roles.Contains(role)) ?? Enumerable.Empty<IUser>();
public static async Task<IUserMessage[]> ReplyLong(this IUserMessage msg, string content, string[] breakOn = null, string addToPartialEnd = "", string addToPartialStart = "")
{
if (content.Length == 0) return null;
var characterLimit = 1750;
if (content.Length < characterLimit) return new[] { await msg.Channel.SendMessageAsync(content).ConfigureAwait(false) };
if (breakOn == null) breakOn = new[] { "\n", " ", " " };
var list = new List<IUserMessage>();
var splitItems = new List<string>();
foreach (var breaker in breakOn)
{
if (splitItems.Count == 0)
{
splitItems = Regex.Split(content, $"(?={breaker})").Where(s => !string.IsNullOrWhiteSpace(s)).ToList();
}
else
{
for (int i = 0; i < splitItems.Count; i++)
{
var temp = splitItems[i];
if (temp.Length > characterLimit)
{
var splitDeep = Regex.Split(temp, $"(?={breaker})").Where(s => !string.IsNullOrWhiteSpace(s));
splitItems.RemoveAt(i);
splitItems.InsertRange(i, splitDeep);
}
}
}
if (splitItems.All(s => s.Length < characterLimit)) break;
}
//We remove any entries that are larger than 2000 chars
if (splitItems.Any(s => s.Length >= characterLimit))
{
splitItems = splitItems.Where(s => s.Length < characterLimit).ToList();
}
//ensured every item can be sent (if individually)
var firstItem = true;
Queue<string> buildItems = new Queue<string>(splitItems);
StringBuilder builder = new StringBuilder();
while (buildItems.Count > 0)
{
if (builder.Length == 0)
{
//first item to add
if (!firstItem)
builder.Append(addToPartialStart);
else
firstItem = false;
builder.Append(buildItems.Dequeue());
}
else
{
builder.Append(buildItems.Dequeue());
}
if (buildItems.Count == 0)
{
list.Add(await msg.Channel.SendMessageAsync(builder.ToString()));
builder.Clear();
}
else
{
var peeked = buildItems.Peek();
if (builder.Length + peeked.Length + addToPartialEnd.Length > characterLimit)
{
builder.Append(addToPartialEnd);
list.Add(await msg.Channel.SendMessageAsync(builder.ToString()));
builder.Clear();
}
}
}
return list.ToArray();
}
public static Task<IUserMessage> EmbedAsync(this IMessageChannel ch, Discord.API.Embed embed, string msg = "")
=> ch.SendMessageAsync(msg, embed: embed);

View File

@ -60,8 +60,11 @@
},
"configurations": {
"GlobalNadeko": {
"buildOptions": { "define": [ "GLOBAL_NADEKO" ] },
"compilationOptions": { "optimize": true }
"buildOptions": {
"define": [ "GLOBAL_NADEKO" ],
"nowarn": [ "CS1573", "CS1591" ],
"optimize": true
}
}
}
}