SanAndreasUnity/Assets/Scripts/Chat/Chat2Commands.cs

55 lines
1.8 KiB
C#
Raw Normal View History

2021-02-20 20:59:29 +00:00
using System;
using SanAndreasUnity.Commands;
using SanAndreasUnity.Net;
using SanAndreasUnity.Utilities;
using UnityEngine;
namespace SanAndreasUnity.Chat
{
public class Chat2Commands : MonoBehaviour
{
private void Start()
{
ChatManager.singleton.RegisterChatPreprocessor(new ChatPreprocessor {processCallback = ProcessChatMessage});
}
private ChatPreprocessorResult ProcessChatMessage(Player player, string chatMessage)
{
if (chatMessage.Length < 2 || !chatMessage.StartsWith("/"))
return new ChatPreprocessorResult { finalChatMessage = chatMessage };
int whiteSpaceIndex = chatMessage.FindIndex(char.IsWhiteSpace);
int commandLength = whiteSpaceIndex < 0 ? chatMessage.Length - 1 : whiteSpaceIndex - 1;
string command = chatMessage.Substring(1, commandLength);
if (!CommandManager.Singleton.HasCommand(command))
return new ChatPreprocessorResult { finalChatMessage = chatMessage };
string fullCommand = chatMessage.Substring(1);
string response;
try
{
response = CommandManager.Singleton.ProcessCommandForPlayer(player, fullCommand).response;
}
catch (Exception exception)
{
response = exception.Message;
}
2021-02-22 21:20:36 +00:00
// send command back to player
2021-02-28 23:58:50 +00:00
ChatManager.SendChatMessageToPlayerAsServer(player, chatMessage, false);
2021-02-22 21:20:36 +00:00
2021-02-20 20:59:29 +00:00
// send response back to player
2021-02-22 14:48:47 +00:00
if (!string.IsNullOrWhiteSpace(response))
2021-02-28 23:58:50 +00:00
ChatManager.SendChatMessageToPlayerAsServer(player, response, true);
2021-02-20 20:59:29 +00:00
// discard chat message
return new ChatPreprocessorResult {shouldBeDiscarded = true};
}
}
}