.timezone command added

This commit is contained in:
Master Kwoth 2017-06-13 01:40:39 +02:00
parent 2ff55a49fb
commit 891afbe7e7
18 changed files with 278 additions and 88 deletions

View File

@ -1,6 +1,6 @@
#NadekoBot Documentation #NadekoBot Documentation
To invite NadekoBot to your server, click on the image bellow: To invite public NadekoBot to your server, click on the image bellow:
[![img][img]](https://discordapp.com/oauth2/authorize?client_id=170254782546575360&scope=bot&permissions=66186303) [![img][img]](https://discordapp.com/oauth2/authorize?client_id=170254782546575360&scope=bot&permissions=66186303)
@ -10,9 +10,7 @@ NadekoBot is an open source project, and it can be found on our [GitHub][GitHub]
Here you can read current [Issues][Issues]. Here you can read current [Issues][Issues].
If you want to contribute, be sure to PR on the **[dev][dev]** branch. If you want to contribute, be sure to PR on the **[1.4][1.4]** branch.
**NadekoBot 1.1 release currently does not support x86/32bit architecture.**
##Content ##Content
- [About](about.md) - [About](about.md)
@ -38,4 +36,4 @@ If you want to contribute, be sure to PR on the **[dev][dev]** branch.
[NadekoBot Server]: https://discord.gg/nadekobot [NadekoBot Server]: https://discord.gg/nadekobot
[GitHub]: https://github.com/Kwoth/NadekoBot [GitHub]: https://github.com/Kwoth/NadekoBot
[Issues]: https://github.com/Kwoth/NadekoBot/issues [Issues]: https://github.com/Kwoth/NadekoBot/issues
[dev]: https://github.com/Kwoth/NadekoBot/tree/dev [1.4]: https://github.com/Kwoth/NadekoBot/tree/1.4

View File

@ -0,0 +1,46 @@
using Discord.Commands;
using NadekoBot.Services.Administration;
using System;
using System.Threading.Tasks;
namespace NadekoBot.TypeReaders
{
public class GuildDateTimeTypeReader : TypeReader
{
private readonly GuildTimezoneService _gts;
public GuildDateTimeTypeReader(GuildTimezoneService gts)
{
_gts = gts;
}
public override Task<TypeReaderResult> Read(ICommandContext context, string input)
{
if (!DateTime.TryParse(input, out var dt))
return Task.FromResult(TypeReaderResult.FromError(CommandError.ParseFailed, "Input string is in an incorrect format."));
var tz = _gts.GetTimeZoneOrUtc(context.Guild.Id);
return Task.FromResult(TypeReaderResult.FromSuccess(new GuildDateTime(tz, dt)));
}
}
public class GuildDateTime
{
public TimeZoneInfo Timezone { get; }
public DateTime CurrentGuildTime { get; }
public DateTime InputTime { get; }
public DateTime InputTimeUtc { get; }
private GuildDateTime() { }
public GuildDateTime(TimeZoneInfo guildTimezone, DateTime inputTime)
{
var now = DateTime.UtcNow;
Timezone = guildTimezone;
CurrentGuildTime = TimeZoneInfo.ConvertTime(now, TimeZoneInfo.Utc, Timezone);
InputTime = inputTime;
InputTimeUtc = TimeZoneInfo.ConvertTime(inputTime, Timezone, TimeZoneInfo.Utc);
}
}
}

View File

@ -9,6 +9,7 @@ using NadekoBot.Services;
using NadekoBot.Attributes; using NadekoBot.Attributes;
using NadekoBot.Services.Database.Models; using NadekoBot.Services.Database.Models;
using NadekoBot.Services.Administration; using NadekoBot.Services.Administration;
using Discord.WebSocket;
namespace NadekoBot.Modules.Administration namespace NadekoBot.Modules.Administration
{ {
@ -319,7 +320,7 @@ namespace NadekoBot.Modules.Administration
var user = await Context.Guild.GetCurrentUserAsync().ConfigureAwait(false); var user = await Context.Guild.GetCurrentUserAsync().ConfigureAwait(false);
var enumerable = (await Context.Channel.GetMessagesAsync().Flatten()) var enumerable = (await Context.Channel.GetMessagesAsync().Flatten())
.Where(x => x.Author.Id == user.Id && DateTime.Now - x.CreatedAt < twoWeeks); .Where(x => x.Author.Id == user.Id && DateTime.UtcNow - x.CreatedAt < twoWeeks);
await Context.Channel.DeleteMessagesAsync(enumerable).ConfigureAwait(false); await Context.Channel.DeleteMessagesAsync(enumerable).ConfigureAwait(false);
Context.Message.DeleteAfter(3); Context.Message.DeleteAfter(3);
} }
@ -339,7 +340,7 @@ namespace NadekoBot.Modules.Administration
await Context.Message.DeleteAsync().ConfigureAwait(false); await Context.Message.DeleteAsync().ConfigureAwait(false);
int limit = (count < 100) ? count + 1 : 100; int limit = (count < 100) ? count + 1 : 100;
var enumerable = (await Context.Channel.GetMessagesAsync(limit: limit).Flatten().ConfigureAwait(false)) var enumerable = (await Context.Channel.GetMessagesAsync(limit: limit).Flatten().ConfigureAwait(false))
.Where(x => DateTime.Now - x.CreatedAt < twoWeeks); .Where(x => DateTime.UtcNow - x.CreatedAt < twoWeeks);
if (enumerable.FirstOrDefault()?.Id == Context.Message.Id) if (enumerable.FirstOrDefault()?.Id == Context.Message.Id)
enumerable = enumerable.Skip(1).ToArray(); enumerable = enumerable.Skip(1).ToArray();
else else
@ -363,7 +364,7 @@ namespace NadekoBot.Modules.Administration
int limit = (count < 100) ? count : 100; int limit = (count < 100) ? count : 100;
var enumerable = (await Context.Channel.GetMessagesAsync(limit: limit).Flatten()) var enumerable = (await Context.Channel.GetMessagesAsync(limit: limit).Flatten())
.Where(m => m.Author == user && DateTime.Now - m.CreatedAt < twoWeeks); .Where(m => m.Author == user && DateTime.UtcNow - m.CreatedAt < twoWeeks);
await Context.Channel.DeleteMessagesAsync(enumerable).ConfigureAwait(false); await Context.Channel.DeleteMessagesAsync(enumerable).ConfigureAwait(false);
Context.Message.DeleteAfter(3); Context.Message.DeleteAfter(3);
@ -428,45 +429,5 @@ namespace NadekoBot.Modules.Administration
} }
await ReplyConfirmLocalized("donadd", don.Amount).ConfigureAwait(false); await ReplyConfirmLocalized("donadd", don.Amount).ConfigureAwait(false);
} }
//[NadekoCommand, Usage, Description, Aliases]
//[RequireContext(ContextType.Guild)]
//public async Task Timezones(int page = 1)
//{
// page -= 1;
// if (page < 0 || page > 20)
// return;
// var timezones = TimeZoneInfo.GetSystemTimeZones();
// var timezonesPerPage = 20;
// await Context.Channel.SendPaginatedConfirmAsync(page + 1, (curPage) => new EmbedBuilder()
// .WithOkColor()
// .WithTitle("Available Timezones")
// .WithDescription(string.Join("\n", timezones.Skip((curPage - 1) * timezonesPerPage).Take(timezonesPerPage).Select(x => $"`{x.Id,-25}` UTC{x.BaseUtcOffset:hhmm}"))),
// timezones.Count / timezonesPerPage);
//}
//[NadekoCommand, Usage, Description, Aliases]
//[RequireContext(ContextType.Guild)]
//public async Task Timezone([Remainder] string id)
//{
// TimeZoneInfo tz;
// try
// {
// tz = TimeZoneInfo.FindSystemTimeZoneById(id);
// if (tz != null)
// await Context.Channel.SendConfirmAsync(tz.ToString()).ConfigureAwait(false);
// }
// catch (Exception ex)
// {
// tz = null;
// _log.Warn(ex);
// }
// if (tz == null)
// await Context.Channel.SendErrorAsync("Timezone not found. You should specify one of the timezones listed in the 'timezones' command.").ConfigureAwait(false);
//}
} }
} }

