Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Threading;
- using System.Collections.Generic;
- using System.Runtime.InteropServices;
- namespace DiscordRegisterCommand
- {
- class Log
- {
- public static void Info(string s)
- {
- Console.WriteLine($"[{DateTime.Now:HH:mm:ss.ff} \x1b[97mINF\x1b[0m] \x1b[97m{s}\x1b[0m");
- }
- public static void Warn(string s)
- {
- Console.WriteLine($"[{DateTime.Now:HH:mm:ss.ff} \x1b[95mWARN\x1b[0m] \x1b[97m{s}\x1b[0m");
- }
- public static void Error(string s)
- {
- Console.WriteLine($"[{DateTime.Now:HH:mm:ss.ff} \x1b[91mERROR\x1b[0m] \x1b[97m{s}\x1b[0m");
- }
- }
- class Program
- {
- static void UpdateActivity(Discord.Discord discord, Discord.Lobby lobby)
- {
- var activityManager = discord.GetActivityManager();
- var lobbyManager = discord.GetLobbyManager();
- var activity = new Discord.Activity
- {
- State = "State",
- Details = "Details",
- Timestamps =
- {
- Start = DateTimeOffset.Now.ToUnixTimeSeconds()
- },
- Party =
- {
- Id = lobby.Id.ToString(),
- Size =
- {
- CurrentSize = lobbyManager.MemberCount(lobby.Id),
- MaxSize = (int)lobby.Capacity,
- },
- },
- Secrets = {
- Join = lobbyManager.GetLobbyActivitySecret(lobby.Id),
- },
- Instance = true,
- };
- Log.Info($"Updating activity...");
- activityManager.UpdateActivity(activity, result =>
- {
- if (result == Discord.Result.Ok)
- Log.Info($"Update activity successful");
- else
- Log.Warn($"Update activity returned result {result}");
- });
- }
- static string FormatLobbyId(long id)
- {
- return $"{id}";
- }
- static string FormatUserId(long id)
- {
- return $"{id}";
- }
- static string FormatTimestamp(string timestamp)
- {
- timestamp = timestamp.Substring(0, 11) + "\x1b[96m" + timestamp.Substring(11, 8) + "\x1b[97m" + timestamp.Substring(19);
- return timestamp;
- }
- static void Main(string[] args)
- {
- EnableTerminalSequences();
- // Provide one in code
- long clientId = -1;
- // ... or have it prompted.
- if (clientId == -1)
- {
- Console.Write("Enter clientId: ");
- string clientIdStr = Console.ReadLine();
- clientId = long.Parse(clientIdStr);
- }
- Console.WriteLine("Enter 0 below if you have only one Discord client.");
- Console.Write("DISCORD_INSTANCE_ID: ");
- string instanceID = Console.ReadLine();
- Environment.SetEnvironmentVariable("DISCORD_INSTANCE_ID", instanceID);
- Discord.Discord discord;
- try
- {
- discord = new Discord.Discord(clientId, (ulong)Discord.CreateFlags.Default);
- }
- catch (Exception ex)
- {
- Console.WriteLine($"Error initializing Discord hook: {ex}");
- Console.WriteLine("Press any key to quit");
- Console.ReadKey(true);
- return;
- }
- discord.SetLogHook(Discord.LogLevel.Debug, (level, message) =>
- {
- switch (level)
- {
- case Discord.LogLevel.Error:
- Log.Error($"Discord: {message}");
- break;
- case Discord.LogLevel.Warn:
- Log.Warn($"Discord: {message}");
- break;
- case Discord.LogLevel.Info:
- Log.Info($"Discord: {message}");
- break;
- default:
- Log.Info($"Discord ({level}): {message}");
- break;
- }
- });
- var lobbyManager = discord.GetLobbyManager();
- var userManager = discord.GetUserManager();
- var activityManager = discord.GetActivityManager();
- Dictionary<long, Discord.Lobby> lobbies = new Dictionary<long, Discord.Lobby>();
- userManager.OnCurrentUserUpdate += () =>
- {
- var user = userManager.GetCurrentUser();
- Log.Info($"Current user: {user.Username} ({FormatUserId(user.Id)})");
- };
- if (args.Length >= 1)
- {
- Log.Info("Launched from Discord.");
- Log.Info($"Registered time is {FormatTimestamp(args[0])}");
- }
- else
- {
- Log.Info("Not launched from Discord.");
- }
- string startupTime = DateTimeOffset.Now.ToString("o");
- Log.Info($"Startup time is {FormatTimestamp(startupTime)}");
- string exePath = System.Reflection.Assembly.GetEntryAssembly().Location;
- if (exePath.EndsWith(".dll"))
- exePath = exePath.Substring(0, exePath.LastIndexOf(".dll")) + ".exe";
- Log.Info($"Exe path is {exePath}");
- Discord.LobbyTransaction tr = lobbyManager.GetLobbyCreateTransaction();
- tr.SetCapacity(5);
- tr.SetType(Discord.LobbyType.Private);
- //tr.SetMetadata("InitTime", startupTime);
- lobbyManager.CreateLobby(tr, (Discord.Result res, ref Discord.Lobby lobby) =>
- {
- Log.Info($"Created lobby {FormatLobbyId(lobby.Id)}");// with InitTime {lobbyManager.GetLobbyMetadataValue(lobby.Id, "InitTime")}");
- lobbies[lobby.Id] = lobby;
- UpdateActivity(discord, lobby);
- });
- activityManager.OnActivityJoin += (string secret) =>
- {
- Log.Info($"Joining lobby...");
- lobbyManager.ConnectLobbyWithActivitySecret(secret, (Discord.Result res, ref Discord.Lobby lobby) =>
- {
- Log.Info($"Joined lobby {FormatLobbyId(lobby.Id)}");
- lobbies[lobby.Id] = lobby;
- UpdateActivity(discord, lobby);
- });
- };
- lobbyManager.OnMemberConnect += (long lobbyId, long userId) =>
- {
- Log.Info($"User {FormatUserId(userId)} joined lobby {FormatLobbyId(lobbyId)}");
- if (lobbies.TryGetValue(lobbyId, out Discord.Lobby lobby))
- UpdateActivity(discord, lobby);
- };
- string launchCommand = $"\"{exePath}\" {startupTime}";
- activityManager.RegisterCommand(launchCommand);
- Log.Info($"RegisterCommand issued with argument \x1b[93m{launchCommand}\x1b[0m");
- Log.Info($"\x1b[92mRunning!\x1b[0m Press Q to quit the application.");
- while (true)
- {
- try
- {
- discord.RunCallbacks();
- }
- catch (Exception ex)
- {
- Log.Error($"RunCallbacks ended with error: {ex.Message}");
- break;
- }
- if (Console.KeyAvailable)
- {
- var key = Console.ReadKey(true);
- if (key.Key == ConsoleKey.Q)
- break;
- }
- Thread.Sleep(16);
- }
- Console.WriteLine("Program ended. Press any key to quit.");
- Console.ReadKey(true);
- }
- // BEGIN Source: https://www.jerriepelser.com/blog/using-ansi-color-codes-in-net-console-apps/
- private const int STD_OUTPUT_HANDLE = -11;
- private const uint ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004;
- private const uint DISABLE_NEWLINE_AUTO_RETURN = 0x0008;
- [DllImport("kernel32.dll")]
- private static extern bool GetConsoleMode(IntPtr hConsoleHandle, out uint lpMode);
- [DllImport("kernel32.dll")]
- private static extern bool SetConsoleMode(IntPtr hConsoleHandle, uint dwMode);
- [DllImport("kernel32.dll", SetLastError = true)]
- private static extern IntPtr GetStdHandle(int nStdHandle);
- [DllImport("kernel32.dll")]
- public static extern uint GetLastError();
- static void EnableTerminalSequences()
- {
- var iStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
- if (!GetConsoleMode(iStdOut, out uint outConsoleMode))
- {
- Console.WriteLine("failed to get output console mode");
- Console.ReadKey();
- return;
- }
- outConsoleMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING | DISABLE_NEWLINE_AUTO_RETURN;
- if (!SetConsoleMode(iStdOut, outConsoleMode))
- {
- Console.WriteLine($"failed to set output console mode, error code: {GetLastError()}");
- Console.ReadKey();
- return;
- }
- }
- // END
- }
- }
Add Comment
Please, Sign In to add comment