// 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 !trivia. // Leave the action out of any blocking queue: it waits for the time limit, and a // blocking queue would hold the answer until after that. // // USAGE: // !trivia get a question (A-D) // !trivia [a-d] answer it within config_trivia_time_limit_seconds (default 20) // A right answer earns config_trivia_min_reward to _max_reward. Questions come from // config_trivia_sheet_url (one per line: Question?|A) ..|B) ..|C) ..|D) ..|Letter); // a few built-in questions are used if the sheet can't be reached. 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("Trivia command: missing 'user' or 'userId' argument"); return false; } int minReward = Cfg("config_trivia_min_reward", 30); int maxReward = Cfg("config_trivia_max_reward", 80); int cooldownMinutes = Cfg("config_trivia_cooldown_minutes", 15); int timeLimit = Cfg("config_trivia_time_limit_seconds", 20); string input = Arg("input0").ToLowerInvariant().TrimEnd(')'); // An answer to this viewer's open question. if (input == "a" || input == "b" || input == "c" || input == "d") { Question open; lock (OpenLock) { if (!Open.TryGetValue(userId, out open) || DateTime.UtcNow > open.Deadline) { Open.Remove(userId); open = null; } else Open.Remove(userId); } if (open == null) { CPH.SendMessage($"{user}, you don't have a question right now. Type !trivia to get one!"); return false; } string right = open.Options[open.Correct]; if (input[0] - 'a' == open.Correct) { int reward = Roll(minReward, Math.Max(minReward, maxReward)); int balance = AddToBalance(userId, reward); LogSuccess("Trivia Correct", $"**User:** {user}\n**Question:** {open.Text}\n**Reward:** {Money(reward)}"); CPH.SendMessage($"📚 CORRECT, {user}! {right} +{Money(reward)} | Balance: {Money(balance)}"); } else { LogInfo("Trivia Wrong", $"**User:** {user}\n**Question:** {open.Text}\n**Answered:** {input.ToUpperInvariant()}"); CPH.SendMessage($"📚 Not quite, {user}! The answer was {right}"); } return true; } lock (OpenLock) { Question pending; if (Open.TryGetValue(userId, out pending) && DateTime.UtcNow <= pending.Deadline) { CPH.SendMessage($"{user}, answer your question first: !trivia a, b, c or d"); return false; } } double wait = CooldownLeft(userId, "trivia_cooldown", TimeSpan.FromMinutes(cooldownMinutes)); if (wait > 0) { CPH.SendMessage($"{user}, next trivia question in {FormatWait(wait)}!"); return false; } List pool = LoadQuestions(); Question q = pool[Roll(pool.Count)]; Question mine = new Question { Text = q.Text, Options = q.Options, Correct = q.Correct, Deadline = DateTime.UtcNow.AddSeconds(timeLimit) }; lock (OpenLock) Open[userId] = mine; StartCooldown(userId, "trivia_cooldown"); LogCommand("!trivia", user, $"Question: {q.Text}"); CPH.SendMessage($"📚 TRIVIA for {user} | {q.Text} | {string.Join(" ", q.Options)} | Type !trivia [letter] ({timeLimit}s)"); // Say the answer if time runs out unanswered. CPH.Wait(timeLimit * 1000 + 500); bool unanswered; lock (OpenLock) { Question still; unanswered = Open.TryGetValue(userId, out still) && ReferenceEquals(still, mine); if (unanswered) Open.Remove(userId); } if (unanswered) CPH.SendMessage($"⏰ Time's up, {user}! The answer was {mine.Options[mine.Correct]}"); return true; } catch (Exception ex) { LogError("Trivia Command Exception", $"**Error:** {ex.Message}\n**Stack Trace:** {ex.StackTrace}"); CPH.SendMessage("⚠️ An error occurred during trivia"); CPH.LogError($"Trivia error: {ex.Message}"); return false; } } private class Question { public string Text; public string[] Options; public int Correct; public DateTime Deadline; } // Open questions by viewer. Static so an answer (a separate run of this action) // sees the question the earlier run asked. private static readonly Dictionary Open = new Dictionary(); private static readonly object OpenLock = new object(); private static List cached; private static DateTime cachedAt = DateTime.MinValue; private List LoadQuestions() { lock (OpenLock) { if (cached != null && cached.Count > 0 && DateTime.UtcNow - cachedAt < TimeSpan.FromHours(1)) return cached; } List found = new List(); string url = CPH.GetGlobalVar("config_trivia_sheet_url", true); if (!string.IsNullOrEmpty(url)) { try { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.Timeout = 8000; using (WebResponse res = req.GetResponse()) using (System.IO.StreamReader reader = new System.IO.StreamReader(res.GetResponseStream(), Encoding.UTF8)) { string line; while ((line = reader.ReadLine()) != null) { Question q = ParseLine(line); if (q != null) found.Add(q); } } } catch (Exception ex) { CPH.LogWarn($"Trivia: could not load the question sheet ({ex.Message}); using built-in questions."); } } if (found.Count == 0) { foreach (string line in BuiltIn) { Question q = ParseLine(line); if (q != null) found.Add(q); } } lock (OpenLock) { cached = found; cachedAt = DateTime.UtcNow; } return found; } // One question per line: Question?|A) ..|B) ..|C) ..|D) ..|Letter. A sheet's CSV // export wraps a cell in quotes when it holds a comma, with "" for a quote. private static Question ParseLine(string line) { if (line == null) return null; line = line.Trim(); if (line.Length > 1 && line[0] == '"' && line[line.Length - 1] == '"') line = line.Substring(1, line.Length - 2).Replace("\"\"", "\""); if (line.Length == 0 || line.StartsWith("#")) return null; string[] parts = line.Split('|'); if (parts.Length != 6) return null; string letter = parts[5].Trim().ToUpperInvariant(); if (letter.Length != 1 || letter[0] < 'A' || letter[0] > 'D') return null; return new Question { Text = parts[0].Trim(), Options = new[] { parts[1].Trim(), parts[2].Trim(), parts[3].Trim(), parts[4].Trim() }, Correct = letter[0] - 'A' }; } private static readonly string[] BuiltIn = { "Which is the largest planet in our solar system?|A) Earth|B) Jupiter|C) Saturn|D) Mars|B", "How many sides does a hexagon have?|A) 5|B) 6|C) 7|D) 8|B", "Which is the largest ocean on Earth?|A) Atlantic|B) Indian|C) Arctic|D) Pacific|D", "What is frozen water called?|A) Steam|B) Ice|C) Fog|D) Dew|B", "How many minutes are in an hour?|A) 30|B) 50|C) 60|D) 100|C", }; // ═══════════════════════════════════════════════════════════ // 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"); } }