示例#1
0
 void UpdateDiscord()
 {
     if (discord == null)
     {
         return;
     }
     try {
         discord.RunCallbacks();
     } catch (Exception) {
         DestroyDiscord();
     }
 }
示例#2
0
 public static void RunCallbacks()
 {
     if (DiscordInstance != null)
     {
         DiscordInstance.RunCallbacks();
     }
 }
示例#3
0
        public static void UpdateStatus()
        {
            if (discord != null)
            {
                if (BepInExLoader.configShowServer.Value)
                {
                    act.Details = DataGrabber.server;
                }
                else
                {
                    act.Details = "Hidden";
                }

                act.State = DataGrabber.location;

                if (DataGrabber.className != null)
                {
                    act.Assets.SmallImage = DataGrabber.className.ToLower();
                    act.Assets.SmallText  = DataGrabber.className;
                }

                discord.GetActivityManager().UpdateActivity(act, OnActivityUpdate);
                discord.RunCallbacks();
            }
        }
示例#4
0
 public void UpdaterThread()
 {
     try
     {
         while (true)
         {
             if (!disposed)
             {
                 discord.RunCallbacks();
                 Thread.Sleep(1000 / 60);
             }
             if (stopThread)
             {
                 break;
             }
         }
     }
     finally
     {
         if (!disposed)
         {
             discord.Dispose();
             disposed = true;
         }
     }
 }
示例#5
0
 protected override async Task ExecuteAsync(CancellationToken stoppingToken)
 {
     while (!stoppingToken.IsCancellationRequested)
     {
         _discord.RunCallbacks();
         await Task.Delay(1000, stoppingToken);
     }
 }
示例#6
0
        public static void Init()
        {
            discord = new Discord.Discord(625092334283128892, (ulong)Discord.CreateFlags.NoRequireDiscord);
            act     = new Discord.Activity();

            act.Type              = Discord.ActivityType.Playing;
            act.Timestamps.Start  = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
            act.State             = "Loading...";
            act.Assets.LargeImage = "icon";

            discord.GetActivityManager().UpdateActivity(act, OnActivityUpdate);
            discord.RunCallbacks();
        }
示例#7
0
        public static void RunCallbacks()
        {
            if (_Discord == null)
            {
                return;
            }

            try
            {
                _Discord.RunCallbacks();
            }
            catch { }
        }
 public static void Update()
 {
     if (discord != null)
     {
         try
         {
             discord.RunCallbacks();
         }
         catch
         {
             MainLogic.Log("Discord update error. (Maybe try opening discord...)");
             Clear();
         }
     }
 }
示例#9
0
 static void Update()
 {
     if (EditorApplication.isCompiling)
     {
         if (discord != null && !disposing)
         {
             disposing = true;
             discord.Dispose();
         }
     }
     else
     {
         if (isRunning == false)
         {
             return;
         }
         if (Time.realtimeSinceStartup - lastUpdate > DRP_Settings.GetData().update_rate)
         {
             try
             {
                 UpdateActivity();
             }catch (Exception e)
             {
                 //throws if discords is not running, too lazy to something else
                 isRunning = false;
                 EditorApplication.update -= Update;
                 EditorApplication.update += TryInitDiscord;
             }
             lastUpdate = Time.realtimeSinceStartup;
         }
         if (Time.realtimeSinceStartup - last_callback > DRP_Settings.GetData().update_rate / 3)
         {
             last_callback = Time.realtimeSinceStartup;
             try
             {
                 discord.RunCallbacks();
             }
             catch (Exception e)
             {
                 //throws if discords is not running, too lazy to something else
                 isRunning = false;
                 EditorApplication.update -= Update;
                 EditorApplication.update += TryInitDiscord;
             }
         }
     }
 }
示例#10
0
 // Update is called once per frame
 void Update()
 {
     Input.Input_Tick();
     UI.UI_Tick();
     World.World_Tick();
     Combat.Combat_Tick();
     if (discordPresence != null)
     {
         try
         {
             discordPresence.RunCallbacks();
         }
         catch (Exception e)
         {
         }
     }
 }
 private async Task StartInstance()
 {
     try
     {
         Console.WriteLine("Start Discord bridge");
         IsRunning = true;
         while (IsRunning)
         {
             discord.RunCallbacks();
             await Task.Delay(1000 / 60);
         }
     }
     finally
     {
         Console.WriteLine("Stop and dispose Discord bridge");
         discord.Dispose();
     }
 }
