// Copyright (c) 2026 HexEchoTV (CUB) // Licensed under the MIT License. See LICENSE file in the project root for full license information. // https://github.com/HexEchoTV/Streamerbot-Commands // // DEPENDENCIES: // - ConfigSetup.cs (run it first: it sets the currency and every config_ value read below; // anything it hasn't set falls back to the default shown in the code) // // SETUP: create an action, add a sub-action "Core > C# > Execute C# Code", paste this file, // then add a Command trigger for !search. // // USAGE: // !search once every config_search_cooldown_minutes (default 20); earns config_search_min to _max using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Text; public class CPHInline { public bool Execute() { try { LoadCurrency(); string user = Arg("user"); string userId = Arg("userId"); if (string.IsNullOrEmpty(user) || string.IsNullOrEmpty(userId)) { CPH.LogError("Search command: missing 'user' or 'userId' argument"); return false; } int minReward = Cfg("config_search_min", 18); int maxReward = Cfg("config_search_max", 75); int cooldownMinutes = Cfg("config_search_cooldown_minutes", 20); if (maxReward < minReward) maxReward = minReward; double wait = CooldownLeft(userId, "search_cooldown", TimeSpan.FromMinutes(cooldownMinutes)); if (wait > 0) { CPH.SendMessage($"{user}, you can search again in {FormatWait(wait)}!"); return false; } LogCommand("!search", user); // Each tier pays a slice of the min-max range, so the rare finds are // also the valuable ones and every payout stays inside the settings. Find[] finds = { new Find(60, 0, 40, "", new[] { "the couch cushions", "an old jacket pocket", "under the car seats" }), new Find(28, 40, 75, "✨", new[] { "the lost-and-found box", "a dusty attic" }), new Find(10, 75, 95, "💫 Rare!", new[] { "a forgotten safe" }), new Find(2, 95, 100, "🌟 LEGENDARY!", new[] { "a hidden treasure chest" }), }; int total = finds.Sum(f => f.Weight), pick = Roll(total), seen = 0; Find found = finds[0]; foreach (Find f in finds) { seen += f.Weight; if (pick < seen) { found = f; break; } } string item = found.Names[Roll(found.Names.Length)]; int span = maxReward - minReward; int reward = Roll(minReward + span * found.Low / 100, minReward + span * found.High / 100); int balance = AddToBalance(userId, reward); StartCooldown(userId, "search_cooldown"); string tag = string.IsNullOrEmpty(found.Tag) ? "" : found.Tag + " "; LogSuccess("Search", $"**User:** {user}\n**Found:** {item} ({(string.IsNullOrEmpty(found.Tag) ? "common" : found.Tag)})\n**Reward:** {Money(reward)}\n**New Balance:** {Money(balance)}"); CPH.SendMessage($"🔍 {tag}{user} searched {item} and found {Money(reward)}! | Balance: {Money(balance)}"); return true; } catch (Exception ex) { LogError("Search Command Exception", $"**Error:** {ex.Message}\n**Stack Trace:** {ex.StackTrace}"); CPH.SendMessage("⚠️ An error occurred during search"); CPH.LogError($"Search error: {ex.Message}"); return false; } } private class Find { public int Weight, Low, High; public string Tag; public string[] Names; public Find(int weight, int low, int high, string tag, string[] names) { Weight = weight; Low = low; High = high; Tag = tag; Names = names; } } // ═══════════════════════════════════════════════════════════ // SHARED HELPERS // ═══════════════════════════════════════════════════════════ // One Random for every run of this action, behind a lock: Streamer.bot can run // the same action for several viewers at once, and Random is not thread-safe. private static readonly Random Rng = new Random(); private static readonly object RngLock = new object(); private static int Roll(int maxExclusive) { lock (RngLock) return Rng.Next(maxExclusive); } private static int Roll(int min, int maxInclusive) { lock (RngLock) return Rng.Next(min, maxInclusive + 1); } private static double RollDouble() { lock (RngLock) return Rng.NextDouble(); } private string currencyName; private string currencyKey; private void LoadCurrency() { currencyName = CPH.GetGlobalVar("config_currency_name", true); if (string.IsNullOrEmpty(currencyName)) currencyName = "Cub Coins"; currencyKey = CPH.GetGlobalVar("config_currency_key", true); if (string.IsNullOrEmpty(currencyKey)) currencyKey = "cubcoins"; } // A config value, or the default if ConfigSetup hasn't set it (unset reads as 0). private int Cfg(string key, int fallback) { int value = CPH.GetGlobalVar(key, true); return value == 0 ? fallback : value; } private int GetBalance(string userId) { return CPH.GetTwitchUserVarById(userId, currencyKey, true); } private void SetBalance(string userId, int amount) { CPH.SetTwitchUserVarById(userId, currencyKey, amount, true); } private int AddToBalance(string userId, int amount) { int balance = GetBalance(userId) + amount; SetBalance(userId, balance); return balance; } // Seconds left on a cooldown (0 when ready). Times are saved as UTC and read // back as UTC; a plain DateTime.Parse turns them into local time, which made // cooldowns hours too long east of UTC and too short west of it. private double CooldownLeft(string userId, string key, TimeSpan length) { string last = CPH.GetTwitchUserVarById(userId, key, true); if (string.IsNullOrEmpty(last)) return 0; DateTime when; if (!DateTime.TryParse(last, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out when)) return 0; double left = (when.ToUniversalTime() + length - DateTime.UtcNow).TotalSeconds; return left > 0 ? left : 0; } private void StartCooldown(string userId, string key) { CPH.SetTwitchUserVarById(userId, key, DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture), true); } private static string FormatWait(double seconds) { TimeSpan t = TimeSpan.FromSeconds(Math.Ceiling(seconds)); if (t.TotalHours >= 1) return $"{(int)t.TotalHours}h {t.Minutes}m"; if (t.TotalMinutes >= 1) return $"{t.Minutes}m {t.Seconds}s"; return $"{t.Seconds}s"; } // $1,500 on every PC (the PC's own culture would write $1.500 in some countries). private static string Money(int amount) { return "$" + amount.ToString("N0", CultureInfo.InvariantCulture); } private string Arg(string name) { string value; return CPH.TryGetArg(name, out value) && value != null ? value.Trim() : ""; } // A bet from chat: a number, or "all" (as much as you have, up to the max bet). private bool ReadBet(string text, int balance, int min, int max, out int bet) { bet = 0; if (string.IsNullOrEmpty(text)) return false; text = text.Trim().TrimStart('$').Replace(",", ""); if (text.Equals("all", StringComparison.OrdinalIgnoreCase) || text.Equals("max", StringComparison.OrdinalIgnoreCase)) { bet = Math.Min(balance, max); return true; } return int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out bet); } // Everything a single-player bet game checks before playing: the bet, the // cooldown and the balance. On success the bet has been taken. private bool TakeBet(string command, string prefix, string betText, int minBet, int maxBet, int cooldownSeconds, string usage, string user, string userId, out int bet) { bet = 0; double wait = CooldownLeft(userId, prefix + "_last_played", TimeSpan.FromSeconds(cooldownSeconds)); if (wait > 0) { CPH.SendMessage($"{user}, {command} cooldown! Wait {FormatWait(wait)} before playing again."); return false; } int balance = GetBalance(userId); if (!ReadBet(betText, balance, minBet, maxBet, out bet)) { CPH.SendMessage($"{user}, usage: {usage} (bet {minBet}-{maxBet} or \"all\")"); return false; } if (bet < minBet || bet > maxBet) { CPH.SendMessage($"{user}, bet must be between {Money(minBet)} and {Money(maxBet)} {currencyName}!"); return false; } if (balance < bet) { LogWarning($"{command} Insufficient Funds", $"**User:** {user}\n**Bet:** {Money(bet)}\n**Balance:** {Money(balance)}"); CPH.SendMessage($"{user}, you only have {Money(balance)} {currencyName}! You need {Money(bet)}."); return false; } SetBalance(userId, balance - bet); StartCooldown(userId, prefix + "_last_played"); return true; } // ═══════════════════════════════════════════════════════════ // DISCORD LOGGING METHODS // ═══════════════════════════════════════════════════════════ private const int COLOR_INFO = 3447003; // Blue private const int COLOR_SUCCESS = 5763719; // Green private const int COLOR_WARNING = 16705372; // Orange private const int COLOR_ERROR = 15548997; // Red private const int COLOR_COMMAND = 10181046; // Purple private void LogInfo(string title, string message) { SendToDiscord(title, message, COLOR_INFO, "INFO"); } private void LogSuccess(string title, string message) { SendToDiscord(title, message, COLOR_SUCCESS, "SUCCESS"); } private void LogWarning(string title, string message) { SendToDiscord(title, message, COLOR_WARNING, "WARNING"); } private void LogError(string title, string message) { SendToDiscord(title, message, COLOR_ERROR, "ERROR"); } private void LogCommand(string commandName, string user, string details = "") { string message = $"**User:** {user}"; if (!string.IsNullOrEmpty(details)) message += $"\n**Details:** {details}"; SendToDiscord($"Command: {commandName}", message, COLOR_COMMAND, "COMMAND"); } private void SendToDiscord(string title, string description, int color, string footer) { try { bool loggingEnabled = CPH.GetGlobalVar("discordLoggingEnabled", true); if (!loggingEnabled) return; string webhookUrl = CPH.GetGlobalVar("discordLogWebhook", true); if (string.IsNullOrEmpty(webhookUrl)) { CPH.LogWarn("Discord webhook not configured. Run ConfigSetup.cs first."); return; } StringBuilder json = new StringBuilder(); json.Append("{\"embeds\":[{"); json.Append($"\"title\":\"{EscapeJson(title)}\","); json.Append($"\"description\":\"{EscapeJson(description)}\","); json.Append($"\"color\":{color},"); json.Append($"\"timestamp\":\"{DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture)}\","); json.Append($"\"footer\":{{\"text\":\"{EscapeJson(footer)} | HexEchoTV Logging System\"}}"); json.Append("}]}"); using (WebClient client = new WebClient()) { client.Encoding = Encoding.UTF8; client.Headers.Add("Content-Type", "application/json"); client.UploadString(webhookUrl, "POST", json.ToString()); } } catch (Exception ex) { CPH.LogError($"DiscordLogger error: {ex.Message}"); } } private string EscapeJson(string str) { if (string.IsNullOrEmpty(str)) return ""; return str.Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\n", "\\n").Replace("\r", "\\r").Replace("\t", "\\t"); } }