GetServerInfo, GetServerList and GetServerStatus done

This commit is contained in:
Brett Hewitson 2021-12-04 21:47:16 +10:00
parent d526a3f457
commit 824daed0d1
27 changed files with 484 additions and 91 deletions

View file

@ -4,7 +4,7 @@ using NLog.Config;
using NLog.Targets; using NLog.Targets;
using ServerManagerTool.Common; using ServerManagerTool.Common;
using ServerManagerTool.Common.Utils; using ServerManagerTool.Common.Utils;
using ServerManagerTool.Discord; using ServerManagerTool.DiscordBot;
using ServerManagerTool.Enums; using ServerManagerTool.Enums;
using ServerManagerTool.Lib; using ServerManagerTool.Lib;
using ServerManagerTool.Plugin.Common; using ServerManagerTool.Plugin.Common;
@ -456,7 +456,7 @@ namespace ServerManagerTool
Task discordTask = Task.Run(async () => Task discordTask = Task.Run(async () =>
{ {
await ServerManagerBotFactory.GetServerManagerBot()?.StartAsync(Config.Default.DiscordBotToken, Config.Default.DiscordBotPrefix, Config.Default.DataDir, DiscordBotHelper.HandleDiscordCommand, _tokenSource.Token); await ServerManagerBotFactory.GetServerManagerBot()?.StartAsync(Config.Default.DiscordBotToken, Config.Default.DiscordBotPrefix, Config.Default.DataDir, DiscordBotHelper.HandleDiscordCommand, DiscordBotHelper.HandleTranslation, _tokenSource.Token);
}, _tokenSource.Token) }, _tokenSource.Token)
.ContinueWith(t => { .ContinueWith(t => {
var message = t.Exception.InnerException is null ? t.Exception.Message : t.Exception.InnerException.Message; var message = t.Exception.InnerException is null ? t.Exception.Message : t.Exception.InnerException.Message;

View file

@ -3,9 +3,9 @@
public enum AvailabilityStatus public enum AvailabilityStatus
{ {
Unknown, Unknown,
NeedPublicIP, SetPublicIP,
Unavailable, Unavailable,
WaitingForPublication, Waiting,
Available Available
} }
} }

View file

@ -5544,6 +5544,18 @@
<sys:String x:Key="DiscordBot_ErrorTitle">Discord Bot Error</sys:String> <sys:String x:Key="DiscordBot_ErrorTitle">Discord Bot Error</sys:String>
<sys:String x:Key="DiscordBot_MissingTokenError">The discord bot requires a valid token so it can log into the discord server\r\nThis can be set in the global settings.</sys:String> <sys:String x:Key="DiscordBot_MissingTokenError">The discord bot requires a valid token so it can log into the discord server\r\nThis can be set in the global settings.</sys:String>
<sys:String x:Key="DiscordBot_InvalidPrefixError">The discord bot prefix contains invalid characters. Only letters and numbers are allowed.</sys:String> <sys:String x:Key="DiscordBot_InvalidPrefixError">The discord bot prefix contains invalid characters. Only letters and numbers are allowed.</sys:String>
<sys:String x:Key="DiscordBot_CommandNotImplemented">Command '{0}' has not been implemented.</sys:String>
<sys:String x:Key="DiscordBot_CommandUnknown">Unknown command '{0}'.</sys:String>
<sys:String x:Key="DiscordBot_CommandRunning">Another command is currently running.</sys:String>
<sys:String x:Key="DiscordBot_CommandProfileMissing">The command requires a profile id.</sys:String>
<sys:String x:Key="DiscordBot_CommandProfileNotFound">Profile id {0} not found or is not associated with the channel.</sys:String>
<sys:String x:Key="DiscordBot_CommandInfoFailed">Call to the server '{0}' failed.</sys:String>
<sys:String x:Key="DiscordBot_CountLabel">Count:</sys:String>
<sys:String x:Key="DiscordBot_MapLabel">Map:</sys:String>
<!--#endregion--> <!--#endregion-->
</Globalization:GlobalizationResourceDictionary> </Globalization:GlobalizationResourceDictionary>

View file

@ -281,13 +281,13 @@ namespace ServerManagerTool.Lib
case WatcherServerStatus.RunningLocalCheck: case WatcherServerStatus.RunningLocalCheck:
if (oldStatus != ServerStatus.Stopping) if (oldStatus != ServerStatus.Stopping)
UpdateServerStatus(ServerStatus.Running, this.Availability != AvailabilityStatus.Available ? AvailabilityStatus.WaitingForPublication : this.Availability, oldStatus != ServerStatus.Running && oldStatus != ServerStatus.Unknown); UpdateServerStatus(ServerStatus.Running, this.Availability != AvailabilityStatus.Available ? AvailabilityStatus.Waiting : this.Availability, oldStatus != ServerStatus.Running && oldStatus != ServerStatus.Unknown);
if (this.ProfileSnapshot.MOTDIntervalEnabled && this.motdIntervalTimer != null && !this.motdIntervalTimer.Enabled) this.motdIntervalTimer.Start(); if (this.ProfileSnapshot.MOTDIntervalEnabled && this.motdIntervalTimer != null && !this.motdIntervalTimer.Enabled) this.motdIntervalTimer.Start();
break; break;
case WatcherServerStatus.RunningExternalCheck: case WatcherServerStatus.RunningExternalCheck:
if (oldStatus != ServerStatus.Stopping) if (oldStatus != ServerStatus.Stopping)
UpdateServerStatus(ServerStatus.Running, AvailabilityStatus.WaitingForPublication, oldStatus != ServerStatus.Running && oldStatus != ServerStatus.Unknown); UpdateServerStatus(ServerStatus.Running, AvailabilityStatus.Waiting, oldStatus != ServerStatus.Running && oldStatus != ServerStatus.Unknown);
if (this.ProfileSnapshot.MOTDIntervalEnabled && this.motdIntervalTimer != null && !this.motdIntervalTimer.Enabled) this.motdIntervalTimer.Start(); if (this.ProfileSnapshot.MOTDIntervalEnabled && this.motdIntervalTimer != null && !this.motdIntervalTimer.Enabled) this.motdIntervalTimer.Start();
break; break;

View file

@ -1,13 +1,189 @@
using ServerManagerTool.Discord.Enums; using QueryMaster;
using ServerManagerTool.Common.Utils;
using ServerManagerTool.DiscordBot.Enums;
using ServerManagerTool.Lib;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Net;
using WPFSharp.Globalizer;
namespace ServerManagerTool.Utils namespace ServerManagerTool.Utils
{ {
internal static class DiscordBotHelper internal static class DiscordBotHelper
{ {
private static readonly GlobalizedApplication _globalizer = GlobalizedApplication.Instance;
private static bool _runningCommand = false;
public static IList<string> HandleDiscordCommand(CommandType commandType, string serverId, string channelId, string profileId) public static IList<string> HandleDiscordCommand(CommandType commandType, string serverId, string channelId, string profileId)
{ {
return new List<string>() { $"{commandType}; {serverId}; {channelId}; {profileId ?? "no profile"}" }; // check if incoming values are valid
if (string.IsNullOrWhiteSpace(serverId) || string.IsNullOrWhiteSpace(channelId))
return null;
// check if the server ids match
if (!serverId.Equals(Config.Default.DiscordBotServerId))
return new List<string>();
if (_runningCommand)
return new List<string> { _globalizer.GetResourceString("DiscordBot_CommandRunning") };
_runningCommand = true;
try
{
switch (commandType)
{
case CommandType.Info:
return GetServerInfo(channelId, profileId);
case CommandType.List:
return GetServerList(channelId);
case CommandType.Status:
return GetServerStatus(channelId, profileId);
case CommandType.Backup:
return BackupServer(channelId, profileId);
case CommandType.Shutdown:
return ShutdownServer(channelId, profileId);
case CommandType.Stop:
return StopServer(channelId, profileId);
case CommandType.Start:
return StartServer(channelId, profileId);
case CommandType.Update:
return UpdateServer(channelId, profileId);
default:
return new List<string> { string.Format(_globalizer.GetResourceString("DiscordBot_CommandUnknown"), commandType) };
}
}
catch (Exception ex)
{
var message = ex.InnerException is null ? ex.Message : ex.InnerException.Message;
return new string[] { message };
}
finally
{
_runningCommand = false;
}
}
public static string HandleTranslation(string translationKey)
{
return string.IsNullOrWhiteSpace(translationKey) ? string.Empty : _globalizer.GetResourceString(translationKey) ?? translationKey;
}
private static IList<string> GetServerInfo(string channelId, string profileId)
{
if (string.IsNullOrWhiteSpace(profileId))
{
return new List<string> { _globalizer.GetResourceString("DiscordBot_CommandProfileMissing") };
}
var serverName = string.Empty;
var serverIp = IPAddress.Loopback;
var queryPort = 0;
TaskUtils.RunOnUIThreadAsync(() =>
{
var server = ServerManager.Instance.Servers.Where(s => Equals(channelId, s.Profile.DiscordChannelId) && Equals(profileId, s.Profile.ProfileID)).FirstOrDefault();
if (server is null)
{
throw new Exception(string.Format(_globalizer.GetResourceString("DiscordBot_CommandProfileNotFound"), profileId));
}
serverName = server.Profile.ServerName;
if (!string.IsNullOrWhiteSpace(server.Profile.ServerIP))
{
IPAddress.TryParse(server.Profile.ServerIP, out serverIp);
}
queryPort = server.Profile.QueryPort;
}).Wait();
List<string> response = new List<string>();
try
{
using (var gameServer = ServerQuery.GetServerInstance(EngineType.Source, new IPEndPoint(serverIp, queryPort)))
{
var info = gameServer?.GetInfo();
if (info is null)
{
response.Add(string.Format(_globalizer.GetResourceString("DiscordBot_CommandInfoFailed"), serverName));
}
else
{
var mapName = _globalizer.GetResourceString($"Map_{info.Map}") ?? info.Map;
response.Add($"```{info.Name}\n{_globalizer.GetResourceString("DiscordBot_MapLabel")} {mapName}\n{_globalizer.GetResourceString("ServerSettings_PlayersLabel")} {info.Players} / {info.MaxPlayers}```");
}
}
}
catch (Exception)
{
response.Add(string.Format(_globalizer.GetResourceString("DiscordBot_CommandInfoFailed"), serverName));
}
return response;
}
private static IList<string> GetServerList(string channelId)
{
List<string> response = new List<string>();
TaskUtils.RunOnUIThreadAsync(() =>
{
var serverList = ServerManager.Instance.Servers.Where(s => Equals(channelId, s.Profile.DiscordChannelId));
response.Add($"**{_globalizer.GetResourceString("DiscordBot_CountLabel")}** {serverList.Count()}");
foreach (var server in serverList)
{
response.Add($"```{_globalizer.GetResourceString("ServerSettings_ProfileIdLabel")} {server.Profile.ProfileID}\n{_globalizer.GetResourceString("ServerSettings_ProfileLabel")} {server.Profile.ProfileName}\n{_globalizer.GetResourceString("ServerSettings_ServerNameLabel")} {server.Profile.ServerName}```");
}
}).Wait();
return response;
}
private static IList<string> GetServerStatus(string channelId, string profileId)
{
List<string> response = new List<string>();
TaskUtils.RunOnUIThreadAsync(() =>
{
var serverList = ServerManager.Instance.Servers.Where(s => Equals(channelId, s.Profile.DiscordChannelId) && (string.IsNullOrWhiteSpace(profileId) || Equals(profileId, s.Profile.ProfileID)));
response.Add($"**{_globalizer.GetResourceString("DiscordBot_CountLabel")}** {serverList.Count()}");
foreach (var server in serverList)
{
response.Add($"```{_globalizer.GetResourceString("ServerSettings_ProfileLabel")} {server.Profile.ProfileName}\n{_globalizer.GetResourceString("ServerSettings_ServerNameLabel")} {server.Profile.ServerName}\n{_globalizer.GetResourceString("ServerSettings_StatusLabel")} {server.Runtime.StatusString}\n{_globalizer.GetResourceString("ServerSettings_AvailabilityLabel")} {_globalizer.GetResourceString($"ServerSettings_Availability_{server.Runtime.Availability}")}```");
}
}).Wait();
return response;
}
private static IList<string> BackupServer(string channelId, string profileId)
{
return new List<string>() { string.Format(_globalizer.GetResourceString("DiscordBot_CommandUnknown"), CommandType.Backup) };
}
private static IList<string> ShutdownServer(string channelId, string profileId)
{
return new List<string>() { string.Format(_globalizer.GetResourceString("DiscordBot_CommandUnknown"), CommandType.Shutdown) };
}
private static IList<string> StopServer(string channelId, string profileId)
{
return new List<string>() { string.Format(_globalizer.GetResourceString("DiscordBot_CommandUnknown"), CommandType.Stop) };
}
private static IList<string> StartServer(string channelId, string profileId)
{
return new List<string>() { string.Format(_globalizer.GetResourceString("DiscordBot_CommandUnknown"), CommandType.Start) };
}
private static IList<string> UpdateServer(string channelId, string profileId)
{
return new List<string>() { string.Format(_globalizer.GetResourceString("DiscordBot_CommandUnknown"), CommandType.Update) };
} }
} }
} }

View file

@ -420,13 +420,13 @@
<DataTrigger Binding="{Binding Availability}" Value="{x:Static enum:AvailabilityStatus.Unknown}"> <DataTrigger Binding="{Binding Availability}" Value="{x:Static enum:AvailabilityStatus.Unknown}">
<Setter Property="Content" Value="{DynamicResource ServerSettings_Availability_Unknown}"/> <Setter Property="Content" Value="{DynamicResource ServerSettings_Availability_Unknown}"/>
</DataTrigger> </DataTrigger>
<DataTrigger Binding="{Binding Availability}" Value="{x:Static enum:AvailabilityStatus.NeedPublicIP}"> <DataTrigger Binding="{Binding Availability}" Value="{x:Static enum:AvailabilityStatus.SetPublicIP}">
<Setter Property="Content" Value="{DynamicResource ServerSettings_Availability_SetPublicIP}"/> <Setter Property="Content" Value="{DynamicResource ServerSettings_Availability_SetPublicIP}"/>
</DataTrigger> </DataTrigger>
<DataTrigger Binding="{Binding Availability}" Value="{x:Static enum:AvailabilityStatus.Unavailable}"> <DataTrigger Binding="{Binding Availability}" Value="{x:Static enum:AvailabilityStatus.Unavailable}">
<Setter Property="Content" Value="{DynamicResource ServerSettings_Availability_Unavailable}"/> <Setter Property="Content" Value="{DynamicResource ServerSettings_Availability_Unavailable}"/>
</DataTrigger> </DataTrigger>
<DataTrigger Binding="{Binding Availability}" Value="{x:Static enum:AvailabilityStatus.WaitingForPublication}"> <DataTrigger Binding="{Binding Availability}" Value="{x:Static enum:AvailabilityStatus.Waiting}">
<Setter Property="Content" Value="{DynamicResource ServerSettings_Availability_Waiting}"/> <Setter Property="Content" Value="{DynamicResource ServerSettings_Availability_Waiting}"/>
</DataTrigger> </DataTrigger>
<DataTrigger Binding="{Binding Availability}" Value="{x:Static enum:AvailabilityStatus.Available}"> <DataTrigger Binding="{Binding Availability}" Value="{x:Static enum:AvailabilityStatus.Available}">

View file

@ -3,15 +3,13 @@ using NLog.Config;
using NLog.Targets; using NLog.Targets;
using ServerManagerTool.Common; using ServerManagerTool.Common;
using ServerManagerTool.Common.Utils; using ServerManagerTool.Common.Utils;
using ServerManagerTool.Discord; using ServerManagerTool.DiscordBot;
using ServerManagerTool.Discord.Enums;
using ServerManagerTool.Enums; using ServerManagerTool.Enums;
using ServerManagerTool.Lib; using ServerManagerTool.Lib;
using ServerManagerTool.Plugin.Common; using ServerManagerTool.Plugin.Common;
using ServerManagerTool.Utils; using ServerManagerTool.Utils;
using ServerManagerTool.Windows; using ServerManagerTool.Windows;
using System; using System;
using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Diagnostics; using System.Diagnostics;
using System.IO; using System.IO;
@ -214,11 +212,6 @@ namespace ServerManagerTool
return LogManager.GetLogger(loggerName); return LogManager.GetLogger(loggerName);
} }
private static IList<string> HandleDiscordCommand(CommandType commandType, string serverId, string channelId, string profileId)
{
return new List<string>() { $"{commandType}; {serverId}; {channelId}; {profileId ?? "no profile"}" };
}
private static void MigrateSettings() private static void MigrateSettings()
{ {
var installFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); var installFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
@ -444,7 +437,7 @@ namespace ServerManagerTool
Task discordTask = Task.Run(async () => Task discordTask = Task.Run(async () =>
{ {
await ServerManagerBotFactory.GetServerManagerBot()?.StartAsync(Config.Default.DiscordBotToken,Config.Default.DiscordBotPrefix, Config.Default.DataPath, DiscordBotHelper.HandleDiscordCommand, _tokenSource.Token); await ServerManagerBotFactory.GetServerManagerBot()?.StartAsync(Config.Default.DiscordBotToken,Config.Default.DiscordBotPrefix, Config.Default.DataPath, DiscordBotHelper.HandleDiscordCommand, DiscordBotHelper.HandleTranslation, _tokenSource.Token);
}, _tokenSource.Token) }, _tokenSource.Token)
.ContinueWith(t => { .ContinueWith(t => {
var message = t.Exception.InnerException is null ? t.Exception.Message : t.Exception.InnerException.Message; var message = t.Exception.InnerException is null ? t.Exception.Message : t.Exception.InnerException.Message;

View file

@ -3,9 +3,9 @@
public enum AvailabilityStatus public enum AvailabilityStatus
{ {
Unknown, Unknown,
NeedPublicIP, SetPublicIP,
Unavailable, Unavailable,
WaitingForPublication, Waiting,
Available Available
} }
} }

View file

@ -1214,6 +1214,18 @@
<sys:String x:Key="DiscordBot_ErrorTitle">Discord Bot Error</sys:String> <sys:String x:Key="DiscordBot_ErrorTitle">Discord Bot Error</sys:String>
<sys:String x:Key="DiscordBot_MissingTokenError">The discord bot requires a valid token so it can log into the discord server\r\nThis can be set in the global settings.</sys:String> <sys:String x:Key="DiscordBot_MissingTokenError">The discord bot requires a valid token so it can log into the discord server\r\nThis can be set in the global settings.</sys:String>
<sys:String x:Key="DiscordBot_InvalidPrefixError">The discord bot prefix contains invalid characters. Only letters and numbers are allowed.</sys:String> <sys:String x:Key="DiscordBot_InvalidPrefixError">The discord bot prefix contains invalid characters. Only letters and numbers are allowed.</sys:String>
<sys:String x:Key="DiscordBot_CommandNotImplemented">Command '{0}' has not been implemented.</sys:String>
<sys:String x:Key="DiscordBot_CommandUnknown">Unknown command '{0}'.</sys:String>
<sys:String x:Key="DiscordBot_CommandRunning">Another command is currently running.</sys:String>
<sys:String x:Key="DiscordBot_CommandProfileMissing">The command requires a profile id.</sys:String>
<sys:String x:Key="DiscordBot_CommandProfileNotFound">Profile id {0} not found or is not associated with the channel.</sys:String>
<sys:String x:Key="DiscordBot_CommandInfoFailed">Call to the server '{0}' failed.</sys:String>
<sys:String x:Key="DiscordBot_CountLabel">Count:</sys:String>
<sys:String x:Key="DiscordBot_MapLabel">Map:</sys:String>
<!--#endregion--> <!--#endregion-->
</Globalization:GlobalizationResourceDictionary> </Globalization:GlobalizationResourceDictionary>

View file

@ -277,13 +277,13 @@ namespace ServerManagerTool.Lib
case WatcherServerStatus.RunningLocalCheck: case WatcherServerStatus.RunningLocalCheck:
if (oldStatus != ServerStatus.Stopping) if (oldStatus != ServerStatus.Stopping)
UpdateServerStatus(ServerStatus.Running, this.Availability != AvailabilityStatus.Available ? AvailabilityStatus.WaitingForPublication : this.Availability, oldStatus != ServerStatus.Running && oldStatus != ServerStatus.Unknown); UpdateServerStatus(ServerStatus.Running, this.Availability != AvailabilityStatus.Available ? AvailabilityStatus.Waiting : this.Availability, oldStatus != ServerStatus.Running && oldStatus != ServerStatus.Unknown);
if (this.ProfileSnapshot.MOTDIntervalEnabled && this.motdIntervalTimer != null && !this.motdIntervalTimer.Enabled) this.motdIntervalTimer.Start(); if (this.ProfileSnapshot.MOTDIntervalEnabled && this.motdIntervalTimer != null && !this.motdIntervalTimer.Enabled) this.motdIntervalTimer.Start();
break; break;
case WatcherServerStatus.RunningExternalCheck: case WatcherServerStatus.RunningExternalCheck:
if (oldStatus != ServerStatus.Stopping) if (oldStatus != ServerStatus.Stopping)
UpdateServerStatus(ServerStatus.Running, AvailabilityStatus.WaitingForPublication, oldStatus != ServerStatus.Running && oldStatus != ServerStatus.Unknown); UpdateServerStatus(ServerStatus.Running, AvailabilityStatus.Waiting, oldStatus != ServerStatus.Running && oldStatus != ServerStatus.Unknown);
if (this.ProfileSnapshot.MOTDIntervalEnabled && this.motdIntervalTimer != null && !this.motdIntervalTimer.Enabled) this.motdIntervalTimer.Start(); if (this.ProfileSnapshot.MOTDIntervalEnabled && this.motdIntervalTimer != null && !this.motdIntervalTimer.Enabled) this.motdIntervalTimer.Start();
break; break;

View file

@ -1,13 +1,188 @@
using ServerManagerTool.Discord.Enums; using QueryMaster;
using ServerManagerTool.Common.Utils;
using ServerManagerTool.DiscordBot.Enums;
using ServerManagerTool.Lib;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Net;
using WPFSharp.Globalizer;
namespace ServerManagerTool.Utils namespace ServerManagerTool.Utils
{ {
internal static class DiscordBotHelper internal static class DiscordBotHelper
{ {
private static readonly GlobalizedApplication _globalizer = GlobalizedApplication.Instance;
private static bool _runningCommand = false;
public static IList<string> HandleDiscordCommand(CommandType commandType, string serverId, string channelId, string profileId) public static IList<string> HandleDiscordCommand(CommandType commandType, string serverId, string channelId, string profileId)
{ {
return new List<string>() { $"{commandType}; {serverId}; {channelId}; {profileId ?? "no profile"}" }; // check if incoming values are valid
if (string.IsNullOrWhiteSpace(serverId) || string.IsNullOrWhiteSpace(channelId))
return null;
// check if the server ids match
if (!serverId.Equals(Config.Default.DiscordBotServerId))
return new List<string>();
if (_runningCommand)
return new List<string> { _globalizer.GetResourceString("DiscordBot_CommandRunning") };
_runningCommand = true;
try
{
switch (commandType)
{
case CommandType.Info:
return GetServerInfo(channelId, profileId);
case CommandType.List:
return GetServerList(channelId);
case CommandType.Status:
return GetServerStatus(channelId, profileId);
case CommandType.Backup:
return BackupServer(channelId, profileId);
case CommandType.Shutdown:
return ShutdownServer(channelId, profileId);
case CommandType.Stop:
return StopServer(channelId, profileId);
case CommandType.Start:
return StartServer(channelId, profileId);
case CommandType.Update:
return UpdateServer(channelId, profileId);
default:
return new List<string> { string.Format(_globalizer.GetResourceString("DiscordBot_CommandUnknown"), commandType) };
}
}
catch (Exception ex)
{
return new string[] { ex.Message };
}
finally
{
_runningCommand = false;
}
}
public static string HandleTranslation(string translationKey)
{
return string.IsNullOrWhiteSpace(translationKey) ? string.Empty : _globalizer.GetResourceString(translationKey) ?? translationKey;
}
private static IList<string> GetServerInfo(string channelId, string profileId)
{
if (string.IsNullOrWhiteSpace(profileId))
{
return new List<string> { _globalizer.GetResourceString("DiscordBot_CommandProfileMissing") };
}
var serverName = string.Empty;
var serverIp = IPAddress.Loopback;
var queryPort = 0;
TaskUtils.RunOnUIThreadAsync(() =>
{
var server = ServerManager.Instance.Servers.Where(s => Equals(channelId, s.Profile.DiscordChannelId) && Equals(profileId, s.Profile.ProfileID)).FirstOrDefault();
if (server is null)
{
throw new Exception(string.Format(_globalizer.GetResourceString("DiscordBot_CommandProfileNotFound"), profileId));
}
serverName = server.Profile.ServerName;
if (!string.IsNullOrWhiteSpace(server.Profile.ServerIP))
{
IPAddress.TryParse(server.Profile.ServerIP, out serverIp);
}
queryPort = server.Profile.QueryPort;
}).Wait();
List<string> response = new List<string>();
try
{
using (var gameServer = ServerQuery.GetServerInstance(EngineType.Source, new IPEndPoint(serverIp, queryPort)))
{
var info = gameServer?.GetInfo();
if (info is null)
{
response.Add(string.Format(_globalizer.GetResourceString("DiscordBot_CommandInfoFailed"), serverName));
}
else
{
var mapName = _globalizer.GetResourceString($"Map_{info.Map}") ?? info.Map;
response.Add($"```{info.Name}\n{_globalizer.GetResourceString("DiscordBot_MapLabel")} {mapName}\n{_globalizer.GetResourceString("ServerSettings_PlayersLabel")} {info.Players} / {info.MaxPlayers}```");
}
}
}
catch (Exception)
{
response.Add(string.Format(_globalizer.GetResourceString("DiscordBot_CommandInfoFailed"), serverName));
}
return response;
}
private static IList<string> GetServerList(string channelId)
{
List<string> response = new List<string>();
TaskUtils.RunOnUIThreadAsync(() =>
{
var serverList = ServerManager.Instance.Servers.Where(s => Equals(channelId, s.Profile.DiscordChannelId));
response.Add($"**{_globalizer.GetResourceString("DiscordBot_CountLabel")}** {serverList.Count()}");
foreach (var server in serverList)
{
response.Add($"```{_globalizer.GetResourceString("ServerSettings_ProfileIdLabel")} {server.Profile.ProfileID}\n{_globalizer.GetResourceString("ServerSettings_ProfileLabel")} {server.Profile.ProfileName}\n{_globalizer.GetResourceString("ServerSettings_ServerNameLabel")} {server.Profile.ServerName}```");
}
}).Wait();
return response;
}
private static IList<string> GetServerStatus(string channelId, string profileId)
{
List<string> response = new List<string>();
TaskUtils.RunOnUIThreadAsync(() =>
{
var serverList = ServerManager.Instance.Servers.Where(s => Equals(channelId, s.Profile.DiscordChannelId) && (string.IsNullOrWhiteSpace(profileId) || Equals(profileId, s.Profile.ProfileID)));
response.Add($"**{_globalizer.GetResourceString("DiscordBot_CountLabel")}** {serverList.Count()}");
foreach (var server in serverList)
{
response.Add($"```{_globalizer.GetResourceString("ServerSettings_ProfileLabel")} {server.Profile.ProfileName}\n{_globalizer.GetResourceString("ServerSettings_ServerNameLabel")} {server.Profile.ServerName}\n{_globalizer.GetResourceString("ServerSettings_StatusLabel")} {server.Runtime.StatusString}\n{_globalizer.GetResourceString("ServerSettings_AvailabilityLabel")} {_globalizer.GetResourceString($"ServerSettings_Availability_{server.Runtime.Availability}")}```");
}
}).Wait();
return response;
}
private static IList<string> BackupServer(string channelId, string profileId)
{
return new List<string>() { string.Format(_globalizer.GetResourceString("DiscordBot_CommandUnknown"), CommandType.Backup) };
}
private static IList<string> ShutdownServer(string channelId, string profileId)
{
return new List<string>() { string.Format(_globalizer.GetResourceString("DiscordBot_CommandUnknown"), CommandType.Shutdown) };
}
private static IList<string> StopServer(string channelId, string profileId)
{
return new List<string>() { string.Format(_globalizer.GetResourceString("DiscordBot_CommandUnknown"), CommandType.Stop) };
}
private static IList<string> StartServer(string channelId, string profileId)
{
return new List<string>() { string.Format(_globalizer.GetResourceString("DiscordBot_CommandUnknown"), CommandType.Start) };
}
private static IList<string> UpdateServer(string channelId, string profileId)
{
return new List<string>() { string.Format(_globalizer.GetResourceString("DiscordBot_CommandUnknown"), CommandType.Update) };
} }
} }
} }

View file

@ -282,13 +282,13 @@
<DataTrigger Binding="{Binding Availability}" Value="{x:Static enum:AvailabilityStatus.Unknown}"> <DataTrigger Binding="{Binding Availability}" Value="{x:Static enum:AvailabilityStatus.Unknown}">
<Setter Property="Content" Value="{DynamicResource ServerSettings_Availability_Unknown}"/> <Setter Property="Content" Value="{DynamicResource ServerSettings_Availability_Unknown}"/>
</DataTrigger> </DataTrigger>
<DataTrigger Binding="{Binding Availability}" Value="{x:Static enum:AvailabilityStatus.NeedPublicIP}"> <DataTrigger Binding="{Binding Availability}" Value="{x:Static enum:AvailabilityStatus.SetPublicIP}">
<Setter Property="Content" Value="{DynamicResource ServerSettings_Availability_SetPublicIP}"/> <Setter Property="Content" Value="{DynamicResource ServerSettings_Availability_SetPublicIP}"/>
</DataTrigger> </DataTrigger>
<DataTrigger Binding="{Binding Availability}" Value="{x:Static enum:AvailabilityStatus.Unavailable}"> <DataTrigger Binding="{Binding Availability}" Value="{x:Static enum:AvailabilityStatus.Unavailable}">
<Setter Property="Content" Value="{DynamicResource ServerSettings_Availability_Unavailable}"/> <Setter Property="Content" Value="{DynamicResource ServerSettings_Availability_Unavailable}"/>
</DataTrigger> </DataTrigger>
<DataTrigger Binding="{Binding Availability}" Value="{x:Static enum:AvailabilityStatus.WaitingForPublication}"> <DataTrigger Binding="{Binding Availability}" Value="{x:Static enum:AvailabilityStatus.Waiting}">
<Setter Property="Content" Value="{DynamicResource ServerSettings_Availability_Waiting}"/> <Setter Property="Content" Value="{DynamicResource ServerSettings_Availability_Waiting}"/>
</DataTrigger> </DataTrigger>
<DataTrigger Binding="{Binding Availability}" Value="{x:Static enum:AvailabilityStatus.Available}"> <DataTrigger Binding="{Binding Availability}" Value="{x:Static enum:AvailabilityStatus.Available}">

View file

@ -1,7 +1,7 @@
using ServerManagerTool.Discord.Enums; using ServerManagerTool.DiscordBot.Enums;
using System.Collections.Generic; using System.Collections.Generic;
namespace ServerManagerTool.Discord.Delegates namespace ServerManagerTool.DiscordBot.Delegates
{ {
public delegate IList<string> HandleCommandDelegate(CommandType commandType, string serverId, string channelId, string profileId); public delegate IList<string> HandleCommandDelegate(CommandType commandType, string serverId, string channelId, string profileId);
} }

View file

@ -0,0 +1,4 @@
namespace ServerManagerTool.DiscordBot.Delegates
{
public delegate string HandleTranslationDelegate(string translationKey);
}

View file

@ -1,6 +1,6 @@
using ServerManagerTool.Discord.Delegates; using ServerManagerTool.DiscordBot.Delegates;
namespace ServerManagerTool.Discord namespace ServerManagerTool.DiscordBot
{ {
public static class DiscordBot public static class DiscordBot
{ {

View file

@ -1,14 +1,15 @@
namespace ServerManagerTool.Discord.Enums namespace ServerManagerTool.DiscordBot.Enums
{ {
public enum CommandType public enum CommandType
{ {
BackupServer, Info,
ServerInfo, List,
ServerList, Status,
ServerStatus,
ShutdownServer, Backup,
StartServer, Shutdown,
StopServer, Start,
UpdateServer, Stop,
Update,
} }
} }

View file

@ -1,11 +1,11 @@
using ServerManagerTool.Discord.Delegates; using ServerManagerTool.DiscordBot.Delegates;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace ServerManagerTool.Discord.Interfaces namespace ServerManagerTool.DiscordBot.Interfaces
{ {
public interface IServerManagerBot public interface IServerManagerBot
{ {
Task StartAsync(string discordToken, string commandPrefix, string dataDirectory, HandleCommandDelegate handleCommandCallback, CancellationToken token); Task StartAsync(string discordToken, string commandPrefix, string dataDirectory, HandleCommandDelegate handleCommandCallback, HandleTranslationDelegate handleTranslationCallback, CancellationToken token);
} }
} }

View file

@ -6,7 +6,7 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace ServerManagerTool.Discord.Modules namespace ServerManagerTool.DiscordBot.Modules
{ {
[Name("Help")] [Name("Help")]
public sealed class HelpModule : ModuleBase<SocketCommandContext> public sealed class HelpModule : ModuleBase<SocketCommandContext>
@ -26,6 +26,7 @@ namespace ServerManagerTool.Discord.Modules
[Command("help")] [Command("help")]
[Summary("Provides a list of available commands")] [Summary("Provides a list of available commands")]
[RequireBotPermission(ChannelPermission.ViewChannel | ChannelPermission.SendMessages)]
public async Task HelpAsync() public async Task HelpAsync()
{ {
var prefix = _config["DiscordSettings:Prefix"]; var prefix = _config["DiscordSettings:Prefix"];
@ -102,6 +103,7 @@ namespace ServerManagerTool.Discord.Modules
[Command("help")] [Command("help")]
[Summary("Searches a list of available commands")] [Summary("Searches a list of available commands")]
[RequireBotPermission(ChannelPermission.ViewChannel | ChannelPermission.SendMessages)]
public async Task HelpAsync(string command) public async Task HelpAsync(string command)
{ {
var searchResults = _service.Search(Context, command); var searchResults = _service.Search(Context, command);

View file

@ -1,12 +1,13 @@
using Discord.Addons.Interactive; using Discord;
using Discord.Addons.Interactive;
using Discord.Commands; using Discord.Commands;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using ServerManagerTool.Discord.Delegates; using ServerManagerTool.DiscordBot.Delegates;
using ServerManagerTool.Discord.Enums; using ServerManagerTool.DiscordBot.Enums;
using System; using System;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace ServerManagerTool.Discord.Modules namespace ServerManagerTool.DiscordBot.Modules
{ {
[Name("Server Commands")] [Name("Server Commands")]
public sealed class ServerCommandModule : InteractiveBase public sealed class ServerCommandModule : InteractiveBase
@ -25,6 +26,7 @@ namespace ServerManagerTool.Discord.Modules
[Command("backup", RunMode = RunMode.Async)] [Command("backup", RunMode = RunMode.Async)]
[Summary("Perform a backup of the server")] [Summary("Perform a backup of the server")]
[Remarks("backup")] [Remarks("backup")]
[RequireBotPermission(ChannelPermission.ViewChannel | ChannelPermission.SendMessages)]
public async Task BackupServerAsync() public async Task BackupServerAsync()
{ {
await BackupServerAsync(null); await BackupServerAsync(null);
@ -33,6 +35,7 @@ namespace ServerManagerTool.Discord.Modules
[Command("backup", RunMode = RunMode.Async)] [Command("backup", RunMode = RunMode.Async)]
[Summary("Perform a backup of the server")] [Summary("Perform a backup of the server")]
[Remarks("backup profileId")] [Remarks("backup profileId")]
[RequireBotPermission(ChannelPermission.ViewChannel | ChannelPermission.SendMessages)]
public async Task BackupServerAsync(string profileId) public async Task BackupServerAsync(string profileId)
{ {
try try
@ -40,8 +43,8 @@ namespace ServerManagerTool.Discord.Modules
var serverId = Context?.Guild?.Id.ToString() ?? string.Empty; var serverId = Context?.Guild?.Id.ToString() ?? string.Empty;
var channelId = Context?.Channel?.Id.ToString() ?? string.Empty; var channelId = Context?.Channel?.Id.ToString() ?? string.Empty;
var response = _handleCommandCallback?.Invoke(CommandType.BackupServer, serverId, channelId, profileId); var response = _handleCommandCallback?.Invoke(CommandType.Backup, serverId, channelId, profileId);
if (response is null || response.Count == 0) if (response is null)
{ {
await ReplyAsync("No servers associated with this channel."); await ReplyAsync("No servers associated with this channel.");
} }
@ -49,7 +52,7 @@ namespace ServerManagerTool.Discord.Modules
{ {
foreach (var output in response) foreach (var output in response)
{ {
await ReplyAsync(output); await ReplyAsync(output.Replace("&", "_"));
await Task.Delay(1000); await Task.Delay(1000);
} }
} }
@ -63,6 +66,7 @@ namespace ServerManagerTool.Discord.Modules
[Command("shutdown", RunMode = RunMode.Async)] [Command("shutdown", RunMode = RunMode.Async)]
[Summary("Shuts down the server properly")] [Summary("Shuts down the server properly")]
[Remarks("shutdown")] [Remarks("shutdown")]
[RequireBotPermission(ChannelPermission.ViewChannel | ChannelPermission.SendMessages)]
public async Task ShutdownServerAsync() public async Task ShutdownServerAsync()
{ {
await ShutdownServerAsync(null); await ShutdownServerAsync(null);
@ -71,6 +75,7 @@ namespace ServerManagerTool.Discord.Modules
[Command("shutdown", RunMode = RunMode.Async)] [Command("shutdown", RunMode = RunMode.Async)]
[Summary("Shuts down the server properly")] [Summary("Shuts down the server properly")]
[Remarks("shutdown profileId")] [Remarks("shutdown profileId")]
[RequireBotPermission(ChannelPermission.ViewChannel | ChannelPermission.SendMessages)]
public async Task ShutdownServerAsync(string profileId) public async Task ShutdownServerAsync(string profileId)
{ {
try try
@ -78,8 +83,8 @@ namespace ServerManagerTool.Discord.Modules
var serverId = Context?.Guild?.Id.ToString() ?? string.Empty; var serverId = Context?.Guild?.Id.ToString() ?? string.Empty;
var channelId = Context?.Channel?.Id.ToString() ?? string.Empty; var channelId = Context?.Channel?.Id.ToString() ?? string.Empty;
var response = _handleCommandCallback?.Invoke(CommandType.ShutdownServer, serverId, channelId, profileId); var response = _handleCommandCallback?.Invoke(CommandType.Shutdown, serverId, channelId, profileId);
if (response is null || response.Count == 0) if (response is null)
{ {
await ReplyAsync("No servers associated with this channel."); await ReplyAsync("No servers associated with this channel.");
} }
@ -87,7 +92,7 @@ namespace ServerManagerTool.Discord.Modules
{ {
foreach (var output in response) foreach (var output in response)
{ {
await ReplyAsync(output); await ReplyAsync(output.Replace("&", "_"));
await Task.Delay(1000); await Task.Delay(1000);
} }
} }
@ -101,6 +106,7 @@ namespace ServerManagerTool.Discord.Modules
[Command("start", RunMode = RunMode.Async)] [Command("start", RunMode = RunMode.Async)]
[Summary("Starts the server")] [Summary("Starts the server")]
[Remarks("start")] [Remarks("start")]
[RequireBotPermission(ChannelPermission.ViewChannel | ChannelPermission.SendMessages)]
public async Task StartServerAsync() public async Task StartServerAsync()
{ {
await StartServerAsync(null); await StartServerAsync(null);
@ -109,6 +115,7 @@ namespace ServerManagerTool.Discord.Modules
[Command("start", RunMode = RunMode.Async)] [Command("start", RunMode = RunMode.Async)]
[Summary("Starts the server")] [Summary("Starts the server")]
[Remarks("start profileId")] [Remarks("start profileId")]
[RequireBotPermission(ChannelPermission.ViewChannel | ChannelPermission.SendMessages)]
public async Task StartServerAsync(string profileId) public async Task StartServerAsync(string profileId)
{ {
try try
@ -116,8 +123,8 @@ namespace ServerManagerTool.Discord.Modules
var serverId = Context?.Guild?.Id.ToString() ?? string.Empty; var serverId = Context?.Guild?.Id.ToString() ?? string.Empty;
var channelId = Context?.Channel?.Id.ToString() ?? string.Empty; var channelId = Context?.Channel?.Id.ToString() ?? string.Empty;
var response = _handleCommandCallback?.Invoke(CommandType.StartServer, serverId, channelId, profileId); var response = _handleCommandCallback?.Invoke(CommandType.Start, serverId, channelId, profileId);
if (response is null || response.Count == 0) if (response is null)
{ {
await ReplyAsync("No servers associated with this channel."); await ReplyAsync("No servers associated with this channel.");
} }
@ -125,7 +132,7 @@ namespace ServerManagerTool.Discord.Modules
{ {
foreach (var output in response) foreach (var output in response)
{ {
await ReplyAsync(output); await ReplyAsync(output.Replace("&", "_"));
await Task.Delay(1000); await Task.Delay(1000);
} }
} }
@ -139,6 +146,7 @@ namespace ServerManagerTool.Discord.Modules
[Command("stop", RunMode = RunMode.Async)] [Command("stop", RunMode = RunMode.Async)]
[Summary("Forcibly stops the server")] [Summary("Forcibly stops the server")]
[Remarks("stop")] [Remarks("stop")]
[RequireBotPermission(ChannelPermission.ViewChannel | ChannelPermission.SendMessages)]
public async Task StopServerAsync() public async Task StopServerAsync()
{ {
await StopServerAsync(null); await StopServerAsync(null);
@ -147,6 +155,7 @@ namespace ServerManagerTool.Discord.Modules
[Command("stop", RunMode = RunMode.Async)] [Command("stop", RunMode = RunMode.Async)]
[Summary("Forcibly stops the server")] [Summary("Forcibly stops the server")]
[Remarks("stop profileId")] [Remarks("stop profileId")]
[RequireBotPermission(ChannelPermission.ViewChannel | ChannelPermission.SendMessages)]
public async Task StopServerAsync(string profileId) public async Task StopServerAsync(string profileId)
{ {
try try
@ -154,8 +163,8 @@ namespace ServerManagerTool.Discord.Modules
var serverId = Context?.Guild?.Id.ToString() ?? string.Empty; var serverId = Context?.Guild?.Id.ToString() ?? string.Empty;
var channelId = Context?.Channel?.Id.ToString() ?? string.Empty; var channelId = Context?.Channel?.Id.ToString() ?? string.Empty;
var response = _handleCommandCallback?.Invoke(CommandType.StopServer, serverId, channelId, profileId); var response = _handleCommandCallback?.Invoke(CommandType.Stop, serverId, channelId, profileId);
if (response is null || response.Count == 0) if (response is null)
{ {
await ReplyAsync("No servers associated with this channel."); await ReplyAsync("No servers associated with this channel.");
} }
@ -163,7 +172,7 @@ namespace ServerManagerTool.Discord.Modules
{ {
foreach (var output in response) foreach (var output in response)
{ {
await ReplyAsync(output); await ReplyAsync(output.Replace("&", "_"));
await Task.Delay(1000); await Task.Delay(1000);
} }
} }
@ -177,6 +186,7 @@ namespace ServerManagerTool.Discord.Modules
[Command("update", RunMode = RunMode.Async)] [Command("update", RunMode = RunMode.Async)]
[Summary("Updates the server")] [Summary("Updates the server")]
[Remarks("update")] [Remarks("update")]
[RequireBotPermission(ChannelPermission.ViewChannel | ChannelPermission.SendMessages)]
public async Task UpdateServerAsync() public async Task UpdateServerAsync()
{ {
await UpdateServerAsync(null); await UpdateServerAsync(null);
@ -185,6 +195,7 @@ namespace ServerManagerTool.Discord.Modules
[Command("update", RunMode = RunMode.Async)] [Command("update", RunMode = RunMode.Async)]
[Summary("Updates the server")] [Summary("Updates the server")]
[Remarks("update profileId")] [Remarks("update profileId")]
[RequireBotPermission(ChannelPermission.ViewChannel | ChannelPermission.SendMessages)]
public async Task UpdateServerAsync(string profileId) public async Task UpdateServerAsync(string profileId)
{ {
try try
@ -192,8 +203,8 @@ namespace ServerManagerTool.Discord.Modules
var serverId = Context?.Guild?.Id.ToString() ?? string.Empty; var serverId = Context?.Guild?.Id.ToString() ?? string.Empty;
var channelId = Context?.Channel?.Id.ToString() ?? string.Empty; var channelId = Context?.Channel?.Id.ToString() ?? string.Empty;
var response = _handleCommandCallback?.Invoke(CommandType.UpdateServer, serverId, channelId, profileId); var response = _handleCommandCallback?.Invoke(CommandType.Update, serverId, channelId, profileId);
if (response is null || response.Count == 0) if (response is null)
{ {
await ReplyAsync("No servers associated with this channel."); await ReplyAsync("No servers associated with this channel.");
} }
@ -201,7 +212,7 @@ namespace ServerManagerTool.Discord.Modules
{ {
foreach (var output in response) foreach (var output in response)
{ {
await ReplyAsync(output); await ReplyAsync(output.Replace("&", "_"));
await Task.Delay(1000); await Task.Delay(1000);
} }
} }

View file

@ -1,12 +1,13 @@
using Discord.Addons.Interactive; using Discord;
using Discord.Addons.Interactive;
using Discord.Commands; using Discord.Commands;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using ServerManagerTool.Discord.Delegates; using ServerManagerTool.DiscordBot.Delegates;
using ServerManagerTool.Discord.Enums; using ServerManagerTool.DiscordBot.Enums;
using System; using System;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace ServerManagerTool.Discord.Modules namespace ServerManagerTool.DiscordBot.Modules
{ {
[Name("Server Query")] [Name("Server Query")]
public sealed class ServerQueryModule : InteractiveBase public sealed class ServerQueryModule : InteractiveBase
@ -25,6 +26,7 @@ namespace ServerManagerTool.Discord.Modules
[Command("info", RunMode = RunMode.Async)] [Command("info", RunMode = RunMode.Async)]
[Summary("Poll server for information")] [Summary("Poll server for information")]
[Remarks("info")] [Remarks("info")]
[RequireBotPermission(ChannelPermission.ViewChannel | ChannelPermission.SendMessages)]
public async Task ServerInfoAsync() public async Task ServerInfoAsync()
{ {
await ServerInfoAsync(null); await ServerInfoAsync(null);
@ -33,6 +35,7 @@ namespace ServerManagerTool.Discord.Modules
[Command("info", RunMode = RunMode.Async)] [Command("info", RunMode = RunMode.Async)]
[Summary("Poll server for information")] [Summary("Poll server for information")]
[Remarks("info profileId")] [Remarks("info profileId")]
[RequireBotPermission(ChannelPermission.ViewChannel | ChannelPermission.SendMessages)]
public async Task ServerInfoAsync(string profileId) public async Task ServerInfoAsync(string profileId)
{ {
try try
@ -40,8 +43,8 @@ namespace ServerManagerTool.Discord.Modules
var serverId = Context?.Guild?.Id.ToString() ?? string.Empty; var serverId = Context?.Guild?.Id.ToString() ?? string.Empty;
var channelId = Context?.Channel?.Id.ToString() ?? string.Empty; var channelId = Context?.Channel?.Id.ToString() ?? string.Empty;
var response = _handleCommandCallback?.Invoke(CommandType.ServerInfo, serverId, channelId, profileId); var response = _handleCommandCallback?.Invoke(CommandType.Info, serverId, channelId, profileId);
if (response is null || response.Count == 0) if (response is null)
{ {
await ReplyAsync("No servers associated with this channel."); await ReplyAsync("No servers associated with this channel.");
} }
@ -49,7 +52,7 @@ namespace ServerManagerTool.Discord.Modules
{ {
foreach (var output in response) foreach (var output in response)
{ {
await ReplyAsync(output); await ReplyAsync(output.Replace("&", "_"));
await Task.Delay(1000); await Task.Delay(1000);
} }
} }
@ -63,6 +66,7 @@ namespace ServerManagerTool.Discord.Modules
[Command("list", RunMode = RunMode.Async)] [Command("list", RunMode = RunMode.Async)]
[Summary("List of all servers associated with this channel")] [Summary("List of all servers associated with this channel")]
[Remarks("list")] [Remarks("list")]
[RequireBotPermission(ChannelPermission.ViewChannel | ChannelPermission.SendMessages)]
public async Task ServerListAsync() public async Task ServerListAsync()
{ {
try try
@ -70,8 +74,8 @@ namespace ServerManagerTool.Discord.Modules
var serverId = Context?.Guild?.Id.ToString() ?? string.Empty; var serverId = Context?.Guild?.Id.ToString() ?? string.Empty;
var channelId = Context?.Channel?.Id.ToString() ?? string.Empty; var channelId = Context?.Channel?.Id.ToString() ?? string.Empty;
var response = _handleCommandCallback?.Invoke(CommandType.ServerList, serverId, channelId, null); var response = _handleCommandCallback?.Invoke(CommandType.List, serverId, channelId, null);
if (response is null || response.Count == 0) if (response is null)
{ {
await ReplyAsync("No servers associated with this channel."); await ReplyAsync("No servers associated with this channel.");
} }
@ -79,7 +83,7 @@ namespace ServerManagerTool.Discord.Modules
{ {
foreach (var output in response) foreach (var output in response)
{ {
await ReplyAsync(output); await ReplyAsync(output.Replace("&", "_"));
await Task.Delay(1000); await Task.Delay(1000);
} }
} }
@ -93,6 +97,7 @@ namespace ServerManagerTool.Discord.Modules
[Command("status", RunMode = RunMode.Async)] [Command("status", RunMode = RunMode.Async)]
[Summary("Poll server for status")] [Summary("Poll server for status")]
[Remarks("status")] [Remarks("status")]
[RequireBotPermission(ChannelPermission.ViewChannel | ChannelPermission.SendMessages)]
public async Task ServerStatusAsync() public async Task ServerStatusAsync()
{ {
await ServerStatusAsync(null); await ServerStatusAsync(null);
@ -101,6 +106,7 @@ namespace ServerManagerTool.Discord.Modules
[Command("status", RunMode = RunMode.Async)] [Command("status", RunMode = RunMode.Async)]
[Summary("Poll server for status")] [Summary("Poll server for status")]
[Remarks("status profileId")] [Remarks("status profileId")]
[RequireBotPermission(ChannelPermission.ViewChannel | ChannelPermission.SendMessages)]
public async Task ServerStatusAsync(string profileId) public async Task ServerStatusAsync(string profileId)
{ {
try try
@ -108,8 +114,8 @@ namespace ServerManagerTool.Discord.Modules
var serverId = Context?.Guild?.Id.ToString() ?? string.Empty; var serverId = Context?.Guild?.Id.ToString() ?? string.Empty;
var channelId = Context?.Channel?.Id.ToString() ?? string.Empty; var channelId = Context?.Channel?.Id.ToString() ?? string.Empty;
var response = _handleCommandCallback?.Invoke(CommandType.ServerStatus, serverId, channelId, profileId); var response = _handleCommandCallback?.Invoke(CommandType.Status, serverId, channelId, profileId);
if (response is null || response.Count == 0) if (response is null)
{ {
await ReplyAsync("No servers associated with this channel."); await ReplyAsync("No servers associated with this channel.");
} }
@ -117,7 +123,7 @@ namespace ServerManagerTool.Discord.Modules
{ {
foreach (var output in response) foreach (var output in response)
{ {
await ReplyAsync(output); await ReplyAsync(output.Replace("&", "_"));
await Task.Delay(1000); await Task.Delay(1000);
} }
} }

View file

@ -5,7 +5,7 @@
<PropertyGroup> <PropertyGroup>
<TargetFramework>net462</TargetFramework> <TargetFramework>net462</TargetFramework>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo> <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<RootNamespace>ServerManagerTool.Discord</RootNamespace> <RootNamespace>ServerManagerTool.DiscordBot</RootNamespace>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<DebugType>none</DebugType> <DebugType>none</DebugType>

View file

@ -5,9 +5,9 @@ using Discord.Net.Providers.WS4Net;
using Discord.WebSocket; using Discord.WebSocket;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using ServerManagerTool.Discord.Delegates; using ServerManagerTool.DiscordBot.Delegates;
using ServerManagerTool.Discord.Interfaces; using ServerManagerTool.DiscordBot.Interfaces;
using ServerManagerTool.Discord.Services; using ServerManagerTool.DiscordBot.Services;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
@ -15,7 +15,7 @@ using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace ServerManagerTool.Discord namespace ServerManagerTool.DiscordBot
{ {
public sealed class ServerManagerBot : IServerManagerBot public sealed class ServerManagerBot : IServerManagerBot
{ {
@ -30,7 +30,7 @@ namespace ServerManagerTool.Discord
set; set;
} }
public async Task StartAsync(string discordToken, string commandPrefix, string dataDirectory, HandleCommandDelegate handleCommandCallback, CancellationToken token) public async Task StartAsync(string discordToken, string commandPrefix, string dataDirectory, HandleCommandDelegate handleCommandCallback, HandleTranslationDelegate handleTranslationCallback, CancellationToken token)
{ {
if (Started) if (Started)
{ {
@ -38,7 +38,7 @@ namespace ServerManagerTool.Discord
} }
Started = true; Started = true;
if (string.IsNullOrWhiteSpace(commandPrefix) || string.IsNullOrWhiteSpace(discordToken) || handleCommandCallback is null) if (string.IsNullOrWhiteSpace(commandPrefix) || string.IsNullOrWhiteSpace(discordToken) || handleTranslationCallback is null || handleCommandCallback is null)
{ {
return; return;
} }
@ -55,8 +55,8 @@ namespace ServerManagerTool.Discord
var settings = new Dictionary<string, string> var settings = new Dictionary<string, string>
{ {
{ "DiscordSettings:Prefix", commandPrefix },
{ "DiscordSettings:Token", discordToken }, { "DiscordSettings:Token", discordToken },
{ "DiscordSettings:Prefix", commandPrefix },
{ "ServerManager:DataDirectory", dataDirectory } { "ServerManager:DataDirectory", dataDirectory }
}; };
@ -106,7 +106,8 @@ namespace ServerManagerTool.Discord
.AddSingleton<ShutdownService>() .AddSingleton<ShutdownService>()
.AddSingleton<Random>() .AddSingleton<Random>()
.AddSingleton(config) .AddSingleton(config)
.AddSingleton(handleCommandCallback); .AddSingleton(handleCommandCallback)
.AddSingleton(handleTranslationCallback);
// Create the service provider // Create the service provider
using (var provider = services.BuildServiceProvider()) using (var provider = services.BuildServiceProvider())

View file

@ -1,6 +1,6 @@
using ServerManagerTool.Discord.Interfaces; using ServerManagerTool.DiscordBot.Interfaces;
namespace ServerManagerTool.Discord namespace ServerManagerTool.DiscordBot
{ {
public static class ServerManagerBotFactory public static class ServerManagerBotFactory
{ {

View file

@ -4,7 +4,7 @@ using Microsoft.Extensions.Configuration;
using System; using System;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace ServerManagerTool.Discord.Services namespace ServerManagerTool.DiscordBot.Services
{ {
public class CommandHandlerService public class CommandHandlerService
{ {

View file

@ -6,7 +6,7 @@ using System;
using System.IO; using System.IO;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace ServerManagerTool.Discord.Services namespace ServerManagerTool.DiscordBot.Services
{ {
public class LoggingService public class LoggingService
{ {

View file

@ -1,7 +1,7 @@
using Discord.WebSocket; using Discord.WebSocket;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace ServerManagerTool.Discord.Services namespace ServerManagerTool.DiscordBot.Services
{ {
public class ShutdownService public class ShutdownService
{ {

View file

@ -6,7 +6,7 @@ using System;
using System.Reflection; using System.Reflection;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace ServerManagerTool.Discord.Services namespace ServerManagerTool.DiscordBot.Services
{ {
public class StartupService public class StartupService
{ {