示例#12
0
        static void RWCheckLoop()
        {
            bool rwIsOpen;

            do
            {
                try
                {
                    lock (discordLock)
                    {
                        discord.RunCallbacks();
                    }
                }
                catch (NullReferenceException) { Console.WriteLine("Discord threw nullref"); }

                Thread.Sleep(500);
                rwIsOpen = CheckRWIsOpen();
            } while (rwIsOpen);

            Log("Rain World closed - self-destruct in T minus a very small time...");
        }
        private void Update(object sender, UpdateTickedEventArgs e, Discord.Discord discord, Discord.Activity activity)
        {
#if MULTI_WAIT
            if (!Context.IsWorldReady)
            {
                return;
            }
#endif
#if USEACC
            var activityManager = discord.GetActivityManager();
            activityManager.RegisterSteam(413150);
            //activityManager.RegisterCommand("steam://run-game-id/413150");
            try
            {
                if (e == null) // should only happen once, for loading screen displayability
                {
                    this.Monitor.Log($"Init Discord setup", LogLevel.Info);
                    activityManager.UpdateActivity(CheckActivity(acc), (result) =>
                    {
                        if (result != Discord.Result.Ok)
                        {
                            this.Monitor.Log($"Update Activity: {result}", LogLevel.Warn);
                        }
                    });

                    discord.RunCallbacks();
                }
                else if (e.IsMultipleOf(30))
                {
                    activityManager.UpdateActivity(CheckActivity(acc), (result) =>
                    {
                        if (result != Discord.Result.Ok)
                        {
                            this.Monitor.Log($"Update Activity: {result}", LogLevel.Warn);
                        }
                    });
                    ///TODO: The `runncallbacks()` function still technically throws an error but it recovers most of the time??? I Think????
                    try
                    {
                        discord.RunCallbacks();
                    }
                    catch (Discord.ResultException exc)
                    {
                        this.Monitor.Log($"Result Exception: {exc}", LogLevel.Warn);
                    }
                }
            }
            catch { }
#else // not sure why the below breaks things - something to do with the lifetime of the Activity?
            var activityManager = discord.GetActivityManager();
            activityManager.RegisterSteam(413150);
            //activityManager.RegisterCommand("steam://run-game-id/413150");
            try
            {
                if (e == null) // should only happen once, for loading screen displayability
                {
                    this.Monitor.Log($"Init Discord setup", LogLevel.Info);
                    activityManager.UpdateActivity(CheckActivity(activity), (result) =>
                    {
                        if (result != Discord.Result.Ok)
                        {
                            this.Monitor.Log($"Update Activity: {result}", LogLevel.Warn);
                        }
                    });

                    discord.RunCallbacks();
                }
                else if (e.IsMultipleOf(20))
                {
                    activityManager.UpdateActivity(CheckActivity(activity), (result) =>
                    {
                        if (result != Discord.Result.Ok)
                        {
                            this.Monitor.Log($"Update Activity: {result}", LogLevel.Warn);
                        }
                    });

                    discord.RunCallbacks();
                }
            }
            catch { }
#endif
        }
 void Update()
 {
     discord.RunCallbacks();
 }
示例#15
0
 private void _PollDiscord(Discord.Discord discord)
 {
     _DisposedTokenSource.Token.ThrowIfCancellationRequested();
     discord.RunCallbacks();
     Thread.Sleep(250);
 }
