private void Timer_Elapsed(object sender, ElapsedEventArgs e) { string songInfo = Tidal.GetCurrentlyPlaying(); // disconnect from discord if nothing is playing if (songInfo == null) { Discord.ClearPresence(); return; } var songTitleAndArtist = Tidal.ExtractSongAndArtist(songInfo); var presence = new RichPresence() { Details = songTitleAndArtist.Item1, State = songTitleAndArtist.Item2, Assets = new Assets { LargeImageKey = LARGEIMAGEKEY, LargeImageText = LARGEIMAGETEXT } }; Discord.SetPresence(presence); }
static void setCurrentRPCApp(dRPCApplication app, bool reInit = true) { pPrint($"[I] Setting RPresence to: '{app.sAppName}'...", ConsoleColor.DarkYellow); if (dRpcClient != null && dRpcClient.IsInitialized) { if (reInit) { pPrint("[I] Closing current RPC instance...", ConsoleColor.Yellow); dRpcClient.ClearPresence(); dRpcClient.Deinitialize(); pPrint("[I] Creating a new RPC instance...", ConsoleColor.Yellow); dRpcClient = new DiscordRpcClient(app.sAppId); dRpcClient.Logger = new ConsoleLoggerFormatted() { Level = lLogLevel }; dRpcClient.Initialize(); } RichPresence rp = new RichPresence(); Assets assets = new Assets(); assets.LargeImageKey = app.sLargeImgKey; assets.SmallImageKey = app.sSmallImgKey; assets.LargeImageText = app.sLargeImgText; assets.SmallImageText = app.sSmallImgText; rp.Assets = assets; rp.Details = app.sDetails; rp.State = app.sState; pPrint("[I] Updating Rich Presence...", ConsoleColor.Yellow); dRpcClient.SetPresence(rp); dRPCActiveApp = app; } }
public void Initialize() { if (isOffline) { return; } if (!CheckForLibraryVersion()) { Debugger.Error("Detected outdated DiscordRPC library. Skipping Rich Presence initialization."); return; } if (!InitializeDiscordClient()) { return; } InitializeJoinScheme(); client.Initialize(); if (!isVisible) { client.ClearPresence(); } }
private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { if (RpcClient != null && RpcClient.IsInitialized) { RpcClient.ClearPresence(); RpcClient.Dispose(); } }
public void CloseConnection() { if (Client != null) { Debugger.Discord("Closed connection"); Client.ClearPresence(); Client.Dispose(); } }
protected override void Dispose(bool disposing) { if (client.IsInitialized) { client.ClearPresence(); } client.Dispose(); base.Dispose(disposing); }
/// <summary> /// Listens on URI for State-Information and handles responses /// </summary> private void Listen() { try { while (true) { this.UpdateServiceStatus(ServiceState.SERVICE_RUNNING); HttpListener listener = new HttpListener(); listener.Prefixes.Add(this.uri + "/"); listener.Start(); HttpListenerContext context = listener.GetContext(); HttpListenerResponse response = context.Response; dynamic Json = JObject.Parse(this.GetRequestData(context.Request)); response.StatusCode = 200; Stream output = response.OutputStream; output.Write(new byte[1], 0, (new byte[1]).Length); listener.Stop(); this.UpdateDiscordPresence(Json); this.Listen(); } } catch (ThreadAbortException) { this.UpdateServiceStatus(ServiceState.SERVICE_STOPPED); discordClient.ClearPresence(); discordClient.Dispose(); } }
private void UpdateFromURL() { client.Invoke(); string url = CurrentURL(); if (url == null || url == "") { client.ClearPresence(); return; } if (url.Contains("game")) { DoGameUpdate(url); return; } if (url.Contains("assess")) { DoAssesUpdate(url); return; } if (url.Contains("essentials")) { DoEssentialsUpdates(url); return; } SetRP("Idle", "", "cd"); }
private void updateStatus() { if (status.Value is UserStatusOffline) { client.ClearPresence(); return; } if (status.Value is UserStatusOnline && activity.Value != null) { presence.State = activity.Value.Status; presence.Details = getDetails(activity.Value); } else { presence.State = "Idle"; presence.Details = string.Empty; } // update user information presence.Assets.LargeImageText = $"{user.Value.Username}" + (user.Value.Statistics?.Ranks.Global > 0 ? $" (rank #{user.Value.Statistics.Ranks.Global:N0})" : string.Empty); // update ruleset presence.Assets.SmallImageKey = ruleset.Value.ID <= 3 ? $"mode_{ruleset.Value.ID}" : "mode_custom"; presence.Assets.SmallImageText = ruleset.Value.Name; client.SetPresence(presence); }
/* Connection */ public void StartRPC() { if (isOffline) { return; } // Check if connection exists to avoid creating multiple connections Instance = new RichPresence(); Debugger.Discord(GStrings.GetLocalizationByXPath("/Console/String[@ID='MESSAGE_DISCORD_CONNECTED']")); Instance.Secrets = new Secrets(); Client = new DiscordRpcClient(APP_ID, autoEvents: true); Client.RegisterUriScheme("582010"); // Events Client.OnReady += Client_OnReady; Client.OnJoinRequested += Client_OnJoinRequested; Client.OnJoin += Client_OnJoin; Client.SetSubscription(EventType.JoinRequest | EventType.Join); Client.Initialize(); if (!UserSettings.PlayerConfig.RichPresence.Enabled && isVisible) { Client?.ClearPresence(); isVisible = false; } }
protected virtual void Dispose(bool disposing) { if (!disposed) { disposed = true; if (disposing) { if (WorkerTimer != null) { using (WorkerTimer) { WorkerTimer.Stop(); WorkerTimer.Close(); } } if (client != null) { using (client) { try { client.ClearPresence(); } catch (NullReferenceException) { } } } if (Game != null) { Game.Dispose(); } } } }
public static void ShutDown() { //temporarily shuts down the rich presence to set a new one up with a different ID client.ShutdownOnly = true; client.ClearPresence(); client.Dispose(); }
public void Close() { LoggingHandler.Log("Closing Discord integration"); client.ClearPresence(); client.Dispose(); }
public void UpdatePresence(MusicKitResponse newData) { // If music is paused, clear presence if (newData.State != null && newData.State != 2) { client.ClearPresence(); return; } // If song's metadata isn't null, update presence with it. Otherwise, just update the playing state. if (newData.Name != null && newData.ArtistName != null && newData.AlbumName != null) { data = newData; } else { data.State = newData.State; } // Update Rich Presence only if we have the song's metadata if (data.Name != null && data.ArtistName != null && data.AlbumName != null) { client.SetPresence(new RichPresence { Details = data.Name, State = $"{data.AlbumName} by {data.ArtistName}", Assets = new Assets { LargeImageKey = "applemusic_logo", LargeImageText = "Apple Music" } }); } }
private void updateStatus() { if (!client.IsInitialized) { return; } if (status.Value is UserStatusOffline || privacyMode.Value == DiscordRichPresenceMode.Off) { client.ClearPresence(); return; } if (status.Value is UserStatusOnline && activity.Value != null) { presence.State = truncate(activity.Value.Status); presence.Details = truncate(getDetails(activity.Value)); if (getBeatmap(activity.Value) is IBeatmapInfo beatmap && beatmap.OnlineID > 0) { presence.Buttons = new[] { new Button { Label = "View beatmap", Url = $@"{api.WebsiteRootUrl}/beatmapsets/{beatmap.BeatmapSet?.OnlineID}#{ruleset.Value.ShortName}/{beatmap.OnlineID}" } }; } else { presence.Buttons = null; } }
public void HandleSettings(object source, EventArgs e) { if (UserSettings.PlayerConfig.RichPresence.Enabled && !isVisible) { isVisible = true; } else if (!UserSettings.PlayerConfig.RichPresence.Enabled && isVisible) { try { Client.ClearPresence(); } catch { } isVisible = false; } }
static async void IssueMultipleSets() { // == Create the client var client = new DiscordRpcClient("424087019149328395", pipe: discordPipe) { Logger = new Logging.ConsoleLogger(logLevel, true) }; // == Subscribe to some events client.OnReady += (sender, msg) => { //Create some events so we know things are happening Console.WriteLine("Connected to discord with user {0}", msg.User.Username); }; client.OnPresenceUpdate += (sender, msg) => { //The presence has updated Console.WriteLine("Presence has been updated! "); }; // == Initialize client.Initialize(); int attempt = 0; while (true && !Console.KeyAvailable) { attempt++; Console.WriteLine("Setting: {0}", attempt); client.SetPresence(new DiscordRPC.RichPresence() { Details = "Test", State = attempt.ToString() + " attempt", Timestamps = Timestamps.Now, Assets = new Assets() { LargeImageKey = $"image_large_" + (attempt % 4), LargeImageText = "Fish Sticks", } }); await Task.Delay(15000); //Thread.Sleep(15000); client.ClearPresence(); await Task.Delay(1500); //Thread.Sleep(1500); } Console.WriteLine("EXITED"); // == At the very end we need to dispose of it Console.ReadKey(); client.Dispose(); }
public static void RemovePresence() { if (IsPrecenseSet) { m_client.ClearPresence(); IsPrecenseSet = false; } }
private static void DataListen() { while (true) { try { byte[] bytes = new byte[600]; int cnt = client.Receive(bytes); Console.WriteLine("'" + System.Text.Encoding.UTF8.GetString(bytes) + "' received..."); Title title = new Title(bytes); if (title.Magic == 0xCAFECAFE) { if (LastGame != title.TitleID) { time = Timestamps.Now; } if ((rpc != null && rpc.CurrentPresence == null) || LastGame != title.TitleID) { rpc.SetPresence(Utils.CreateDiscordPresence(title, time)); LastGame = title.TitleID; } } else { if (rpc != null && !rpc.IsDisposed) { rpc.ClearPresence(); } client.Close(); return; } } catch (SocketException) { if (rpc != null && !rpc.IsDisposed) { rpc.ClearPresence(); } client.Close(); return; } } }
private void useRpc_CheckedChanged(object sender, EventArgs e) { rpcTimer.Enabled = useRpc.Enabled; if (!useRpc.Checked) { rpc.ClearPresence(); } }
private void ClearPresence() { try { discordRpcClient.ClearPresence(); } catch (Exception) { } }
private void button_Click(object sender, EventArgs e) { var client = new DiscordRpcClient(clientId.Text); Timestamps timestamp; client.Initialize(); if (button.Text == "Start RP") { timestamp = timestampBox.Checked ? Timestamps.Now : null; client.SetPresence(new RichPresence() { Details = detailsBox.Text, Timestamps = timestamp, State = stateBox.Text, Assets = new Assets() { //small image SmallImageKey = smallImageKey.Text, SmallImageText = smallImageText.Text, //large image LargeImageKey = largeImageKey.Text, LargeImageText = largeImageText.Text } }); button.Enabled = false; client.OnReady += (senderOnready, eOnready) => { labelUsername.Text = $"{client.CurrentUser.Username}#{client.CurrentUser.Discriminator}"; var request = WebRequest.Create($"https://cdn.discordapp.com/avatars/{client.CurrentUser.ID}/{client.CurrentUser.Avatar}.png?width=70&height=70"); using (var response = request.GetResponse()) using (var stream = response.GetResponseStream()) { pictureBox1.Image = Bitmap.FromStream(stream); } label6.Text = "Online"; button.Text = "Stop RP"; button.BackColor = Color.Crimson; button.Enabled = true; button1.Enabled = true; }; } else if (button.Text == "Stop RP") { button.Enabled = false; client.ClearPresence(); label6.Text = "Offline"; button.Text = "Start RP"; button.BackColor = Color.GreenYellow; button.Enabled = true; } }
public void QueryQuest() { Console.WriteLine("Querying Quest for presence . . ."); while (true) { int timeBefore = DateTime.UtcNow.Millisecond; client.Invoke(); // Dispatch events ClientStatus oldRequestStatus = LastRequestStatus; Status fetchedStatus; try { fetchedStatus = GetStatus(); if (fetchedStatus.elapsed && !wasElapsed) { elapsedStartTime = DateTime.UtcNow; Console.WriteLine("Started counting elapsed time"); wasElapsed = true; } else if (!fetchedStatus.elapsed && wasElapsed) { Console.WriteLine("Stopped counting elapsed time"); wasElapsed = false; } // Set the received presence client.SetPresence(fetchedStatus.ConvertToDiscord(elapsedStartTime)); Console.WriteLine("Successfully fetched presence"); LastRequestStatus = ClientStatus.RequestSucceeded; } catch (Exception ex) { Console.Error.WriteLine("Exception occured while fetching the presence from the Quest (is your IP address correct and Beat Saber open?): " + ex.Message); // Disable the precence, since we aren't connected/Beat Saber is closed. Console.WriteLine("Disabling presense due to failed connection."); client.ClearPresence(); LastRequestStatus = ClientStatus.RequestFailed; wasElapsed = false; } // Invoke the StatusChanged event if we couldn't get the presence last time but could this time, or vice-versa if (oldRequestStatus != LastRequestStatus && LastRequestStatusChanged != null) { LastRequestStatusChanged.Invoke(this, new StatusChangedEventArgs() { OldStatus = oldRequestStatus, NewStatus = LastRequestStatus }); } // Sleep for the remaining time int timeElapsed = DateTime.UtcNow.Millisecond - timeBefore; Thread.Sleep(Math.Max(app.Config.UpdateInterval - timeElapsed, 0)); // Make sure we don't sleep for a negative amount of time! } }
public static void RemovePresence() { if (IsPrecenseSet) { m_client.ClearPresence(); IsPrecenseSet = false; ShownServer = null; } }
public static void PresenceDelete() { if (client == null || client.CurrentPresence == null) { return; } client.ClearPresence(); client.Dispose(); }
private void buttonRemovePresence_Click(object sender, EventArgs e) { if (client == null || !client.IsInitialized) { return; } client.ClearPresence(); }
private static void DataListen() { while (true) { try { byte[] bytes = new byte[600]; int cnt = client.Receive(bytes); Title title = new Title(bytes); if (title.Magic == 0xffaadd23) { if (LastGame != title.Name) { time = Timestamps.Now; } if ((rpc != null && rpc.CurrentPresence == null) || LastGame != title.Name) { rpc.SetPresence(Utils.CreateDiscordPresence(title, time)); LastGame = title.Name; } } else { if (rpc != null && !rpc.IsDisposed) { rpc.ClearPresence(); } client.Close(); return; } } catch (SocketException) { if (rpc != null && !rpc.IsDisposed) { rpc.ClearPresence(); } client.Close(); return; } } }
/// <summary> /// Turn the rich pressence off. /// </summary> public void TurnOff() { //Remove all presences from queue, and clear it. rpc.DequeueAll(); rpc.ClearPresence(); rpc.Dispose(); //Mark as not running. IsRunning = false; }
static void InitWmp() { try { loopTimer = new System.Timers.Timer(); loopTimer.Interval = 1000; loopTimer.Elapsed += async(o, e) => { loopTimer.Stop(); if (form != null) { Console.WriteLine("Windows Media Player Plugin checking media state..."); MediaItem mediaDetail = await GetMediaDetail(); if (mediaDetail != null && currentTrack?.TrackName != mediaDetail?.TrackName) { currentTrack = mediaDetail; Console.WriteLine("Raising Track Change Method."); if (isPlaying) { DoPresenceChange(mediaDetail); } } if (currentTrack != null) { form.albumName = currentTrack.AlbumName; form.artistName = currentTrack.ArtistName; form.trackName = currentTrack.TrackName; form.endTime = (int)currentTrack.TrackLength; form.currTime = playerPosition; } if (!isPlaying) { client.ClearPresence(); } if (currentTrack != null) { Console.WriteLine($"Player position {playerPosition} of {currentTrack.TrackLength}."); } //Console.WriteLine("Windows Media Plugin checking media state complete."); } loopTimer.Start(); }; loopTimer.Start(); } catch (Exception) { loopTimer.Start(); } }
/// <summary> /// Turn the rich presence off. /// </summary> public RichPresenceClient TurnOff() { api.Logger.Log("Terminating rich presence."); //Remove all presences from queue, and clear it. rpc.DequeueAll(); rpc.ClearPresence(); rpc.Dispose(); //Mark as not running. IsRunning = false; return(this); }