Skip to content

Commit

Permalink
Merge pull request #95 from egebilecen/v1.11.x
Browse files Browse the repository at this point in the history
v1.11.0
  • Loading branch information
egebilecen authored Sep 6, 2023
2 parents f9c49a9 + af0d5f3 commit e934e63
Show file tree
Hide file tree
Showing 8 changed files with 166 additions and 12 deletions.
16 changes: 9 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,17 +95,19 @@ This bot uses 3 different channels to operate. First channel is *Public* channel

#### Command Channel
Bot Commands:
- `!set_command_channel` Sets the channel for bot to work in. (!set_command_channel <channel tag>)<br>
- `!set_log_channel` Sets the channel for bot to work in. (!set_log_channel <channel tag>)<br>
- `!set_public_channel` Sets the channel for bot to work in. (!set_public_channel <channel tag>)<br>
- `!set_command_channel` Sets the channel for bot to work in. (!set_command_channel [channel tag>)<br>
- `!set_log_channel` Sets the channel for bot to work in. (!set_log_channel [channel tag])<br>
- `!set_public_channel` Sets the channel for bot to work in. (!set_public_channel [channel tag])<br>
- `!get_settings` Gets the bot settings. (!get_settings)<br>
- `!get_schedules` Gets the remaining times until schedules to be executed. (!get_schedules)<br>
- `!get_ram_cpu` Gets the total RAM and CPU usage of the machine. (!get_ram_cpu)<br>
- `!set_restart_interval` Set the server's restart schedule interval. (in minutes!) (!set_restart_interval <interval in minutes>)<br>
- `!set_mod_update_check_interval` Set the workshop mod update check schedule interval. (in minutes!) (!set_mod_update_check_interval <interval in minutes>)<br>
- `!set_mod_update_restart_timer` Sets the restart timer for server when mod update detected. (in minutes!) (!set_mod_update_restart_timer <timer in minutes>)<br>
- `!set_restart_schedule_type` Set the server's restart schedule type. (!set_restart_schedule_type ["interval"|"time"])<br>
- `!set_restart_time` Set the server's restart time(s). The time format is "HH:mm" (using 24-hour time). Server restart schedule type must be "time". (!set_restart_time [times separated by space])<br>
- `!set_restart_interval` Set the server's restart schedule interval. Restart schedule type must be "interval". (in minutes!) (!set_restart_interval [interval in minutes])<br>
- `!set_mod_update_check_interval` Set the workshop mod update check schedule interval. (in minutes!) (!set_mod_update_check_interval [interval in minutes])<br>
- `!set_mod_update_restart_timer` Sets the restart timer for server when mod update detected. (in minutes!) (!set_mod_update_restart_timer [timer in minutes])<br>
- `!toggle_non_public_mod_logging` Bot will print out non-public mods to log channel if enabled. (!toggle_non_public_mod_logging)<br>
- `!set_perk_cache_duration` Set the perk cache duration. (in minutes!) (!set_perk_cache_duration <duration in minutes>)<br>
- `!set_perk_cache_duration` Set the perk cache duration. (in minutes!) (!set_perk_cache_duration [duration in minutes])<br>
- `!reset_perk_cache` Reset the perk cache. (!reset_perk_cache)<br>
- `!toggle_server_auto_start` Enables/Disables the server auto start feature if server is not running. (!toggle_server_auto_start)<br>
- `!backup_server` Creates a backup of the server. Backup files can be found in "server_backup" folder in the directory where bot has been launched. (!backup_server)<br>
Expand Down
7 changes: 7 additions & 0 deletions localization/default.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,15 +49,22 @@
"disc_cmd_get_settings_log_chan_id": "**Log Channel ID:** `{channel_id}` (<#{channel_id}>)",
"disc_cmd_get_settings_pub_chan_id": "**Public Channel ID:** `{channel_id}` (<#{channel_id}>)",
"disc_cmd_get_settings_perk_cac_dur": "**Perk Parser Cache Duration:** {minutes} minute(s)",
"disc_cmd_get_settings_res_serv_sch_type": "**Restart Server Schedule Type:** {type}",
"disc_cmd_get_settings_serv_res_times": "**Server Restart Time(s):** {timeList}",
"disc_cmd_get_settings_res_sch_int": "**Restart Schedule Interval:** {minutes} minute(s)",
"disc_cmd_get_settings_mod_sch_int": "**Workshop Mod Update Checker Interval:** {minutes} minute(s)",
"disc_cmd_get_settings_mod_rst_timer": "**Workshop Mod Update Restart Timer:** {minutes} minute(s)",
"disc_cmd_get_settings_serv_aut_strt": "**Server Auto Start:** {state}",
"disc_cmd_get_settings_mod_logging": "**Non-public Mod Logging:** {state}",
"disc_cmd_get_schedules_run": "**{name}** schedule will run <t:{timestamp}:R>.",
"disc_cmd_get_schedules_not_fnd": "No schedule found.",
"disc_cmd_set_restart_schedule_type_warn": "Schedule type must be \"interval\" or \"time\".",
"disc_cmd_set_restart_schedule_type_ok": "Updated the server restart schedule type to {type}.",
"disc_cmd_set_restart_interval_int_warn": "Restart interval must be at least 60 minutes.",
"disc_cmd_set_restart_interval_int_ok": "Server restart schedule is updated.",
"disc_cmd_set_restart_time_warn_miss_param": "\"Time\" is a missing parameter.",
"disc_cmd_set_restart_time_warn_invld_time": "\"{time}\" is an invalid time.\nThe time format must be \"HH:mm\" (using 24-hour time) and times must be separated with a space.",
"disc_cmd_set_restart_time_ok": "The server will restart at: {timeList}.",
"disc_cmd_set_mod_update_check_interval_int_warn": "Interval minutes cannot be smaller than 0. But it can be 0 which means there won't be any workshop mod update checking.",
"disc_cmd_set_mod_update_check_interval_int_ok": "Workshop mod update check schedule is updated.",
"disc_cmd_set_mod_update_restart_timer_warn": "Interval must be at least 1 minute(s).",
Expand Down
67 changes: 66 additions & 1 deletion src/Bot/Commands/BotCommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using Discord.WebSocket;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;

Expand Down Expand Up @@ -76,6 +77,10 @@ public async Task GetSettings()
botSettings += "\n";
botSettings += Localization.Get("disc_cmd_get_settings_perk_cac_dur").KeyFormat(("minutes", Application.BotSettings.ServerLogParserSettings.PerkParserCacheDuration));
botSettings += "\n";
botSettings += Localization.Get("disc_cmd_get_settings_res_serv_sch_type").KeyFormat(("type", Application.BotSettings.ServerScheduleSettings.ServerRestartScheduleType));
botSettings += "\n";
botSettings += Localization.Get("disc_cmd_get_settings_serv_res_times").KeyFormat(("timeList", String.Join(", ", Application.BotSettings.ServerScheduleSettings.ServerRestartTimes)));
botSettings += "\n";
botSettings += Localization.Get("disc_cmd_get_settings_res_sch_int").KeyFormat(("minutes", Application.BotSettings.ServerScheduleSettings.ServerRestartSchedule / (60 * 1000)));
botSettings += "\n";
botSettings += Localization.Get("disc_cmd_get_settings_mod_sch_int").KeyFormat(("minutes", Application.BotSettings.ServerScheduleSettings.WorkshopItemUpdateSchedule / (60 * 1000)));
Expand All @@ -85,7 +90,7 @@ public async Task GetSettings()
botSettings += Localization.Get("disc_cmd_get_settings_serv_aut_strt").KeyFormat(("state", Application.BotSettings.BotFeatureSettings.AutoServerStart ? Localization.Get("gen_enab_up") : Localization.Get("gen_disa_up")));
botSettings += "\n";
botSettings += Localization.Get("disc_cmd_get_settings_mod_logging").KeyFormat(("state", Application.BotSettings.BotFeatureSettings.NonPublicModLogging ? Localization.Get("gen_enab_up") : Localization.Get("gen_disa_up")));

await Context.Channel.SendMessageAsync(botSettings);
}

