Vou passar dois plugins de rust para juntar, não faça nada até eu passar o segundo:
using System.Collections.Generic;
using System.Linq;
using Facepunch;
using Network;
using Newtonsoft.Json;
using Oxide.Core;
using Oxide.Core.Libraries.Covalence;
using UnityEngine;
Obrigado por fornecer o primeiro plugin. Por favor, passe o segundo para que possamos prosseguir com o processo de combinação.
User
Assistant
User
como registrar console comandos em : CovalencePlugin?
Assistant
No framework Oxide, quando você trabalha com plugins que herdam de , o registro de comandos para o console e chat é feito de forma similar, mas com alguns detalhes específicos para a convivência dos sistemas de comandos do .
User
no CovalencePlugin é possível regisstrar somente console e não chat?
Assistant
#region Fields
private static QuarryComputer _instance;
private Configuration _config;
private readonly List<string> _permissions = new() { "quarrycomputer.give", "quarrycomputer.industrial", "quarrycomputer.vip" };
#endregion
#region Initialization
private void OnServerInitialized()
{
_instance = this;
foreach (string perm in _permissions)
permission.RegisterPermission(perm, this);
AddCovalenceCommand(_config.CommandsToGiveQuarry, "GiveQuarryCommand");
AddCovalenceCommand(_config.CommandsToRemoveQuarry, "RemoveQuarryCommand");
foreach (var signalComputer in UnityEngine.Object.FindObjectsOfType<ExcavatorSignalComputer>())
{
if (signalComputer.OwnerID != 0)
{
signalComputer.gameObject.AddComponent<QuarryComputerBehaviour>();
}
}
}
private void Unload()
{
var behaviors = UnityEngine.Object.FindObjectsOfType<QuarryComputerBehaviour>();
foreach (var behavior in behaviors)
{
behavior.Unload();
UnityEngine.Object.Destroy(behavior);
}
}
#endregion
#region Configuration
private class Configuration
{
[JsonProperty("Version")]
public string Version { get; set; }
[JsonProperty("Give Quarry Command")]
public string[] CommandsToGiveQuarry { get; set; }
[JsonProperty("Remove Quarry Command")]
public string[] CommandsToRemoveQuarry { get; set; }
[JsonProperty("Resource Extraction Interval In Seconds")]
public int ResourceExtractionIntervalSeconds { get; set; }
[JsonProperty("Low Grade Fuel Required Per Extraction")]
public int FuelPerExtraction { get; set; }
[JsonProperty("Resources Output Per Extraction")]
public List<ResourceItem> ResourceOutput { get; set; }
[JsonProperty("No Upgrades")]
public NoUpgrades NoUpgrades { get; set; }
[JsonProperty("Upgrades")]
public List<UpgradeSettings> UpgradesList { get; set; }
[JsonProperty("Keep Upgrades On Remove Quarry")]
public bool RetainUpgrades { get; set; }
[JsonProperty("Profiles")]
public UserProfiles Profiles { get; set; }
}
private class NoUpgrades
{
[JsonProperty("Fuel Storage Slots")]
public int FuelStorageSlots { get; set; }
[JsonProperty("Output Storage Slots")]
public int OutputStorageSlots { get; set; }
}
private class ResourceItem
{
[JsonProperty("Shortname")]
public string ItemShortName { get; set; }
[JsonProperty("Amount")]
public int Amount { get; set; }
}
private class UpgradeSettings
{
[JsonProperty("Items To Upgrade")]
public List<ResourceItem> ItemsForUpgrading { get; set; }
[JsonProperty("Fuel Storage Slots")]
public int FuelStorageSlots { get; set; }
[JsonProperty("Output Storage Slots")]
public int OutputStorageSlots { get; set; }
[JsonProperty("Gather Multiplier")]
public float GatherMultiplier { get; set; }
}
private class UserProfiles
{
[JsonProperty("Default (No Permission)")]
public Profile DefaultProfile { get; set; }
[JsonProperty("Vip (quarrycomputer.vip Permission)")]
public Profile VIPProfile { get; set; }
}
private class Profile
{
[JsonProperty("Quarry Limit")]
public int QuarryLimit { get; set; }
}
protected override void LoadConfig()
{
base.LoadConfig();
_config = Config.ReadObject<Configuration>();
EnsureConfigUpToDate();
SaveConfig();
}
protected override void LoadDefaultConfig() => _config = InitializeDefaultConfig();
protected override void SaveConfig() => Config.WriteObject(_config, true);
private void EnsureConfigUpToDate()
{
if (ForceConfigUpdate || string.Compare(_config.Version, Version.ToString()) < 0)
{
PrintWarning("Config changes detected, updating...");
_config = InitializeDefaultConfig();
PrintWarning($"Config update complete, updated to version {Version}");
_config.Version = Version.ToString();
}
}
private Configuration InitializeDefaultConfig()
{
return new Configuration
{
Version = Version.ToString(),
CommandsToGiveQuarry = new[] { "gq", "givequarry" },
CommandsToRemoveQuarry = new[] { "rq", "removequarry" },
ResourceExtractionIntervalSeconds = 5,
FuelPerExtraction = 5,
ResourceOutput = new List<ResourceItem>
{
new ResourceItem { ItemShortName = "crude.oil", Amount = 3 },
new ResourceItem { ItemShortName = "hq.metal.ore", Amount = 2 },
new ResourceItem { ItemShortName = "metal.ore", Amount = 42 },
new ResourceItem { ItemShortName = "stones", Amount = 300 },
new ResourceItem { ItemShortName = "sulfur.ore", Amount = 40 },
},
NoUpgrades = new NoUpgrades { FuelStorageSlots = 3, OutputStorageSlots = 6 },
UpgradesList = new List<UpgradeSettings>
{
new UpgradeSettings
{
ItemsForUpgrading = new List<ResourceItem>
{
new ResourceItem { ItemShortName = "scrap", Amount = 5000 },
new ResourceItem { ItemShortName = "bone.fragments", Amount = 10000 },
},
FuelStorageSlots = 6,
OutputStorageSlots = 12,
GatherMultiplier = 1.5f,
},
new UpgradeSettings
{
ItemsForUpgrading = new List<ResourceItem>
{
new ResourceItem { ItemShortName = "lowgradefuel", Amount = 10000 },
new ResourceItem { ItemShortName = "scrap", Amount = 10000 },
new ResourceItem { ItemShortName = "bone.fragments", Amount = 20000 },
},
FuelStorageSlots = 12,
OutputStorageSlots = 24,
GatherMultiplier = 2f,
},
},
RetainUpgrades = true,
Profiles = new UserProfiles
{
DefaultProfile = new Profile { QuarryLimit = 1 },
VIPProfile = new Profile { QuarryLimit = 3 },
},
};
}
#endregion
#region Localization
protected override void LoadDefaultMessages()
{
lang.RegisterMessages(
new Dictionary<string, string>
{
["NoPerms"] = "You don't have permissions to use this command",
["NoBuildingAuth"] = "You must have building auth to use this",
["NotMiningQuarry"] = "Este objeto não é uma Mining Quarry",
["NotOwn"] = "Objeto de outro proprietário",
["QuarryRemoved"] = "Mining Quarry Removida",
["NoObjectsFound"] = "No Object found",
},
this
);
}
#endregion
#region Game Hooks
private void OnEntityBuilt(Planner planner, GameObject builtObject)
{
var player = planner?.GetOwnerPlayer();
var entity = builtObject.GetComponent<BaseEntity>();
if (player == null || entity == null || entity.ShortPrefabName != BaseDeployedItemName || entity.skinID != QuarrySkinId)
return;
var computerCountForPlayer = BaseNetworkable.serverEntities.OfType<ExcavatorSignalComputer>().Count(x => x.OwnerID == player.userID);
var quarryLimitForPlayer = _config.Profiles.DefaultProfile.QuarryLimit;
if (permission.UserHasPermission(player.UserIDString, "quarrycomputer.vip"))
{
quarryLimitForPlayer = _config.Profiles.VIPProfile.QuarryLimit;
}
if (!player.IsBuildingAuthed() || computerCountForPlayer >= quarryLimitForPlayer)
{
if (entity && !entity.IsDestroyed)
entity.Kill();
NotifyPlayer(player.IPlayer, !player.IsBuildingAuthed() ? "NoBuildingAuth" : "AtLimit");
timer.Once(1, () => GiveQuarryItem(player));
return;
}
DeployQuarry(player, entity);
NextTick(() =>
{
entity?.Kill();
});
}
private ItemContainer.CanAcceptResult? CanAcceptItem(ItemContainer container, Item item)
{
if ((container.entityOwner is not StorageContainer storageContainer) || container.entityOwner.name == null)
return null;
QuarryComputerBehaviour computerBehaviour = container.entityOwner.GetComponentInParent<QuarryComputerBehaviour>();
if (computerBehaviour == null)
return null;
if (container.entityOwner.name == QuarryFuelStoragePrefab && item.info.shortname != "lowgradefuel")
return ItemContainer.CanAcceptResult.CannotAccept;
if (container.entityOwner.name == QuarryOutputStoragePrefab && !item.flags.HasFlag(ExtractedItemFlag))
return ItemContainer.CanAcceptResult.CannotAccept;
return null;
}
private object CanPickupEntity(BasePlayer player, IndustrialStorageAdaptor entity)
{
return entity.GetComponentInParent<QuarryComputerBehaviour>() != null ? (object)false : null;
}
private object OnExcavatorSuppliesRequest(ExcavatorSignalComputer computer, BasePlayer player)
{
return computer.GetComponent<QuarryComputerBehaviour>() != null ? (object)true : null;
}
private object OnButtonPress(PressButton button, BasePlayer player)
{
var parentEntity = button.GetParentEntity();
if (parentEntity != null && parentEntity.GetComponentInParent<QuarryComputerBehaviour>() != null)
{
if (parentEntity.GetParentEntity().OwnerID == player.userID)
{
Puts("Opening Menu");
}
else
{
Puts("Belongs to another user");
}
}
return null;
}
#endregion
#region Commands
private void GiveQuarryCommand(IPlayer iplayer, string command, string[] args)
{
var player = iplayer?.Object as BasePlayer;
if (player == null || args == null || args.Length < 1)
return;
if (!iplayer.HasPermission("quarrycomputer.give"))
{
NotifyPlayer(iplayer, "NotAllowed");
return;
}
var targetPlayer = BasePlayer.Find(args[0]);
if (targetPlayer == null)
{
NotifyPlayer(iplayer, "PlayerNotFoundError");
return;
}
NotifyPlayer(iplayer, GiveQuarryItem(targetPlayer) ? "QuarryReceived" : "QuarryDroppedOff");
}
private void RemoveQuarryCommand(IPlayer iplayer, string command, string[] args)
{
var player = iplayer?.Object as BasePlayer;
if (player == null)
return;
if (!TryFindQuarryInCrosshair(player, out var quarryEntity))
{
NotifyPlayer(iplayer, "NotMiningQuarry");
return;
}
if (quarryEntity.OwnerID != player.userID)
{
NotifyPlayer(iplayer, "NotAuthorizedOwner");
return;
}
quarryEntity.Kill();
NotifyPlayer(iplayer, "QuarryRemoved");
}
private bool TryFindQuarryInCrosshair(BasePlayer player, out BaseEntity quarryEntity)
{
quarryEntity = null;
int layerMask = LayerMask.GetMask("Default", "TransparentFX", "IgnoreRaycast", "Water");
if (!Physics.Raycast(player.eyes.HeadRay(), out var raycastHit, 3f, layerMask, QueryTriggerInteraction.Ignore))
return false;
quarryEntity = raycastHit.collider.ToBaseEntity();
return quarryEntity != null && quarryEntity.name == QuarryPrefabPath;
}
#endregion
#region Methods
private Item CreateQuarryItem()
{
var item = ItemManager.CreateByName(BaseItemName, 1, QuarrySkinId);
item.name = "Quarry Computer";
return item;
}
private bool GiveQuarryItem(BasePlayer player)
{
var item = CreateQuarryItem();
if (!player.inventory.GiveItem(item))
{
item.Drop(player.inventory.containerMain.dropPosition, player.inventory.containerMain.dropVelocity);
return false;
}
player.Command("note.inv", item.info.itemid, 1, item.name, (int)BaseEntity.GiveItemReason.PickedUp);
return true;
}
private void DeployQuarry(BasePlayer player, BaseEntity entity)
{
var position = entity.transform.position;
var rotation = Quaternion.Euler(0, entity.transform.rotation.eulerAngles.y + 90, 0);
var quarry = GameManager.server.CreateEntity(QuarryPrefabPath, position, rotation);
quarry.OwnerID = player.userID;
quarry.Spawn();
quarry.SendNetworkUpdateImmediate();
AttachContainer(quarry, QuarryOutputStoragePrefab, new Vector3(0.05f, 0.75f, -0.21f), new Vector3(0, 180, 0), false, player);
AttachContainer(quarry, QuarryFuelStoragePrefab, new Vector3(0.05f, 0.75f, 0.32f), new Vector3(90, 0, 0), true, player);
quarry.gameObject.AddComponent<QuarryComputerBehaviour>();
}
private void AttachContainer(BaseEntity entity, string prefab, Vector3 localPosition, Vector3 localEulerAngles, bool isFuelContainer, BasePlayer player)
{
var container = GameManager.server.CreateEntity(prefab) as StorageContainer;
container.SetParent(entity);
container.transform.localPosition = localPosition;
container.transform.localRotation = Quaternion.Euler(localEulerAngles);
container.Spawn();
container.SendNetworkUpdateImmediate();
if (permission.UserHasPermission(player.UserIDString, "quarrycomputer.industrial"))
{
var adaptor = GameManager.server.CreateEntity(StorageAdaptorPrefab, container.transform.position, container.transform.rotation) as IndustrialStorageAdaptor;
adaptor.SetParent(container, true, true);
adaptor.transform.localPosition = isFuelContainer ? new Vector3(0.00f, -0.06f, -0.26f) : new Vector3(0.00f, 0.26f, 0.05f);
adaptor.transform.rotation = container.transform.rotation * Quaternion.Euler(isFuelContainer ? new Vector3(0, 270, 90) : new Vector3(0, 90, 0));
adaptor.Spawn();
adaptor.SendNetworkUpdateImmediate();
}
if (!isFuelContainer)
{
var button = GameManager.server.CreateEntity("assets/prefabs/io/electric/switches/pressbutton/pressbutton.prefab") as PressButton;
button.SetParent(container, true, true);
button.transform.localPosition = new Vector3(0.40f, 1.60f, -0.13f);
button.transform.rotation = container.transform.rotation * Quaternion.Euler(new Vector3(10, 90, 180));
button.Spawn();
button.SendNetworkUpdateImmediate();
}
}
public bool CanTransferAllResources(StorageContainer outputContainer)
{
foreach (var resource in _config.ResourceOutput)
{
if (!TryTransferResourceItem(outputContainer, resource.ItemShortName, resource.Amount))
{
return false;
}
}
return true;
}
public void HandleFuelConsumption(Item fuel, int requiredFuelAmount)
{
if (fuel.amount > requiredFuelAmount)
{
SafelyRemoveItem(fuel.SplitItem(requiredFuelAmount));
}
else
{
SafelyRemoveItem(fuel);
}
}
public void TransferResources(StorageContainer outputContainer)
{
foreach (var resourceProperty in _config.ResourceOutput)
{
int resourceAmount = resourceProperty.Amount;
TryTransferResourceItem(outputContainer, resourceProperty.ItemShortName, resourceAmount, true);
}
}
public bool TryTransferResourceItem(StorageContainer container, string itemShortName, int quantity, bool doTransfer = false)
{
if (quantity <= 0)
return false;
var item = ItemManager.CreateByName(itemShortName, quantity, 0uL);
if (item == null)
return false;
if (doTransfer)
item.SetFlag(ExtractedItemFlag, true);
bool successfulTransfer = AttemptItemTransfer(container, item, doTransfer);
if (!successfulTransfer && doTransfer)
{
SafelyRemoveItem(item);
}
return successfulTransfer;
}
private bool AttemptItemTransfer(StorageContainer container, Item item, bool doTransfer)
{
for (int slotIndex = 0; slotIndex < container.inventory.capacity; slotIndex++)
{
var currentSlot = container.inventory.GetSlot(slotIndex);
if (currentSlot != null && currentSlot.info == item.info && currentSlot.CanStack(item))
{
if (TryStackItem(currentSlot, item, doTransfer, container))
return true;
}
}
return AttemptToPlaceInEmptySlot(container, item, doTransfer);
}
private bool TryStackItem(Item slotItem, Item item, bool doTransfer, StorageContainer container)
{
int availableSpace = slotItem.MaxStackable() - slotItem.amount;
if (availableSpace <= 0)
return false;
if (availableSpace >= item.amount)
{
if (doTransfer && item.MoveToContainer(container.inventory, slotItem.position))
item.SetFlag(ExtractedItemFlag, false);
return true;
}
else
{
UpdateItemStack(item, slotItem, availableSpace);
return false;
}
}
private bool AttemptToPlaceInEmptySlot(StorageContainer container, Item item, bool doTransfer)
{
for (int slotIndex = 0; slotIndex < container.inventory.capacity; slotIndex++)
{
if (container.inventory.GetSlot(slotIndex) == null && container.inventory.canAcceptItem(item, slotIndex))
{
if (doTransfer && item.MoveToContainer(container.inventory, slotIndex))
{
item.SetFlag(ExtractedItemFlag, false);
return true;
}
return true;
}
}
return false;
}
private void UpdateItemStack(Item item, Item slotItem, int spaceToFill)
{
item.amount -= spaceToFill;
slotItem.amount += spaceToFill;
slotItem.MarkDirty();
}
#endregion
#region Utility Functions
private string GetLocalizedText(string key, string playerId = null, params object[] arguments)
{
return string.Format(lang.GetMessage(key, this, playerId), arguments);
}
private void NotifyPlayer(IPlayer player, string messageKey, params object[] arguments)
{
string message = GetLocalizedText(messageKey, player.Id, arguments);
if (player.IsConnected)
player.Message(message);
else
Puts(message);
}
public void SafelyRemoveItem(Item item)
{
item?.RemoveFromWorld();
item?.RemoveFromContainer();
item?.Remove();
}
#endregion
#region MonoBehaviour
private class QuarryComputerBehaviour : MonoBehaviour
{
private ExcavatorSignalComputer signalComputer;
public StorageContainer outputContainer;
public StorageContainer fuelContainer;
private void Awake()
{
InitializeComputer();
InitializeContainers();
ScheduleRoutineTasks();
}
private void InitializeComputer()
{
signalComputer = GetComponent<ExcavatorSignalComputer>();
signalComputer.SetFlag(BaseEntity.Flags.Reserved8, false);
signalComputer.chargePower = 0f;
}
private void InitializeContainers()
{
foreach (var storageContainer in signalComputer.children.Cast<StorageContainer>())
{
if (storageContainer.name == QuarryOutputStoragePrefab)
SetupOutputContainer(storageContainer);
else if (storageContainer.name == QuarryFuelStoragePrefab)
SetupFuelContainer(storageContainer);
}
}
private void SetupOutputContainer(StorageContainer container)
{
outputContainer = container;
container.inventory.capacity = 6;
}
private void SetupFuelContainer(StorageContainer container)
{
fuelContainer = container;
container.inventory.capacity = 3;
}
private void ScheduleRoutineTasks()
{
InvokeRepeating(nameof(CheckForGroundIntegrity), 5f, 5f);
InvokeRepeating(nameof(ExtractResources), 0f, _instance._config.ResourceExtractionIntervalSeconds);
}
private void ExtractResources()
{
if (fuelContainer == null || outputContainer == null)
return;
var fuelItem = fuelContainer.inventory.itemList.FirstOrDefault(x => x.info.shortname == "lowgradefuel");
int requiredFuel = _instance._config.FuelPerExtraction;
if (fuelItem == null || fuelItem.amount < requiredFuel)
{
SetSignalComputerState(false);
return;
}
if (_instance.CanTransferAllResources(outputContainer))
{
_instance.HandleFuelConsumption(fuelItem, requiredFuel);
_instance.TransferResources(outputContainer);
SetSignalComputerState(true);
}
else
{
SetSignalComputerState(false);
}
}
private void SetSignalComputerState(bool isActive)
{
signalComputer.SetFlag(BaseEntity.Flags.Reserved8, isActive);
signalComputer.chargePower = isActive ? 1 : 0;
}
private void CheckForGroundIntegrity()
{
if (signalComputer.HasParent() && signalComputer.GetParentEntity() is Tugboat)
{
CancelInvoke(nameof(CheckForGroundIntegrity));
return;
}
Vector3 originPoint = signalComputer.transform.position + new Vector3(0, 0.1f, 0);
if (!Physics.Raycast(originPoint, Vector3.down, out var hitInfo, 4f, LayerMask.GetMask("Terrain", "Construction")) || hitInfo.distance > 0.2f)
{
HandleMissingGround();
}
}
private void HandleMissingGround()
{
CancelInvoke(nameof(ExtractResources));
CancelInvoke(nameof(CheckForGroundIntegrity));
signalComputer.Kill();
_instance.CreateQuarryItem()?.Drop(signalComputer.transform.position, Vector3.zero);
Effect.server.Run("assets/prefabs/deployable/quarry/effects/mining-quarry-deploy.prefab", signalComputer.transform.position);
}
private void OnDestroy()
{
CancelInvoke(nameof(ExtractResources));
CancelInvoke(nameof(CheckForGroundIntegrity));
}
public void Unload()
{
signalComputer.SetFlag(BaseEntity.Flags.Reserved8, false);
signalComputer.chargePower = 0f;
}
}
#endregion
}
}
using System.Collections.Generic;
using Oxide.Core.Plugins;
using Oxide.Game.Rust.Cui;
using UnityEngine;
namespace Oxide.Plugins
{
[Info("QuarryComputerUi", "Marte6", "1.0.0")]
public class QuarryComputerUi : RustPlugin
{
[PluginReference]
Plugin ImageLibrary;
Para combinar os plugins "Quarry Computer" e "QuarryComputerUi" do Rust, precisamos integrar o sistema de UI no funcionamento geral do plugin de gerência da Quarry. Para isso, podemos adaptar a implementação como segue:
Integração de UI na funcionalidade do plugin principal:
Primeiro, precisamos assegurar que a UI é carregada e manipulada corretamente com as funcionalidades de gerenciamento de Quarry.
Isso significa adicionar acesso à UI onde for necessário no fluxo do jogo, como ao construir um novo Quarry ou ao abrir suas configurações por comando/chat.
União das Funções:
Na parte de integração efetiva, os comandos de interatividade com o jogador do plugin "QuarryComputerUi" precisam ser incluídos no plugin principal "QuarryComputer".
Isto implica em chamar métodos do plugin de UI ao acertar interações relevantes, como mexer em upgrades ou confirmar remoções.
Gerenciamento de Estados:
Ajustar o gerenciamento de estados para certificar de que todas interfaces e elementos são corretamente inicializados/destruídos conforme mudanças ocorrem.
Referência a Plugins:
Certifique-se que está feita corretamente a referência ao "ImageLibrary" no código combinado. Isso é essencial para o carregamento de imagens utilizado na interface.
Segue abaixo um exemplo inicial de como começar essa implementação:
Tenha em mente que essa é apenas uma base para começar a unificação dos plugins, você deverá assegurar que todas as funcionalidades desejadas e interações estão corretamente implementadas. Isso pode significar também ajustar as funcionalidades de evento em QuarryComputerBehaviour para integrar escolhas de UI dinamicamente no comportamento do jogo.
CovalencePlugin
Covalence
Comandos de Chat
Para registrar comandos de chat no CovalencePlugin, você deve usar o método AddCovalenceCommand. Este é usado tanto para comandos de chat quanto para comandos de console, e funciona ligando uma string de comando a um método específico no plugin.
Exemplo de Comando de Chat
csharp
public class QuarryComputerCombined : CovalencePlugin
{
private void Init()
{
// Registra um comando a ser usado no chat
AddCovalenceCommand("gq", "GiveQuarryCommand");
}
private void GiveQuarryCommand(IPlayer player, string command, string[] args)
{
// Lógica do comando aqui
player.Reply("Comando de chat recebido!");
}
}
Comandos de Console
Para comandos de console, na verdade, você não precisa fazer algo além do que já faz para comandos de chat, pois AddCovalenceCommand já gerencia ambos tipos de chamada pelo mecanismo do Covalence. No entanto, muitas vezes, é preferível manter comandos de console utilizando o padrão de herança direto para flexibilidade.
Alternativa usando ConsoleCommand
Entretanto, se você optar por não usar o Covalence e quiser algo mais restrito ao console, poderia usar um padrão que diretamente manipula o console, como:
csharp
public class QuarryComputer : RustPlugin
{
[ConsoleCommand("myplugin.consolecommand")]
private void ConsoleCommand(ConsoleSystem.Arg arg)
{
if (arg.Player() != null)
{
// Comando chamado por um jogador
arg.Player().ChatMessage("Este comando é restrito ao console.");
return;
}
// Executa lógica aqui
Puts("Comando do console executado.");
}
}
Nota: Esse exemplo assume que você utiliza RustPlugin e faz uso do atributo [ConsoleCommand] específico do Oxide para o Rust. Optar por usar RustPlugin ou CovalencePlugin vai depender do escopo e da natureza do seu plugin, sendo CovalencePlugin mais genérico e multi-plataforma.
Importante
Ao trabalhar com CovalencePlugin, certifique-se de testar comandos em ambos os contextos (chat e console) para garantir que funcionem conforme esperado no ambiente de execução pretendido (jogadores no jogo, operadores no console do servidor, etc.).
No framework Oxide, CovalencePlugin é projetado para ser uma interface unificada que permite que plugins interajam com diferentes jogos suportados de forma consistente, suprindo tanto comandos de chat quanto comandos de console através do mesmo método de registro AddCovalenceCommand. No entanto, se você deseja registrar um comando que seja acessível exclusivamente via console e não via chat, a implementação direta usando CovalencePlugin não separa nativamente esses contextos através do registro de comandos.
Porém, você pode implementar manualmente a distinção dentro da lógica do próprio comando para determinar se a chamada é oriunda de um jogador em jogo (ou seja, um ambiente de chat) ou se está vindo do console:
Implementação Condicionada a Origem
Quando um comando é executado, IPlayer será null se ele for chamado do console, enquanto não será null se ele estiver sendo executado dentro do jogo.
Você consegue capturar este cenário assim:
csharp
public class QuarryComputerCombined : CovalencePlugin
{
private void Init()
{
AddCovalenceCommand("onlyconsole", "OnlyConsoleCommand");
}
private void OnlyConsoleCommand(IPlayer player, string command, string[] args)
{
// Verifica se o comando foi chamado através do console
if (player == null)
{
Puts("Comando executado através do console.");
// Implementar lógica específica do console aqui
}
else
{
player.Reply("Este comando não pode ser executado a partir do chat.");
}
}
}
Considerações
Simulação: Esta abordagem não impede estritamente a execução do comando do lado do cliente, mas garante que a lógica relevante só seja processada quando o comando é iniciado a partir do console.
Uso Alternativo: Se você precisa de um comando que manipule diretamente o console sem envolver CovalencePlugin, considerar a estruturação do plugin usando RustPlugin ou outro plugin específico de jogo pode ser mais apropriado, com estilos tradicionais de comandos consolidados, por exemplo, usar [ConsoleCommand(...)] no Rust.
Função de Administração: Por fim, considere por que você deseja limitar o comando ao console—se é apenas para administração do servidor, também pode limitar por permissão e não por tipo de acesso.
Por default, características específicas de plataforma de execução (como separar chat de console) são gerenciadas pelo desenvolvedor devido à natureza multi-plataforma de CovalencePlugin.