示例#16
0
        static void Main(string[] args)
        {
            // Get Discord client ID from app config file
            long client_id = Convert.ToInt64(ConfigurationManager.AppSettings["client_id"]);

            Console.WriteLine("Client ID: {0}", client_id);

            // Create new Discord GameSDK instance
            var discord = new Discord.Discord(client_id, (ulong)Discord.CreateFlags.Default);

            // Create new Discord Rich Presence activity
            var activity = new Discord.Activity
            {
                ApplicationId = client_id,
                State         = "",
                Details       = "Not playing anything",
                Timestamps    =
                {
                    Start = 0,
                    End   = 0
                },
                Assets =
                {
                    LargeImage = "mpc_hc_icon_classic",
                },
            };

            // Set up Discord GameSDK debug logging
            discord.SetLogHook(Discord.LogLevel.Debug, (level, message) =>
            {
                Console.WriteLine("Discord:{0} - {1}", level, message);
            });

            // Get current activity manager from Discord
            var activityManager = discord.GetActivityManager();


            // Main loop: Detect last active MPC-HC window, update presence and run Discord callbacks
            Process activeMPCHCProcess = null;

            while (true)
            {
                bool activityChanged = false;

                if (activeMPCHCProcess != null && activeMPCHCProcess.HasExited)
                {
                    activeMPCHCProcess = null;
                }

                var activeWindowHandle = GetForegroundWindow();

                var processes = Process.GetProcessesByName("mpc-hc64");
                foreach (var process in processes)
                {
                    if (!string.IsNullOrEmpty(process.MainWindowTitle) && process.MainWindowTitle != "Media Player Classic Home Cinema" && process.MainWindowHandle == activeWindowHandle)
                    {
                        activeMPCHCProcess = process;
                        break;
                    }
                }

                if (activeMPCHCProcess != null)
                {
                    if (activity.State != activeMPCHCProcess.MainWindowTitle)
                    {
                        activity.State  = activeMPCHCProcess.MainWindowTitle;
                        activityChanged = true;
                    }

                    int i = 0;
                    EnumChildWindows(activeMPCHCProcess.MainWindowHandle, (hwnd, param) =>
                    {
                        string text = "";
                        if (i == 4 || i == 5)
                        {
                            var bld = new StringBuilder(32);
                            GetWindowText(hwnd, bld, 32);
                            text = bld.ToString();
                        }

                        if (i == 4)
                        {
                            var parts = text.Split(new string[] { " / " }, StringSplitOptions.None);
                            if (parts.Length == 2)
                            {
                                TimeSpan startOffset = TimeSpan.Zero, endOffset = TimeSpan.Zero;
                                try
                                {
                                    startOffset = TimeSpan.ParseExact(parts[0], "g", CultureInfo.CurrentCulture);
                                    endOffset   = TimeSpan.ParseExact(parts[1], "g", CultureInfo.CurrentCulture);
                                }
                                catch (OverflowException)
                                {
                                    startOffset = TimeSpan.ParseExact(parts[0], "mm\\:ss", CultureInfo.CurrentCulture);
                                    endOffset   = TimeSpan.ParseExact(parts[1], "mm\\:ss", CultureInfo.CurrentCulture);
                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine(ex);
                                }
                                finally
                                {
                                    var now     = new DateTimeOffset(DateTime.Now);
                                    var start   = now.Subtract(startOffset);
                                    var end     = start.Add(endOffset);
                                    var tsStart = start.ToUnixTimeSeconds();
                                    var tsEnd   = end.ToUnixTimeSeconds();

                                    if (activity.Timestamps.Start != tsStart)
                                    {
                                        activity.Timestamps.Start = tsStart;
                                        activityChanged           = true;
                                    }
                                    if (activity.Timestamps.End != tsEnd)
                                    {
                                        activity.Timestamps.End = tsEnd;
                                        activityChanged         = true;
                                    }
                                }
                            }
                        }
                        else if (i == 5)
                        {
                            if (activity.Details != text)
                            {
                                activity.Details = text;
                                activityChanged  = true;
                            }
                        }

                        i++;
                        return(i <= 5);
                    }, 0);
                }
                else
                {
                    if (activity.State != "")
                    {
                        activity.State  = "";
                        activityChanged = true;
                    }
                    if (activity.Details != "Not playing anything")
                    {
                        activity.Details = "Not playing anything";
                        activityChanged  = true;
                    }
                    if (activity.Timestamps.Start != 0)
                    {
                        activity.Timestamps.Start = 0;
                        activityChanged           = true;
                    }
                    if (activity.Timestamps.End != 0)
                    {
                        activity.Timestamps.End = 0;
                        activityChanged         = true;
                    }
                }

                // Update presence if changed
                if (activityChanged)
                {
                    activityManager.UpdateActivity(activity, (result) => {});
                }

                // Run Discord callbacks
                discord.RunCallbacks();

                Thread.Sleep(1000);
            }
        }