Expand Down Expand Up @@ -130,6 +135,28 @@ public async Task GetRAMCPU()
await Context.Channel.SendMessageAsync(progressBarStr);
}

[Command("set_restart_schedule_type")]
[Summary("Set the server's restart schedule type. (\"Interval\" or \"Time\") (!set_restart_schedule_type <\"interval\"|\"time\">)")]
public async Task SetRestartScheduleType(string scheduleType)
{
if(scheduleType.ToLower() != "interval" && scheduleType.ToLower()!="time")
{
await Context.Message.AddReactionAsync(EmojiList.RedCross);
await Context.Channel.SendMessageAsync(Localization.Get("disc_cmd_set_restart_schedule_type_warn"));
return;
}

Logger.WriteLog(string.Format("[BotCommands - set_restart_schedule_type] Caller: {0}, Params: {1}", Context.User.ToString(), scheduleType));
await Context.Message.AddReactionAsync(EmojiList.GreenCheck);

Application.BotSettings.ServerScheduleSettings.ServerRestartScheduleType = scheduleType.ToLower();
Application.BotSettings.Save();

ServerUtility.ResetServerRestartInterval();

await Context.Channel.SendMessageAsync(Localization.Get("disc_cmd_set_restart_schedule_type_ok").KeyFormat(("type", scheduleType)));
}