View File

@ -0,0 +1,69 @@
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using NadekoBot.Attributes;
using NadekoBot.Extensions;
using NadekoBot.Services.Administration;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace NadekoBot.Modules.Administration
{
public partial class Administration
{
[Group]
public class TimeZoneCommands : NadekoSubmodule
{
private readonly GuildTimezoneService _service;
public TimeZoneCommands(GuildTimezoneService service)
{
_service = service;
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task Timezones(int page = 1)
{
page -= 1;
if (page < 0 || page > 20)
return;
var timezones = TimeZoneInfo.GetSystemTimeZones();
var timezonesPerPage = 20;
await Context.Channel.SendPaginatedConfirmAsync((DiscordShardedClient)Context.Client, page + 1, (curPage) => new EmbedBuilder()
.WithOkColor()
.WithTitle("Available Timezones")
.WithDescription(string.Join("\n", timezones.Skip((curPage - 1) * timezonesPerPage).Take(timezonesPerPage).Select(x => $"`{x.Id,-25}` UTC{x.BaseUtcOffset:hhmm}"))),
timezones.Count / timezonesPerPage);
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task Timezone([Remainder] string id = null)
{
if (string.IsNullOrWhiteSpace(id))
{
await ReplyConfirmLocalized("timezone_guild", _service.GetTimeZoneOrUtc(Context.Guild.Id)).ConfigureAwait(false);
return;
}
TimeZoneInfo tz;
try { tz = TimeZoneInfo.FindSystemTimeZoneById(id); } catch { tz = null; }
_service.SetTimeZone(Context.Guild.Id, tz);
if (tz == null)
{
await Context.Channel.SendErrorAsync("Timezone not found. You should specify one of the timezones listed in the 'timezones' command.").ConfigureAwait(false);
return;
}
await Context.Channel.SendConfirmAsync(tz.ToString()).ConfigureAwait(false);
}
}
}
}

View File

@ -83,7 +83,7 @@ namespace NadekoBot.Modules.Searches
// try // try
// { // {
// CachedChampionImages = CachedChampionImages // CachedChampionImages = CachedChampionImages
// .Where(kvp => DateTime.Now - kvp.Value.AddedAt > new TimeSpan(1, 0, 0)) // .Where(kvp => DateTime.UtcNow - kvp.Value.AddedAt > new TimeSpan(1, 0, 0))
// .ToDictionary(kvp => kvp.Key, kvp => kvp.Value); // .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
// } // }
// catch { } // catch { }
@ -303,7 +303,7 @@ namespace NadekoBot.Modules.Searches
// smallImgSize)); // smallImgSize));
// } // }
// } // }
// var cachedChamp = new CachedChampion { AddedAt = DateTime.Now, ImageStream = img.ToStream(System.Drawing.Imaging.ImageFormat.Png), Name = name.ToLower() + "_" + resolvedRole }; // var cachedChamp = new CachedChampion { AddedAt = DateTime.UtcNow, ImageStream = img.ToStream(System.Drawing.Imaging.ImageFormat.Png), Name = name.ToLower() + "_" + resolvedRole };
// CachedChampionImages.Add(cachedChamp.Name, cachedChamp); // CachedChampionImages.Add(cachedChamp.Name, cachedChamp);
// await e.Channel.SendFile(data["title"] + "_stats.png", cachedChamp.ImageStream).ConfigureAwait(false); // await e.Channel.SendFile(data["title"] + "_stats.png", cachedChamp.ImageStream).ConfigureAwait(false);
// } // }

View File

@ -148,6 +148,56 @@ namespace NadekoBot.Modules.Utility
Format.Bold(rep.Repeater.Interval.Minutes.ToString()))).ConfigureAwait(false); Format.Bold(rep.Repeater.Interval.Minutes.ToString()))).ConfigureAwait(false);
} }
//[NadekoCommand, Usage, Description, Aliases]
//[RequireContext(ContextType.Guild)]
//[RequireUserPermission(GuildPermission.ManageMessages)]
//[Priority(1)]
//public async Task Repeat(GuildTime gt, int minutes, [Remainder] string message)
//{
// if (!_service.RepeaterReady)
// return;
// if (minutes < 1 || minutes > 10080)
// return;
// if (string.IsNullOrWhiteSpace(message))
// return;
// var toAdd = new GuildRepeater()
// {
// ChannelId = Context.Channel.Id,
// GuildId = Context.Guild.Id,
// Interval = TimeSpan.FromMinutes(minutes),
// StartTimeOfDay = gt.BotTime,
// Message = message
// };
// using (var uow = _db.UnitOfWork)
// {
// var gc = uow.GuildConfigs.For(Context.Guild.Id, set => set.Include(x => x.GuildRepeaters));
// if (gc.GuildRepeaters.Count >= 5)
// return;
// gc.GuildRepeaters.Add(toAdd);
// await uow.CompleteAsync().ConfigureAwait(false);
// }
// var rep = new RepeatRunner(_client, toAdd, (ITextChannel)Context.Channel);
// _service.Repeaters.AddOrUpdate(Context.Guild.Id, new ConcurrentQueue<RepeatRunner>(new[] { rep }), (key, old) =>
// {
// old.Enqueue(rep);
// return old;
// });
// await Context.Channel.SendConfirmAsync(
// "🔁 " + GetText("repeater",
// Format.Bold(((IGuildUser)Context.User).GuildPermissions.MentionEveryone ? rep.Repeater.Message : rep.Repeater.Message.SanitizeMentions()),
// Format.Bold(rep.Repeater.Interval.Days.ToString()),
// Format.Bold(rep.Repeater.Interval.Hours.ToString()),
// Format.Bold(rep.Repeater.Interval.Minutes.ToString()))).ConfigureAwait(false);
//}
[NadekoCommand, Usage, Description, Aliases] [NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)] [RequireContext(ContextType.Guild)]
[RequireUserPermission(GuildPermission.ManageMessages)] [RequireUserPermission(GuildPermission.ManageMessages)]

