quite a bit of cleanup

This commit is contained in:
Kwoth 2017-02-14 14:30:21 +01:00
parent d49af3389e
commit db49096246
35 changed files with 174 additions and 192 deletions

View File

@ -74,8 +74,8 @@ namespace NadekoBot.Modules.Administration
var title = $"DM from [{msg.Author}]({msg.Author.Id})"; var title = $"DM from [{msg.Author}]({msg.Author.Id})";
if (ForwardDMsToAllOwners) if (ForwardDMsToAllOwners)
{ {
var msgs = await Task.WhenAll(ownerChannels.Where(ch => ch.Recipient.Id != msg.Author.Id) await Task.WhenAll(ownerChannels.Where(ch => ch.Recipient.Id != msg.Author.Id)
.Select(ch => ch.SendConfirmAsync(title, msg.Content))).ConfigureAwait(false); .Select(ch => ch.SendConfirmAsync(title, msg.Content))).ConfigureAwait(false);
} }
else else
{ {

View File

@ -35,19 +35,15 @@ namespace NadekoBot.Modules.Administration
private static ConcurrentDictionary<ITextChannel, List<string>> PresenceUpdates { get; } = new ConcurrentDictionary<ITextChannel, List<string>>(); private static ConcurrentDictionary<ITextChannel, List<string>> PresenceUpdates { get; } = new ConcurrentDictionary<ITextChannel, List<string>>();
private static Timer timerReference { get; } private static Timer timerReference { get; }
private IGoogleApiService _google { get; }
static LogCommands() static LogCommands()
{ {
_client = NadekoBot.Client; _client = NadekoBot.Client;
_log = LogManager.GetCurrentClassLogger(); _log = LogManager.GetCurrentClassLogger();
var sw = Stopwatch.StartNew(); var sw = Stopwatch.StartNew();
using (var uow = DbHandler.UnitOfWork()) GuildLogSettings = new ConcurrentDictionary<ulong, LogSetting>(NadekoBot.AllGuildConfigs
{ .ToDictionary(g => g.GuildId, g => g.LogSetting));
GuildLogSettings = new ConcurrentDictionary<ulong, LogSetting>(NadekoBot.AllGuildConfigs
.ToDictionary(g => g.GuildId, g => g.LogSetting));
}
timerReference = new Timer(async (state) => timerReference = new Timer(async (state) =>
{ {
@ -59,7 +55,11 @@ namespace NadekoBot.Modules.Administration
{ {
List<string> messages; List<string> messages;
if (PresenceUpdates.TryRemove(key, out messages)) if (PresenceUpdates.TryRemove(key, out messages))
try { await key.SendConfirmAsync("Presence Updates", string.Join(Environment.NewLine, messages)); } catch { } try { await key.SendConfirmAsync("Presence Updates", string.Join(Environment.NewLine, messages)); }
catch
{
// ignored
}
})); }));
} }
catch (Exception ex) catch (Exception ex)
@ -159,7 +159,9 @@ namespace NadekoBot.Modules.Administration
//} //}
} }
catch catch
{ } {
// ignored
}
} }
private static async Task _client_UserVoiceStateUpdated_TTS(SocketUser iusr, SocketVoiceState before, SocketVoiceState after) private static async Task _client_UserVoiceStateUpdated_TTS(SocketUser iusr, SocketVoiceState before, SocketVoiceState after)
@ -188,7 +190,7 @@ namespace NadekoBot.Modules.Administration
var str = ""; var str = "";
if (beforeVch?.Guild == afterVch?.Guild) if (beforeVch?.Guild == afterVch?.Guild)
{ {
str = $"{usr.Username} moved from {beforeVch.Name} to {afterVch.Name}"; str = $"{usr.Username} moved from {beforeVch?.Name} to {afterVch?.Name}";
} }
else if (beforeVch == null) else if (beforeVch == null)
{ {
@ -201,7 +203,10 @@ namespace NadekoBot.Modules.Administration
var toDelete = await logChannel.SendMessageAsync(str, true).ConfigureAwait(false); var toDelete = await logChannel.SendMessageAsync(str, true).ConfigureAwait(false);
toDelete.DeleteAfter(5); toDelete.DeleteAfter(5);
} }
catch { } catch
{
// ignored
}
} }
private static async void MuteCommands_UserMuted(IGuildUser usr, MuteCommands.MuteType muteType) private static async void MuteCommands_UserMuted(IGuildUser usr, MuteCommands.MuteType muteType)
@ -216,7 +221,7 @@ namespace NadekoBot.Modules.Administration
ITextChannel logChannel; ITextChannel logChannel;
if ((logChannel = await TryGetLogChannel(usr.Guild, logSetting, LogType.UserMuted)) == null) if ((logChannel = await TryGetLogChannel(usr.Guild, logSetting, LogType.UserMuted)) == null)
return; return;
string mutes = ""; var mutes = "";
switch (muteType) switch (muteType)
{ {
case MuteCommands.MuteType.Voice: case MuteCommands.MuteType.Voice:

View File

@ -103,11 +103,8 @@ namespace NadekoBot.Modules.Administration
var greetChannel = (ulong)(long)reader["GreetChannelId"]; var greetChannel = (ulong)(long)reader["GreetChannelId"];
var greetMsg = (string)reader["GreetText"]; var greetMsg = (string)reader["GreetText"];
var bye = (long)reader["Bye"] == 1; var bye = (long)reader["Bye"] == 1;
var byeDM = (long)reader["ByePM"] == 1;
var byeChannel = (ulong)(long)reader["ByeChannelId"]; var byeChannel = (ulong)(long)reader["ByeChannelId"];
var byeMsg = (string)reader["ByeText"]; var byeMsg = (string)reader["ByeText"];
var grdel = false;
var byedel = grdel;
var gc = uow.GuildConfigs.For(gid, set => set); var gc = uow.GuildConfigs.For(gid, set => set);
if (greetDM) if (greetDM)
@ -121,7 +118,6 @@ namespace NadekoBot.Modules.Administration
gc.ByeMessageChannelId = byeChannel; gc.ByeMessageChannelId = byeChannel;
gc.ChannelByeMessageText = byeMsg; gc.ChannelByeMessageText = byeMsg;
gc.AutoDeleteGreetMessagesTimer = gc.AutoDeleteByeMessagesTimer = grdel ? 30 : 0;
_log.Info(++i); _log.Info(++i);
} }
} }
@ -129,12 +125,12 @@ namespace NadekoBot.Modules.Administration
_log.Warn("Greet/bye messages won't be migrated"); _log.Warn("Greet/bye messages won't be migrated");
} }
var com2 = db.CreateCommand(); var com2 = db.CreateCommand();
com.CommandText = "SELECT * FROM CurrencyState GROUP BY UserId"; com2.CommandText = "SELECT * FROM CurrencyState GROUP BY UserId";
i = 0; i = 0;
try try
{ {
var reader2 = com.ExecuteReader(); var reader2 = com2.ExecuteReader();
while (reader2.Read()) while (reader2.Read())
{ {
_log.Info(++i); _log.Info(++i);
@ -203,7 +199,6 @@ namespace NadekoBot.Modules.Administration
guildConfig.ExclusiveSelfAssignedRoles = data.ExclusiveSelfAssignedRoles; guildConfig.ExclusiveSelfAssignedRoles = data.ExclusiveSelfAssignedRoles;
guildConfig.GenerateCurrencyChannelIds = new HashSet<GCChannelId>(data.GenerateCurrencyChannels.Select(gc => new GCChannelId() { ChannelId = gc.Key })); guildConfig.GenerateCurrencyChannelIds = new HashSet<GCChannelId>(data.GenerateCurrencyChannels.Select(gc => new GCChannelId() { ChannelId = gc.Key }));
selfAssRoles.AddRange(data.ListOfSelfAssignableRoles.Select(r => new SelfAssignedRole() { GuildId = guildConfig.GuildId, RoleId = r }).ToArray()); selfAssRoles.AddRange(data.ListOfSelfAssignableRoles.Select(r => new SelfAssignedRole() { GuildId = guildConfig.GuildId, RoleId = r }).ToArray());
var logSetting = guildConfig.LogSetting;
guildConfig.LogSetting.IgnoredChannels = new HashSet<IgnoredLogChannel>(data.LogserverIgnoreChannels.Select(id => new IgnoredLogChannel() { ChannelId = id })); guildConfig.LogSetting.IgnoredChannels = new HashSet<IgnoredLogChannel>(data.LogserverIgnoreChannels.Select(id => new IgnoredLogChannel() { ChannelId = id }));
guildConfig.LogSetting.LogUserPresenceId = data.LogPresenceChannel; guildConfig.LogSetting.LogUserPresenceId = data.LogPresenceChannel;
@ -249,7 +244,7 @@ namespace NadekoBot.Modules.Administration
private void MigratePermissions0_9(IUnitOfWork uow) private void MigratePermissions0_9(IUnitOfWork uow)
{ {
var PermissionsDict = new ConcurrentDictionary<ulong, ServerPermissions0_9>(); var permissionsDict = new ConcurrentDictionary<ulong, ServerPermissions0_9>();
if (!Directory.Exists("data/permissions/")) if (!Directory.Exists("data/permissions/"))
{ {
_log.Warn("No data from permissions will be migrated."); _log.Warn("No data from permissions will be migrated.");
@ -263,12 +258,15 @@ namespace NadekoBot.Modules.Administration
if (string.IsNullOrWhiteSpace(strippedFileName)) continue; if (string.IsNullOrWhiteSpace(strippedFileName)) continue;
var id = ulong.Parse(strippedFileName); var id = ulong.Parse(strippedFileName);
var data = JsonConvert.DeserializeObject<ServerPermissions0_9>(File.ReadAllText(file)); var data = JsonConvert.DeserializeObject<ServerPermissions0_9>(File.ReadAllText(file));
PermissionsDict.TryAdd(id, data); permissionsDict.TryAdd(id, data);
}
catch
{
// ignored
} }
catch { }
} }
var i = 0; var i = 0;
PermissionsDict permissionsDict
.Select(p => new { data = p.Value, gconfig = uow.GuildConfigs.For(p.Key) }) .Select(p => new { data = p.Value, gconfig = uow.GuildConfigs.For(p.Key) })
.AsParallel() .AsParallel()
.ForAll(perms => .ForAll(perms =>

View File

@ -36,8 +36,6 @@ namespace NadekoBot.Modules.Administration
static MuteCommands() static MuteCommands()
{ {
var _log = LogManager.GetCurrentClassLogger();
var configs = NadekoBot.AllGuildConfigs; var configs = NadekoBot.AllGuildConfigs;
GuildMuteRoles = new ConcurrentDictionary<ulong, string>(configs GuildMuteRoles = new ConcurrentDictionary<ulong, string>(configs
.Where(c => !string.IsNullOrWhiteSpace(c.MuteRoleName)) .Where(c => !string.IsNullOrWhiteSpace(c.MuteRoleName))

View File

@ -402,8 +402,6 @@ namespace NadekoBot.Modules.Administration
[RequireContext(ContextType.Guild)] [RequireContext(ContextType.Guild)]
public async Task AntiList() public async Task AntiList()
{ {
var channel = (ITextChannel)Context.Channel;
AntiSpamStats spam; AntiSpamStats spam;
antiSpamGuilds.TryGetValue(Context.Guild.Id, out spam); antiSpamGuilds.TryGetValue(Context.Guild.Id, out spam);

View File

@ -37,26 +37,22 @@ namespace NadekoBot.Modules.Administration
public bool CheckUserRatelimit(ulong id) public bool CheckUserRatelimit(ulong id)
{ {
RatelimitedUser usr = Users.GetOrAdd(id, (key) => new RatelimitedUser() { UserId = id }); var usr = Users.GetOrAdd(id, (key) => new RatelimitedUser() { UserId = id });
if (usr.MessageCount == MaxMessages) if (usr.MessageCount == MaxMessages)
{ {
return true; return true;
} }
else usr.MessageCount++;
var _ = Task.Run(async () =>
{ {
usr.MessageCount++; try
var t = Task.Run(async () =>
{ {
try await Task.Delay(PerSeconds * 1000, cancelSource.Token);
{ }
await Task.Delay(PerSeconds * 1000, cancelSource.Token); catch (OperationCanceledException) { }
} usr.MessageCount--;
catch (OperationCanceledException) { } });
usr.MessageCount--; return false;
});
return false;
}
} }
} }

View File

@ -18,10 +18,10 @@ namespace NadekoBot.Modules.Administration
public partial class Administration public partial class Administration
{ {
[Group] [Group]
public class ServerGreetCommands : ModuleBase public class ServerGreetCommands : NadekoSubmodule
{ {
//make this to a field in the guildconfig table //make this to a field in the guildconfig table
class GreetSettings private class GreetSettings
{ {
public int AutoDeleteGreetMessagesTimer { get; set; } public int AutoDeleteGreetMessagesTimer { get; set; }
public int AutoDeleteByeMessagesTimer { get; set; } public int AutoDeleteByeMessagesTimer { get; set; }
@ -129,7 +129,10 @@ namespace NadekoBot.Modules.Administration
catch (Exception ex) { _log.Warn(ex); } catch (Exception ex) { _log.Warn(ex); }
} }
} }
catch { } catch
{
// ignored
}
}); });
return Task.CompletedTask; return Task.CompletedTask;
} }
@ -212,7 +215,10 @@ namespace NadekoBot.Modules.Administration
} }
} }
} }
catch { } catch
{
// ignored
}
}); });
return Task.CompletedTask; return Task.CompletedTask;
} }
@ -222,7 +228,6 @@ namespace NadekoBot.Modules.Administration
[RequireUserPermission(GuildPermission.ManageGuild)] [RequireUserPermission(GuildPermission.ManageGuild)]
public async Task GreetDel(int timer = 30) public async Task GreetDel(int timer = 30)
{ {
var channel = (ITextChannel)Context.Channel;
if (timer < 0 || timer > 600) if (timer < 0 || timer > 600)
return; return;
@ -375,7 +380,7 @@ namespace NadekoBot.Modules.Administration
await Context.Channel.SendConfirmAsync("🆗 New DM greet message **set**.").ConfigureAwait(false); await Context.Channel.SendConfirmAsync("🆗 New DM greet message **set**.").ConfigureAwait(false);
if (!sendGreetEnabled) if (!sendGreetEnabled)
await Context.Channel.SendConfirmAsync($" Enable DM greet messsages by typing `{NadekoBot.ModulePrefixes[typeof(Administration).Name]}greetdm`").ConfigureAwait(false); await Context.Channel.SendConfirmAsync($" Enable DM greet messsages by typing `{Prefix}greetdm`").ConfigureAwait(false);
} }
public static bool SetGreetDmMessage(ulong guildId, ref string message) public static bool SetGreetDmMessage(ulong guildId, ref string message)
@ -450,7 +455,7 @@ namespace NadekoBot.Modules.Administration
await Context.Channel.SendConfirmAsync("🆗 New bye message **set**.").ConfigureAwait(false); await Context.Channel.SendConfirmAsync("🆗 New bye message **set**.").ConfigureAwait(false);
if (!sendByeEnabled) if (!sendByeEnabled)
await Context.Channel.SendConfirmAsync($" Enable bye messsages by typing `{NadekoBot.ModulePrefixes[typeof(Administration).Name]}bye`").ConfigureAwait(false); await Context.Channel.SendConfirmAsync($" Enable bye messsages by typing `{Prefix}bye`").ConfigureAwait(false);
} }
public static bool SetByeMessage(ulong guildId, ref string message) public static bool SetByeMessage(ulong guildId, ref string message)

