CounterStrikeSharp icon indicating copy to clipboard operation
CounterStrikeSharp copied to clipboard

[Need help] Problems when buliding a plugin

Open DearCrazyLeaf opened this issue 1 month ago • 1 comments

Im trying to bulid a plugin which function is when players type "!dj {volume}" in chat, plugin will mimics them typing "snd_musicvolume {volume}"at their console. But it didnt work, the "snd_musicvolume" didnt change.

using ExecuteClientCommand(string) form CSSharp API https://docs.cssharp.dev/api/CounterStrikeSharp.API.Core.CCSPlayerController.html?q=ExecuteClientCommand#CounterStrikeSharp_API_Core_CCSPlayerController_CannotBeKicked

here is my code:

using System.Globalization; using Microsoft.Extensions.Logging; using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Core.Attributes; using CounterStrikeSharp.API;

namespace DJPlugin { [MinimumApiVersion(164)] public class DJPlugin : BasePlugin { private readonly ILogger<DJPlugin> _logger;

    public DJPlugin(ILogger<DJPlugin> logger)
    {
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    public override string ModuleName => "DJ Plugin";
    public override string ModuleVersion => "0.0.1 [bulid]";
    public override string ModuleAuthor => "Name";

    public override void Load(bool hotReload)
    {
        RegisterEventHandler<EventPlayerChat>(OnPlayerChat, HookMode.Post);
    }

    private HookResult OnPlayerChat(EventPlayerChat chatEvent, GameEventInfo eventInfo)
    {
        if (chatEvent.Text.StartsWith("!dj "))
        {
            try
            {
                var volumeStr = chatEvent.Text.Substring("!dj ".Length).Trim();
                if (float.TryParse(volumeStr, NumberStyles.Float, CultureInfo.InvariantCulture, out float volume) && volume >= 0 && volume <= 1)
                {
                    var playerId = chatEvent.Userid;
                    var player = Utilities.GetPlayerFromUserid(playerId);
                    if (player != null && player.IsValid)
                    {
                        player.ExecuteClientCommand($"snd_musicvolume {volume}");
                        _logger.LogInformation($"Player {player.PlayerName} set music volume to {volume}");
                    }
                    else
                    {
                        _logger.LogWarning($"Player with ID {playerId} not found or invalid.");
                    }
                }
                else
                {
                    _logger.LogWarning("Invalid volume specified.");
                }
            }
            catch (FormatException)
            {
                _logger.LogWarning("Volume input could not be parsed.");
            }
        }
        return HookResult.Continue;
    }
}

}

DearCrazyLeaf avatar May 21 '24 18:05 DearCrazyLeaf