// ===== FOLLOWAGE COMMAND ===== // Copyright (c) 2025 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: None // // Shows how long a user has been following the channel // Usage: !followage or !followage @username // Displays follow date and duration using System; using System.IO; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Collections.Generic; public class CPHInline { public bool Execute() { try { CPH.TryGetArg("user", out string user); if (string.IsNullOrEmpty(user)) user = "Unknown"; if (!CPH.TryGetArg("userId", out string userId) || string.IsNullOrEmpty(userId)) { CPH.SendMessage("⚠️ Error: Could not get user ID from command"); CPH.LogError("FollowageCommand: Missing 'userId' argument"); return false; } // Resolve broadcaster ID - args first, then fall back to the connected broadcaster account string broadcasterId = null; if (CPH.TryGetArg("broadcastUserId", out string bid1) && !string.IsNullOrEmpty(bid1)) broadcasterId = bid1; else if (CPH.TryGetArg("broadcasterUserId", out string bid2) && !string.IsNullOrEmpty(bid2)) broadcasterId = bid2; else { // CUB Studio doesn't expose TwitchGetBroadcaster, so resolve via the Twitch API instead broadcasterId = GetBroadcasterIdFromToken(); } if (string.IsNullOrEmpty(broadcasterId)) { CPH.SendMessage("⚠️ Error: Could not get broadcaster ID"); CPH.LogError("FollowageCommand: broadcaster ID unavailable from args or TwitchGetBroadcaster"); return false; } // Log command execution LogCommand("!followage", user); // Resolve the optional target argument. CUB Studio may split args across input0..N // (with input0 holding the command itself) OR pass everything in rawInput, so gather // from whichever is populated, then drop a leading "!command" token. string targetUsername = ResolveTargetArg(); // Leaderboard mode: triggered by "!followage-lb" (its own command) or "!followage lb" // (also leaderboard / top). Shows the top 5 longest-standing followers. string sub = targetUsername.TrimStart('-').ToLower(); bool wantsLeaderboard = sub == "lb" || sub == "leaderboard" || sub == "top" || sub == "top5" || CommandLine().Contains("-lb"); if (wantsLeaderboard) { return ShowLeaderboard(user, broadcasterId); } // Check if checking another user's followage string targetUser = user; string targetUserId = userId; // Parse target user from command arguments (empty target = check the caller's own followage) if (!string.IsNullOrEmpty(targetUsername) && targetUsername.ToLower() != user.ToLower()) { targetUser = targetUsername; // Get target user info var userInfo = CPH.TwitchGetExtendedUserInfoByLogin(targetUser); if (userInfo == null) { CPH.SendMessage($"⚠️ Could not find user: {targetUser}"); return false; } targetUserId = userInfo.UserId; } // Check if user is trying to check their own followage as the broadcaster if (targetUserId == broadcasterId) { CPH.SendMessage($"{targetUser}, you're the broadcaster! You can't follow yourself. 😄"); return true; } // Get follow information using Twitch API DateTime? followDate = GetFollowDate(targetUserId, broadcasterId); if (!followDate.HasValue) { // Check if it failed due to missing credentials string accessToken = CPH.GetGlobalVar("twitchApiAccessToken"); if (string.IsNullOrEmpty(accessToken)) { CPH.SendMessage("⚠️ Followage command not configured. Please configure Twitch API in ConfigSetup.cs"); return false; } if (targetUser.ToLower() == user.ToLower()) { CPH.SendMessage($"{user}, you are not following the channel yet! Hit that follow button! 💜"); } else { CPH.SendMessage($"{targetUser} is not following the channel."); } return true; } // Calculate follow duration DateTime now = DateTime.UtcNow; TimeSpan followDuration = now - followDate.Value; // Calculate years, months, days int years = (int)(followDuration.TotalDays / 365); int months = (int)((followDuration.TotalDays % 365) / 30); int days = (int)((followDuration.TotalDays % 365) % 30); int hours = followDuration.Hours; // Build duration string string durationText = ""; if (years > 0) durationText += $"{years} year{(years != 1 ? "s" : "")} "; if (months > 0) durationText += $"{months} month{(months != 1 ? "s" : "")} "; if (days > 0) durationText += $"{days} day{(days != 1 ? "s" : "")} "; if (years == 0 && months == 0 && hours > 0) durationText += $"{hours} hour{(hours != 1 ? "s" : "")} "; durationText = durationText.Trim(); if (string.IsNullOrEmpty(durationText)) { durationText = "less than an hour"; } // Send message if (targetUser.ToLower() == user.ToLower()) { CPH.SendMessage($"{user}, you have been following for {durationText}! 💜"); } else { CPH.SendMessage($"{targetUser} has been following for {durationText}!"); } return true; } catch (Exception ex) { CPH.SendMessage($"⚠️ Followage command error: {ex.Message}"); CPH.LogError($"Followage command error: {ex.Message}"); CPH.LogError($"Stack trace: {ex.StackTrace}"); LogError("Followage Command Error", $"Error: {ex.Message}"); return false; } } // Returns the full triggered command line (command + args), lowercased, from whatever // CUB Studio populated. Used to detect the "-lb" leaderboard trigger. private string CommandLine() { string combined = ""; if (CPH.TryGetArg("rawInput", out string raw) && !string.IsNullOrEmpty(raw)) combined = raw; if (string.IsNullOrEmpty(combined) || combined.IndexOf(' ') < 0) { string rebuilt = ""; for (int i = 0; i < 10; i++) if (CPH.TryGetArg("input" + i, out string p) && !string.IsNullOrEmpty(p)) rebuilt += (rebuilt.Length > 0 ? " " : "") + p; if (!string.IsNullOrEmpty(rebuilt)) combined = rebuilt; } // Prepend the matched command name if available (rawInput may omit it) if (CPH.TryGetArg("command", out string cmd) && !string.IsNullOrEmpty(cmd)) combined = cmd + " " + combined; return (combined ?? "").ToLower(); } // Pages through every follower, sorts oldest-first, and posts the top 5 with durations. private bool ShowLeaderboard(string user, string broadcasterId) { try { string accessToken = CPH.GetGlobalVar("twitchApiAccessToken"); string clientId = CPH.GetGlobalVar("twitchApiClientId"); if (string.IsNullOrEmpty(accessToken) || string.IsNullOrEmpty(clientId)) { CPH.SendMessage("⚠️ Followage leaderboard not configured. Set twitchApiAccessToken and twitchApiClientId."); return false; } var followers = new List>(); string cursor = ""; int pages = 0; do { string url = $"https://api.twitch.tv/helix/channels/followers?broadcaster_id={broadcasterId}&first=100"; if (!string.IsNullOrEmpty(cursor)) url += "&after=" + cursor; string response; using (var client = new System.Net.WebClient()) { client.Headers.Add("Authorization", $"Bearer {accessToken}"); client.Headers.Add("Client-Id", clientId); response = client.DownloadString(url); } foreach (Match m in Regex.Matches(response, "\"user_name\":\"((?:[^\"\\\\]|\\\\.)*)\",\"followed_at\":\"([^\"]+)\"")) { DateTime date; if (DateTime.TryParse(m.Groups[2].Value, out date)) followers.Add(new KeyValuePair(date.ToUniversalTime(), Unescape(m.Groups[1].Value))); } var cm = Regex.Match(response, "\"cursor\":\"([^\"]+)\""); cursor = cm.Success ? cm.Groups[1].Value : ""; pages++; } while (!string.IsNullOrEmpty(cursor) && pages < 200); if (followers.Count == 0) { CPH.SendMessage("No followers found yet!"); return true; } followers.Sort((a, b) => a.Key.CompareTo(b.Key)); // oldest first DateTime now = DateTime.UtcNow; int count = Math.Min(5, followers.Count); var sb = new StringBuilder("🏆 Longest followers: "); for (int i = 0; i < count; i++) { sb.Append($"{i + 1}. {followers[i].Value} ({FormatDuration(now - followers[i].Key)})"); if (i < count - 1) sb.Append(" | "); } string message = sb.ToString(); if (message.Length > 480) message = message.Substring(0, 477) + "..."; CPH.SendMessage(message); LogSuccess("Followage Leaderboard", $"**By:** {user}\n**Followers scanned:** {followers.Count}"); return true; } catch (WebException webEx) { CPH.LogError($"Followage-LB WebException: {webEx.Message}"); if (webEx.Message.Contains("401")) CPH.SendMessage("💡 401: Token invalid/expired. Regenerate with 'moderator:read:followers' scope."); else if (webEx.Message.Contains("403")) CPH.SendMessage("💡 403: Token missing 'moderator:read:followers' scope. Regenerate it."); else CPH.SendMessage($"⚠️ Followage leaderboard API error: {webEx.Message}"); return false; } catch (Exception ex) { CPH.SendMessage($"⚠️ Followage leaderboard error: {ex.Message}"); CPH.LogError($"Followage-LB error: {ex.Message}"); return false; } } // Compact duration for the leaderboard line, e.g. "3y 2mo", "5mo", "12d", "4h" private string FormatDuration(TimeSpan d) { int years = (int)(d.TotalDays / 365); int months = (int)((d.TotalDays % 365) / 30); if (years > 0) return months > 0 ? $"{years}y {months}mo" : $"{years}y"; if (months > 0) return $"{months}mo"; int days = (int)d.TotalDays; if (days > 0) return $"{days}d"; return $"{Math.Max(1, (int)d.TotalHours)}h"; } private string Unescape(string s) { if (string.IsNullOrEmpty(s)) return ""; return s.Replace("\\\"", "\"").Replace("\\\\", "\\").Replace("\\/", "/"); } // Returns the target username the caller typed after the command, or "" for none. // Handles every CUB Studio arg layout: rawInput with/without the command, or the // args split across input0..input9 (where input0 is often the command itself). private string ResolveTargetArg() { string combined = ""; if (CPH.TryGetArg("rawInput", out string raw) && !string.IsNullOrEmpty(raw)) combined = raw; // If rawInput is empty or only holds a single token (e.g. just the command), // rebuild the full line from input0..input9. if (string.IsNullOrEmpty(combined) || combined.IndexOf(' ') < 0) { string rebuilt = ""; for (int i = 0; i < 10; i++) if (CPH.TryGetArg("input" + i, out string p) && !string.IsNullOrEmpty(p)) rebuilt += (rebuilt.Length > 0 ? " " : "") + p; if (!string.IsNullOrEmpty(rebuilt)) combined = rebuilt; } combined = (combined ?? "").Trim(); // Drop a leading "!command" token if present if (combined.StartsWith("!")) { int cmdSpace = combined.IndexOf(' '); combined = cmdSpace > 0 ? combined.Substring(cmdSpace + 1).Trim() : ""; } if (string.IsNullOrEmpty(combined)) return ""; // First remaining token, minus the @ string target = combined.Replace("@", "").Trim(); int sp = target.IndexOf(' '); if (sp > 0) target = target.Substring(0, sp); return target; } // Resolves the broadcaster's user ID by querying /helix/users with no login param, // which returns the account that owns the access token (i.e. the broadcaster). private string GetBroadcasterIdFromToken() { try { string accessToken = CPH.GetGlobalVar("twitchApiAccessToken"); string clientId = CPH.GetGlobalVar("twitchApiClientId"); if (string.IsNullOrEmpty(accessToken) || string.IsNullOrEmpty(clientId)) { CPH.LogWarn("FollowageCommand: twitchApiAccessToken or twitchApiClientId not set."); return null; } using (System.Net.WebClient client = new System.Net.WebClient()) { client.Headers.Add("Authorization", $"Bearer {accessToken}"); client.Headers.Add("Client-Id", clientId); string response = client.DownloadString("https://api.twitch.tv/helix/users"); int idStart = response.IndexOf("\"id\":\"") + 6; int idEnd = response.IndexOf("\"", idStart); if (idStart > 5 && idEnd > idStart) return response.Substring(idStart, idEnd - idStart); } } catch (Exception ex) { CPH.LogWarn($"FollowageCommand: GetBroadcasterIdFromToken failed - {ex.Message}"); } return null; } private DateTime? GetFollowDate(string userId, string broadcasterId) { try { // Get credentials from global variables (same as clip command) string accessToken = CPH.GetGlobalVar("twitchApiAccessToken"); string clientId = CPH.GetGlobalVar("twitchApiClientId"); // If not configured, try to get follow info without API if (string.IsNullOrEmpty(accessToken) || string.IsNullOrEmpty(clientId)) { CPH.LogWarn("Twitch API credentials not configured. Followage command requires ConfigSetup.cs to be configured."); return null; } using (System.Net.WebClient client = new System.Net.WebClient()) { client.Headers.Add("Authorization", $"Bearer {accessToken}"); client.Headers.Add("Client-Id", clientId); string url = $"https://api.twitch.tv/helix/channels/followers?broadcaster_id={broadcasterId}&user_id={userId}"; string response = client.DownloadString(url); CPH.LogInfo($"Followage API Response: {response.Substring(0, Math.Min(200, response.Length))}"); // Check if user is following if (response.Contains("\"total\":0") || response.Contains("\"data\":[]")) { return null; // Not following } // Parse followed_at date int dateStart = response.IndexOf("\"followed_at\":\"") + 15; int dateEnd = response.IndexOf("\"", dateStart); if (dateStart > 14 && dateEnd > dateStart) { string dateString = response.Substring(dateStart, dateEnd - dateStart); DateTime followDate = DateTime.Parse(dateString).ToUniversalTime(); CPH.LogInfo($"Follow date parsed: {followDate}"); return followDate; } else { CPH.LogError("Failed to parse follow date from response"); } } } catch (WebException webEx) { CPH.LogError($"GetFollowDate WebException: {webEx.Message}"); CPH.SendMessage($"⚠️ Followage API error: {webEx.Message}"); LogError("Followage API Error", $"WebException: {webEx.Message}"); if (webEx.Response != null) { using (var reader = new StreamReader(webEx.Response.GetResponseStream())) { string errorResponse = reader.ReadToEnd(); CPH.LogError($"API Error Response: {errorResponse}"); // Check for specific errors if (errorResponse.Contains("401") || webEx.Message.Contains("401")) { CPH.SendMessage("💡 401 Error: Token invalid/expired. Get new token from twitchtokengenerator.com with 'moderator:read:followers' scope"); } else if (errorResponse.Contains("403") || webEx.Message.Contains("403")) { CPH.SendMessage("💡 403 Error: Missing 'moderator:read:followers' scope. Regenerate token with this scope!"); } } } } catch (Exception ex) { CPH.LogError($"GetFollowDate error: {ex.Message}"); CPH.SendMessage($"⚠️ Followage error: {ex.Message}"); LogError("Followage Error", $"GetFollowDate error: {ex.Message}"); } return null; } // ═══════════════════════════════════════════════════════════ // 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 { // Check if logging is enabled (global toggle) bool loggingEnabled = CPH.GetGlobalVar("discordLoggingEnabled", true); if (!loggingEnabled) { return; // Logging is disabled } // Get webhook URL from global variable (set in ConfigSetup.cs) string webhookUrl = CPH.GetGlobalVar("discordLogWebhook", true); if (string.IsNullOrEmpty(webhookUrl)) { CPH.LogWarn("Discord webhook not configured. Run ConfigSetup.cs first."); return; } // Escape special characters for JSON title = EscapeJson(title); description = EscapeJson(description); footer = EscapeJson(footer); // Get current timestamp in ISO format string timestamp = DateTime.UtcNow.ToString("o"); // Build Discord embed JSON manually (no JSON library in StreamerBot) StringBuilder json = new StringBuilder(); json.Append("{"); json.Append("\"embeds\":[{"); json.Append($"\"title\":\"{title}\","); json.Append($"\"description\":\"{description}\","); json.Append($"\"color\":{color},"); json.Append($"\"timestamp\":\"{timestamp}\","); json.Append("\"footer\":{"); json.Append($"\"text\":\"{footer} | HexEchoTV Logging System\""); json.Append("}"); json.Append("}]"); json.Append("}"); // Send to Discord webhook using (System.Net.WebClient client = new System.Net.WebClient()) { 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"); } }