View File

@ -30,10 +30,8 @@ namespace NadekoBot.Modules.Administration
{ {
var _log = LogManager.GetCurrentClassLogger(); var _log = LogManager.GetCurrentClassLogger();
var sw = Stopwatch.StartNew(); var sw = Stopwatch.StartNew();
using (var uow = DbHandler.UnitOfWork())
{ voicePlusTextCache = new ConcurrentHashSet<ulong>(NadekoBot.AllGuildConfigs.Where(g => g.VoicePlusTextEnabled).Select(g => g.GuildId));
voicePlusTextCache = new ConcurrentHashSet<ulong>(NadekoBot.AllGuildConfigs.Where(g => g.VoicePlusTextEnabled).Select(g => g.GuildId));
}
NadekoBot.Client.UserVoiceStateUpdated += UserUpdatedEventHandler; NadekoBot.Client.UserVoiceStateUpdated += UserUpdatedEventHandler;
sw.Stop(); sw.Stop();

View File

@ -23,12 +23,8 @@ namespace NadekoBot.Modules.ClashOfClans
private static Timer checkWarTimer { get; } private static Timer checkWarTimer { get; }
private static new readonly Logger _log;
static ClashOfClans() static ClashOfClans()
{ {
_log = LogManager.GetCurrentClassLogger();
var sw = Stopwatch.StartNew();
using (var uow = DbHandler.UnitOfWork()) using (var uow = DbHandler.UnitOfWork())
{ {
ClashWars = new ConcurrentDictionary<ulong, List<ClashWar>>( ClashWars = new ConcurrentDictionary<ulong, List<ClashWar>>(
@ -244,7 +240,6 @@ namespace NadekoBot.Modules.ClashOfClans
SaveWar(war); SaveWar(war);
await ReplyConfirmLocalized("war_ended", warsInfo.Item1[warsInfo.Item2].ShortPrint()).ConfigureAwait(false); await ReplyConfirmLocalized("war_ended", warsInfo.Item1[warsInfo.Item2].ShortPrint()).ConfigureAwait(false);
var size = warsInfo.Item1[warsInfo.Item2].Size;
warsInfo.Item1.RemoveAt(warsInfo.Item2); warsInfo.Item1.RemoveAt(warsInfo.Item2);
} }

View File

@ -165,7 +165,7 @@ namespace NadekoBot.Modules.CustomReactions
} }
else else
{ {
var reactions = GuildReactions.AddOrUpdate(Context.Guild.Id, GuildReactions.AddOrUpdate(Context.Guild.Id,
new CustomReaction[] { cr }, new CustomReaction[] { cr },
(k, old) => (k, old) =>
{ {

View File

@ -17,7 +17,7 @@ namespace NadekoBot.Modules.Gambling
public partial class Gambling public partial class Gambling
{ {
[Group] [Group]
public class AnimalRacing : ModuleBase public class AnimalRacing : NadekoSubmodule
{ {
public static ConcurrentDictionary<ulong, AnimalRace> AnimalRaces { get; } = new ConcurrentDictionary<ulong, AnimalRace>(); public static ConcurrentDictionary<ulong, AnimalRace> AnimalRaces { get; } = new ConcurrentDictionary<ulong, AnimalRace>();
@ -25,7 +25,7 @@ namespace NadekoBot.Modules.Gambling
[RequireContext(ContextType.Guild)] [RequireContext(ContextType.Guild)]
public async Task Race() public async Task Race()
{ {
var ar = new AnimalRace(Context.Guild.Id, (ITextChannel)Context.Channel); var ar = new AnimalRace(Context.Guild.Id, (ITextChannel)Context.Channel, Prefix);
if (ar.Fail) if (ar.Fail)
await Context.Channel.SendErrorAsync("🏁 `Failed starting a race. Another race is probably running.`").ConfigureAwait(false); await Context.Channel.SendErrorAsync("🏁 `Failed starting a race. Another race is probably running.`").ConfigureAwait(false);
@ -59,13 +59,16 @@ namespace NadekoBot.Modules.Gambling
public List<Participant> participants = new List<Participant>(); public List<Participant> participants = new List<Participant>();
private ulong serverId; private ulong serverId;
private int messagesSinceGameStarted = 0; private int messagesSinceGameStarted = 0;
private readonly string _prefix;
private Logger _log { get; } private Logger _log { get; }
public ITextChannel raceChannel { get; set; } public ITextChannel raceChannel { get; set; }
public bool Started { get; private set; } = false; public bool Started { get; private set; } = false;
public AnimalRace(ulong serverId, ITextChannel ch) public AnimalRace(ulong serverId, ITextChannel ch, string prefix)
{ {
this._prefix = prefix;
this._log = LogManager.GetCurrentClassLogger(); this._log = LogManager.GetCurrentClassLogger();
this.serverId = serverId; this.serverId = serverId;
this.raceChannel = ch; this.raceChannel = ch;
@ -74,11 +77,8 @@ namespace NadekoBot.Modules.Gambling
Fail = true; Fail = true;
return; return;
} }
using (var uow = DbHandler.UnitOfWork()) animals = new ConcurrentQueue<string>(NadekoBot.BotConfig.RaceAnimals.Select(ra => ra.Icon).Shuffle());
{
animals = new ConcurrentQueue<string>(NadekoBot.BotConfig.RaceAnimals.Select(ra => ra.Icon).Shuffle());
}
var cancelSource = new CancellationTokenSource(); var cancelSource = new CancellationTokenSource();
@ -91,7 +91,7 @@ namespace NadekoBot.Modules.Gambling
try try
{ {
await raceChannel.SendConfirmAsync("Animal Race", $"Starting in 20 seconds or when the room is full.", await raceChannel.SendConfirmAsync("Animal Race", $"Starting in 20 seconds or when the room is full.",
footer: $"Type {NadekoBot.ModulePrefixes[typeof(Gambling).Name]}jr to join the race."); footer: $"Type {_prefix}jr to join the race.");
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -280,9 +280,7 @@ namespace NadekoBot.Modules.Gambling
public override bool Equals(object obj) public override bool Equals(object obj)
{ {
var p = obj as Participant; var p = obj as Participant;
return p == null ? return p != null && p.User == User;
false :
p.User == User;
} }
public override string ToString() public override string ToString()

View File

@ -43,22 +43,15 @@ namespace NadekoBot.Modules.Gambling
[OwnerOnly] [OwnerOnly]
public async Task StartEvent(CurrencyEvent e, int arg = -1) public async Task StartEvent(CurrencyEvent e, int arg = -1)
{ {
var channel = (ITextChannel)Context.Channel; switch (e)
try
{ {
switch (e) case CurrencyEvent.FlowerReaction:
{ await FlowerReactionEvent(Context).ConfigureAwait(false);
case CurrencyEvent.FlowerReaction: break;
await FlowerReactionEvent(Context).ConfigureAwait(false); case CurrencyEvent.SneakyGameStatus:
break; await SneakyGameStatusEvent(Context, arg).ConfigureAwait(false);
case CurrencyEvent.SneakyGameStatus: break;
await SneakyGameStatusEvent(Context, arg).ConfigureAwait(false);
break;
default:
break;
}
} }
catch { }
} }
public static async Task SneakyGameStatusEvent(CommandContext Context, int? arg) public static async Task SneakyGameStatusEvent(CommandContext Context, int? arg)
@ -77,8 +70,7 @@ namespace NadekoBot.Modules.Gambling
{ {
_secretCode += _sneakyGameStatusChars[rng.Next(0, _sneakyGameStatusChars.Length)]; _secretCode += _sneakyGameStatusChars[rng.Next(0, _sneakyGameStatusChars.Length)];
} }
var game = NadekoBot.Client.Game?.Name;
await NadekoBot.Client.SetGameAsync($"type {_secretCode} for " + NadekoBot.BotConfig.CurrencyPluralName) await NadekoBot.Client.SetGameAsync($"type {_secretCode} for " + NadekoBot.BotConfig.CurrencyPluralName)
.ConfigureAwait(false); .ConfigureAwait(false);
try try
@ -88,7 +80,10 @@ namespace NadekoBot.Modules.Gambling
$"Lasts {num} seconds. Don't tell anyone. Shhh.") $"Lasts {num} seconds. Don't tell anyone. Shhh.")
.ConfigureAwait(false); .ConfigureAwait(false);
} }
catch { } catch
{
// ignored
}
NadekoBot.Client.MessageReceived += SneakyGameMessageReceivedEventHandler; NadekoBot.Client.MessageReceived += SneakyGameMessageReceivedEventHandler;
@ -114,15 +109,18 @@ namespace NadekoBot.Modules.Gambling
.ConfigureAwait(false); .ConfigureAwait(false);
try { await arg.DeleteAsync(new RequestOptions() { RetryMode = RetryMode.AlwaysFail }).ConfigureAwait(false); } try { await arg.DeleteAsync(new RequestOptions() { RetryMode = RetryMode.AlwaysFail }).ConfigureAwait(false); }
catch { } catch
{
// ignored
}
}); });
} }
return Task.Delay(0); return Task.Delay(0);
} }
public static Task FlowerReactionEvent(CommandContext Context) => public static Task FlowerReactionEvent(CommandContext context) =>
new FlowerReactionEvent().Start(Context); new FlowerReactionEvent().Start(context);
} }
} }
@ -163,7 +161,7 @@ namespace NadekoBot.Modules.Gambling
if (msg?.Id == id) if (msg?.Id == id)
{ {
_log.Warn("Stopping flower reaction event because message is deleted."); _log.Warn("Stopping flower reaction event because message is deleted.");
Task.Run(() => End()); var __ = Task.Run(End);
} }
return Task.CompletedTask; return Task.CompletedTask;
@ -194,10 +192,14 @@ namespace NadekoBot.Modules.Gambling
{ {
if (r.Emoji.Name == "🌸" && r.User.IsSpecified && ((DateTime.UtcNow - r.User.Value.CreatedAt).TotalDays > 5) && _flowerReactionAwardedUsers.Add(r.User.Value.Id)) if (r.Emoji.Name == "🌸" && r.User.IsSpecified && ((DateTime.UtcNow - r.User.Value.CreatedAt).TotalDays > 5) && _flowerReactionAwardedUsers.Add(r.User.Value.Id))
{ {
try { await CurrencyHandler.AddCurrencyAsync(r.User.Value, "Flower Reaction Event", 100, false).ConfigureAwait(false); } catch { } await CurrencyHandler.AddCurrencyAsync(r.User.Value, "Flower Reaction Event", 100, false)
.ConfigureAwait(false);
} }
} }
catch { } catch
{
// ignored
}
})) }))
{ {
try try

View File

@ -260,7 +260,7 @@ namespace NadekoBot.Modules.Gambling
} }
finally finally
{ {
var t = Task.Run(async () => var _ = Task.Run(async () =>
{ {
await Task.Delay(2000); await Task.Delay(2000);
runningUsers.Remove(Context.User.Id); runningUsers.Remove(Context.User.Id);

View File

@ -197,8 +197,6 @@ namespace NadekoBot.Modules.Gambling
[RequireContext(ContextType.Guild)] [RequireContext(ContextType.Guild)]
public async Task Divorce([Remainder]IUser target) public async Task Divorce([Remainder]IUser target)
{ {
var channel = (ITextChannel)Context.Channel;
if (target.Id == Context.User.Id) if (target.Id == Context.User.Id)
return; return;

View File

@ -103,7 +103,6 @@ namespace NadekoBot.Modules.Gambling
[Priority(0)] [Priority(0)]
public async Task Award(int amount, [Remainder] IRole role) public async Task Award(int amount, [Remainder] IRole role)
{ {
var channel = (ITextChannel)Context.Channel;
var users = (await Context.Guild.GetUsersAsync()) var users = (await Context.Guild.GetUsersAsync())
.Where(u => u.GetRoles().Contains(role)) .Where(u => u.GetRoles().Contains(role))
.ToList(); .ToList();

View File

@ -21,12 +21,6 @@ namespace NadekoBot.Modules.Games
{ {
private static Logger _log { get; } private static Logger _log { get; }
class CleverAnswer
{
public string Status { get; set; }
public string Response { get; set; }
}
public static ConcurrentDictionary<ulong, Lazy<ChatterBotSession>> CleverbotGuilds { get; } = new ConcurrentDictionary<ulong, Lazy<ChatterBotSession>>(); public static ConcurrentDictionary<ulong, Lazy<ChatterBotSession>> CleverbotGuilds { get; } = new ConcurrentDictionary<ulong, Lazy<ChatterBotSession>>();
static CleverBotCommands() static CleverBotCommands()
@ -34,14 +28,12 @@ namespace NadekoBot.Modules.Games
_log = LogManager.GetCurrentClassLogger(); _log = LogManager.GetCurrentClassLogger();
var sw = Stopwatch.StartNew(); var sw = Stopwatch.StartNew();
using (var uow = DbHandler.UnitOfWork())
{ var bot = ChatterBotFactory.Create(ChatterBotType.CLEVERBOT);
var bot = ChatterBotFactory.Create(ChatterBotType.CLEVERBOT); CleverbotGuilds = new ConcurrentDictionary<ulong, Lazy<ChatterBotSession>>(
CleverbotGuilds = new ConcurrentDictionary<ulong, Lazy<ChatterBotSession>>( NadekoBot.AllGuildConfigs
NadekoBot.AllGuildConfigs .Where(gc => gc.CleverbotEnabled)
.Where(gc => gc.CleverbotEnabled) .ToDictionary(gc => gc.GuildId, gc => new Lazy<ChatterBotSession>(() => bot.CreateSession(), true)));
.ToDictionary(gc => gc.GuildId, gc => new Lazy<ChatterBotSession>(() => bot.CreateSession(), true)));
}
sw.Stop(); sw.Stop();
_log.Debug($"Loaded in {sw.Elapsed.TotalSeconds:F2}s"); _log.Debug($"Loaded in {sw.Elapsed.TotalSeconds:F2}s");

View File

@ -23,7 +23,8 @@ namespace NadekoBot.Modules.Games
static HangmanCommands() static HangmanCommands()
{ {
_log = LogManager.GetCurrentClassLogger(); _log = LogManager.GetCurrentClassLogger();
typesStr = $"`List of \"{NadekoBot.ModulePrefixes[typeof(Games).Name]}hangman\" term types:`\n" + String.Join(", ", HangmanTermPool.data.Keys); typesStr =
string.Format("`List of \"{0}hangman\" term types:`\n", NadekoBot.ModulePrefixes[typeof(Games).Name]) + String.Join(", ", HangmanTermPool.data.Keys);
} }
[NadekoCommand, Usage, Description, Aliases] [NadekoCommand, Usage, Description, Aliases]

View File

@ -29,7 +29,7 @@ namespace NadekoBot.Modules.Games
/// https://discord.gg/0TYNJfCU4De7YIk8 /// https://discord.gg/0TYNJfCU4De7YIk8
/// </summary> /// </summary>
[Group] [Group]
public class PlantPickCommands : ModuleBase public class PlantPickCommands : NadekoSubmodule
{ {
private static ConcurrentHashSet<ulong> generationChannels { get; } = new ConcurrentHashSet<ulong>(); private static ConcurrentHashSet<ulong> generationChannels { get; } = new ConcurrentHashSet<ulong>();
//channelid/message //channelid/message
@ -103,7 +103,8 @@ namespace NadekoBot.Modules.Games
var sent = await channel.SendFileAsync( var sent = await channel.SendFileAsync(
fileStream, fileStream,
file.Key, file.Key,
$"❗ {firstPart} Pick it up by typing `{NadekoBot.ModulePrefixes[typeof(Games).Name]}pick`") string.Format("❗ {0} Pick it up by typing `{1}pick`", firstPart,
NadekoBot.ModulePrefixes[typeof(Games).Name]))
.ConfigureAwait(false); .ConfigureAwait(false);
msgs[0] = sent; msgs[0] = sent;
@ -160,7 +161,7 @@ namespace NadekoBot.Modules.Games
var imgData = GetRandomCurrencyImage(); var imgData = GetRandomCurrencyImage();
var vowelFirst = new[] { 'a', 'e', 'i', 'o', 'u' }.Contains(NadekoBot.BotConfig.CurrencyName[0]); var vowelFirst = new[] { 'a', 'e', 'i', 'o', 'u' }.Contains(NadekoBot.BotConfig.CurrencyName[0]);
var msgToSend = $"Oh how Nice! **{Context.User.Username}** planted {(amount == 1 ? (vowelFirst ? "an" : "a") : amount.ToString())} {(amount > 1 ? NadekoBot.BotConfig.CurrencyPluralName : NadekoBot.BotConfig.CurrencyName)}. Pick it using {NadekoBot.ModulePrefixes[typeof(Games).Name]}pick"; var msgToSend = $"Oh how Nice! **{Context.User.Username}** planted {(amount == 1 ? (vowelFirst ? "an" : "a") : amount.ToString())} {(amount > 1 ? NadekoBot.BotConfig.CurrencyPluralName : NadekoBot.BotConfig.CurrencyName)}. Pick it using {Prefix}pick";
IUserMessage msg; IUserMessage msg;
using (var toSend = imgData.Value.ToStream()) using (var toSend = imgData.Value.ToStream())

View File

@ -307,7 +307,7 @@ namespace NadekoBot.Modules.Games
var del2 = previousMessage?.DeleteAsync(); var del2 = previousMessage?.DeleteAsync();
try { previousMessage = await _channel.EmbedAsync(GetEmbed(reason)); } catch { } try { previousMessage = await _channel.EmbedAsync(GetEmbed(reason)); } catch { }
try { await del1; } catch { } try { await del1; } catch { }
try { await del2; } catch { } try { if (del2 != null) await del2; } catch { }
}); });
curUserIndex ^= 1; curUserIndex ^= 1;

View File

@ -32,7 +32,6 @@ namespace NadekoBot.Modules.Games
{ {
if (string.IsNullOrWhiteSpace(question)) if (string.IsNullOrWhiteSpace(question))
return; return;
var rng = new NadekoRandom();
await Context.Channel.EmbedAsync(new EmbedBuilder().WithColor(NadekoBot.OkColor) await Context.Channel.EmbedAsync(new EmbedBuilder().WithColor(NadekoBot.OkColor)
.AddField(efb => efb.WithName("❓ Question").WithValue(question).WithIsInline(false)) .AddField(efb => efb.WithName("❓ Question").WithValue(question).WithIsInline(false))

View File

@ -415,27 +415,26 @@ namespace NadekoBot.Modules.Music
var arg = directory; var arg = directory;
if (string.IsNullOrWhiteSpace(arg)) if (string.IsNullOrWhiteSpace(arg))
return; return;
try var dir = new DirectoryInfo(arg);
var fileEnum = dir.GetFiles("*", SearchOption.AllDirectories)
.Where(x => !x.Attributes.HasFlag(FileAttributes.Hidden | FileAttributes.System));
var gusr = (IGuildUser)Context.User;
foreach (var file in fileEnum)
{ {
var dir = new DirectoryInfo(arg); try
var fileEnum = dir.GetFiles("*", SearchOption.AllDirectories)
.Where(x => !x.Attributes.HasFlag(FileAttributes.Hidden | FileAttributes.System));
var gusr = (IGuildUser)Context.User;
foreach (var file in fileEnum)
{ {
try await QueueSong(gusr, (ITextChannel)Context.Channel, gusr.VoiceChannel, file.FullName, true, MusicType.Local).ConfigureAwait(false);
{ }
await QueueSong(((IGuildUser)Context.User), (ITextChannel)Context.Channel, ((IGuildUser)Context.User).VoiceChannel, file.FullName, true, MusicType.Local).ConfigureAwait(false); catch (PlaylistFullException)
} {
catch (PlaylistFullException) break;
{ }
break; catch
} {
catch { } // ignored
} }
await Context.Channel.SendConfirmAsync("🎵 Directory queue complete.").ConfigureAwait(false);
} }
catch { } await Context.Channel.SendConfirmAsync("🎵 Directory queue complete.").ConfigureAwait(false);
} }
[NadekoCommand, Usage, Description, Aliases] [NadekoCommand, Usage, Description, Aliases]

View File

@ -101,23 +101,23 @@ namespace NadekoBot.Modules.Permissions
{ {
return true; return true;
} }
else activeCdsForGuild.Add(new ActiveCooldown()
{ {
activeCdsForGuild.Add(new ActiveCooldown() UserId = user.Id,
Command = cmd.Aliases.First().ToLowerInvariant(),
});
var _ = Task.Run(async () =>
{
try
{ {
UserId = user.Id, await Task.Delay(cdRule.Seconds * 1000);
Command = cmd.Aliases.First().ToLowerInvariant(), activeCdsForGuild.RemoveWhere(ac => ac.Command == cmd.Aliases.First().ToLowerInvariant() && ac.UserId == user.Id);
}); }
var t = Task.Run(async () => catch
{ {
try // ignored
{ }
await Task.Delay(cdRule.Seconds * 1000); });
activeCdsForGuild.RemoveWhere(ac => ac.Command == cmd.Aliases.First().ToLowerInvariant() && ac.UserId == user.Id);
}
catch { }
});
}
} }
return false; return false;
} }

View File

@ -42,23 +42,19 @@ namespace NadekoBot.Modules.Permissions
static FilterCommands() static FilterCommands()
{ {
using (var uow = DbHandler.UnitOfWork()) var guildConfigs = NadekoBot.AllGuildConfigs;
{
var guildConfigs = NadekoBot.AllGuildConfigs;
InviteFilteringServers = new ConcurrentHashSet<ulong>(guildConfigs.Where(gc => gc.FilterInvites).Select(gc => gc.GuildId)); InviteFilteringServers = new ConcurrentHashSet<ulong>(guildConfigs.Where(gc => gc.FilterInvites).Select(gc => gc.GuildId));
InviteFilteringChannels = new ConcurrentHashSet<ulong>(guildConfigs.SelectMany(gc => gc.FilterInvitesChannelIds.Select(fci => fci.ChannelId))); InviteFilteringChannels = new ConcurrentHashSet<ulong>(guildConfigs.SelectMany(gc => gc.FilterInvitesChannelIds.Select(fci => fci.ChannelId)));
var dict = guildConfigs.ToDictionary(gc => gc.GuildId, gc => new ConcurrentHashSet<string>(gc.FilteredWords.Select(fw => fw.Word))); var dict = guildConfigs.ToDictionary(gc => gc.GuildId, gc => new ConcurrentHashSet<string>(gc.FilteredWords.Select(fw => fw.Word)));
ServerFilteredWords = new ConcurrentDictionary<ulong, ConcurrentHashSet<string>>(dict); ServerFilteredWords = new ConcurrentDictionary<ulong, ConcurrentHashSet<string>>(dict);
var serverFiltering = guildConfigs.Where(gc => gc.FilterWords); var serverFiltering = guildConfigs.Where(gc => gc.FilterWords);
WordFilteringServers = new ConcurrentHashSet<ulong>(serverFiltering.Select(gc => gc.GuildId)); WordFilteringServers = new ConcurrentHashSet<ulong>(serverFiltering.Select(gc => gc.GuildId));
WordFilteringChannels = new ConcurrentHashSet<ulong>(guildConfigs.SelectMany(gc => gc.FilterWordsChannelIds.Select(fwci => fwci.ChannelId))); WordFilteringChannels = new ConcurrentHashSet<ulong>(guildConfigs.SelectMany(gc => gc.FilterWordsChannelIds.Select(fwci => fwci.ChannelId)));
}
} }
[NadekoCommand, Usage, Description, Aliases] [NadekoCommand, Usage, Description, Aliases]

View File

@ -230,7 +230,7 @@ namespace NadekoBot.Modules.Searches
var link = "http://anilist.co/api/anime/search/" + Uri.EscapeUriString(query); var link = "http://anilist.co/api/anime/search/" + Uri.EscapeUriString(query);
using (var http = new HttpClient()) using (var http = new HttpClient())
{ {
var res = await http.GetStringAsync("http://anilist.co/api/anime/search/" + Uri.EscapeUriString(query) + $"?access_token={anilistToken}").ConfigureAwait(false); var res = await http.GetStringAsync(link + $"?access_token={anilistToken}").ConfigureAwait(false);
var smallObj = JArray.Parse(res)[0]; var smallObj = JArray.Parse(res)[0];
var aniData = await http.GetStringAsync("http://anilist.co/api/anime/" + smallObj["id"] + $"?access_token={anilistToken}").ConfigureAwait(false); var aniData = await http.GetStringAsync("http://anilist.co/api/anime/" + smallObj["id"] + $"?access_token={anilistToken}").ConfigureAwait(false);

View File

@ -36,7 +36,7 @@ namespace NadekoBot.Modules.Searches
var rankimg = $"{model.Competitive.rank_img}"; var rankimg = $"{model.Competitive.rank_img}";
var rank = $"{model.Competitive.rank}"; var rank = $"{model.Competitive.rank}";
var competitiveplay = $"{model.Games.Competitive.played}"; //var competitiveplay = $"{model.Games.Competitive.played}";
if (string.IsNullOrWhiteSpace(rank)) if (string.IsNullOrWhiteSpace(rank))
{ {
var embed = new EmbedBuilder() var embed = new EmbedBuilder()

View File

@ -12,7 +12,8 @@ namespace NadekoBot.Modules.Searches
[Group] [Group]
public class PlaceCommands : ModuleBase public class PlaceCommands : ModuleBase
{ {
private static string typesStr { get; } = $"`List of \"{NadekoBot.ModulePrefixes[typeof(Searches).Name]}place\" tags:`\n" + String.Join(", ", Enum.GetNames(typeof(PlaceType))); private static string typesStr { get; } =
string.Format("`List of \"{0}place\" tags:`\n", NadekoBot.ModulePrefixes[typeof(Searches).Name]) + String.Join(", ", Enum.GetNames(typeof(PlaceType)));
public enum PlaceType public enum PlaceType
{ {

View File

@ -103,19 +103,23 @@ namespace NadekoBot.Modules.Searches
oldStatus.IsLive != newStatus.IsLive) oldStatus.IsLive != newStatus.IsLive)
{ {
var server = NadekoBot.Client.GetGuild(fs.GuildId); var server = NadekoBot.Client.GetGuild(fs.GuildId);
if (server == null) var channel = server?.GetTextChannel(fs.ChannelId);
return;
var channel = server.GetTextChannel(fs.ChannelId);
if (channel == null) if (channel == null)
return; return;
try try
{ {
var msg = await channel.EmbedAsync(fs.GetEmbed(newStatus)).ConfigureAwait(false); var msg = await channel.EmbedAsync(fs.GetEmbed(newStatus)).ConfigureAwait(false);
} }
catch { } catch
{
// ignored
}
} }
} }
catch { } catch
{
// ignored
}
})); }));
FirstPass = false; FirstPass = false;

View File

@ -499,12 +499,12 @@ namespace NadekoBot.Modules.Searches
var data = JsonConvert.DeserializeObject<DefineModel>(res); var data = JsonConvert.DeserializeObject<DefineModel>(res);
var sense = data.Results.Where(x => x.Senses != null && x.Senses[0].Definition != null).FirstOrDefault()?.Senses[0]; var sense = data.Results.FirstOrDefault(x => x.Senses?[0].Definition != null)?.Senses[0];
if (sense?.Definition == null) if (sense?.Definition == null)
return; return;
string definition = sense.Definition.ToString(); var definition = sense.Definition.ToString();
if (!(sense.Definition is string)) if (!(sense.Definition is string))
definition = ((JArray)JToken.Parse(sense.Definition.ToString())).First.ToString(); definition = ((JArray)JToken.Parse(sense.Definition.ToString())).First.ToString();
@ -536,7 +536,7 @@ namespace NadekoBot.Modules.Searches
} }
await Context.Channel.TriggerTypingAsync().ConfigureAwait(false); await Context.Channel.TriggerTypingAsync().ConfigureAwait(false);
string res = ""; var res = "";
using (var http = new HttpClient()) using (var http = new HttpClient())
{ {
http.DefaultRequestHeaders.Clear(); http.DefaultRequestHeaders.Clear();
@ -548,7 +548,7 @@ namespace NadekoBot.Modules.Searches
{ {
var items = JObject.Parse(res); var items = JObject.Parse(res);
var item = items["defs"]["def"]; var item = items["defs"]["def"];
var hashtag = item["hashtag"].ToString(); //var hashtag = item["hashtag"].ToString();
var link = item["uri"].ToString(); var link = item["uri"].ToString();
var desc = item["text"].ToString(); var desc = item["text"].ToString();
await Context.Channel.EmbedAsync(new EmbedBuilder().WithOkColor() await Context.Channel.EmbedAsync(new EmbedBuilder().WithOkColor()

View File

@ -32,7 +32,6 @@ namespace NadekoBot.Modules.Utility
var voicechn = (await guild.GetVoiceChannelsAsync()).Count(); var voicechn = (await guild.GetVoiceChannelsAsync()).Count();
var createdAt = new DateTime(2015, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(guild.Id >> 22); var createdAt = new DateTime(2015, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(guild.Id >> 22);
var sb = new StringBuilder();
var users = await guild.GetUsersAsync().ConfigureAwait(false); var users = await guild.GetUsersAsync().ConfigureAwait(false);
var features = string.Join("\n", guild.Features); var features = string.Join("\n", guild.Features);
if (string.IsNullOrWhiteSpace(features)) if (string.IsNullOrWhiteSpace(features))
@ -45,13 +44,13 @@ namespace NadekoBot.Modules.Utility
.AddField(fb => fb.WithName("**Members**").WithValue(users.Count.ToString()).WithIsInline(true)) .AddField(fb => fb.WithName("**Members**").WithValue(users.Count.ToString()).WithIsInline(true))
.AddField(fb => fb.WithName("**Text Channels**").WithValue(textchn.ToString()).WithIsInline(true)) .AddField(fb => fb.WithName("**Text Channels**").WithValue(textchn.ToString()).WithIsInline(true))
.AddField(fb => fb.WithName("**Voice Channels**").WithValue(voicechn.ToString()).WithIsInline(true)) .AddField(fb => fb.WithName("**Voice Channels**").WithValue(voicechn.ToString()).WithIsInline(true))
.AddField(fb => fb.WithName("**Created At**").WithValue($"{createdAt.ToString("dd.MM.yyyy HH:mm")}").WithIsInline(true)) .AddField(fb => fb.WithName("**Created At**").WithValue($"{createdAt:dd.MM.yyyy HH:mm}").WithIsInline(true))
.AddField(fb => fb.WithName("**Region**").WithValue(guild.VoiceRegionId.ToString()).WithIsInline(true)) .AddField(fb => fb.WithName("**Region**").WithValue(guild.VoiceRegionId.ToString()).WithIsInline(true))
.AddField(fb => fb.WithName("**Roles**").WithValue((guild.Roles.Count - 1).ToString()).WithIsInline(true)) .AddField(fb => fb.WithName("**Roles**").WithValue((guild.Roles.Count - 1).ToString()).WithIsInline(true))
.AddField(fb => fb.WithName("**Features**").WithValue(features).WithIsInline(true)) .AddField(fb => fb.WithName("**Features**").WithValue(features).WithIsInline(true))
.WithImageUrl(guild.IconUrl) .WithImageUrl(guild.IconUrl)
.WithColor(NadekoBot.OkColor); .WithColor(NadekoBot.OkColor);
if (guild.Emojis.Count() > 0) if (guild.Emojis.Any())
{ {
embed.AddField(fb => fb.WithName($"**Custom Emojis ({guild.Emojis.Count})**").WithValue(string.Join(" ", guild.Emojis.Shuffle().Take(25).Select(e => $"{e.Name} <:{e.Name}:{e.Id}>")))); embed.AddField(fb => fb.WithName($"**Custom Emojis ({guild.Emojis.Count})**").WithValue(string.Join(" ", guild.Emojis.Shuffle().Take(25).Select(e => $"{e.Name} <:{e.Name}:{e.Id}>"))));
} }
@ -71,7 +70,7 @@ namespace NadekoBot.Modules.Utility
.WithTitle(ch.Name) .WithTitle(ch.Name)
.WithDescription(ch.Topic?.SanitizeMentions()) .WithDescription(ch.Topic?.SanitizeMentions())
.AddField(fb => fb.WithName("**ID**").WithValue(ch.Id.ToString()).WithIsInline(true)) .AddField(fb => fb.WithName("**ID**").WithValue(ch.Id.ToString()).WithIsInline(true))
.AddField(fb => fb.WithName("**Created At**").WithValue($"{createdAt.ToString("dd.MM.yyyy HH:mm")}").WithIsInline(true)) .AddField(fb => fb.WithName("**Created At**").WithValue($"{createdAt:dd.MM.yyyy HH:mm}").WithIsInline(true))
.AddField(fb => fb.WithName("**Users**").WithValue(usercount.ToString()).WithIsInline(true)) .AddField(fb => fb.WithName("**Users**").WithValue(usercount.ToString()).WithIsInline(true))
.WithColor(NadekoBot.OkColor); .WithColor(NadekoBot.OkColor);
await Context.Channel.EmbedAsync(embed).ConfigureAwait(false); await Context.Channel.EmbedAsync(embed).ConfigureAwait(false);
@ -81,7 +80,6 @@ namespace NadekoBot.Modules.Utility
[RequireContext(ContextType.Guild)] [RequireContext(ContextType.Guild)]
public async Task UserInfo(IGuildUser usr = null) public async Task UserInfo(IGuildUser usr = null)
{ {
var channel = (ITextChannel)Context.Channel;
var user = usr ?? Context.User as IGuildUser; var user = usr ?? Context.User as IGuildUser;
if (user == null) if (user == null)
@ -95,7 +93,7 @@ namespace NadekoBot.Modules.Utility
} }
embed.AddField(fb => fb.WithName("**ID**").WithValue(user.Id.ToString()).WithIsInline(true)) embed.AddField(fb => fb.WithName("**ID**").WithValue(user.Id.ToString()).WithIsInline(true))
.AddField(fb => fb.WithName("**Joined Server**").WithValue($"{user.JoinedAt?.ToString("dd.MM.yyyy HH:mm") ?? "unavail."}").WithIsInline(true)) .AddField(fb => fb.WithName("**Joined Server**").WithValue($"{user.JoinedAt?.ToString("dd.MM.yyyy HH:mm") ?? "unavail."}").WithIsInline(true))
.AddField(fb => fb.WithName("**Joined Discord**").WithValue($"{user.CreatedAt.ToString("dd.MM.yyyy HH:mm")}").WithIsInline(true)) .AddField(fb => fb.WithName("**Joined Discord**").WithValue($"{user.CreatedAt:dd.MM.yyyy HH:mm}").WithIsInline(true))
.AddField(fb => fb.WithName("**Roles**").WithValue($"**({user.RoleIds.Count - 1})** - {string.Join("\n", user.GetRoles().Take(10).Where(r => r.Id != r.Guild.EveryoneRole.Id).Select(r => r.Name)).SanitizeMentions()}").WithIsInline(true)) .AddField(fb => fb.WithName("**Roles**").WithValue($"**({user.RoleIds.Count - 1})** - {string.Join("\n", user.GetRoles().Take(10).Where(r => r.Id != r.Guild.EveryoneRole.Id).Select(r => r.Name)).SanitizeMentions()}").WithIsInline(true))
.WithColor(NadekoBot.OkColor); .WithColor(NadekoBot.OkColor);

View File

@ -91,7 +91,7 @@ namespace NadekoBot.Modules.Utility
public void Reset() public void Reset()
{ {
source.Cancel(); source.Cancel();
var t = Task.Run(Run); var _ = Task.Run(Run);
} }
public void Stop() public void Stop()

View File

@ -45,15 +45,15 @@ namespace NadekoBot.Modules.Utility
foreach (var r in reminders) foreach (var r in reminders)
{ {
try { var t = StartReminder(r); } catch (Exception ex) { _log.Warn(ex); } Task.Run(() => StartReminder(r));
} }
} }
private static async Task StartReminder(Reminder r) private static async Task StartReminder(Reminder r)
{ {
var now = DateTime.Now; var now = DateTime.Now;
var twoMins = new TimeSpan(0, 2, 0);
TimeSpan time = r.When - now; var time = r.When - now;
if (time.TotalMilliseconds > int.MaxValue) if (time.TotalMilliseconds > int.MaxValue)
return; return;

View File

@ -468,7 +468,6 @@ namespace NadekoBot.Modules.Utility
[OwnerOnly] [OwnerOnly]
public async Task SaveChat(int cnt) public async Task SaveChat(int cnt)
{ {
var sb = new StringBuilder();
var msgs = new List<IMessage>(cnt); var msgs = new List<IMessage>(cnt);
await Context.Channel.GetMessagesAsync(cnt).ForEachAsync(dled => msgs.AddRange(dled)).ConfigureAwait(false); await Context.Channel.GetMessagesAsync(cnt).ForEachAsync(dled => msgs.AddRange(dled)).ConfigureAwait(false);

View File

@ -132,7 +132,7 @@ namespace NadekoBot.Services.Database
{ {
#region QUOTES #region QUOTES
var quoteEntity = modelBuilder.Entity<Quote>(); //var quoteEntity = modelBuilder.Entity<Quote>();
#endregion #endregion
@ -166,7 +166,7 @@ namespace NadekoBot.Services.Database
#endregion #endregion
#region BotConfig #region BotConfig
var botConfigEntity = modelBuilder.Entity<BotConfig>(); //var botConfigEntity = modelBuilder.Entity<BotConfig>();
//botConfigEntity //botConfigEntity
// .HasMany(c => c.ModulePrefixes) // .HasMany(c => c.ModulePrefixes)
// .WithOne(mp => mp.BotConfig) // .WithOne(mp => mp.BotConfig)

View File

@ -96,18 +96,21 @@ namespace NadekoBot.Services.Impl
content.Headers.Clear(); content.Headers.Clear();
content.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
var res = await http.PostAsync("https://www.carbonitex.net/discord/data/botdata.php", content).ConfigureAwait(false); await http.PostAsync("https://www.carbonitex.net/discord/data/botdata.php", content).ConfigureAwait(false);
} }
}; };
} }
catch { } catch
{
// ignored
}
}, null, TimeSpan.FromHours(1), TimeSpan.FromHours(1)); }, null, TimeSpan.FromHours(1), TimeSpan.FromHours(1));
} }
public void Initialize() public void Initialize()
{ {
var guilds = this.client.GetGuilds(); var guilds = this.client.GetGuilds().ToArray();
_textChannels = guilds.Sum(g => g.Channels.Where(cx => cx is ITextChannel).Count()); _textChannels = guilds.Sum(g => g.Channels.Count(cx => cx is ITextChannel));
_voiceChannels = guilds.Sum(g => g.Channels.Count) - _textChannels; _voiceChannels = guilds.Sum(g => g.Channels.Count) - _textChannels;
} }

View File

@ -41,7 +41,6 @@ namespace NadekoBot.Services
return minValue; return minValue;
var bytes = new byte[sizeof(int)]; var bytes = new byte[sizeof(int)];
rng.GetBytes(bytes); rng.GetBytes(bytes);
var num = BitConverter.ToInt32(bytes, 0);
var sign = Math.Sign(BitConverter.ToInt32(bytes, 0)); var sign = Math.Sign(BitConverter.ToInt32(bytes, 0));
return (sign * BitConverter.ToInt32(bytes, 0)) % (maxValue - minValue) + minValue; return (sign * BitConverter.ToInt32(bytes, 0)) % (maxValue - minValue) + minValue;
} }