public void OnPresenceUpdated(DiscordPresence presence) { foreach (var e in status) { e.OnPresenceUpdated(presence); } }
static void Main(string[] args) { Console.WriteLine("Hello from C#!", Console.LogLevel.Info); Console.WriteLine(string.Format("args = [{0}]", string.Join(",", args)), Console.LogLevel.Info); Console.AddCommand("test", TestCommand); Console.Execute("print t"); Events.Add <Input.KeyEvent>(KeyCallback); Events.Add <TestEvent>(TestEventCallback); DiscordEventHandler discordEventHandler = new DiscordEventHandler(); DiscordRPC.Init("424302031822520320", ref discordEventHandler, true, "480"); DiscordPresence presence = new DiscordPresence(); presence.details = "Jazz weeb"; presence.state = ":3c:"; presence.largeImageKey = "icon-large"; presence.smallImageKey = "icon-small"; DiscordRPC.UpdatePresence(ref presence); SteamworksClient = new Client(480); }
protected override string FormatState(PlayerInfoResponse playerInfo, DiscordPresence presence) { bool hasActivePlanet = !string.IsNullOrWhiteSpace(playerInfo.ActivePlanet); bool hasActiveZone = !string.IsNullOrWhiteSpace(playerInfo.ActiveZonePosition); bool hasActiveBossZone = !string.IsNullOrWhiteSpace(playerInfo.ActiveBossGame); var state = "Inactive"; if (hasActivePlanet && (hasActiveZone || hasActiveBossZone)) { state = $"Planet {playerInfo.ActivePlanet} - "; if (hasActiveBossZone) { state += $"Boss Zone"; } else if (hasActiveZone) { state += $"Zone {playerInfo.ActiveZonePosition}"; } var planet = SaliensApi.GetPlanet(playerInfo.ActivePlanet); if (hasActiveZone && int.TryParse(playerInfo.ActiveZonePosition, out int zonePos)) { var zone = planet.Zones[zonePos]; if (zone != null) { state += $" ({zone.RealDifficulty.ToString().Substring(0, 1)})"; } } } else if (hasActivePlanet && !hasActiveZone) { state = $"Planet {playerInfo.ActivePlanet}"; } return(state); }
public static bool HasMinimumStatus(DiscordPresence MemberPresence, UserStatus MinimumStatus) { UserStatus MemberStatus = UserStatus.Offline; if (MemberPresence != null) // Apparently offline means null presence instead of offline presence { MemberStatus = MemberPresence.Status; } switch (MinimumStatus) { case UserStatus.Offline: return(true); case UserStatus.Online: return(MemberStatus == UserStatus.Online); case UserStatus.Idle: case UserStatus.DoNotDisturb: return(MemberStatus == UserStatus.Idle || MemberStatus == UserStatus.Online || MemberStatus == UserStatus.DoNotDisturb); case UserStatus.Invisible: return(MemberStatus != UserStatus.Offline); default: return(false); } }
protected override string FormatDetails(PlayerInfoResponse playerInfo, DiscordPresence presence) { var details = $"Level {playerInfo.Level}"; if (long.TryParse(playerInfo.Score, out long xp)) { details += $" - {xp.ToString("#,##0", CultureInfo.InvariantCulture)} XP"; } return(details); }
static void Main(string[] args) { FFProcess process = new FFProcess(FFProcess.DX11_DEFAULT_NAME, true); DiscordPresence presence = new DiscordPresence(DISCORD_CLIENT_ID); bool shutdown = false; new Thread(x => { while (!shutdown) { if (Console.ReadKey(true).Key == ConsoleKey.Escape) { shutdown = true; Console.WriteLine("Stopping application..."); } } }).Start(); Console.WriteLine("Press ESC to stop"); do { while (Scanner.Instance.IsScanning) { Thread.Sleep(1000); Console.WriteLine("Scanning..."); } CurrentPlayer currentPlayer = Reader.GetCurrentPlayer().CurrentPlayer; ActorItem player = null /*ActorItem.CurrentUser*/; if (player == null) { ActorResult aResult = Reader.GetActors(); KeyValuePair <uint, ActorItem> playerKeyValue = aResult.CurrentPCs.ToList().Find(x => x.Value.Name == currentPlayer.Name); ActorItem playerItem = playerKeyValue.Value; player = playerItem; } if (player != null) { presence.playerName = player.Name; presence.lvl = player.Level.ToString(); presence.job = player.Job.ToString(); uint mapID = player.MapTerritory; MapItem zone = ZoneLookup.GetZoneInfo(mapID); presence.place = zone.Name.English; presence.UpdatePresence(); } Thread.Sleep(5000); } while (!shutdown); presence.Deinitialize(); }
public void UpdateFields(DiscordPresence presence) { this.presence = presence; inputState.text = presence.state; inputDetails.text = presence.details; inputLargeTooltip.text = presence.largeAsset.tooltip; inputLargeKey.text = presence.largeAsset.image; inputSmallTooltip.text = presence.smallAsset.tooltip; inputSmallKey.text = presence.smallAsset.image; }
/// <summary> /// Sets the Rich Presence of the Discord Client through a HTTP connection. This differs from <see cref="SetPresence(DiscordPresence)"/> as it does not attempt to connect to the websocket and is a write-only operation with no state validation. /// </summary> /// <param name="applicationID">The ID of this application</param> /// <param name="presence">The presence to set the client</param> /// <returns></returns> public static IEnumerator SendPresence(string applicationID, DiscordPresence presence) { var requestPayload = DiscordRPC.Web.WebRPC.PrepareRequest(presence.ToRichPresence(), applicationID); byte[] encodedRequest = System.Text.Encoding.UTF8.GetBytes(requestPayload.Data); WWW www = new WWW(requestPayload.URL, encodedRequest, requestPayload.Headers); yield return(www); /* * RichPresence p; * string response = System.Text.Encoding.UTF8.GetString(www.bytes); * DiscordRPC.Web.WebRPC.TryParseResponse(response, out p); */ }
/// <summary> /// Sets the Discord Rich Presence /// </summary> /// <param name="presence">The Rich Presence to be shown to the client</param> public void SetPresence(DiscordPresence presence) { if (client == null) { Debug.LogError("[DRP] Attempted to send a presence update but no client exists!"); return; } if (!client.IsInitialized) { Debug.LogError("[DRP] Attempted to send a presence update to a client that is not initialized!"); return; } //Set the presence client.SetPresence(presence != null ? presence.ToRichPresence() : null); }
protected override Assets GetAssets(PlayerInfoResponse playerInfoResponse, DiscordPresence presence) { string smallImageKey = null; string smallImageText = null; switch (playerInfoResponse.Level) { case var level when level > 0 && level < 6: smallImageKey = "badge1"; smallImageText = "Rank 1"; break; case var level when level >= 6 && level < 9: smallImageKey = "badge2"; smallImageText = "Rank 2"; break; case var level when level >= 9 && level < 11: smallImageKey = "badge3"; smallImageText = "Rank 3"; break; case var level when level >= 11 && level < 16: smallImageKey = "badge4"; smallImageText = "Rank 4"; break; case var level when level >= 16 && level < 21: smallImageKey = "badge5"; smallImageText = "Rank 5"; break; case var level when level >= 21: smallImageKey = "badge6"; smallImageText = "Rank 6"; break; } return(new Assets { SmallImageKey = smallImageKey, SmallImageText = smallImageText, LargeImageKey = !string.IsNullOrWhiteSpace(playerInfoResponse.ActiveBossGame) ? "logo_boss" : "logo_large", LargeImageText = "Steam Summer Saliens" }); }
public virtual RichPresence FormatPresence(PlayerInfoResponse playerInfo, DiscordPresence presence) { if (playerInfo == null) { throw new ArgumentNullException(nameof(playerInfo)); } if (presence == null) { throw new ArgumentNullException(nameof(presence)); } return(new RichPresence { Details = this.FormatDetails(playerInfo, presence), State = this.FormatState(playerInfo, presence), Timestamps = this.FormatTimestamps(playerInfo, presence), Assets = this.GetAssets(playerInfo, presence) }); }
public static void GameStateMessage(string csgoDataJson) { Console.WriteLine(csgoDataJson); var csgoData = new JavaScriptSerializer().Deserialize <dynamic>(csgoDataJson); string steamId = csgoData["provider"]["steamid"]; if (!rpcInitialized) { rpcInitialized = true; var eventHandler = new DiscordEventHandler(); DiscordRPC.Init(discordAppId, ref eventHandler, true, steamId); startAt = (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds; DiscordAssets.Init(discordAppId); } DiscordPresence presence = FormatPresence(csgoData); DiscordRPC.UpdatePresence(ref presence); }
/// <summary> /// Sets the Rich Presence of the Discord Client through the pipe connection. /// <para>This will log a error if the client is null or not yet initiated.</para> /// </summary> /// <param name="presence">The Rich Presence to be shown to the client</param> public void SetPresence(DiscordPresence presence) { if (client == null) { Debug.LogError("[DRP] Attempted to send a presence update but no client exists!"); return; } if (!client.IsInitialized) { //Debug.LogWarning("[DRP] Attempted to send a presence update to a client that is not initialized! The messages will be enqueued instead!"); } //Just do some validation if (!presence.secrets.IsEmpty() && _currentSubscription == DiscordEvent.None) { Debug.LogWarning("[DRP] Sending a secret, however we are not actually subscribed to any events. This will cause the messages to be ignored!"); } //Set the presence _currentPresence = presence; client.SetPresence(presence != null ? presence.ToRichPresence() : null); }
protected abstract Timestamps FormatTimestamps(PlayerInfoResponse playerInfo, DiscordPresence presence);
protected abstract string FormatState(PlayerInfoResponse playerInfo, DiscordPresence presence);
/// <summary> /// Initializes the discord client if able to. Wont initialize if <see cref="active"/> is false, we are not in playmode, we already have a instance or we already have a client. /// <para>This function is empty unless UNITY_WSA || UNITY_WSA_10_0 || UNITY_STANDALONE) && !DISABLE_DISCORD is meet.</para> /// </summary> public void Initialize() { #if (UNITY_WSA || UNITY_WSA_10_0 || UNITY_STANDALONE) && !DISABLE_DISCORD if (!active) { return; //Are we allowed to be active? } if (!Application.isPlaying) { return; //We are not allowed to initialize while in the editor. } //This has a instance already that isn't us if (_instance != null && _instance != this) { Debug.LogWarning("[DAPI] Multiple DiscordManagers exist already. Destroying self.", _instance); Destroy(this); return; } //Make sure the client doesnt already exit if (_client != null) { Debug.LogError("[DAPI] Cannot initialize a new client when one is already initialized."); return; } //Assign the instance _instance = this; DontDestroyOnLoad(this); //Prepare the logger DiscordRPC.Logging.ILogger logger = null; //Update the logger to the unity logger if (Debug.isDebugBuild) { logger = new DiscordRPC.Logging.FileLogger("discordrpc.log") { Level = logLevel } } ; if (Application.isEditor) { logger = new DiscordRPC.Unity.UnityLogger() { Level = logLevel } } ; //We are starting the client. Below is a break down of the parameters. Debug.Log("[DRP] Starting Discord Rich Presence"); _client = new DiscordRPC.DiscordRpcClient( applicationID, //The Discord Application ID pipe: (int)targetPipe, //The target pipe to connect too logger: logger, //The logger, autoEvents: false, //WE will manually invoke events client: new DiscordRPC.Unity.UnityNamedPipe() //The client for the pipe to use. Unity MUST use a NativeNamedPipeClient since its managed client is broken. ); if (registerUriScheme) { client.RegisterUriScheme(steamID); } //Subscribe to some initial events #region Event Registration client.OnError += (s, args) => Debug.LogError("[DRP] Error Occured within the Discord IPC: (" + args.Code + ") " + args.Message); client.OnJoinRequested += (s, args) => Debug.Log("[DRP] Join Requested"); client.OnReady += (s, args) => { //We have connected to the Discord IPC. We should send our rich presence just incase it lost it. Debug.Log("[DRP] Connection established and received READY from Discord IPC. Sending our previous Rich Presence and Subscription."); //Set the user and cache their avatars _currentUser = args.User; _currentUser.GetAvatar(this, DiscordAvatarSize.x128); }; client.OnPresenceUpdate += (s, args) => { Debug.Log("[DRP] Our Rich Presence has been updated. Applied changes to local store."); Debug.Log(args.Presence.State); _currentPresence = (DiscordPresence)args.Presence; }; client.OnSubscribe += (s, a) => { Debug.Log("[DRP] New Subscription. Updating local store."); _currentSubscription = client.Subscription.ToUnity(); }; client.OnUnsubscribe += (s, a) => { Debug.Log("[DRP] Removed Subscription. Updating local store."); _currentSubscription = client.Subscription.ToUnity(); }; //Register the unity events events.RegisterEvents(client); #endregion //Set initial presence and sub. (This will enqueue it) SetSubscription(_currentSubscription); SetPresence(_currentPresence); //Start the client _client.Initialize(); Debug.Log("[DRP] Discord Rich Presence intialized and connecting..."); #endif }
private static DiscordPresence FormatPresence(dynamic csgoData) { DiscordPresence presence = new DiscordPresence { startTimestamp = startAt }; string map = ""; string tScore = "0"; string ctScore = "0"; if (!csgoData.ContainsKey("player") || !csgoData["player"].ContainsKey("activity")) { presence.state = "?"; presence.largeImageKey = "menu"; } else { string activity = csgoData["player"]["activity"]; presence.state = activity; presence.largeImageKey = "menu"; if (csgoData.ContainsKey("map")) { if (csgoData["map"].ContainsKey("mode")) { presence.smallImageKey = DiscordAssets.AssetForGameString(csgoData["map"]["mode"]); string mode = csgoData["map"]["mode"]; presence.smallImageText = "Mode: " + csgoData["map"]["mode"]; presence.state = mode + " - " + activity; } if (csgoData["map"].ContainsKey("name")) { presence.largeImageKey = DiscordAssets.AssetForGameString(csgoData["map"]["name"]); map = csgoData["map"]["name"]; presence.largeImageText = "Map: " + map; } if (csgoData["map"].ContainsKey("phase")) { if ("warmup" == csgoData["map"]["phase"]) { presence.details = "Warmup"; } else { if (csgoData.ContainsKey("player") && csgoData["player"].ContainsKey("team")) { if (csgoData["map"].ContainsKey("team_t") && csgoData["map"]["team_t"].ContainsKey("score")) { tScore = csgoData["map"]["team_t"]["score"].ToString(); } if (csgoData["map"].ContainsKey("team_ct") && csgoData["map"]["team_ct"].ContainsKey("score")) { ctScore = csgoData["map"]["team_ct"]["score"].ToString(); } if (tScore == "0" && ctScore == "0") { if (!matchStarted) { matchStarted = true; matchStartAt = (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds; } } else { matchStarted = false; } string teamName = csgoData["player"]["team"]; string displayScore; if ("T" == csgoData["player"]["team"]) { displayScore = "[ " + tScore + " : " + ctScore + " ]"; } else if ("CT" == csgoData["player"]["team"]) { displayScore = "[ " + ctScore + " : " + tScore + " ]"; } else { displayScore = "[ T:" + tScore + " , CT:" + ctScore + " ]"; } presence.details = displayScore + " " + map + " (" + teamName + ")"; presence.startTimestamp = matchStartAt != 0 ? matchStartAt : startAt; } else { presence.details = map; } } } } else if ("menu" == csgoData["player"]["activity"]) { presence.state = "In Main Menu"; presence.largeImageKey = "menu"; presence.largeImageText = "Main Menu"; if (csgoData.ContainsKey("player") && csgoData["player"].ContainsKey("name")) { //presence.details = Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(csgoData["player"]["name"])); } } } return(presence); }
protected override Timestamps FormatTimestamps(PlayerInfoResponse playerInfo, DiscordPresence presence) { return(null); }
internal PresenceUpdatedEventArgs(DiscordPresence presence) { Presence = presence; }
protected override Timestamps FormatTimestamps(PlayerInfoResponse playerInfo, DiscordPresence presence) { bool hasActivePlanet = !string.IsNullOrWhiteSpace(playerInfo.ActivePlanet); bool hasActiveZone = !string.IsNullOrWhiteSpace(playerInfo.ActiveZonePosition); bool hasActiveBossZone = !string.IsNullOrWhiteSpace(playerInfo.ActiveBossGame); Timestamps timestamps = null; if (!hasActiveBossZone) { if (hasActivePlanet && hasActiveZone && long.TryParse(playerInfo.Score, out long xp) && long.TryParse(playerInfo.NextLevelScore, out long nextLevelXp)) { if (xp > this.LastXp) { if (this.LastXp > 0 && this.MeasureStartTime.Ticks > 0) { int diffXp = (int)(xp - this.LastXp); var diffTime = DateTime.Now - this.MeasureStartTime - playerInfo.TimeInZone; var eta = TimeSpan.FromSeconds(diffTime.TotalSeconds * ((double)(nextLevelXp - xp) / diffXp)); this.PredictedLevelUpDate = DateTime.Now + eta - playerInfo.TimeInZone; } this.MeasureStartTime = DateTime.Now - playerInfo.TimeInZone; } this.LastXp = xp; } else if (string.IsNullOrWhiteSpace(playerInfo.NextLevelScore)) { this.PredictedLevelUpDate = DateTime.Now; } // Only show when it's less than a day: Discord doesn't show days if (this.PredictedLevelUpDate > DateTime.Now && this.PredictedLevelUpDate < DateTime.Now.AddDays(1)) { timestamps = new Timestamps { End = this.PredictedLevelUpDate.ToUniversalTime() } } ; } // Fallbacks if (timestamps == null && hasActivePlanet && (hasActiveZone || hasActiveBossZone)) { timestamps = new Timestamps { Start = (DateTime.Now - playerInfo.TimeInZone).ToUniversalTime() } } ; if (timestamps == null && hasActivePlanet) { timestamps = new Timestamps { Start = (DateTime.Now - playerInfo.TimeOnPlanet).ToUniversalTime() } } ; if (hasActivePlanet && hasActiveZone) { this.MeasureStartTime = DateTime.Now - playerInfo.TimeInZone; } return(timestamps); } } }
private void OnEnable() { //Make sure we are allowed to be active. if (!active || !gameObject.activeSelf) { return; } if (!Application.isPlaying) { return; } //This has a instance already that isn't us if (_instance != null && _instance != this) { Destroy(this); return; } //Assign the instance _instance = this; DontDestroyOnLoad(this); //We are starting the client. Below is a break down of the parameters. Debug.Log("[DRP] Starting Discord Rich Presence"); _client = new DiscordRpcClient( applicationID, //The Discord Application ID steamID, //The Steam App. This can be null or empty string to disable steam intergration. registerUriScheme, //Should the client register a custom URI Scheme? This must be true for endpoints (int )targetPipe, //The target pipe to connect too new NativeNamedPipeClient() //The client for the pipe to use. Unity MUST use a NativeNamedPipeClient since its managed client is broken. ); //Update the logger to the unity logger _client.Logger = new UnityLogger() { Level = logLevel }; //Subscribe to some initial events #region Event Registration client.OnReady += (s, args) => { //We have connected to the Discord IPC. We should send our rich presence just incase it lost it. Debug.Log("[DRP] Connection established and received READY from Discord IPC. Sending our previous Rich Presence and Subscription."); //Set the user and cache their avatars _currentUser = args.User; _currentUser.GetAvatar(this, DiscordAvatarSize.x128); }; client.OnPresenceUpdate += (s, args) => { Debug.Log("[DRP] Our Rich Presence has been updated. Applied changes to local store."); _currentPresence = (DiscordPresence)args.Presence; }; client.OnSubscribe += (s, a) => { Debug.Log("[DRP] New Subscription. Updating local store."); _currentSubscription = client.Subscription.ToUnity(); }; client.OnUnsubscribe += (s, a) => { Debug.Log("[DRP] Removed Subscription. Updating local store."); _currentSubscription = client.Subscription.ToUnity(); }; client.OnError += (s, args) => { //Something bad happened while we tried to send a event. We will just log this for clarity. Debug.LogError("[DRP] Error Occured within the Discord IPC: (" + args.Code + ") " + args.Message); }; client.OnJoinRequested += (s, args) => { Debug.Log("[DRP] Join Requested"); }; events.RegisterEvents(client); #endregion //Start the client _client.Initialize(); Debug.Log("[DRP] Discord Rich Presence intialized and connecting..."); //Set initial presence and sub. (This will enqueue it) SetSubscription(_currentSubscription); SetPresence(_currentPresence); }
// discord status events public void OnPresenceUpdated(DiscordPresence presence) { }
protected abstract Assets GetAssets(PlayerInfoResponse playerInfoResponse, DiscordPresence presence);
private void ClientOnPresenceUpdate(object sender, PresenceMessage args) { //Our Rich Presence has updated, better update our reference Debug.Log("[DRP] Our Rich Presence has been updated. Applied changes to local store."); _currentPresence = (DiscordPresence)args.Presence; }
protected override Timestamps FormatTimestamps(PlayerInfoResponse playerInfo, DiscordPresence presence) { bool hasActivePlanet = !string.IsNullOrWhiteSpace(playerInfo.ActivePlanet); bool hasActiveBossZone = !string.IsNullOrWhiteSpace(playerInfo.ActiveBossGame); if (hasActivePlanet && hasActiveBossZone) { return(new Timestamps { Start = (DateTime.Now - playerInfo.TimeInZone).ToUniversalTime() }); } if (hasActivePlanet) { return(new Timestamps { Start = (DateTime.Now - playerInfo.TimeOnPlanet).ToUniversalTime() }); } return(null); }