コード例 #1
0
ファイル: Presence.cs プロジェクト: moyi7712/HunterPie
        /* 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;
            }
        }
コード例 #2
0
ファイル: DiscordService.cs プロジェクト: lujiawen/OpenRA
        public DiscordService(MiniYaml yaml)
        {
            FieldLoader.Load(this, yaml);

            // HACK: Prevent service from starting when launching the utility or server.
            if (Game.Renderer == null)
            {
                return;
            }

            client = new DiscordRpcClient(ApplicationId, autoEvents: true)
            {
                SkipIdenticalPresence = false
            };

            client.OnJoin          += OnJoin;
            client.OnJoinRequested += OnJoinRequested;

            // HACK: We need to set HasRegisteredUriScheme to bypass the check that is done when calling SetPresence with a joinSecret.
            // DiscordRpc lib expect us to register uri handlers with RegisterUriScheme(), we are doing it ourselves in our installers/launchers.
            client.GetType().GetProperty("HasRegisteredUriScheme").SetValue(client, true);

            client.SetSubscription(EventType.Join | EventType.JoinRequest);
            client.Initialize();
        }
コード例 #3
0
        public static void SetData(int Mode)
        {
            Regex reg      = new Regex("([0-9]{1,2}):([0-9]{1,2})");
            Match m        = reg.Match(Functions.playlist[Functions.PlaylistPosition][4]);
            int   duration = 0;

            if (m.Groups[1].Length > 0)
            {
                int minuteToSec = Convert.ToInt32(m.Groups[1].Value) * 60;
                int seconds     = Convert.ToInt32(m.Groups[2].Value);
                duration = minuteToSec + seconds;
            }
            presence = new RichPresence()
            {
                Details = "Слушает:",
                State   = Functions.playlist[Functions.PlaylistPosition][0],
                Assets  = new Assets()
                {
#if DEBUG
                    LargeImageKey  = "logo_debug",
                    LargeImageText = "SYMP DebugMode      (Процесс разработки)",
#else
                    LargeImageKey  = "logo",
                    LargeImageText = Functions.playlist[Functions.PlaylistPosition][0],
#endif
                    SmallImageKey  = "stop",
                    SmallImageText = "Стоп"
                }
            };
            presence.Secrets = new Secrets()
            {
                SpectateSecret = Functions.playlist[Functions.PlaylistPosition][5]
            };
            switch (Mode)
            {
            case 1:
                presence.Assets.SmallImageKey  = "play";
                presence.Assets.SmallImageText = "Воспроизведение";
                presence.Timestamps            = new Timestamps()
                {
                    Start = DateTime.UtcNow,
                    End   = DateTime.UtcNow + TimeSpan.FromSeconds(duration)
                };
                break;

            case 2:
                presence.Assets.SmallImageKey  = "pause";
                presence.Assets.SmallImageText = "Пауза";
                presence.Timestamps            = new Timestamps();
                break;

            default:
                presence.Assets.SmallImageKey  = "stop";
                presence.Assets.SmallImageText = "Стоп";
                presence.Timestamps            = new Timestamps();
                break;
            }
            client.SetSubscription(EventType.Join | EventType.Spectate | EventType.JoinRequest);
            client.SetPresence(presence);
        }
コード例 #4
0
        /// <summary>
        /// Turn the rich presence on.
        /// </summary>
        /// <param name="automatic">Whether to have EliteAPI send events to the presence.</param>
        public RichPresenceClient TurnOn(bool automatic = true)
        {
            //Create RPC client.
            rpc = new DiscordRpcClient(clientID, true);
            api.Logger.Log("Starting rich presence.");

            //Subscribe to events.
            rpc.OnConnectionEstablished += (sender, e) => api.Logger.Log(Severity.Debug, $"Attempting to connect to Discord ... ");
            rpc.OnConnectionFailed      += (sender, e) => { api.Logger.Log(Severity.Error, $"There was an error while trying to connect to Discord. Make sure Discord is running.", new ExternalException("Discord is unresponsive, or might not be running on this machine.")); TurnOff(); };
            rpc.OnError              += (sender, e) => api.Logger.Log(Severity.Error, $"Discord Rich Presence stumbled upon an error.", new ExternalException(e.Message, (int)e.Code));
            rpc.OnReady              += (sender, e) => { api.Logger.Log(Severity.Success, $"Discord Rich Presence has connected and is running."); IsReady = true; };
            rpc.OnClose              += (sender, e) => { api.Logger.Log($"Discord Rich Presence closed.", new ExternalException(e.Reason, e.Code)); TurnOff(); };
            rpc.OnJoin               += (sender, e) => api.Logger.Log(Severity.Debug, $"Discord Rich Presence joined with secret '{e.Secret}'.");
            rpc.OnJoinRequested      += (sender, e) => api.Logger.Log(Severity.Debug, $"Discord Rich Presence joining with '{e.User.Username}' (ID {e.User.ID})");
            api.Events.DockedEvent   += (sender, e) => { justDocked = true; };
            api.Events.UndockedEvent += (sender, e) => { justDocked = false; };

            //Start the RPC.
            //Mark as running.
            IsRunning = true;
            rpc.SetSubscription(EventType.Join | EventType.JoinRequest | EventType.Spectate);
            rpc.Initialize();
            Task.Run(() => { while (!IsReady)
                             {
                                 Thread.Sleep(1000); rpc.Invoke();
                             }
                     });
            if (automatic)
            {
                DoAutomaticEvents();
            }
            return(this);
        }
コード例 #5
0
        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();
        }
コード例 #6
0
        /* 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;
            }
        }
コード例 #7
0
        private static void OnReady(object sender, ReadyMessage args)
        {
            //This is called when we are all ready to start receiving and sending discord events.
            // It will give us some basic information about discord to use in the future.

            //It can be a good idea to send a inital presence update on this event too, just to setup the inital game state.
            Console.WriteLine("On Ready. RPC Version: {0}", args.Version);

            //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);

            //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
        }
コード例 #8
0
        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
            });
        }
コード例 #9
0
        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);
            }
        }
コード例 #10
0
        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();
        }
コード例 #11
0
        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
        }
コード例 #12
0
ファイル: MainPlugin.cs プロジェクト: CaseyK9/SDR-RPC
        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");
        }
コード例 #13
0
        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();
            }
        }
コード例 #14
0
ファイル: Program.cs プロジェクト: qipa/discord-rpc-csharp
        static void FullClientExample()
        {
            //Creates a new Discord RPC Client. Below are some of the ways to register:
            //using (DiscordRpcClient client = new DiscordRpcClient("424087019149328395", null, true, DiscordPipe, new IO.NativeNamedPipeClient()))	//This will create a new client with the specified pipe client
            //using (DiscordRpcClient client = new DiscordRpcClient("424087019149328395", null, true, DiscordPipe))									//This will create a new client on the specified pipe
            //using (DiscordRpcClient client = new DiscordRpcClient("424087019149328395", null, true))												//This will create a new client with a SteamID (null if no steam)
            using (client = new DiscordRpcClient(ClientID, true, DiscordPipe))                                                                                                  //This will create a new client that will register itself a URI scheme (for join / spectate)
            {
                //Set the logger. This way we can see the output of the client.
                client.Logger = new Logging.ConsoleLogger()
                {
                    Level = DiscordLogLevel, Coloured = true
                };

                //Register to the events we care about. We are registering to everyone just to show off the events
                client.OnReady += OnReady;
                client.OnClose += OnClose;
                client.OnError += OnError;

                client.OnConnectionEstablished += OnConnectionEstablished;
                client.OnConnectionFailed      += OnConnectionFailed;

                client.OnPresenceUpdate += OnPresenceUpdate;

                client.OnSubscribe   += OnSubscribe;
                client.OnUnsubscribe += OnUnsubscribe;

                client.OnJoin          += OnJoin;
                client.OnSpectate      += OnSpectate;
                client.OnJoinRequested += OnJoinRequested;

                //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"
                };

                presence.Timestamps = new Timestamps()
                {
                    Start = DateTime.UtcNow
                };

                //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
                };

                //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);

                //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

                //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();
            }
        }
コード例 #15
0
        /// <summary>
        /// Turn the rich presence on.
        /// </summary>
        public void TurnOn()
        {
            //Create RPC client.
            rpc = new DiscordRpcClient(clientID, true);
            api.Logger.LogInfo("Starting rich presence.");

            //Subscribe to events.
            rpc.OnConnectionEstablished += (sender, e) => api.Logger.LogDebug($"Rich presence connected to pipe {e.ConnectedPipe}.");
            rpc.OnConnectionFailed      += (sender, e) => api.Logger.LogWarning($"There was an error while trying to connect to rich presence pipe {e.FailedPipe}. Make sure Discord is running.");
            rpc.OnError         += (sender, e) => api.Logger.LogError($"Rich presence stumbled upon an error.", new Exception(e.Message));
            rpc.OnReady         += (sender, e) => { api.Logger.LogSuccess($"Rich presence is running."); IsReady = true; };
            rpc.OnClose         += (sender, e) => api.Logger.LogDebug($"Rich presence closed: '{e.Reason}'.");
            rpc.OnJoin          += (sender, e) => api.Logger.LogDebug($"Rich presence joined with secret '{e.Secret}'.");
            rpc.OnJoinRequested += (sender, e) => api.Logger.LogDebug($"Rich presence joining with '{e.User.Username}' (ID {e.User.ID})");

            //Start the RPC.
            //Mark as running.
            IsRunning = true;
            rpc.SetSubscription(EventType.Join | EventType.JoinRequest | EventType.Spectate);
            rpc.Initialize();
            Task.Run(() => { while (!IsReady)
                             {
                                 Thread.Sleep(1000); rpc.Invoke();
                             }
                     });

            api.Events.DockingGrantedEvent += (sender, e) => UpdatePresence(new RichPresence
            {
                Text        = $"Attemping to dock",
                TextTwo     = $"at {e.StationName}",
                Icon        = "coriolis",
                IconTwo     = "ed",
                IconTextTwo = "EliteAPI"
            });
            api.Events.DockedEvent += (sender, e) => UpdatePresence(new RichPresence
            {
                Text        = $"Docked at {e.StationName}",
                TextTwo     = $"in {e.StarSystem}",
                Icon        = "coriolis",
                IconTwo     = "ed",
                IconTextTwo = "EliteAPI"
            });
            api.Events.UndockedEvent += (sender, e) => UpdatePresence(new RichPresence
            {
                Text        = $"Leaving {e.StationName}",
                TextTwo     = $"in {api.Location.StarSystem}",
                Icon        = "coriolis",
                IconTwo     = "ed",
                IconTextTwo = "EliteAPI"
            });
            api.Events.StartJumpEvent += (sender, e) =>
            {
                if (e.JumpType == "FSDJump")
                {
                    UpdatePresence(new RichPresence
                    {
                        Text     = $"Jumping to {e.StarSystem}",
                        TextTwo  = $"Class {e.StarClass} star",
                        Icon     = "ed",
                        IconText = "EliteAPI"
                    });
                }
            };
            api.Events.FSDJumpEvent += (sender, e) => UpdatePresence(new RichPresence
            {
                Text        = $"Arrived in {e.StarSystem}",
                TextTwo     = $"after travelling {Math.Round(e.JumpDist, 1)} ly",
                Icon        = "route",
                IconTwo     = "ed",
                IconTextTwo = "EliteAPI"
            });
            api.Events.ApproachBodyEvent += (sender, e) => UpdatePresence(new RichPresence
            {
                Text        = $"Approaching planet",
                TextTwo     = e.Body,
                Icon        = "loading",
                IconTwo     = "ed",
                IconTextTwo = "EliteAPI"
            });
            api.Events.LeaveBodyEvent += (sender, e) => UpdatePresence(new RichPresence
            {
                Text        = $"Leaving planet",
                TextTwo     = e.Body,
                Icon        = "loading",
                IconTwo     = "ed",
                IconTextTwo = "EliteAPI"
            });
            api.Events.TouchdownEvent += (sender, e) => UpdatePresence(new RichPresence
            {
                Text        = $"Touched down on",
                TextTwo     = api.Location.Body,
                Icon        = "exploration",
                IconTwo     = "ed",
                IconTextTwo = "EliteAPI"
            });
            api.Events.LiftoffEvent += (sender, e) => UpdatePresence(new RichPresence
            {
                Text        = $"Lifted off from",
                TextTwo     = api.Location.Body,
                Icon        = "exploration",
                IconTwo     = "ed",
                IconTextTwo = "EliteAPI"
            });
            api.Events.SupercruiseEntryEvent += (sender, e) => UpdatePresence(new RichPresence
            {
                Text        = $"Travelling in supercruise",
                TextTwo     = $"in {e.StarSystem}",
                Icon        = "loading",
                IconTwo     = "ed",
                IconTextTwo = "EliteAPI"
            });
            api.Events.SupercruiseExitEvent += (sender, e) => UpdatePresence(new RichPresence
            {
                Text        = $"Travelling in normal space",
                TextTwo     = $"near {e.BodyType.ToLower().Replace("planetaryring", "ring")} {e.Body.Replace("Ring", "")}",
                Icon        = "exploration",
                IconTwo     = "ed",
                IconTextTwo = "EliteAPI"
            });
            api.Events.MusicEvent += (sender, e) =>
            {
                if (e.MusicTrack == "DockingComputer")
                {
                    UpdatePresence(new RichPresence
                    {
                        Text        = $"Having autopilot dock",
                        TextTwo     = $"them at {api.Location.Body}",
                        Icon        = "coriolis",
                        IconTwo     = "ed",
                        IconTextTwo = "EliteAPI"
                    });
                }
            };

            UpdatePresence(new RichPresence {
                Text = "Just started playing", Icon = "ed", IconText = "EliteAPI"
            });
        }