View File

@ -96,7 +96,7 @@ namespace NadekoBot.Modules.Utility
namesAndValues[groupName] = value; namesAndValues[groupName] = value;
output += m.Groups[groupName].Value + " " + groupName + " "; output += m.Groups[groupName].Value + " " + groupName + " ";
} }
var time = DateTime.Now + new TimeSpan(30 * namesAndValues["months"] + var time = DateTime.UtcNow + new TimeSpan(30 * namesAndValues["months"] +
7 * namesAndValues["weeks"] + 7 * namesAndValues["weeks"] +
namesAndValues["days"], namesAndValues["days"],
namesAndValues["hours"], namesAndValues["hours"],

View File

@ -120,7 +120,7 @@ namespace NadekoBot
#region utility #region utility
var crossServerTextService = new CrossServerTextService(AllGuildConfigs, Client); var crossServerTextService = new CrossServerTextService(AllGuildConfigs, Client);
var remindService = new RemindService(Client, BotConfig, Db); var remindService = new RemindService(Client, BotConfig, Db);
var repeaterService = new MessageRepeaterService(Client, AllGuildConfigs); var repeaterService = new MessageRepeaterService(this, Client, AllGuildConfigs);
var converterService = new ConverterService(Db); var converterService = new ConverterService(Db);
var commandMapService = new CommandMapService(AllGuildConfigs); var commandMapService = new CommandMapService(AllGuildConfigs);
var patreonRewardsService = new PatreonRewardsService(Credentials, Db, Currency); var patreonRewardsService = new PatreonRewardsService(Credentials, Db, Currency);
@ -164,6 +164,7 @@ namespace NadekoBot
var gameVcService = new GameVoiceChannelService(Client, Db, AllGuildConfigs); var gameVcService = new GameVoiceChannelService(Client, Db, AllGuildConfigs);
var autoAssignRoleService = new AutoAssignRoleService(Client, AllGuildConfigs); var autoAssignRoleService = new AutoAssignRoleService(Client, AllGuildConfigs);
var logCommandService = new LogCommandService(Client, Strings, AllGuildConfigs, Db, muteService, protectionService); var logCommandService = new LogCommandService(Client, Strings, AllGuildConfigs, Db, muteService, protectionService);
var guildTimezoneService = new GuildTimezoneService(AllGuildConfigs, Db);
#endregion #endregion
#region pokemon #region pokemon
@ -215,6 +216,7 @@ namespace NadekoBot
.Add(autoAssignRoleService) .Add(autoAssignRoleService)
.Add(protectionService) .Add(protectionService)
.Add(logCommandService) .Add(logCommandService)
.Add(guildTimezoneService)
.Add<PermissionService>(permissionsService) .Add<PermissionService>(permissionsService)
.Add(blacklistService) .Add(blacklistService)
.Add(cmdcdsService) .Add(cmdcdsService)
@ -232,6 +234,7 @@ namespace NadekoBot
CommandService.AddTypeReader<ModuleInfo>(new ModuleTypeReader(CommandService)); CommandService.AddTypeReader<ModuleInfo>(new ModuleTypeReader(CommandService));
CommandService.AddTypeReader<ModuleOrCrInfo>(new ModuleOrCrTypeReader(CommandService)); CommandService.AddTypeReader<ModuleOrCrInfo>(new ModuleOrCrTypeReader(CommandService));
CommandService.AddTypeReader<IGuild>(new GuildTypeReader(Client)); CommandService.AddTypeReader<IGuild>(new GuildTypeReader(Client));
CommandService.AddTypeReader<GuildDateTime>(new GuildTypeReader(Client));
} }
private async Task LoginAsync(string token) private async Task LoginAsync(string token)