示例#17
0
        public async Task <object> Invoke(object _)
        {
            try
            {
                startDiscord();
                isDiscordConnected = true;
            }
            catch
            {
                isDiscordConnected = false;
            }
            return((Func <object, Task <object> >)(async(dynamic input) =>
            {
                if (!isDiscordConnected)
                {
                    try
                    {
                        startDiscord();
                        isDiscordConnected = true;
                    }
                    catch
                    {
                        isDiscordConnected = false;
                    }
                    return returnHelper();
                }

                Discord.Activity activity;
                lastInput = input;
                currentView = input.currentView;
                if (currentView == null)
                {
                    activity = new Discord.Activity
                    {
                        Details = "Not logged in",
                        Assets =
                        {
                            LargeImage = "logo"
                        }
                    };
                }
                else
                {
                    string largeKeyValue;
                    string largeTextValue;
                    if (input.avatar != null)
                    {
                        largeKeyValue = $"{input.avatar.avatar}_{input.avatar.outfit}_{input.avatar.option}".Replace(" ", "_").ToLower();
                        largeTextValue = input.avatar.avatar;
                    }
                    else
                    {
                        largeKeyValue = "logo";
                        largeTextValue = null;
                    }

                    if (currentView == "Lobby")
                    {
                        activity = new Discord.Activity
                        {
                            Details = $"Waiting",
                            State = (input.gameMode == "Ranked") ? "Ranked Lobby" : ((input.lobbyIsPrivate) ? "Private Lobby" : "Public Lobby"),
                            Assets =
                            {
                                LargeImage = largeKeyValue,
                                LargeText  = largeTextValue,
                                SmallImage = getGameModeKey(input.gameMode),
                                SmallText  = input.gameMode
                            },
                            Party =
                            {
                                Id              = $"lobby id={input.lobbyId}",
                                Size            =
                                {
                                    CurrentSize = input.currentPlayers,
                                    MaxSize     = input.totalPlayers,
                                },
                            },
                            Secrets =
                            {
                                Join = encodeSecret()
                            },
                            Instance = true
                        };
                    }
                    else if (currentView == "Quiz")
                    {
                        activity = new Discord.Activity
                        {
                            Details = ((input.isSpectator) ? "Spectating" : "Playing") + ((input.gameMode == "Ranked") ? " Ranked" : ""),
                            State = $"{input.currentSongs}/{input.totalSongs} Songs",
                            Assets =
                            {
                                LargeImage = largeKeyValue,
                                LargeText  = largeTextValue,
                                SmallImage = getGameModeKey(input.gameMode),
                                SmallText  = input.gameMode
                            },
                            Party =
                            {
                                Id              = $"lobby id={input.lobbyId}",
                                Size            =
                                {
                                    CurrentSize = input.currentPlayers,
                                    MaxSize     = input.totalPlayers,
                                },
                            }
                        };
                    }
                    else if (currentView == "Expand Library" && input.songName != null)
                    {
                        activity = new Discord.Activity
                        {
                            Details = $"Currently in Expand Library",
                            State = $"Checking out '{input.songName}' by '{input.artistName}' from '{input.animeName}' [{input.typeName}]",
                            Assets =
                            {
                                LargeImage = largeKeyValue,
                                LargeText  = largeTextValue
                            }
                        };
                    }
                    else
                    {
                        activity = new Discord.Activity
                        {
                            Details = $"Currently in {currentView}",
                            Assets =
                            {
                                LargeImage = largeKeyValue,
                                LargeText  = largeTextValue
                            }
                        };
                    }
                }

                activityManager.UpdateActivity(activity, result => { });
                try
                {
                    discord.RunCallbacks();
                }
                catch
                {
                    isDiscordConnected = false;
                }

                return returnHelper();
            }));
        }
示例#18
0
        public void Run()
        {
            /*
             * Addresses:
             * +007CB2DC: Int32 - Cash
             * +00871F74: String - level name (jungle, hallow, fantasy, space)
             * +0087505C: Ditto
             * +00876668: Ditto
             * +00FAA40D: Ditto
             * +00768F3D / 05C4D745?: "lobby" or "level", depending on whether the player is in lobby or not
             * +00FAA40D: Previous load (if in lobby, this will be different to level name at 00871F74).
             * +007CB360: Visitor count (only updates when info screen is shown)
             * +00752EC4: Golden ticket count
             * +007CC4B8: Golden key count
             * +05E6DAE0*: User index (saves folder prefixes, add one)
             */

            Log($"Looking for {GlobalSettings.Default.ProcessName}...");
            var found      = false;
            var shouldExit = false;

            while (!found)
            {
                found = Memory.Attach(GlobalSettings.Default.ProcessName);
                Thread.Sleep(GlobalSettings.Default.UpdateDelay);
            }
            Log($"Found {GlobalSettings.Default.ProcessName}.");

            while (!shouldExit)
            {
                var rpcData = new TpwRpcData();

                rpcData.Cash              = Memory.ReadMemory <int>(0x007CB2DC);
                rpcData.Level             = Memory.ReadMemoryString(0x00871F74, 6);
                rpcData.LastLoad          = Memory.ReadMemoryString(0x00FAA40D, 6);
                rpcData.GoldenTicketCount = Memory.ReadMemory <int>(0x00752EC4);
                rpcData.GoldenKeyCount    = Memory.ReadMemory <int>(0x007CC4B8);

                var savesIndex    = Memory.ReadMemory <int>(0x05E6DAE0);
                var savesContents = Directory.GetDirectories(@"C:\Program Files (x86)\Bullfrog\Theme Park World\save\users");
                rpcData.SaveName = "";

                if (savesIndex >= 0 && savesIndex < 5)
                {
                    foreach (var save in savesContents)
                    {
                        var saveName      = Path.GetFileName(save);
                        var relSavesIndex = savesIndex + 1;
                        if (saveName.StartsWith(relSavesIndex.ToString()))
                        {
                            rpcData.SaveName = saveName.Substring(1);
                        }
                    }
                }

                rpcData.InLobby = rpcData.Cash == 0 || rpcData.Level != rpcData.LastLoad || savesIndex < 0;

                UpdateActivity(rpcData);
                discord.RunCallbacks();
                Thread.Sleep(GlobalSettings.Default.UpdateDelay);
            }

            startTime = GetUnixTime();
        }