[Command("set_restart_interval")]
[Summary("Set the server's restart schedule interval. (in minutes!) (!set_restart_interval <interval in minutes>)")]
public async Task SetRestartInterval(uint intervalMinute)
Expand All @@ -152,6 +179,44 @@ public async Task SetRestartInterval(uint intervalMinute)
await Context.Channel.SendMessageAsync(Localization.Get("disc_cmd_set_restart_interval_int_ok"));
}

[Command("set_restart_time")]
[Summary("Set the server's restart time(s). The time format must be \"HH:mm\" (using 24-hour time). (!set_restart_time <times separated by space>)")]
public async Task SetRestartTimes(params string[] timeArray)
{
if (timeArray.Count() == 0)
{
await Context.Message.AddReactionAsync(EmojiList.RedCross);
await Context.Channel.SendMessageAsync(Localization.Get("disc_cmd_set_restart_time_warn_miss_param"));
return;
}

List<string> timeList = new List<string>(timeArray);
foreach (string time in timeList)
{
DateTime timeDT;
try
{
timeDT = DateTime.ParseExact(time, "HH:mm", CultureInfo.InvariantCulture);
}
catch (Exception)
{
await Context.Message.AddReactionAsync(EmojiList.RedCross);
await Context.Channel.SendMessageAsync(Localization.Get("disc_cmd_set_restart_time_warn_invld_time").KeyFormat(("time", time)));
return;
}
}

Logger.WriteLog(string.Format("[BotCommands - set_restart_times] Caller: {0}, Params: {1}", Context.User.ToString(), timeList));
await Context.Message.AddReactionAsync(EmojiList.GreenCheck);

Scheduler.GetItem("ServerRestart").UpdateInterval(Scheduler.GetIntervalFromTimes(timeList));

Application.BotSettings.ServerScheduleSettings.ServerRestartTimes = timeList;
Application.BotSettings.Save();

await Context.Channel.SendMessageAsync(Localization.Get("disc_cmd_set_restart_time_ok").KeyFormat(("timeList", String.Join(", ",timeList))));
}