View File

@ -1632,10 +1632,10 @@
<data name="songremove_cmd" xml:space="preserve"> <data name="songremove_cmd" xml:space="preserve">
<value>songremove srm</value> <value>songremove srm</value>
</data> </data>
<data name="remove_desc" xml:space="preserve"> <data name="songremove_desc" xml:space="preserve">
<value>Remove a song by its # in the queue, or 'all' to remove all songs from the queue.</value> <value>Remove a song by its # in the queue, or 'all' to remove all songs from the queue.</value>
</data> </data>
<data name="remove_usage" xml:space="preserve"> <data name="songremove_usage" xml:space="preserve">
<value>`{0}srm 5`</value> <value>`{0}srm 5`</value>
</data> </data>
<data name="movesong_cmd" xml:space="preserve"> <data name="movesong_cmd" xml:space="preserve">

View File

@ -0,0 +1,65 @@
using NadekoBot.Extensions;
using NadekoBot.Services.Database.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections.Concurrent;
using NadekoBot.Services;
namespace NadekoBot.Services.Administration
{
public class GuildTimezoneService
{
private ConcurrentDictionary<ulong, TimeZoneInfo> _timezones;
private readonly DbService _db;
public GuildTimezoneService(IEnumerable<GuildConfig> gcs, DbService db)
{
_timezones = gcs
.Select(x =>
{
TimeZoneInfo tz;
try
{
tz = TimeZoneInfo.FindSystemTimeZoneById(x.TimeZoneId);
}
catch
{
tz = null;
}
return (x.GuildId, tz);
})
.Where(x => x.Item2 != null)
.ToDictionary(x => x.Item1, x => x.Item2)
.ToConcurrent();
_db = db;
}
public TimeZoneInfo GetTimeZoneOrDefault(ulong guildId)
{
if (_timezones.TryGetValue(guildId, out var tz))
return tz;
return null;
}
public void SetTimeZone(ulong guildId, TimeZoneInfo tz)
{
using (var uow = _db.UnitOfWork)
{
var gc = uow.GuildConfigs.For(guildId, set => set);
gc.TimeZoneId = tz?.Id;
uow.Complete();
if (tz == null)
_timezones.TryRemove(guildId, out tz);
else
_timezones.AddOrUpdate(guildId, tz, (key, old) => tz);
}
}
public TimeZoneInfo GetTimeZoneOrUtc(ulong guildId)
=> GetTimeZoneOrDefault(guildId) ?? TimeZoneInfo.Utc;
}
}

