Beispiel #1
0
        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);
            };
        }
        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 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 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;
        }