/* 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; } }
public static void Initalize(MainWindow window) { if (initialised && window.ClientIDTextBox.Text != "") { ShutDown(); } client = new DiscordRpcClient(window.ClientIDTextBox.Text); client.OnError += (sender, e) => { MessageBox.Show("Error"); }; client.OnReady += (sender, e) => { }; client.OnConnectionFailed += (sender, e) => { MessageBox.Show("Connection Failed"); }; client.OnPresenceUpdate += (sender, e) => { MessageBox.Show("Updated Presence"); }; client.Initialize(); client.RegisterUriScheme(); ChangePresence(window); client.Invoke(); initialised = true; }
private void UpdatePresence(DateTime Timestamp, string details = "", string state = "", string LargeImg = "", string LargeImgText = "", string SmallImg = "", string SmallImgText = "", string Party = "", string Spectate = "", string AskToJoin = "") { client.RegisterUriScheme(null, PartyID); client.RegisterUriScheme(null, SpectateCode); client.RegisterUriScheme(null, AskToJoinCode); presence = new RichPresence() { Assets = new Assets() { LargeImageKey = LargeImg, LargeImageText = LargeImgText, SmallImageKey = SmallImg, SmallImageText = SmallImgText }, Details = details, State = state, Party = new Party() { ID = Party, Size = Int32.ParseOrDefault(partySize.Text), Max = Int32.ParseOrDefault(partySizeMax.Text) }, Secrets = new Secrets() { JoinSecret = AskToJoin, SpectateSecret = Spectate } }; if (DateTime.UtcNow.Subtract(TimeStamp).TotalSeconds > 0) { presence.Timestamps = new Timestamps() { Start = Timestamp }; } else { presence.Timestamps = new Timestamps() { End = Timestamp }; } }
static void Main(string[] args) { client = new DiscordRpcClient("711984686108508171"); client.OnReady += (sender, e) => { Console.WriteLine("Received Ready from user {0}", e.User.Username); }; client.OnPresenceUpdate += (sender, e) => { Console.WriteLine("Received Update! {0}", e.Presence); }; client.Initialize(); Secrets secrets = new Secrets() { JoinSecret = "MTI4NzM0OjFpMmhuZToxMjMxMjM= ", SpectateSecret = "MTIzNDV8MTIzNDV8MTMyNDU0" }; Party party = new Party() { ID = Secrets.CreateFriendlySecret(new Random()), //ID = "ae488379-351d-4a4f-ad32-2b9b01c91657", Size = 1, Max = 64 }; //Give the game some time so we have a nice countdown Timestamps timestamps = new Timestamps() { Start = DateTime.UtcNow }; client.RegisterUriScheme("711984686108508171"); client.SetSubscription(EventType.Join | EventType.Spectate | EventType.JoinRequest); client.SetPresence(new RichPresence() { Details = "sadRP", State = "sadRP", Assets = new Assets() { LargeImageKey = "sadRP", LargeImageText = "Galaksinin En Kötüsü", SmallImageKey = "küçük resim id", SmallImageText = "küçük resim mesajı" }, Secrets = secrets, Party = party, Timestamps = timestamps }); Console.ReadKey(); }
static async void IssueJoinLogic() { // == Create the client var random = new Random(); var client = new DiscordRpcClient("424087019149328395", pipe: 0) { Logger = new Logging.ConsoleLogger(Logging.LogLevel.Info, true) }; // == Subscribe to some events client.OnReady += (sender, msg) => { Console.WriteLine("Connected to discord with user {0}", msg.User.Username); }; client.OnPresenceUpdate += (sender, msg) => { Console.WriteLine("Presence has been updated! "); }; //Setup the join event client.Subscribe(EventType.Join | EventType.JoinRequest); client.RegisterUriScheme(); //= Request Event client.OnJoinRequested += (sender, msg) => { Console.WriteLine("Someone wants to join us: {0}", msg.User.Username); }; //= Join Event client.OnJoin += (sender, msg) => { Console.WriteLine("Joining this dude: {0}", msg.Secret); }; // == Initialize client.Initialize(); //Set the presence client.SetPresence(new RichPresence() { State = "Potato Pitata", Details = "Testing Join Feature", Party = new Party() { ID = Secrets.CreateFriendlySecret(random), Size = 1, Max = 4, Privacy = Party.PrivacySetting.Public }, Secrets = new Secrets() { JoinSecret = Secrets.CreateFriendlySecret(random), } }); // == At the very end we need to dispose of it Console.ReadKey(); client.Dispose(); }
public void Awake() { Logger.LogInfo("Starting Discord Rich Presence..."); UnityNamedPipe pipe = new UnityNamedPipe(); //Get your own clientid! client = new DiscordRpcClient("597759084187484160", -1, null, true, pipe); client.RegisterUriScheme("632360"); client.Initialize(); currentPrivacyLevel = PrivacyLevel.Join; //Subscribe to join events client.Subscribe(DiscordRPC.EventType.Join); client.Subscribe(DiscordRPC.EventType.JoinRequest); //Setup Discord client hooks client.OnReady += Client_OnReady; client.OnError += Client_OnError; client.OnJoinRequested += Client_OnJoinRequested; client.OnJoin += Client_OnJoin; //When a new stage is entered, update stats On.RoR2.Run.BeginStage += Run_BeginStage; //Used to handle additional potential presence changes SceneManager.activeSceneChanged += SceneManager_activeSceneChanged; //Handle Presence when Lobby is created On.RoR2.SteamworksLobbyManager.OnLobbyCreated += SteamworksLobbyManager_OnLobbyCreated; //Handle Presence when Lobby is joined On.RoR2.SteamworksLobbyManager.OnLobbyJoined += SteamworksLobbyManager_OnLobbyJoined; //Handle Presence when Lobby changes On.RoR2.SteamworksLobbyManager.OnLobbyChanged += SteamworksLobbyManager_OnLobbyChanged; //Handle Presence when user leaves Lobby On.RoR2.SteamworksLobbyManager.LeaveLobby += SteamworksLobbyManager_LeaveLobby; On.RoR2.CharacterBody.Awake += CharacterBody_Awake; //Messy work around for hiding timer in Discord when user pauses the game during a run RoR2Application.onPauseStartGlobal += OnGamePaused; //When the user un-pauses, re-broadcast run time to Discord RoR2Application.onPauseEndGlobal += OnGameUnPaused; //Register console commands On.RoR2.Console.Awake += (orig, self) => { CommandHelper.RegisterCommands(self); orig(self); }; }
/* 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(); try { Client = new DiscordRpcClient(AppId, autoEvents: true); } catch (Exception err) { Debugger.Error($"Failed to create Rich Presence connection:\n{err}"); return; } try { Client.RegisterUriScheme("582010"); } catch (Exception err) { Debugger.Error(err); FailedToRegisterScheme = true; } if (!FailedToRegisterScheme) { // Events Client.OnReady += Client_OnReady; Client.OnJoinRequested += Client_OnJoinRequested; Client.OnJoin += Client_OnJoin; Client.SetSubscription(EventType.JoinRequest | EventType.Join); } Client.Initialize(); if (!ConfigManager.Settings.RichPresence.Enabled && isVisible) { Client?.ClearPresence(); isVisible = false; } }
internal static void SetupRpc() { client = new DiscordRpcClient("652538071530864653"); client.Initialize(); Secrets secrets = new Secrets() { JoinSecret = "MTI4NzM0OjFpMmhuZToxMjMxMjM", SpectateSecret = "MTIzNDV8MTIzNDV8MTMyNDU0" }; Party party = new Party() { ID = Secrets.CreateFriendlySecret(new Random()), Size = 1, Max = 64 }; //Give the game some time so we have a nice countdown Timestamps timestamps = new Timestamps() { Start = DateTime.UtcNow }; client.RegisterUriScheme("652538071530864653"); client.SetSubscription(EventType.Join | EventType.Spectate | EventType.JoinRequest); client.SetPresence(new RichPresence() { Details = "Sunucuya Bağlanıyor.", State = "Launcher Giriş Ekranında...", Assets = new Assets() { LargeImageKey = "fadesx", LargeImageText = "khchosting.com", SmallImageKey = "tikfade", SmallImageText = "discord.gg/adonisrp" }, Secrets = secrets, Party = party, Timestamps = timestamps }); }
public static void Init() { client.RegisterUriScheme(); var logFile = Path.Combine(AppDataDir, "discord-rpc.log"); //MessageBox.Show(logFile); //Set the logger. This way we can see the output of the client. //We can set it this way, but doing it directly in the constructor allows for the Register Uri Scheme to be logged too. System.IO.File.WriteAllBytes(logFile, new byte[0]); client.Logger = new FileLogger(logFile, DiscordLogLevel); //Register to the events we care about. We are registering to everyone just to show off the events client.OnReady += OnReady; //Called when the client is ready to send presences client.OnClose += OnClose; //Called when connection to discord is lost client.OnError += OnError; //Called when discord has a error client.OnConnectionEstablished += OnConnectionEstablished; //Called when a pipe connection is made, but not ready client.OnConnectionFailed += OnConnectionFailed; //Called when a pipe connection failed. client.OnPresenceUpdate += OnPresenceUpdate; //Called when the presence is updated client.OnSubscribe += OnSubscribe; //Called when a event is subscribed too client.OnUnsubscribe += OnUnsubscribe; //Called when a event is unsubscribed from. client.OnJoin += OnJoin; //Called when the client wishes to join someone else. Requires RegisterUriScheme to be called. client.OnSpectate += OnSpectate; //Called when the client wishes to spectate someone else. Requires RegisterUriScheme to be called. client.OnJoinRequested += OnJoinRequested; //Called when someone else has requested to join this client. presence.Secrets = new Secrets() { //These secrets should contain enough data for external clients to be able to know which // game to connect too. A simple approach would be just to use IP address, but this is highly discouraged // and can leave your players vulnerable! JoinSecret = "", SpectateSecret = "" }; client.SetPresence(presence); //Initialize the connection. This must be called ONLY once. //It must be called before any updates are sent or received from the discord client. client.Initialize(); isRunning = true; }
private void InitializeJoinScheme() { try { client.RegisterUriScheme("582010"); } catch (Exception err) { Debugger.Error(err); failedToRegisterScheme = true; } if (!failedToRegisterScheme) { client.OnReady += OnReady; client.OnJoinRequested += OnJoinRequested; client.OnJoin += OnJoin; client.SetSubscription(EventType.JoinRequest | EventType.Join); } }
protected override void ProcessRecord() { #region init client Client = new DiscordRpcClient(Statics.ApplicationId, autoEvents: true, //Should the events be automatically called? client: new DiscordRPC.IO.ManagedNamedPipeClient() //The pipe client to use. Required in mono to be changed.); ); Client.RegisterUriScheme(); //Subscribe to events Client.OnReady += (sender, e) => { WriteVerbose($"Received Ready from user {e.User.Username}"); }; Client.OnPresenceUpdate += (sender, e) => { WriteVerbose($"Received Update! {e.Presence}"); }; Client.Initialize(); Client.ClearPresence(); #endregion WriteObject(@"Connected!"); }
public void Initialize(ISharpControl control) { _controlPanel = new SettingsPanel(); _control = control; if (Utils.GetBooleanSetting("EnableRPC", true)) { if (Utils.GetStringSetting("ClientID").Replace(" ", "").Length != 18) { Utils.SaveSetting("ClientID", "765213507321856078"); } client = new DiscordRpcClient(Utils.GetStringSetting("ClientID"), pipe: discordPipe) { Logger = new ConsoleLogger(logLevel, true) }; client.RegisterUriScheme(); client.OnRpcMessage += Client_OnRpcMessage; client.OnPresenceUpdate += Client_OnPresenceUpdate; client.OnReady += OnReady; client.OnClose += OnClose; client.OnError += OnError; client.OnConnectionEstablished += OnConnectionEstablished; client.OnConnectionFailed += OnConnectionFailed; presence.Timestamps = new Timestamps { Start = DateTime.UtcNow }; client.SkipIdenticalPresence = true; client.SetPresence(presence); client.Initialize(); _ = MainLoop(); } else { _controlPanel.ChangeStatus = "RPC is disabled"; } LogWriter.WriteToFile("EOM Initialize"); }
public static void InitializeDiscord() { // Create a Discord client discordClient = new DiscordRpcClient(SecretKeys.discordRPCClientID); discordClient.RegisterUriScheme(); // Set the logger discordClient.Logger = new ConsoleLogger { Level = LogLevel.Warning }; // Subscribe to events discordClient.OnJoin += OnJoin; discordClient.OnSpectate += OnSpectate; discordClient.OnJoinRequested += OnJoinRequested; discordClient.SetSubscription(EventType.Join | EventType.Spectate | EventType.JoinRequest); lobbyEntryTime = DateTime.UtcNow; // Connect to the RPC discordClient.Initialize(); }
public void Initialize(ISharpControl control) { IConfigurationPanelProvider configurationPanelProvider; if (Utils.GetBooleanSetting("ShowWelcomePage", true)) { new WelcomeForm().ShowDialog(); } _controlPanel = new SettingsPanel(); windowMessages = new TopWindowMessages(); // TODO: do something when "EnableRPCInvite" is set to false _control = control; try { if (Utils.GetBooleanSetting("EnableRPCInvite", false)) { _control.RegisterFrontControl(windowMessages, PluginPosition.Top); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } if (Utils.GetBooleanSetting("EnableRPCInvite", false)) { presence.Secrets = new Secrets() { JoinSecret = "invalid_secret" }; presence.Party = new Party() { ID = Secrets.CreateFriendlySecret(new Random()), Size = 1, Max = 100 }; } if (Utils.GetBooleanSetting("EnableRPCInvite", false)) { windowMessages.Show(); } if (Utils.GetBooleanSetting("EnableRPC", true)) { if (RPCalreadyLoaded) { _controlPanel.ChangeStatus = "Restart required"; return; } if (Utils.GetStringSetting("ClientID").Replace(" ", "").Length != 18) { client = new DiscordRpcClient("765213507321856078", pipe: discordPipe) { Logger = new ConsoleLogger(logLevel, true) }; } else { client = new DiscordRpcClient(Utils.GetStringSetting("ClientID"), pipe: discordPipe) { Logger = new ConsoleLogger(logLevel, true) }; } client.RegisterUriScheme(); client.OnRpcMessage += Client_OnRpcMessage; client.OnPresenceUpdate += Client_OnPresenceUpdate; client.OnReady += OnReady; client.OnClose += OnClose; client.OnError += OnError; client.OnConnectionEstablished += OnConnectionEstablished; client.OnConnectionFailed += OnConnectionFailed; client.OnSubscribe += OnSubscribe; client.OnUnsubscribe += OnUnsubscribe; client.OnJoin += OnJoin; client.OnJoinRequested += OnJoinRequested; presence.Timestamps = new Timestamps() { Start = DateTime.UtcNow }; if (Utils.GetBooleanSetting("EnableRPCInvite", false)) { client.SetSubscription(EventType.Join | EventType.JoinRequest); } client.SetPresence(presence); client.Initialize(); try { configurationPanelProvider = (IConfigurationPanelProvider)_control.Source; controllerPanel = (SDRSharp.FrontEnds.SpyServer.ControllerPanel)configurationPanelProvider.Gui; } catch (Exception ex) { LogWriter.WriteToFile("----> " + ex); MessageBox.Show($"Cannot get Spy Server Network address\n\nError:\n{ex}", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); } _ = MainLoop(); } else { _controlPanel.ChangeStatus = "RPC is disabled"; } LogWriter.WriteToFile("EOM Initialize"); }
public override void Entry(IModHelper helper) { #if DEBUG Monitor.Log("THIS IS A DEBUG BUILD...", LogLevel.Alert); Monitor.Log("...FOR DEBUGGING...", LogLevel.Alert); Monitor.Log("...AND STUFF...", LogLevel.Alert); if (ModManifest.Version.IsPrerelease()) { Monitor.Log("oh wait this is a pre-release.", LogLevel.Info); Monitor.Log("carry on.", LogLevel.Info); } else { Monitor.Log("If you're Fayne, keep up the good work. :)", LogLevel.Alert); Monitor.Log("If you're not Fayne...", LogLevel.Alert); Monitor.Log("...please go yell at Fayne...", LogLevel.Alert); Monitor.Log("...because you shouldn't have this...", LogLevel.Alert); Monitor.Log("...it's for debugging. (:", LogLevel.Alert); } #else if (ModManifest.Version.IsPrerelease()) { Monitor.Log("WAIT A MINUTE.", LogLevel.Alert); Monitor.Log("FAYNE.", LogLevel.Alert); Monitor.Log("WHY DID YOU RELEASE A NON-DEBUG DEV BUILD?!", LogLevel.Alert); Monitor.Log("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", LogLevel.Alert); } #endif api = new RichPresenceAPI(this); client = new DiscordRpcClient(applicationId, logger: new RPLogger(Monitor, DiscordRPC.Logging.LogLevel.Warning), autoEvents: false, client: new DiscordRPC.IO.ManagedNamedPipeClient() ); client.OnReady += (sender, e) => { Monitor.Log("Connected to Discord: " + e.User, LogLevel.Info); }; client.OnClose += (sender, e) => { Monitor.Log("Lost connection: " + e.Reason, LogLevel.Warn); }; client.OnError += (sender, e) => { Monitor.Log("Discord error: " + e.Message, LogLevel.Error); }; client.OnJoin += (sender, e) => { Monitor.Log("Attempting to join game", LogLevel.Info); JoinGame(e.Secret); }; client.OnJoinRequested += (sender, e) => { Monitor.Log(e.User + " is requesting to join your game.", LogLevel.Alert); Monitor.Log("You can respond to this request in Discord Overlay.", LogLevel.Info); Game1.chatBox.addInfoMessage(e.User + " is requesting to join your game. You can respond to this request in Discord Overlay."); }; client.Initialize(); client.RegisterUriScheme(); client.Subscribe(EventType.Join); client.Subscribe(EventType.JoinRequest); Helper.ConsoleCommands.Add("DiscordRP_TestJoin", "Command for debugging.", (string command, string[] args) => { JoinGame(string.Join(" ", args)); } ); Helper.ConsoleCommands.Add("DiscordRP_Reload", "Reloads the config for Discord Rich Presence.", (string command, string[] args) => { LoadConfig(); Monitor.Log("Config reloaded.", LogLevel.Info); } ); Helper.ConsoleCommands.Add("DiscordRP_Format", "Formats and prints a provided configuration string.", (string command, string[] args) => { string text = api.FormatText(string.Join(" ", args)); Monitor.Log("Result: " + text, LogLevel.Info); } ); Helper.ConsoleCommands.Add("DiscordRP_Tags", "Lists tags usable for configuration strings.", (string command, string[] args) => { IDictionary <string, string> tags = string.Join("", args).ToLower().StartsWith("all") ? api.ListTags("[NULL]", "[ERROR]") : api.ListTags(removeNull: false); IDictionary <string, IDictionary <string, string> > groups = new Dictionary <string, IDictionary <string, string> >(); foreach (KeyValuePair <string, string> tag in tags) { string owner = api.GetTagOwner(tag.Key) ?? "Unknown-Mod"; if (!groups.ContainsKey(owner)) { groups[owner] = new Dictionary <string, string>(); } groups[owner][tag.Key] = tag.Value; } IList <string> output = new List <string>(tags.Count + groups.Count) { "Available Tags:" }; int longest = 0; foreach (KeyValuePair <string, string> tag in groups[ModManifest.UniqueID]) { if (tag.Value != null) { longest = Math.Max(longest, tag.Key.Length); } } int nulls = 0; foreach (KeyValuePair <string, string> tag in groups[ModManifest.UniqueID]) { if (tag.Value is null) { nulls++; } else { output.Add(" {{ " + tag.Key.PadLeft(longest) + " }}: " + tag.Value); } } foreach (KeyValuePair <string, IDictionary <string, string> > group in groups) { if (group.Key == this.ModManifest.UniqueID) { continue; } string head = group.Value.Count + " tag"; if (group.Value.Count != 1) { head += "s"; } head += " from " + (Helper.ModRegistry.Get(group.Key)?.Manifest.Name ?? "an unknown mod"); output.Add(head); longest = 0; foreach (KeyValuePair <string, string> tag in group.Value) { if (tag.Value != null) { longest = Math.Max(longest, tag.Key.Length); } } foreach (KeyValuePair <string, string> tag in group.Value) { if (tag.Value == null) { nulls++; } else { output.Add(" {{ " + tag.Key.PadLeft(longest) + " }}: " + tag.Value); } } } if (nulls > 0) { output.Add(nulls + " tag" + (nulls != 1 ? "s" : "") + " unavailable; type `DiscordRP_Tags all` to show all"); } Monitor.Log(string.Join(Environment.NewLine, output), LogLevel.Info); } ); LoadConfig(); Helper.Events.Input.ButtonReleased += HandleButton; Helper.Events.GameLoop.UpdateTicked += DoUpdate; Helper.Events.GameLoop.SaveLoaded += SetTimestamp; Helper.Events.GameLoop.ReturnedToTitle += SetTimestamp; Helper.Events.GameLoop.SaveLoaded += (object sender, SaveLoadedEventArgs e) => api.GamePresence = "Getting Started"; Helper.Events.GameLoop.SaveCreated += (object sender, SaveCreatedEventArgs e) => api.GamePresence = "Starting a New Game"; Helper.Events.GameLoop.GameLaunched += (object sender, GameLaunchedEventArgs e) => { SetTimestamp(); timestampSession = DateTime.UtcNow; }; ITagRegister tagReg = api.GetTagRegister(this); tagReg.SetTag("Activity", () => api.GamePresence); tagReg.SetTag("ModCount", () => Helper.ModRegistry.GetAll().Count()); tagReg.SetTag("SMAPIVersion", () => Constants.ApiVersion.ToString()); tagReg.SetTag("StardewVersion", () => Game1.version); tagReg.SetTag("Song", () => Utility.getSongTitleFromCueName(Game1.currentSong?.Name ?? api.None)); // All the tags below are only available while in-game. tagReg.SetTag("Name", () => Game1.player.Name, true); tagReg.SetTag("Farm", () => Game1.content.LoadString("Strings\\UI:Inventory_FarmName", api.GetTag("FarmName")), true); tagReg.SetTag("FarmName", () => Game1.player.farmName, true); tagReg.SetTag("PetName", () => Game1.player.hasPet() ? Game1.player.getPetDisplayName() : api.None, true); tagReg.SetTag("Location", () => Game1.currentLocation.Name, true); tagReg.SetTag("RomanticInterest", () => Utility.getTopRomanticInterest(Game1.player)?.getName() ?? api.None, true); tagReg.SetTag("PercentComplete", () => Utility.percentGameComplete(), true); tagReg.SetTag("Money", () => { // Copied from LoadGameMenu string text = Game1.content.LoadString("Strings\\StringsFromCSFiles:LoadGameMenu.cs.11020", Utility.getNumberWithCommas(Game1.player.Money)); if (Game1.player.Money == 1 && LocalizedContentManager.CurrentLanguageCode == LocalizedContentManager.LanguageCode.pt) { text = text.Substring(0, text.Length - 1); } return(text); }, true); tagReg.SetTag("MoneyNumber", () => Game1.player.Money, true); tagReg.SetTag("MoneyCommas", () => Utility.getNumberWithCommas(Game1.player.Money), true); tagReg.SetTag("Level", () => Game1.content.LoadString("Strings\\UI:Inventory_PortraitHover_Level", Game1.player.Level.ToString()), true); tagReg.SetTag("LevelNumber", () => Game1.player.Level, true); tagReg.SetTag("Title", () => Game1.player.getTitle(), true); tagReg.SetTag("TotalTime", () => Utility.getHoursMinutesStringFromMilliseconds(Game1.player.millisecondsPlayed), true); tagReg.SetTag("Health", () => Game1.player.health, true); tagReg.SetTag("HealthMax", () => Game1.player.maxHealth, true); tagReg.SetTag("HealthPercent", () => (double)Game1.player.health / Game1.player.maxHealth * 100, 2, true); tagReg.SetTag("Energy", () => Game1.player.Stamina.ToString(), true); tagReg.SetTag("EnergyMax", () => Game1.player.MaxStamina, true); tagReg.SetTag("EnergyPercent", () => (double)Game1.player.Stamina / Game1.player.MaxStamina * 100, 2, true); tagReg.SetTag("Time", () => Game1.getTimeOfDayString(Game1.timeOfDay), true); tagReg.SetTag("Date", () => Utility.getDateString(), true); tagReg.SetTag("Season", () => Utility.getSeasonNameFromNumber(Utility.getSeasonNumber(SDate.Now().Season)), true); tagReg.SetTag("DayOfWeek", () => Game1.shortDayDisplayNameFromDayOfSeason(SDate.Now().Day), true); tagReg.SetTag("Day", () => SDate.Now().Day, true); tagReg.SetTag("DayPad", () => $"{SDate.Now().Day:00}", true); tagReg.SetTag("DaySuffix", () => Utility.getNumberEnding(SDate.Now().Day), true); tagReg.SetTag("Year", () => SDate.Now().Year, true); tagReg.SetTag("YearSuffix", () => Utility.getNumberEnding(SDate.Now().Year), true); tagReg.SetTag("GameVerb", () => Context.IsMultiplayer && Context.IsMainPlayer ? "Hosting" : "Playing", true); tagReg.SetTag("GameNoun", () => Context.IsMultiplayer ? "Co-op" : "Solo", true); tagReg.SetTag("GameInfo", () => api.GetTag("GameVerb") + " " + api.GetTag("GameNoun"), true); }
static void FullClientExample() { //Create a new DiscordRpcClient. We are filling some of the defaults as examples. using (client = new DiscordRpcClient("424087019149328395", //The client ID of your Discord Application pipe: discordPipe, //The pipe number we can locate discord on. If -1, then we will scan. logger: new Logging.ConsoleLogger(logLevel, true), //The loger to get information back from the client. autoEvents: true, //Should the events be automatically called? client: new IO.ManagedNamedPipeClient() //The pipe client to use. Required in mono to be changed. )) { //If you are going to make use of the Join / Spectate buttons, you are required to register the URI Scheme with the client. client.RegisterUriScheme(); //Set the logger. This way we can see the output of the client. //We can set it this way, but doing it directly in the constructor allows for the Register Uri Scheme to be logged too. //System.IO.File.WriteAllBytes("discord-rpc.log", new byte[0]); //client.Logger = new Logging.FileLogger("discord-rpc.log", DiscordLogLevel); //Register to the events we care about. We are registering to everyone just to show off the events client.OnReady += OnReady; //Called when the client is ready to send presences client.OnClose += OnClose; //Called when connection to discord is lost client.OnError += OnError; //Called when discord has a error client.OnConnectionEstablished += OnConnectionEstablished; //Called when a pipe connection is made, but not ready client.OnConnectionFailed += OnConnectionFailed; //Called when a pipe connection failed. client.OnPresenceUpdate += OnPresenceUpdate; //Called when the presence is updated client.OnSubscribe += OnSubscribe; //Called when a event is subscribed too client.OnUnsubscribe += OnUnsubscribe; //Called when a event is unsubscribed from. client.OnJoin += OnJoin; //Called when the client wishes to join someone else. Requires RegisterUriScheme to be called. client.OnSpectate += OnSpectate; //Called when the client wishes to spectate someone else. Requires RegisterUriScheme to be called. client.OnJoinRequested += OnJoinRequested; //Called when someone else has requested to join this client. //Before we send a initial presence, we will generate a random "game ID" for this example. // For a real game, this "game ID" can be a unique ID that your Match Maker / Master Server generates. // This is used for the Join / Specate feature. This can be ignored if you do not plan to implement that feature. presence.Secrets = new Secrets() { //These secrets should contain enough data for external clients to be able to know which // game to connect too. A simple approach would be just to use IP address, but this is highly discouraged // and can leave your players vulnerable! JoinSecret = "join_myuniquegameid", SpectateSecret = "spectate_myuniquegameid" }; //We also need to generate a initial party. This is because Join requires the party to be created too. // If no party is set, the join feature will not work and may cause errors within the discord client itself. presence.Party = new Party() { ID = Secrets.CreateFriendlySecret(new Random()), Size = 1, Max = 4 }; //Give the game some time so we have a nice countdown presence.Timestamps = new Timestamps() { Start = DateTime.UtcNow, End = DateTime.UtcNow + TimeSpan.FromSeconds(15) }; //Subscribe to the join / spectate feature. //These require the RegisterURI to be true. client.SetSubscription(EventType.Join | EventType.Spectate | EventType.JoinRequest); //This will alert us if discord wants to join a game //Set some new presence to tell Discord we are in a game. // If the connection is not yet available, this will be queued until a Ready event is called, // then it will be sent. All messages are queued until Discord is ready to receive them. client.SetPresence(presence); //Initialize the connection. This must be called ONLY once. //It must be called before any updates are sent or received from the discord client. client.Initialize(); //Start our main loop. In a normal game you probably don't have to do this step. // Just make sure you call .Invoke() or some other dequeing event to receive your events. MainLoop(); } }
public override void Entry(IModHelper helper) { #if DEBUG Monitor.Log("THIS IS A DEBUG BUILD...", LogLevel.Alert); Monitor.Log("...FOR DEBUGGING...", LogLevel.Alert); Monitor.Log("...AND STUFF...", LogLevel.Alert); if (ModManifest.Version.IsPrerelease()) { Monitor.Log("oh wait this is a pre-release.", LogLevel.Info); Monitor.Log("carry on.", LogLevel.Info); } else { Monitor.Log("If you're Fayne, keep up the good work. :)", LogLevel.Alert); Monitor.Log("If you're not Fayne...", LogLevel.Alert); Monitor.Log("...please go yell at Fayne...", LogLevel.Alert); Monitor.Log("...because you shouldn't have this...", LogLevel.Alert); Monitor.Log("...it's for debugging. (:", LogLevel.Alert); } #else if (ModManifest.Version.IsPrerelease()) { Monitor.Log("WAIT A MINUTE.", LogLevel.Alert); Monitor.Log("FAYNE.", LogLevel.Alert); Monitor.Log("WHY DID YOU RELEASE A NON-DEBUG DEV BUILD?!", LogLevel.Alert); Monitor.Log("https://youtu.be/T3djXcx2ewQ", LogLevel.Alert); } #endif if (Constants.TargetPlatform == GamePlatform.Android) { Monitor.Log("Discord RPC is not supported on Android.", LogLevel.Error); Monitor.Log("Aborting mod initialization.", LogLevel.Error); Dispose(); return; } api = new RichPresenceAPI(this); client = new DiscordRpcClient(clientId, autoEvents: false, logger: new MonitorLogger(Monitor)); client.RegisterUriScheme(steamId); client.OnReady += (sender, e) => { Monitor.Log("Connected to Discord: " + e.User.ToString(), LogLevel.Info); }; client.OnJoin += (sender, args) => { Monitor.Log("Attempting to join game: " + args.Secret, LogLevel.Info); JoinGame(args.Secret); }; client.OnJoinRequested += (sender, msg) => { string name = msg.User.Username; string tag = msg.User.ToString(); ushort id = (ushort)rand.Next(ushort.MinValue, ushort.MaxValue); requests[id] = msg; lastRequestID = id; string hex = id.ToString("X"); Monitor.Log(tag + " wants to join your game via Discord.", LogLevel.Alert); Monitor.Log("To respond type \"discord " + hex + " yes/no\" or just \"discord yes/no\"", LogLevel.Info); Game1.chatBox.addMessage(name + " wants to join your game via Discord.\nTo respond check the console or use Discord or its overlay.", blurple); }; client.Initialize(); client.SetSubscription(EventType.Join | EventType.JoinRequest); #region Console Commands Helper.ConsoleCommands.Add("discord", "Respond to a Discord join request.", (command, args) => { // Yes, I know this code is a mess. switch (args[0].ToLower()) { case "yes": case "y": Respond(lastRequestID, true); break; case "no": case "n": Respond(lastRequestID, false); break; default: try { var id = ushort.Parse(args[0], System.Globalization.NumberStyles.HexNumber); switch (args[1].ToLower()) { case "yes": case "y": Respond(id, true); break; case "no": case "n": Respond(id, false); break; default: Monitor.Log("Invalid response.", LogLevel.Error); break; } } catch (Exception) { Monitor.Log("Invalid request ID.", LogLevel.Error); } break; } } ); Helper.ConsoleCommands.Add("DiscordRP_Join", "Join a co-op game via invite code.", (string command, string[] args) => { JoinGame(string.Join(" ", args)); } ); Helper.ConsoleCommands.Add("DiscordRP_Reload", "Reloads the config for Discord Rich Presence.", (string command, string[] args) => { LoadConfig(); Monitor.Log("Config reloaded.", LogLevel.Info); } ); Helper.ConsoleCommands.Add("DiscordRP_Format", "Formats and prints a provided configuration string.", (string command, string[] args) => { string text = api.FormatText(string.Join(" ", args)); Monitor.Log("Result: " + text, LogLevel.Info); } ); Helper.ConsoleCommands.Add("DiscordRP_Tags", "Lists tags usable for configuration strings.", (string command, string[] args) => { IDictionary <string, string> tags = string.Join("", args).ToLower().StartsWith("all") ? api.ListTags("[NULL]", "[ERROR]") : api.ListTags(removeNull: false); IDictionary <string, IDictionary <string, string> > groups = new Dictionary <string, IDictionary <string, string> >(); foreach (KeyValuePair <string, string> tag in tags) { string owner = api.GetTagOwner(tag.Key) ?? "Unknown-Mod"; if (!groups.ContainsKey(owner)) { groups[owner] = new Dictionary <string, string>(); } groups[owner][tag.Key] = tag.Value; } IList <string> output = new List <string>(tags.Count + groups.Count) { "Available Tags:" }; int longest = 0; foreach (KeyValuePair <string, string> tag in groups[ModManifest.UniqueID]) { if (tag.Value != null) { longest = Math.Max(longest, tag.Key.Length); } } int nulls = 0; foreach (KeyValuePair <string, string> tag in groups[ModManifest.UniqueID]) { if (tag.Value is null) { nulls++; } else { output.Add(" {{ " + tag.Key.PadLeft(longest) + " }}: " + tag.Value); } } foreach (KeyValuePair <string, IDictionary <string, string> > group in groups) { if (group.Key == ModManifest.UniqueID) { continue; } string head = group.Value.Count + " tag"; if (group.Value.Count != 1) { head += "s"; } head += " from " + (Helper.ModRegistry.Get(group.Key)?.Manifest.Name ?? "an unknown mod"); output.Add(head); longest = 0; foreach (KeyValuePair <string, string> tag in group.Value) { if (tag.Value != null) { longest = Math.Max(longest, tag.Key.Length); } } foreach (KeyValuePair <string, string> tag in group.Value) { if (tag.Value == null) { nulls++; } else { output.Add(" {{ " + tag.Key.PadLeft(longest) + " }}: " + tag.Value); } } } if (nulls > 0) { output.Add(nulls + " tag" + (nulls != 1 ? "s" : "") + " unavailable; type `DiscordRP_Tags all` to show all"); } Monitor.Log(string.Join(Environment.NewLine, output), LogLevel.Info); } ); #endregion LoadConfig(); Helper.Events.Input.ButtonReleased += HandleButton; Helper.Events.GameLoop.UpdateTicked += DoUpdate; Helper.Events.GameLoop.SaveLoaded += SetTimestamp; Helper.Events.GameLoop.ReturnedToTitle += SetTimestamp; Helper.Events.GameLoop.SaveLoaded += (object sender, SaveLoadedEventArgs e) => api.GamePresence = "Getting Started"; Helper.Events.GameLoop.SaveCreated += (object sender, SaveCreatedEventArgs e) => api.GamePresence = "Starting a New Game"; Helper.Events.GameLoop.GameLaunched += (object sender, GameLaunchedEventArgs e) => { SetTimestamp(); timestampSession = Timestamps.Now; }; ITagRegister tagReg = api.GetTagRegister(this); #region Default Tags tagReg.SetTag("Activity", () => api.GamePresence); tagReg.SetTag("ModCount", () => Helper.ModRegistry.GetAll().Count()); tagReg.SetTag("SMAPIVersion", () => Constants.ApiVersion.ToString()); tagReg.SetTag("StardewVersion", () => Game1.version); tagReg.SetTag("Song", () => Utility.getSongTitleFromCueName(Game1.currentSong?.Name ?? api.None)); // All the tags below are only available while in-game. tagReg.SetTag("Name", () => Game1.player.Name, true); tagReg.SetTag("Farm", () => Game1.content.LoadString("Strings\\UI:Inventory_FarmName", api.GetTag("FarmName")), true); tagReg.SetTag("FarmName", () => Game1.player.farmName, true); tagReg.SetTag("PetName", () => Game1.player.hasPet() ? Game1.player.getPetDisplayName() : api.None, true); tagReg.SetTag("Location", () => Game1.currentLocation.Name, true); tagReg.SetTag("RomanticInterest", () => Utility.getTopRomanticInterest(Game1.player)?.getName() ?? api.None, true); tagReg.SetTag("PercentComplete", () => Utility.percentGameComplete(), true); tagReg.SetTag("Money", () => { // Copied from LoadGameMenu string text = Game1.content.LoadString("Strings\\StringsFromCSFiles:LoadGameMenu.cs.11020", Utility.getNumberWithCommas(Game1.player.Money)); if (Game1.player.Money == 1 && LocalizedContentManager.CurrentLanguageCode == LocalizedContentManager.LanguageCode.pt) { text = text.Substring(0, text.Length - 1); } return(text); }, true); tagReg.SetTag("MoneyNumber", () => Game1.player.Money, true); tagReg.SetTag("MoneyCommas", () => Utility.getNumberWithCommas(Game1.player.Money), true); tagReg.SetTag("Level", () => Game1.content.LoadString("Strings\\UI:Inventory_PortraitHover_Level", Game1.player.Level.ToString()), true); tagReg.SetTag("LevelNumber", () => Game1.player.Level, true); tagReg.SetTag("Title", () => Game1.player.getTitle(), true); tagReg.SetTag("TotalTime", () => Utility.getHoursMinutesStringFromMilliseconds(Game1.player.millisecondsPlayed), true); tagReg.SetTag("Health", () => Game1.player.health, true); tagReg.SetTag("HealthMax", () => Game1.player.maxHealth, true); tagReg.SetTag("HealthPercent", () => (double)Game1.player.health / Game1.player.maxHealth * 100, 2, true); tagReg.SetTag("Energy", () => Game1.player.Stamina.ToString(), true); tagReg.SetTag("EnergyMax", () => Game1.player.MaxStamina, true); tagReg.SetTag("EnergyPercent", () => (double)Game1.player.Stamina / Game1.player.MaxStamina * 100, 2, true); tagReg.SetTag("Time", () => Game1.getTimeOfDayString(Game1.timeOfDay), true); tagReg.SetTag("Date", () => Utility.getDateString(), true); tagReg.SetTag("Season", () => Utility.getSeasonNameFromNumber(Utility.getSeasonNumber(SDate.Now().Season)), true); tagReg.SetTag("DayOfWeek", () => Game1.shortDayDisplayNameFromDayOfSeason(SDate.Now().Day), true); tagReg.SetTag("Day", () => SDate.Now().Day, true); tagReg.SetTag("DayPad", () => $"{SDate.Now().Day:00}", true); tagReg.SetTag("DaySuffix", () => Utility.getNumberEnding(SDate.Now().Day), true); tagReg.SetTag("Year", () => SDate.Now().Year, true); tagReg.SetTag("YearSuffix", () => Utility.getNumberEnding(SDate.Now().Year), true); tagReg.SetTag("GameVerb", () => Context.IsMultiplayer && Context.IsMainPlayer ? "Hosting" : "Playing", true); tagReg.SetTag("GameNoun", () => Context.IsMultiplayer ? "Co-op" : "Solo", true); tagReg.SetTag("GameInfo", () => api.GetTag("GameVerb") + " " + api.GetTag("GameNoun"), true); #endregion }
public void Init() { client = new DiscordRpcClient("726077029195448430"); client.RegisterUriScheme(); this.client.Initialize(); }
static async Task DiscordSetup() { var discordRpcClient = new DiscordRpcClient(ClientId); //Set the logger discordRpcClient.Logger = new ConsoleLogger() { Level = DiscordRPC.Logging.LogLevel.Info }; //Subscribe to events discordRpcClient.OnReady += (sender, e) => { Console.WriteLine("Received Ready from user {0}", e.User.Username); }; discordRpcClient.OnPresenceUpdate += (sender, e) => { Console.WriteLine("Received Update! {0}", e.Presence); }; //Connect to the RPC discordRpcClient.Initialize(); discordRpcClient.Authorize(DefaultScopes); while (string.IsNullOrWhiteSpace(discordRpcClient.AccessCode)) { await Task.Delay(500, CancellableShellHelper.CancellationToken); } discordRpcClient.Authenticate(null); while (string.IsNullOrWhiteSpace(discordRpcClient.AccessToken)) { await Task.Delay(500, CancellableShellHelper.CancellationToken); } discordRpcClient.RegisterUriScheme(); discordRpcClient.GetVoiceSettings(); var newPresence = new RichPresence() { State = "Accessing Named Pipes", }; discordRpcClient.SetPresence(newPresence); discordRpcClient.Subscribe(EventType.VoiceSettingsUpdate); discordRpcClient.OnVoiceSettingsUpdate += ProcessDiscordVoiceStatus; while (!CancellableShellHelper.CancellationToken.WaitHandle.WaitOne(0)) { await Task.Delay(500, CancellableShellHelper.CancellationToken); } discordRpcClient.ClearPresence(); discordRpcClient.ShutdownOnly = true; }