[Command("set_mod_update_check_interval")]
[Summary("Set the workshop mod update check schedule interval. (in minutes!) (!set_mod_update_check_interval <interval in minutes>)")]
public async Task SetWorkshopItemUpdateChecker(uint intervalMinute)
Expand Down
11 changes: 11 additions & 0 deletions src/Bot/Localization.cs
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,8 @@ public LocalizationInfo(string name, SemanticVersion version, string description
{ "disc_cmd_get_settings_log_chan_id", "**Log Channel ID:** `{channel_id}` (<#{channel_id}>)" },
{ "disc_cmd_get_settings_pub_chan_id", "**Public Channel ID:** `{channel_id}` (<#{channel_id}>)" },
{ "disc_cmd_get_settings_perk_cac_dur", "**Perk Parser Cache Duration:** {minutes} minute(s)" },
{ "disc_cmd_get_settings_res_serv_sch_type", "**Restart Server Schedule Type:** {type}"},
{ "disc_cmd_get_settings_serv_res_times", "**Server Restart Time(s):** {timeList}"},
{ "disc_cmd_get_settings_res_sch_int", "**Restart Schedule Interval:** {minutes} minute(s)" },
{ "disc_cmd_get_settings_mod_sch_int", "**Workshop Mod Update Checker Interval:** {minutes} minute(s)" },
{ "disc_cmd_get_settings_mod_rst_timer", "**Workshop Mod Update Restart Timer:** {minutes} minute(s)" },
Expand All @@ -128,10 +130,19 @@ public LocalizationInfo(string name, SemanticVersion version, string description
{ "disc_cmd_get_schedules_run", "**{name}** schedule will run <t:{timestamp}:R>." },
{ "disc_cmd_get_schedules_not_fnd", "No schedule found." },

// -------- !set_restart_schedule_type
{ "disc_cmd_set_restart_schedule_type_warn", "Schedule type must be \"interval\" or \"time\"." },
{ "disc_cmd_set_restart_schedule_type_ok", "Updated the server restart schedule type to {type}." },

// -------- !set_restart_interval
{ "disc_cmd_set_restart_interval_int_warn", "Restart interval must be at least 60 minutes." },
{ "disc_cmd_set_restart_interval_int_ok", "Server restart schedule is updated." },

// -------- !set_restart_time
{ "disc_cmd_set_restart_time_warn_miss_param", "\"Time\" is a missing parameter." },
{ "disc_cmd_set_restart_time_warn_invld_time", "\"{time}\" is an invalid time.\nThe time format must be \"HH:mm\" (using 24-hour time) and times must be separated with a space." },
{ "disc_cmd_set_restart_time_ok", "The server will restart at: {timeList}." },

// -------- !set_mod_update_check_interval
{ "disc_cmd_set_mod_update_check_interval_int_warn", "Interval minutes cannot be smaller than 0. But it can be 0 which means there won't be any workshop mod update checking." },
{ "disc_cmd_set_mod_update_check_interval_int_ok", "Workshop mod update check schedule is updated." },
Expand Down
57 changes: 57 additions & 0 deletions src/Bot/Scheduler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -104,4 +104,61 @@ public static void Dispose()
if(clock != null)
clock.Dispose();
}

public static uint GetIntervalFromTimes(List<string> scheduleTimes)
{
scheduleTimes.Sort();

DateTime now = DateTime.Now;
string nowString = now.ToString("HH:mm");

DateTime nextRestartTimeDT = new DateTime();
string nextRestartTime = "";

if (scheduleTimes.Count == 0) return 999999999;

foreach (string time in scheduleTimes)
{
DateTime timeDT;
try
{
timeDT = DateTime.Parse(time);
}
catch (Exception)
{
Logger.WriteLog(string.Format("Scheduler.GetIntervalFromTimes() - ERROR: \"{0}\" is an invalid time.", time));
continue;
}

if (DateTime.Compare(timeDT, now) > 0)
{
nextRestartTimeDT = timeDT;
break;
}
}

try
{
TimeSpan interval;

if (nextRestartTimeDT == DateTime.MinValue)
{
interval = DateTime.Parse(scheduleTimes[0]).AddDays(1) - DateTime.Now;
nextRestartTime = nextRestartTimeDT.ToString("HH:mm");
nextRestartTime = string.Format("Tomorrow, {0}", scheduleTimes[0]);
}
else
{
interval = nextRestartTimeDT - DateTime.Parse(nowString);
}

Logger.WriteLog(string.Format("[GetIntervalFromTimes] - Next Restart Time: {0}", nextRestartTime));
return Convert.ToUInt32(interval.TotalMilliseconds);
}
catch (Exception)
{
Logger.WriteLog(string.Format("[Scheduler.GetIntervalFromTimes] - Error. Next restart time: {0}, Current time: {1}", nextRestartTime, nowString));
return 4294967295;
}
}
}
11 changes: 11 additions & 0 deletions src/Bot/SettingsModel.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;

