VincentK2000

Discord Game SDK RegisterCommand

May 10th, 2021 (edited)
288
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 9.42 KB | None | 0 0
  1. using System;
  2. using System.Threading;
  3. using System.Collections.Generic;
  4. using System.Runtime.InteropServices;
  5.  
  6. namespace DiscordRegisterCommand
  7. {
  8.     class Log
  9.     {
  10.         public static void Info(string s)
  11.         {
  12.             Console.WriteLine($"[{DateTime.Now:HH:mm:ss.ff} \x1b[97mINF\x1b[0m] \x1b[97m{s}\x1b[0m");
  13.         }
  14.  
  15.         public static void Warn(string s)
  16.         {
  17.             Console.WriteLine($"[{DateTime.Now:HH:mm:ss.ff} \x1b[95mWARN\x1b[0m] \x1b[97m{s}\x1b[0m");
  18.         }
  19.  
  20.         public static void Error(string s)
  21.         {
  22.             Console.WriteLine($"[{DateTime.Now:HH:mm:ss.ff} \x1b[91mERROR\x1b[0m] \x1b[97m{s}\x1b[0m");
  23.         }
  24.     }
  25.  
  26.     class Program
  27.     {
  28.         static void UpdateActivity(Discord.Discord discord, Discord.Lobby lobby)
  29.         {
  30.             var activityManager = discord.GetActivityManager();
  31.             var lobbyManager = discord.GetLobbyManager();
  32.  
  33.             var activity = new Discord.Activity
  34.             {
  35.                 State = "State",
  36.                 Details = "Details",
  37.                 Timestamps =
  38.                     {
  39.                         Start = DateTimeOffset.Now.ToUnixTimeSeconds()
  40.                     },
  41.                 Party =
  42.                     {
  43.                         Id = lobby.Id.ToString(),
  44.                         Size =
  45.                             {
  46.                                 CurrentSize = lobbyManager.MemberCount(lobby.Id),
  47.                                 MaxSize = (int)lobby.Capacity,
  48.                             },
  49.                     },
  50.                 Secrets = {
  51.                 Join = lobbyManager.GetLobbyActivitySecret(lobby.Id),
  52.             },
  53.                 Instance = true,
  54.             };
  55.  
  56.             Log.Info($"Updating activity...");
  57.             activityManager.UpdateActivity(activity, result =>
  58.             {
  59.                 if (result == Discord.Result.Ok)
  60.                     Log.Info($"Update activity successful");
  61.                 else
  62.                     Log.Warn($"Update activity returned result {result}");
  63.             });
  64.         }
  65.  
  66.         static string FormatLobbyId(long id)
  67.         {
  68.             return $"{id}";
  69.         }
  70.  
  71.         static string FormatUserId(long id)
  72.         {
  73.             return $"{id}";
  74.         }
  75.  
  76.         static string FormatTimestamp(string timestamp)
  77.         {
  78.             timestamp = timestamp.Substring(0, 11) + "\x1b[96m" + timestamp.Substring(11, 8) + "\x1b[97m" + timestamp.Substring(19);
  79.             return timestamp;
  80.         }
  81.  
  82.         static void Main(string[] args)
  83.         {
  84.             EnableTerminalSequences();
  85.             // Provide one in code
  86.             long clientId = -1;
  87.             // ... or have it prompted.
  88.             if (clientId == -1)
  89.             {
  90.                 Console.Write("Enter clientId: ");
  91.                 string clientIdStr = Console.ReadLine();
  92.                 clientId = long.Parse(clientIdStr);
  93.             }
  94.  
  95.             Console.WriteLine("Enter 0 below if you have only one Discord client.");
  96.  
  97.             Console.Write("DISCORD_INSTANCE_ID: ");
  98.             string instanceID = Console.ReadLine();
  99.  
  100.             Environment.SetEnvironmentVariable("DISCORD_INSTANCE_ID", instanceID);
  101.  
  102.             Discord.Discord discord;
  103.             try
  104.             {
  105.                 discord = new Discord.Discord(clientId, (ulong)Discord.CreateFlags.Default);
  106.             }
  107.             catch (Exception ex)
  108.             {
  109.                 Console.WriteLine($"Error initializing Discord hook: {ex}");
  110.                 Console.WriteLine("Press any key to quit");
  111.                 Console.ReadKey(true);
  112.                 return;
  113.             }
  114.  
  115.             discord.SetLogHook(Discord.LogLevel.Debug, (level, message) =>
  116.             {
  117.                 switch (level)
  118.                 {
  119.                     case Discord.LogLevel.Error:
  120.                         Log.Error($"Discord: {message}");
  121.                         break;
  122.                     case Discord.LogLevel.Warn:
  123.                         Log.Warn($"Discord: {message}");
  124.                         break;
  125.                     case Discord.LogLevel.Info:
  126.                         Log.Info($"Discord: {message}");
  127.                         break;
  128.                     default:
  129.                         Log.Info($"Discord ({level}): {message}");
  130.                         break;
  131.                 }
  132.             });
  133.  
  134.             var lobbyManager = discord.GetLobbyManager();
  135.             var userManager = discord.GetUserManager();
  136.             var activityManager = discord.GetActivityManager();
  137.  
  138.             Dictionary<long, Discord.Lobby> lobbies = new Dictionary<long, Discord.Lobby>();
  139.  
  140.             userManager.OnCurrentUserUpdate += () =>
  141.             {
  142.                 var user = userManager.GetCurrentUser();
  143.                 Log.Info($"Current user: {user.Username} ({FormatUserId(user.Id)})");
  144.             };
  145.  
  146.             if (args.Length >= 1)
  147.             {
  148.                 Log.Info("Launched from Discord.");
  149.                 Log.Info($"Registered time is {FormatTimestamp(args[0])}");
  150.             }
  151.             else
  152.             {
  153.                 Log.Info("Not launched from Discord.");
  154.             }
  155.  
  156.             string startupTime = DateTimeOffset.Now.ToString("o");
  157.             Log.Info($"Startup time is    {FormatTimestamp(startupTime)}");
  158.  
  159.             string exePath = System.Reflection.Assembly.GetEntryAssembly().Location;
  160.             if (exePath.EndsWith(".dll"))
  161.                 exePath = exePath.Substring(0, exePath.LastIndexOf(".dll")) + ".exe";
  162.  
  163.             Log.Info($"Exe path is {exePath}");
  164.  
  165.             Discord.LobbyTransaction tr = lobbyManager.GetLobbyCreateTransaction();
  166.             tr.SetCapacity(5);
  167.             tr.SetType(Discord.LobbyType.Private);
  168.             //tr.SetMetadata("InitTime", startupTime);
  169.  
  170.             lobbyManager.CreateLobby(tr, (Discord.Result res, ref Discord.Lobby lobby) =>
  171.             {
  172.                 Log.Info($"Created lobby {FormatLobbyId(lobby.Id)}");// with InitTime {lobbyManager.GetLobbyMetadataValue(lobby.Id, "InitTime")}");
  173.                 lobbies[lobby.Id] = lobby;
  174.                 UpdateActivity(discord, lobby);
  175.             });
  176.  
  177.             activityManager.OnActivityJoin += (string secret) =>
  178.             {
  179.                 Log.Info($"Joining lobby...");
  180.                 lobbyManager.ConnectLobbyWithActivitySecret(secret, (Discord.Result res, ref Discord.Lobby lobby) =>
  181.                 {
  182.                     Log.Info($"Joined lobby {FormatLobbyId(lobby.Id)}");
  183.                     lobbies[lobby.Id] = lobby;
  184.                     UpdateActivity(discord, lobby);
  185.                 });
  186.             };
  187.  
  188.             lobbyManager.OnMemberConnect += (long lobbyId, long userId) =>
  189.             {
  190.                 Log.Info($"User {FormatUserId(userId)} joined lobby {FormatLobbyId(lobbyId)}");
  191.                 if (lobbies.TryGetValue(lobbyId, out Discord.Lobby lobby))
  192.                     UpdateActivity(discord, lobby);
  193.             };
  194.  
  195.             string launchCommand = $"\"{exePath}\" {startupTime}";
  196.             activityManager.RegisterCommand(launchCommand);
  197.             Log.Info($"RegisterCommand issued with argument \x1b[93m{launchCommand}\x1b[0m");
  198.             Log.Info($"\x1b[92mRunning!\x1b[0m Press Q to quit the application.");
  199.  
  200.             while (true)
  201.             {
  202.                 try
  203.                 {
  204.                     discord.RunCallbacks();
  205.                 }
  206.                 catch (Exception ex)
  207.                 {
  208.                     Log.Error($"RunCallbacks ended with error: {ex.Message}");
  209.                     break;
  210.                 }
  211.  
  212.                 if (Console.KeyAvailable)
  213.                 {
  214.                     var key = Console.ReadKey(true);
  215.                     if (key.Key == ConsoleKey.Q)
  216.                         break;
  217.                 }
  218.                 Thread.Sleep(16);
  219.             }
  220.  
  221.             Console.WriteLine("Program ended. Press any key to quit.");
  222.             Console.ReadKey(true);
  223.         }
  224.  
  225.         // BEGIN Source: https://www.jerriepelser.com/blog/using-ansi-color-codes-in-net-console-apps/
  226.         private const int STD_OUTPUT_HANDLE = -11;
  227.         private const uint ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004;
  228.         private const uint DISABLE_NEWLINE_AUTO_RETURN = 0x0008;
  229.  
  230.         [DllImport("kernel32.dll")]
  231.         private static extern bool GetConsoleMode(IntPtr hConsoleHandle, out uint lpMode);
  232.  
  233.         [DllImport("kernel32.dll")]
  234.         private static extern bool SetConsoleMode(IntPtr hConsoleHandle, uint dwMode);
  235.  
  236.         [DllImport("kernel32.dll", SetLastError = true)]
  237.         private static extern IntPtr GetStdHandle(int nStdHandle);
  238.  
  239.         [DllImport("kernel32.dll")]
  240.         public static extern uint GetLastError();
  241.  
  242.         static void EnableTerminalSequences()
  243.         {
  244.             var iStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
  245.             if (!GetConsoleMode(iStdOut, out uint outConsoleMode))
  246.             {
  247.                 Console.WriteLine("failed to get output console mode");
  248.                 Console.ReadKey();
  249.                 return;
  250.             }
  251.  
  252.             outConsoleMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING | DISABLE_NEWLINE_AUTO_RETURN;
  253.             if (!SetConsoleMode(iStdOut, outConsoleMode))
  254.             {
  255.                 Console.WriteLine($"failed to set output console mode, error code: {GetLastError()}");
  256.                 Console.ReadKey();
  257.                 return;
  258.             }
  259.         }
  260.         // END
  261.     }
  262. }
  263.  
Add Comment
Please, Sign In to add comment