private Discord.Discord _CreateDiscordClient() { var discord = new Discord.Discord(630023869389996044, (long)Discord.CreateFlags.NoRequireDiscord); App.Logger.Info(nameof(DiscordManager), "Discord client created"); discord.SetLogHook(Discord.LogLevel.Debug, (level, message) => { const string LogDomain = nameof(DiscordManager) + "/LogHook"; switch (level) { case Discord.LogLevel.Debug: case Discord.LogLevel.Info: App.Logger.Info(LogDomain, message); break; case Discord.LogLevel.Warn: App.Logger.Warning(LogDomain, message); break; case Discord.LogLevel.Error: App.Logger.Error(LogDomain, message); break; } }); return(discord); }
public static void Init() { try { discord = new Discord.Discord(long.Parse(applicationId), (long)CreateFlags.Default); } catch (Exception e) { if (debugMode) { LogWarning("Expected Error, retrying\n" + e.ToString()); } if (!Failed) { DelayStart(2000); } Failed = true; return; } if (EditorClosed) { EditorClosed = false; lastTimestamp = GetTimestamp(); } projectName = Application.productName; sceneName = EditorSceneManager.GetActiveScene().name; UpdateActivity(); EditorApplication.update += Update; EditorSceneManager.sceneOpened += SceneOpened; EditorApplication.quitting += Quitting; Log("Started!"); }
public static void Initialize() { if (DiscordInstance == null) { try { DiscordInstance = new Discord.Discord(721934748825550931L, (ulong)Discord.CreateFlags.NoRequireDiscord); DiscordInstance.SetLogHook(Discord.LogLevel.Debug, (logLevel, message) => { switch (logLevel) { case Discord.LogLevel.Debug: case Discord.LogLevel.Info: Mod.Logger.Info(message); break; case Discord.LogLevel.Warn: Mod.Logger.Warn(message); break; case Discord.LogLevel.Error: Mod.Logger.Error(message); break; } }); } finally { } } }
public DiscordService( ILogger <DiscordService> logger, Discord.Discord discord) { _logger = logger; _discord = discord; }
private void startDiscord() { //Environment.SetEnvironmentVariable("DISCORD_INSTANCE_ID", "0"); discord = new Discord.Discord(Int64.Parse(clientID), (UInt64)Discord.CreateFlags.NoRequireDiscord); activityManager = discord.GetActivityManager(); activityManager.OnActivityJoinRequest += (ref Discord.User user) => { var reply = lastInput.lobbyIsPrivate ? Discord.ActivityJoinRequestReply.No : Discord.ActivityJoinRequestReply.Yes; activityManager.SendRequestReply(user.Id, reply, (res) => { }); }; activityManager.OnActivityJoin += secret => { if (currentView == "Quiz") { return; } if (lastInput.avatar == null) { return; } var decoded = decodeSecret(secret); if (decoded.id == -1) { toExecute = (decoded.spectateOnly) ? $"roomBrowser.fireSpectateGame(null)" : $"roomBrowser.fireJoinLobby(null)"; } else { toExecute = (decoded.spectateOnly) ? $"roomBrowser.fireSpectateGame({decoded.id}, '{decoded.password}')" : $"roomBrowser.fireJoinLobby({decoded.id}, '{decoded.password}')"; } }; }
static void Init() { if (discord == null) { discord = new Discord.Discord(751435145315221615, (UInt64)Discord.CreateFlags.Default); activityManager = discord.GetActivityManager(); } }
void Awake() { DontDestroyOnLoad(this.gameObject); discord = new Discord.Discord(CLIENT_ID, (UInt64)Discord.CreateFlags.NoRequireDiscord); RefreshAndSendActivity(); SceneManager.activeSceneChanged += SceneManager_activeSceneChanged; }
public void Setup() { try { discord = new(869621858016829561, (UInt64)Discord.CreateFlags.NoRequireDiscord); } catch { Program.Discordstatus = "Discord Intergration Status: Error"; } }
public DiscordBridge Start(long clinetId) { discord = new Discord.Discord(clinetId, (UInt64)Discord.CreateFlags.Default); SetActivity(new DisplayItem() { State = "é–’ç½®ä¸ []~( ̄▽ ̄)~*" }); Task.Run(StartInstance); return(this); }
// Update user's activity for your game. // Party and secrets are vital. // Read https://discordapp.com/developers/docs/rich-presence/how-to for more details. static void UpdateActivity(Discord.Discord discord, Discord.Lobby lobby) { var activityManager = discord.GetActivityManager(); var lobbyManager = discord.GetLobbyManager(); var activity = new Discord.Activity { State = "olleh", Details = "foo details", Timestamps = { Start = 5, End = 6, }, Assets = { LargeImage = "foo largeImageKey", LargeText = "foo largeImageText", SmallImage = "foo smallImageKey", SmallText = "foo smallImageText", }, Party = { Id = lobby.Id.ToString(), Size = { CurrentSize = lobbyManager.MemberCount(lobby.Id), MaxSize = (int)lobby.Capacity, }, }, Secrets = { Join = lobbyManager.GetLobbyActivitySecret(lobby.Id), }, Instance = true, }; activityManager.UpdateActivity(activity, result => { //Console.WriteLine("Update Activity {0}", result); // Send an invite to another user for this activity. // Receiver should see an invite in their DM. // Use a relationship user's ID for this. // activityManager // .SendInvite( // 364843917537050624, // Discord.ActivityActionType.Join, // "", // inviteResult => // { // Console.WriteLine("Invite {0}", inviteResult); // } // ); }); }
public static void Init() { if (Errored && lastSessionID == EditorAnalyticsSessionInfo.id) { if (debugMode) { LogWarning($"Error but in same session"); } return; } if (!DiscordRunning()) { LogWarning("Can't find Discord's Process"); Failed = true; Errored = true; ERPSettings.SaveSettings(); return; } try { discord = new Discord.Discord(long.Parse(applicationId), (long)CreateFlags.Default); } catch (Exception e) { if (debugMode) { LogWarning("Expected Error, retrying\n" + e.ToString()); } if (!Failed) { DelayStart(2000); } Failed = true; return; } if (!resetOnSceneChange || EditorAnalyticsSessionInfo.id != lastSessionID) { lastTimestamp = GetTimestamp(); ERPSettings.SaveSettings(); } lastSessionID = EditorAnalyticsSessionInfo.id; projectName = Application.productName; sceneName = EditorSceneManager.GetActiveScene().name; UpdateActivity(); EditorApplication.update += Update; EditorSceneManager.sceneOpened += SceneOpened; Log("Started!"); }
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(); }
void DestroyDiscord() { if (discord == null) { return; } try { discord.GetActivityManager()?.ClearActivity(_ => { }); discord.RunCallbacks(); } finally { discord.Dispose(); discord = null; } }
public static void Clear() { MainLogic.Log("Disconnecting from discord..."); if (discord != null) { try { discord.Dispose(); } catch { } } discord = null; }
public static void Dispose() { if (_Discord == null) { return; } try { _Discord.GetActivityManager().ClearActivity((result) => { _Discord.Dispose(); _Discord = null; }); } catch { } }
static bool InitDiscord() { try { discord = new Discord.Discord(Int64.Parse(clientID), (UInt64)Discord.CreateFlags.NoRequireDiscord); }catch (Exception e) { if (e.GetType() == typeof(Discord.ResultException)) { return(false); } return(false); } discord.SetLogHook(Discord.LogLevel.Debug, (level, message) => { Debug.Log("Log[" + level + "] " + message); }); var applicationManager = discord.GetApplicationManager(); applicationManager.GetOAuth2Token((Discord.Result result, ref Discord.OAuth2Token oauth2Token) => { Debug.Log("Access Token " + oauth2Token.AccessToken); }); var userManager = discord.GetUserManager(); userManager.OnCurrentUserUpdate += () => { Debug.Log("----------------------------Discord Rich Presence---------------------------"); var currentUser = userManager.GetCurrentUser(); Debug.Log("Username: \"" + currentUser.Username + "\", Id: \"" + currentUser.Id + "\""); Debug.Log("-------------------------------------------------------------------------------"); }; UpdateActivity(); isRunning = true; return(true); }
public static void Initialize() { if (_Discord != null) { return; } try { _Discord = new Discord.Discord(721934748825550931L, (ulong)Discord.CreateFlags.NoRequireDiscord); _Discord.SetLogHook(Discord.LogLevel.Debug, (logLevel, message) => { switch (logLevel) { case Discord.LogLevel.Debug: Mod.Logger.Debug(message); break; case Discord.LogLevel.Info: Mod.Logger.Info(message); break; case Discord.LogLevel.Warn: Mod.Logger.Warn(message); break; case Discord.LogLevel.Error: Mod.Logger.Error(message); break; } }); _Discord.GetUserManager().OnCurrentUserUpdate += () => { Mod.Logger.Debug($"Connected to Discord for Rich Presence."); }; } catch { } }
void CreateDiscord() { if (discord != null) { return; } try { discord = new Discord.Discord(clientId, (ulong)createFlags); discord.GetActivityManager()?.UpdateActivity( new Discord.Activity { Type = Discord.ActivityType.Playing, Assets = new Discord.ActivityAssets { LargeImage = assets.largeImage, LargeText = assets.largeText, }, }, _ => { } ); } catch (Exception) { DestroyDiscord(); } }
public override void Entry(IModHelper helper) { #if DEBUG this.Monitor.Log($"HEY!!! You shouldn't be seeing this!", LogLevel.Alert); this.Monitor.Log($"Unless you're Tortellini... then maybe this should be here", LogLevel.Alert); this.Monitor.Log($"IF YOURE NOT TORTELLINI THEN YELL AT HIM TO BUILD IN RELEASE MODE", LogLevel.Alert); #endif starttime = CurrentTime(); var discord = new Discord.Discord(824160913908039729, (UInt64)Discord.CreateFlags.NoRequireDiscord); modcount = helper.ModRegistry.GetAll().Count(); var Activity = new Discord.Activity { ApplicationId = 824160913908039729, Name = "DewCord Rich Presence", State = $"In a Menu", Details = $"Living the Valley Life", Timestamps = { Start = starttime, }, Assets = { LargeImage = "title_card", LargeText = $"Stardew Valley v{Game1.version}", SmallImage = "placeholder", SmallText = $"Running {modcount} mods", }, Party = { Id = "foo", Size = { CurrentSize = 1, MaxSize = 1, } }, Secrets = { Match = "bar", Join = "baz", Spectate = "foobar", }, Instance = true, }; acc = Activity; var userManager = discord.GetUserManager(); var imageManager = discord.GetImageManager(); var lobbyManager = discord.GetLobbyManager(); var applicationManager = discord.GetApplicationManager(); userManager.OnCurrentUserUpdate += () => { var currentUser = userManager.GetCurrentUser(); this.Monitor.Log($"Discord User: {currentUser.Username}#{currentUser.Discriminator}", LogLevel.Debug); Update(null, null, discord, Activity); //this.Monitor.Log($"Discriminator: {currentUser.Discriminator}", LogLevel.Debug); //this.Monitor.Log($"ID: {currentUser.Id}", LogLevel.Debug); }; helper.Events.GameLoop.DayStarted += this.NewDay; helper.Events.GameLoop.UpdateTicked += (sender, e) => this.Update(sender, e, discord, Activity); helper.Events.GameLoop.ReturnedToTitle += (sender, e) => this.TimesUp(sender, e, discord, Activity); }
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 }
private void _BackgroundLoop() { App.Logger.Info(nameof(DiscordManager), "Background loop started"); try { while (true) { _DisposedTokenSource.Token.ThrowIfCancellationRequested(); var workingVisible = StatusVisible; if (workingVisible != LastStatusVisible) { if (workingVisible) { _Discord?.Dispose(); _Discord = _CreateDiscordClient(); var activity = new Discord.Activity { State = "Optimised PSO2 Patcher", Details = "https://astra.yen.gg", Assets = new Discord.ActivityAssets { LargeImage = "icon-borderless", LargeText = "PSRT Astra" } }; Discord.Result?result = null; _Discord.GetActivityManager().UpdateActivity(activity, res => result = res); while (result == null) { _PollDiscord(_Discord); } if (result == Discord.Result.Ok) { App.Logger.Info(nameof(DiscordManager), "Activity updated"); } else { App.Logger.Info(nameof(DiscordManager), $"Activity update failed: {result}"); } } else if (_Discord != null) { Discord.Result?result = null; _Discord.GetActivityManager().ClearActivity(res => result = res); while (result == null) { _PollDiscord(_Discord); } _Discord.Dispose(); _Discord = null; if (result == Discord.Result.Ok) { App.Logger.Info(nameof(DiscordManager), "Activity cleared"); } else { App.Logger.Info(nameof(DiscordManager), $"Activity clearing failed: {result}"); } } LastStatusVisible = workingVisible; } Thread.Sleep(250); } } catch (OperationCanceledException) { App.Logger.Info(nameof(DiscordManager), "Background loop canceled"); } catch (Exception ex) { App.Logger.Error(nameof(DiscordManager), "Fatal error in background loop", ex); } finally { _Discord?.Dispose(); } }
public static void SecondStart() { discord = new Discord.Discord(658097781482848257, (UInt64)Discord.CreateFlags.Default); DiscordController.Load(); }
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); } }
public void Load(ILua lua, bool is_serverside, ModuleAssemblyLoadContext assembly_context) { lua.PushSpecial(SPECIAL_TABLES.SPECIAL_GLOB); lua.GetField(-1, "print"); lua.PushString("Hello World RPC"); lua.MCall(1, 0); lua.Pop(); int DiscordRPC_update_callbacks(ILua lua) { lua.PushSpecial(SPECIAL_TABLES.SPECIAL_GLOB); lua.GetField(-1, "print"); lua.PushString("It Works!"); lua.MCall(1, 0); lua.Pop(); lua.PushSpecial(SPECIAL_TABLES.SPECIAL_GLOB); lua.GetField(-1, "game"); lua.GetField(-1, "GetMap"); lua.MCall(0, 1); map = lua.GetString(-1); lua.Pop(); lua.PushSpecial(SPECIAL_TABLES.SPECIAL_GLOB); lua.GetField(-1, "game"); lua.GetField(-1, "SinglePlayer"); lua.MCall(0, 1); bool IsSinglePlayer = lua.GetBool(-1); lua.Pop(); lua.PushSpecial(SPECIAL_TABLES.SPECIAL_GLOB); lua.GetField(-1, "engine"); lua.GetField(-1, "ActiveGamemode"); lua.MCall(0, 1); gamemode = lua.GetString(-1); lua.Pop(); if (IsSinglePlayer) { activityDetails = "SinglePlayer"; } else { lua.PushSpecial(SPECIAL_TABLES.SPECIAL_GLOB); lua.GetField(-1, "player"); lua.GetField(-1, "GetCount"); lua.MCall(0, 1); int players = (int)lua.GetNumber(-1); lua.Pop(); lua.PushSpecial(SPECIAL_TABLES.SPECIAL_GLOB); lua.GetField(-1, "game"); lua.GetField(-1, "MaxPlayers"); lua.MCall(0, 1); int maxPlayers = (int)lua.GetNumber(-1); lua.Pop(); activityDetails = $"{players}/{maxPlayers}"; } /*if (!is_serverside) * { * lua.PushSpecial(SPECIAL_TABLES.SPECIAL_GLOB); * lua.GetField(-1, "LocalPlayer"); //team.GetScore(ply:Team()) * lua.MCall(0, 1); * * lua.GetField(-1, "Team"); * lua.Push(-2); * lua.MCall(0, 1); * double team = lua.GetNumber(-1); * lua.Pop(); * * lua.PushSpecial(SPECIAL_TABLES.SPECIAL_GLOB); * lua.GetField(-1, "teams"); * lua.GetField(-1, "GetScore"); * lua.PushNumber(team); * lua.MCall(1, 1); * score = (int)lua.GetNumber(-1); * lua.Pop(); * }*/ UpdateActivity(); return(0); }; lua.PushSpecial(SPECIAL_TABLES.SPECIAL_GLOB); lua.PushManagedFunction(DiscordRPC_update_callbacks); lua.SetField(-2, "DiscordRPC_update_activity"); lua.Pop(1); discord = new Discord.Discord(client_ID, (UInt64)Discord.CreateFlags.Default); discord.SetLogHook(Discord.LogLevel.Debug, (level, message) => { Console.WriteLine("Log[{0}] {1}", level, message); }); var applicationManager = discord.GetApplicationManager(); // Get the current locale. This can be used to determine what text or audio the user wants. Console.WriteLine("Current Locale: {0}", applicationManager.GetCurrentLocale()); // Get the current branch. For example alpha or beta. Console.WriteLine("Current Branch: {0}", applicationManager.GetCurrentBranch()); // If you want to verify information from your game's server then you can // grab the access token and send it to your server. // // This automatically looks for an environment variable passed by the Discord client, // if it does not exist the Discord client will focus itself for manual authorization. // // By-default the SDK grants the identify and rpc scopes. // Read more at https://discordapp.com/developers/docs/topics/oauth2 // applicationManager.GetOAuth2Token((Discord.Result result, ref Discord.OAuth2Token oauth2Token) => // { // Console.WriteLine("Access Token {0}", oauth2Token.AccessToken); // }); var activityManager = discord.GetActivityManager(); var lobbyManager = discord.GetLobbyManager(); // Received when someone accepts a request to join or invite. // Use secrets to receive back the information needed to add the user to the group/party/match activityManager.OnActivityJoin += secret => { Console.WriteLine("OnJoin {0}", secret); lobbyManager.ConnectLobbyWithActivitySecret(secret, (Discord.Result result, ref Discord.Lobby lobby) => { Console.WriteLine("Connected to lobby: {0}", lobby.Id); lobbyManager.ConnectNetwork(lobby.Id); lobbyManager.OpenNetworkChannel(lobby.Id, 0, true); foreach (var user in lobbyManager.GetMemberUsers(lobby.Id)) { lobbyManager.SendNetworkMessage(lobby.Id, user.Id, 0, Encoding.UTF8.GetBytes(String.Format("Hello, {0}!", user.Username))); } UpdateActivity(); }); }; // Received when someone accepts a request to spectate activityManager.OnActivitySpectate += secret => { Console.WriteLine("OnSpectate {0}", secret); }; // A join request has been received. Render the request on the UI. activityManager.OnActivityJoinRequest += (ref Discord.User user) => { Console.WriteLine("OnJoinRequest {0} {1}", user.Id, user.Username); }; // An invite has been received. Consider rendering the user / activity on the UI. activityManager.OnActivityInvite += (Discord.ActivityActionType Type, ref Discord.User user, ref Discord.Activity activity2) => { Console.WriteLine("OnInvite {0} {1} {2}", Type, user.Username, activity2.Name); // activityManager.AcceptInvite(user.Id, result => // { // Console.WriteLine("AcceptInvite {0}", result); // }); }; // This is used to register the game in the registry such that Discord can find it. // This is only needed by games acquired from other platforms, like Steam. // activityManager.RegisterCommand(); var imageManager = discord.GetImageManager(); var userManager = discord.GetUserManager(); lobbyManager.OnLobbyMessage += (lobbyID, userID, data) => { Console.WriteLine("lobby message: {0} {1}", lobbyID, Encoding.UTF8.GetString(data)); }; lobbyManager.OnNetworkMessage += (lobbyId, userId, channelId, data) => { Console.WriteLine("network message: {0} {1} {2} {3}", lobbyId, userId, channelId, Encoding.UTF8.GetString(data)); }; lobbyManager.OnSpeaking += (lobbyID, userID, speaking) => { Console.WriteLine("lobby speaking: {0} {1} {2}", lobbyID, userID, speaking); }; UpdateActivity(); /* * var overlayManager = discord.GetOverlayManager(); * overlayManager.OnOverlayLocked += locked => * { * Console.WriteLine("Overlay Locked: {0}", locked); * }; * overlayManager.SetLocked(false); */ var storageManager = discord.GetStorageManager(); var contents = new byte[20000]; var random = new Random(); random.NextBytes(contents); Console.WriteLine("storage path: {0}", storageManager.GetPath()); storageManager.WriteAsync("foo", contents, res => { var files = storageManager.Files(); foreach (var file in files) { Console.WriteLine("file: {0} size: {1} last_modified: {2}", file.Filename, file.Size, file.LastModified); } storageManager.ReadAsyncPartial("foo", 400, 50, (result, data) => { Console.WriteLine("partial contents of foo match {0}", Enumerable.SequenceEqual(data, new ArraySegment <byte>(contents, 400, 50))); }); storageManager.ReadAsync("foo", (result, data) => { Console.WriteLine("length of contents {0} data {1}", contents.Length, data.Length); Console.WriteLine("contents of foo match {0}", Enumerable.SequenceEqual(data, contents)); Console.WriteLine("foo exists? {0}", storageManager.Exists("foo")); storageManager.Delete("foo"); Console.WriteLine("post-delete foo exists? {0}", storageManager.Exists("foo")); }); }); var storeManager = discord.GetStoreManager(); storeManager.OnEntitlementCreate += (ref Discord.Entitlement entitlement) => { Console.WriteLine("Entitlement Create1: {0}", entitlement.Id); }; // Start a purchase flow. // storeManager.StartPurchase(487507201519255552, result => // { // if (result == Discord.Result.Ok) // { // Console.WriteLine("Purchase Complete"); // } // else // { // Console.WriteLine("Purchase Canceled"); // } // }); // Get all entitlements. storeManager.FetchEntitlements(result => { if (result == Discord.Result.Ok) { foreach (var entitlement in storeManager.GetEntitlements()) { Console.WriteLine("entitlement: {0} - {1} {2}", entitlement.Id, entitlement.Type, entitlement.SkuId); } } }); // Get all SKUs. storeManager.FetchSkus(result => { if (result == Discord.Result.Ok) { foreach (var sku in storeManager.GetSkus()) { Console.WriteLine("sku: {0} - {1} {2}", sku.Name, sku.Price.Amount, sku.Price.Currency); } } }); updater = new Thread(UpdaterThread); updater.Start(); }
public override void OnStart(OnStartProperties onStartProperties) { base.OnStart(onStartProperties); discord = new Discord.Discord(DISCORD_CLIENT_ID, (UInt64)Discord.CreateFlags.Default); discord.SetLogHook(Discord.LogLevel.Debug, (level, message) => { // Console.WriteLine("Log[{0}] {1}", level, message); }); DontDestroyOnLoad(this); applicationManager = discord.GetApplicationManager(); //Console.WriteLine("Current Locale: {0}", applicationManager.GetCurrentLocale()); // Get the current branch. For example alpha or beta. //Console.WriteLine("Current Branch: {0}", applicationManager.GetCurrentBranch()); var activityManager = discord.GetActivityManager(); LobbyManager = discord.GetLobbyManager(); activityManager.OnActivityJoin += secret => { //Console.WriteLine("OnJoin {0}", secret); LobbyManager.ConnectLobbyWithActivitySecret(secret, (Discord.Result result, ref Discord.Lobby lobby) => { //Console.WriteLine("Connected to lobby: {0}", lobby.Id); LobbyManager.ConnectNetwork(lobby.Id); LobbyManager.OpenNetworkChannel(lobby.Id, 0, true); foreach (var user in LobbyManager.GetMemberUsers(lobby.Id)) { LobbyManager.SendNetworkMessage(lobby.Id, user.Id, 0, Encoding.UTF8.GetBytes(string.Format("Hello, {0}!", user.Username))); } UpdateActivity(discord, lobby); }); }; // Received when someone accepts a request to spectate activityManager.OnActivitySpectate += secret => { //Console.WriteLine("OnSpectate {0}", secret); }; // A join request has been received. Render the request on the UI. activityManager.OnActivityJoinRequest += (ref Discord.User user) => { //Console.WriteLine("OnJoinRequest {0} {1}", user.Id, user.Username); }; // An invite has been received. Consider rendering the user / activity on the UI. activityManager.OnActivityInvite += (Discord.ActivityActionType Type, ref Discord.User user, ref Discord.Activity activity2) => { //Console.WriteLine("OnInvite {0} {1} {2}", Type, user.Username, activity2.Name); // activityManager.AcceptInvite(user.Id, result => // { // Console.WriteLine("AcceptInvite {0}", result); // }); }; // This is used to register the game in the registry such that Discord can find it. // This is only needed by games acquired from other platforms, like Steam. // activityManager.RegisterCommand(); var imageManager = discord.GetImageManager(); var userManager = discord.GetUserManager(); // The auth manager fires events as information about the current user changes. // This event will fire once on init. // // GetCurrentUser will error until this fires once. userManager.OnCurrentUserUpdate += () => { var currentUser = userManager.GetCurrentUser(); //Console.WriteLine(currentUser.Username); //Console.WriteLine(currentUser.Id); }; // If you store Discord user ids in a central place like a leaderboard and want to render them. // The users manager can be used to fetch arbitrary Discord users. This only provides basic // information and does not automatically update like relationships. userManager.GetUser(450795363658366976, (Discord.Result result, ref Discord.User user) => { if (result == Discord.Result.Ok) { //Console.WriteLine("user fetched: {0}", user.Username); // Request users's avatar data. // This can only be done after a user is successfully fetched. FetchAvatar(imageManager, user.Id); } else { //Console.WriteLine("user fetch error: {0}", result); } }); var relationshipManager = discord.GetRelationshipManager(); // It is important to assign this handle right away to get the initial relationships refresh. // This callback will only be fired when the whole list is initially loaded or was reset relationshipManager.OnRefresh += () => { // Filter a user's relationship list to be just friends relationshipManager.Filter((ref Discord.Relationship relationship) => { return(relationship.Type == Discord.RelationshipType.Friend); }); // Loop over all friends a user has. //Console.WriteLine("relationships updated: {0}", relationshipManager.Count()); for (uint i = 0; i < Math.Min(relationshipManager.Count(), 10); i++) { // Get an individual relationship from the list var r = relationshipManager.GetAt(i); //Console.WriteLine("relationships: {0} {1} {2} {3}", r.Type, r.User.Username, r.Presence.Status, r.Presence.Activity.Name); // Request relationship's avatar data. FetchAvatar(imageManager, r.User.Id); } }; // All following relationship updates are delivered individually. // These are fired when a user gets a new friend, removes a friend, or a relationship's presence changes. /* * relationshipManager.OnRelationshipUpdate += (ref Discord.Relationship r) => { * Console.WriteLine("relationship updated: {0} {1} {2} {3}", r.Type, r.User.Username, r.Presence.Status, r.Presence.Activity.Name); * }; */ LobbyManager.OnLobbyMessage += (lobbyID, userID, data) => { Console.WriteLine("lobby message: ", lobbyID, data.Length); }; LobbyManager.OnNetworkMessage += (long lobbyId, long userId, byte channelId, byte[] data) => { }; /* * lobbyManager.OnSpeaking += (lobbyID, userID, speaking) => { * Console.WriteLine("lobby speaking: {0} {1} {2}", lobbyID, userID, speaking); * }; */ // Create a lobby. var transaction = LobbyManager.GetLobbyCreateTransaction(); transaction.SetCapacity(20); transaction.SetType(Discord.LobbyType.Public); transaction.SetMetadata("a", "123"); transaction.SetMetadata("a", "456"); transaction.SetMetadata("b", "111"); transaction.SetMetadata("c", "222"); LobbyManager.CreateLobby(transaction, (Discord.Result result, ref Discord.Lobby lobby) => { if (result != Discord.Result.Ok) { return; } var _lobby = lobby; newLobbyListener.ForEach(x => x(_lobby)); // Print all the members of the lobby. foreach (var user in LobbyManager.GetMemberUsers(lobby.Id)) { //Console.WriteLine("lobby member: {0}", user.Username); } // Update lobby. var lobbyTransaction = LobbyManager.GetLobbyUpdateTransaction(lobby.Id); lobbyTransaction.SetMetadata("d", "e"); lobbyTransaction.SetCapacity(16); LobbyManager.UpdateLobby(lobby.Id, lobbyTransaction, (_) => { //Console.WriteLine("lobby has been updated"); }); // Update a member. var lobbyID = lobby.Id; var userID = lobby.OwnerId; var memberTransaction = LobbyManager.GetMemberUpdateTransaction(lobbyID, userID); memberTransaction.SetMetadata("hello", "there"); LobbyManager.UpdateMember(lobbyID, userID, memberTransaction, (_) => { //Console.WriteLine("lobby member has been updated: {0}", lobbyManager.GetMemberMetadataValue(lobbyID, userID, "hello")); }); // Search lobbies. var query = LobbyManager.GetSearchQuery(); // Filter by a metadata value. query.Filter("metadata.a", Discord.LobbySearchComparison.GreaterThan, Discord.LobbySearchCast.Number, "455"); query.Sort("metadata.a", Discord.LobbySearchCast.Number, "0"); // Only return 1 result max. query.Limit(1); LobbyManager.Search(query, (_) => { //Console.WriteLine("search returned {0} lobbies", lobbyManager.LobbyCount()); if (LobbyManager.LobbyCount() == 1) { //Console.WriteLine("first lobby secret: {0}", lobbyManager.GetLobby(lobbyManager.GetLobbyId(0)).Secret); } }); // Connect to voice chat. LobbyManager.ConnectVoice(lobby.Id, (_) => { //Console.WriteLine("Connected to voice chat!"); }); // Setup networking. LobbyManager.ConnectNetwork(lobby.Id); LobbyManager.OpenNetworkChannel(lobby.Id, 0, true); // Update activity. UpdateActivity(discord, lobby); }); /* * var overlayManager = discord.GetOverlayManager(); * overlayManager.OnOverlayLocked += locked => * { * Console.WriteLine("Overlay Locked: {0}", locked); * }; * overlayManager.SetLocked(false); */ /* * var storageManager = discord.GetStorageManager(); * var contents = new byte[20000]; * var random = new Random(); * random.NextBytes(contents); * Console.WriteLine("storage path: {0}", storageManager.GetPath()); * storageManager.WriteAsync("foo", contents, res => { * var files = storageManager.Files(); * foreach (var file in files) { * Console.WriteLine("file: {0} size: {1} last_modified: {2}", file.Filename, file.Size, file.LastModified); * } * storageManager.ReadAsyncPartial("foo", 400, 50, (result, data) => { * Console.WriteLine("partial contents of foo match {0}", Enumerable.SequenceEqual(data, new ArraySegment<byte>(contents, 400, 50))); * }); * storageManager.ReadAsync("foo", (result, data) => { * Console.WriteLine("length of contents {0} data {1}", contents.Length, data.Length); * Console.WriteLine("contents of foo match {0}", Enumerable.SequenceEqual(data, contents)); * Console.WriteLine("foo exists? {0}", storageManager.Exists("foo")); * storageManager.Delete("foo"); * Console.WriteLine("post-delete foo exists? {0}", storageManager.Exists("foo")); * }); * }); * */ var storeManager = discord.GetStoreManager(); storeManager.OnEntitlementCreate += (ref Discord.Entitlement entitlement) => { Console.WriteLine("Entitlement Create1: {0}", entitlement.Id); }; // Start a purchase flow. // storeManager.StartPurchase(487507201519255552, result => // { // if (result == Discord.Result.Ok) // { // Console.WriteLine("Purchase Complete"); // } // else // { // Console.WriteLine("Purchase Canceled"); // } // }); // Get all entitlements. storeManager.FetchEntitlements(result => { if (result == Discord.Result.Ok) { foreach (var entitlement in storeManager.GetEntitlements()) { //Console.WriteLine("entitlement: {0} - {1} {2}", entitlement.Id, entitlement.Type, entitlement.SkuId); } } }); // Get all SKUs. storeManager.FetchSkus(result => { if (result == Discord.Result.Ok) { foreach (var sku in storeManager.GetSkus()) { //Console.WriteLine("sku: {0} - {1} {2}", sku.Name, sku.Price.Amount, sku.Price.Currency); } } }); }
private void TimesUp(object sender, ReturnedToTitleEventArgs e, Discord.Discord discord, Discord.Activity acc) { Update(null, null, discord, acc); }
private void _PollDiscord(Discord.Discord discord) { _DisposedTokenSource.Token.ThrowIfCancellationRequested(); discord.RunCallbacks(); Thread.Sleep(250); }
public static void Init() { if (Errored && lastSessionID == EditorAnalyticsSessionInfo.id) { if (DebugMode) { LogWarning($"Error but in same session"); } return; } if (!DiscordRunning()) { LogWarning("Can't find Discord's Process"); Failed = true; Errored = true; ERPSettings.SaveSettings(); return; } try { if (discord == null) { Log("Creating new discord"); discord = new Discord.Discord(long.Parse(_applicationId), (long)CreateFlags.NoRequireDiscord); } else { Log("Discord isn't null but we are trying to creating a new one"); } } catch (Exception e) { if (DebugMode) { LogWarning($"Expected Error, retrying\n{e}"); } if (!Failed) { DelayStart(2000); } Failed = true; return; } if (!ResetOnSceneChange || EditorAnalyticsSessionInfo.id != lastSessionID) { lastTimestamp = GetTimestamp(); ERPSettings.SaveSettings(); } lastSessionID = EditorAnalyticsSessionInfo.id; GetNames(); UpdateActivity(); EditorApplication.update += Update; EditorSceneManager.sceneOpened += SceneOpened; Log("Started!"); if (ERPWindow.Window != null) { ERPWindow.Window.Repaint(); } }
public TpwRpc() { discord = new Discord.Discord(784571542221750283, (ulong)Discord.CreateFlags.Default); }