namespace Settings
Expand All @@ -14,6 +15,14 @@ public class ServerScheduleSettings
public uint ServerRestartSchedule = Convert.ToUInt32(TimeSpan.FromHours(6).TotalMilliseconds);
public uint WorkshopItemUpdateSchedule = Convert.ToUInt32(TimeSpan.FromMinutes(10).TotalMilliseconds);
public uint WorkshopItemUpdateRestartTimer = Convert.ToUInt32(TimeSpan.FromMinutes(15).TotalMilliseconds);
public string ServerRestartScheduleType = "Interval";
public List<string> ServerRestartTimes = new List<string>{"03:00"};

public uint GetServerRestartSchedule()
{
return this.ServerRestartScheduleType.ToLower() == "interval" ? this.ServerRestartSchedule : Scheduler.GetIntervalFromTimes(this.ServerRestartTimes);
}

}

public class BotFeatureSettings
Expand Down Expand Up @@ -42,5 +51,7 @@ public void Save()
{
File.WriteAllText(SettingsFile, JsonConvert.SerializeObject(this, Formatting.Indented));
}


}
}
2 changes: 1 addition & 1 deletion src/PZServer/Util/ServerUtility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public static uint InitiateServerRestart(uint intervalMS)

public static void ResetServerRestartInterval()
{
Scheduler.GetItem("ServerRestart")?.UpdateInterval(Application.BotSettings.ServerScheduleSettings.ServerRestartSchedule);
Scheduler.GetItem("ServerRestart")?.UpdateInterval(Application.BotSettings.ServerScheduleSettings.GetServerRestartSchedule());
ResetServerRestartAnnouncerInterval();
}

Expand Down
7 changes: 4 additions & 3 deletions src/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
public static class Application
{
public const string BotRepoURL = "https://github.com/egebilecen/PZServerDiscordBot";
public static readonly SemanticVersion BotVersion = new SemanticVersion(1, 10, 0, DevelopmentStage.Release);
public static readonly SemanticVersion BotVersion = new SemanticVersion(1, 11, 0, DevelopmentStage.Release);
public static Settings.BotSettings BotSettings;

public static DiscordSocketClient Client;
Expand All @@ -35,7 +35,8 @@ private static async Task MainAsync()
}
else
{
BotSettings = JsonConvert.DeserializeObject<Settings.BotSettings>(File.ReadAllText(Settings.BotSettings.SettingsFile));
BotSettings = JsonConvert.DeserializeObject<Settings.BotSettings>(File.ReadAllText(Settings.BotSettings.SettingsFile),
new JsonSerializerSettings{ObjectCreationHandling = ObjectCreationHandling.Replace});
}

Localization.Load();
Expand Down Expand Up @@ -109,7 +110,7 @@ private static async Task MainAsync()

Scheduler.AddItem(new ScheduleItem("ServerRestart",
Localization.Get("sch_name_serverrestart"),
BotSettings.ServerScheduleSettings.ServerRestartSchedule,
BotSettings.ServerScheduleSettings.GetServerRestartSchedule(),
Schedules.ServerRestart,
null));
Scheduler.AddItem(new ScheduleItem("ServerRestartAnnouncer",
Expand Down

0 comments on commit e934e63

Please sign in to comment.