View File

@ -19,8 +19,8 @@ namespace NadekoBot.Services.Administration
private readonly DiscordShardedClient _client; private readonly DiscordShardedClient _client;
private readonly Logger _log; private readonly Logger _log;
private string PrettyCurrentTime => $"【{DateTime.Now:HH:mm:ss}】"; private string PrettyCurrentTime => $"【{DateTime.UtcNow:HH:mm:ss}】";
private string CurrentTime => $"{DateTime.Now:HH:mm:ss}"; private string CurrentTime => $"{DateTime.UtcNow:HH:mm:ss}";
public ConcurrentDictionary<ulong, LogSetting> GuildLogSettings { get; } public ConcurrentDictionary<ulong, LogSetting> GuildLogSettings { get; }

View File

@ -8,6 +8,7 @@ namespace NadekoBot.Services.Database.Models
public ulong ChannelId { get; set; } public ulong ChannelId { get; set; }
public string Message { get; set; } public string Message { get; set; }
public TimeSpan Interval { get; set; } public TimeSpan Interval { get; set; }
//public TimeSpan? StartTimeOfDay { get; set; }
} }
public class GuildRepeater : Repeater public class GuildRepeater : Repeater

View File

@ -118,11 +118,11 @@ namespace NadekoBot.Services.Games
var lastGeneration = LastGenerations.GetOrAdd(channel.Id, DateTime.MinValue); var lastGeneration = LastGenerations.GetOrAdd(channel.Id, DateTime.MinValue);
var rng = new NadekoRandom(); var rng = new NadekoRandom();
if (DateTime.Now - TimeSpan.FromSeconds(_bc.CurrencyGenerationCooldown) < lastGeneration) //recently generated in this channel, don't generate again if (DateTime.UtcNow - TimeSpan.FromSeconds(_bc.CurrencyGenerationCooldown) < lastGeneration) //recently generated in this channel, don't generate again
return; return;
var num = rng.Next(1, 101) + _bc.CurrencyGenerationChance * 100; var num = rng.Next(1, 101) + _bc.CurrencyGenerationChance * 100;
if (num > 100 && LastGenerations.TryUpdate(channel.Id, DateTime.Now, lastGeneration)) if (num > 100 && LastGenerations.TryUpdate(channel.Id, DateTime.UtcNow, lastGeneration))
{ {
var dropAmount = _bc.CurrencyDropAmount; var dropAmount = _bc.CurrencyDropAmount;

View File

@ -41,7 +41,7 @@ namespace NadekoBot.Services.Impl
_client = client; _client = client;
_creds = creds; _creds = creds;
_started = DateTime.Now; _started = DateTime.UtcNow;
_client.MessageReceived += _ => Task.FromResult(Interlocked.Increment(ref _messageCounter)); _client.MessageReceived += _ => Task.FromResult(Interlocked.Increment(ref _messageCounter));
cmdHandler.CommandExecuted += (_, e) => Task.FromResult(Interlocked.Increment(ref _commandsRan)); cmdHandler.CommandExecuted += (_, e) => Task.FromResult(Interlocked.Increment(ref _commandsRan));
@ -166,7 +166,7 @@ Messages: {MessageCounter} [{MessagesPerSecond:F2}/sec] Heap: [{Heap} MB]");
} }
public TimeSpan GetUptime() => public TimeSpan GetUptime() =>
DateTime.Now - _started; DateTime.UtcNow - _started;
public string GetUptimeString(string separator = ", ") public string GetUptimeString(string separator = ", ")
{ {

View File

@ -144,7 +144,7 @@ namespace NadekoBot.Services.Music
public async Task Play(IAudioClient voiceClient, CancellationToken cancelToken) public async Task Play(IAudioClient voiceClient, CancellationToken cancelToken)
{ {
BytesSent = (ulong) SkipTo * 3840 * 50; BytesSent = (ulong) SkipTo * 3840 * 50;
var filename = Path.Combine(MusicService.MusicDataPath, DateTime.Now.UnixTimestamp().ToString()); var filename = Path.Combine(MusicService.MusicDataPath, DateTime.UtcNow.UnixTimestamp().ToString());
var inStream = new SongBuffer(MusicPlayer, filename, SongInfo, SkipTo, _frameBytes * 100); var inStream = new SongBuffer(MusicPlayer, filename, SongInfo, SkipTo, _frameBytes * 100);
var bufferTask = inStream.BufferSong(cancelToken).ConfigureAwait(false); var bufferTask = inStream.BufferSong(cancelToken).ConfigureAwait(false);

View File

@ -15,15 +15,14 @@ namespace NadekoBot.Services.Utility
public ConcurrentDictionary<ulong, ConcurrentQueue<RepeatRunner>> Repeaters { get; set; } public ConcurrentDictionary<ulong, ConcurrentQueue<RepeatRunner>> Repeaters { get; set; }
public bool RepeaterReady { get; private set; } public bool RepeaterReady { get; private set; }
public MessageRepeaterService(DiscordShardedClient client, IEnumerable<GuildConfig> gcs) public MessageRepeaterService(NadekoBot bot, DiscordShardedClient client, IEnumerable<GuildConfig> gcs)
{ {
System.Console.WriteLine(bot.Ready);
var _ = Task.Run(async () => var _ = Task.Run(async () =>
{ {
#if !GLOBAL_NADEKO while (!bot.Ready)
await Task.Delay(5000).ConfigureAwait(false); await Task.Delay(1000);
#else
await Task.Delay(30000).ConfigureAwait(false);
#endif
Repeaters = new ConcurrentDictionary<ulong, ConcurrentQueue<RepeatRunner>>(gcs Repeaters = new ConcurrentDictionary<ulong, ConcurrentQueue<RepeatRunner>>(gcs
.ToDictionary(gc => gc.GuildId, .ToDictionary(gc => gc.GuildId,
gc => new ConcurrentQueue<RepeatRunner>(gc.GuildRepeaters gc => new ConcurrentQueue<RepeatRunner>(gc.GuildRepeaters

View File

@ -58,7 +58,7 @@ namespace NadekoBot.Services.Utility
public async Task StartReminder(Reminder r) public async Task StartReminder(Reminder r)
{ {
var t = cancelAllToken; var t = cancelAllToken;
var now = DateTime.Now; var now = DateTime.UtcNow;
var time = r.When - now; var time = r.When - now;

View File

@ -14,12 +14,11 @@ namespace NadekoBot.Services.Utility
{ {
private readonly Logger _log; private readonly Logger _log;
private CancellationTokenSource source { get; set; }
private CancellationToken token { get; set; }
public Repeater Repeater { get; } public Repeater Repeater { get; }
public SocketGuild Guild { get; } public SocketGuild Guild { get; }
public ITextChannel Channel { get; private set; } public ITextChannel Channel { get; private set; }
private IUserMessage oldMsg = null; private IUserMessage oldMsg = null;
private Timer _t;
public RepeatRunner(DiscordShardedClient client, Repeater repeater, ITextChannel channel = null) public RepeatRunner(DiscordShardedClient client, Repeater repeater, ITextChannel channel = null)
{ {
@ -30,25 +29,24 @@ namespace NadekoBot.Services.Utility
//todo 40 @.@ fix all of this //todo 40 @.@ fix all of this
Guild = client.GetGuild(repeater.GuildId); Guild = client.GetGuild(repeater.GuildId);
if (Guild != null) if (Guild != null)
Task.Run(Run); Run();
} }
private async Task Run() private void Run()
{ {
source = new CancellationTokenSource(); TimeSpan initialInterval = Repeater.Interval;
token = source.Token;
try
{
while (!token.IsCancellationRequested)
{
await Task.Delay(Repeater.Interval, token).ConfigureAwait(false);
await Trigger().ConfigureAwait(false); //if (Repeater.StartTimeOfDay != null)
} //{
} // if ((initialInterval = Repeater.StartTimeOfDay.Value - DateTime.UtcNow.TimeOfDay) < TimeSpan.Zero)
catch (OperationCanceledException) // initialInterval += TimeSpan.FromDays(1);
{ //}
}
_t = new Timer(async (_) => {
try { await Trigger().ConfigureAwait(false); } catch { }
}, null, initialInterval, Repeater.Interval);
} }
public async Task Trigger() public async Task Trigger()
@ -93,13 +91,13 @@ namespace NadekoBot.Services.Utility
public void Reset() public void Reset()
{ {
source.Cancel(); Stop();
var _ = Task.Run(Run); Run();
} }
public void Stop() public void Stop()
{ {
source.Cancel(); _t.Change(Timeout.Infinite, Timeout.Infinite);
} }
public override string ToString() => public override string ToString() =>