public void SetAmount(UserDataModel user, int amount) { RankModel prevRank = this.GetRank(user); user.CurrencyAmounts[this.ID] = Math.Min(Math.Max(amount, 0), this.MaxAmount); if (ChannelSession.Settings != null) { ChannelSession.Settings.UserData.ManualValueChanged(user.ID); } RankModel newRank = this.GetRank(user); UserViewModel userViewModel = ChannelSession.Services.User.GetUserByID(user.ID); if (userViewModel == null) { userViewModel = new UserViewModel(user); } if (newRank.Amount > prevRank.Amount && this.RankChangedCommand != null) { AsyncRunner.RunAsyncBackground((cancellationToken) => this.RankChangedCommand.Perform(new CommandParametersModel(userViewModel)), new CancellationToken()); } else if (newRank.Amount < prevRank.Amount && this.RankDownCommand != null) { AsyncRunner.RunAsyncBackground((cancellationToken) => this.RankDownCommand.Perform(new CommandParametersModel(userViewModel)), new CancellationToken()); } }
protected override async Task <Result> InitializeInternal() { this.cancellationTokenSource = new CancellationTokenSource(); this.startTime = DateTimeOffset.Now; this.user = await this.GetCurrentAccount(); if (this.user != null) { if (!string.IsNullOrEmpty(ChannelSession.Settings.JustGivingPageShortName)) { IEnumerable <JustGivingFundraiser> fundraisers = await this.GetCurrentFundraisers(); this.fundraiser = fundraisers.FirstOrDefault(f => f.pageShortName.Equals(ChannelSession.Settings.JustGivingPageShortName)); } #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed AsyncRunner.RunAsyncBackground(this.BackgroundDonationCheck, this.cancellationTokenSource.Token, 60000); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed this.TrackServiceTelemetry("JustGiving"); return(new Result()); } return(new Result(Resources.JustGivingUserDataFailed)); }
protected override async Task <Result> InitializeInternal() { this.cancellationTokenSource = new CancellationTokenSource(); this.team = await this.GetTeam(); this.participant = await this.GetParticipant(); if (this.team != null && this.participant != null) { IEnumerable <ExtraLifeDonation> donations = (ChannelSession.Settings.ExtraLifeIncludeTeamDonations) ? await this.GetTeamDonations() : await this.GetParticipantDonations(); foreach (ExtraLifeDonation donation in donations) { if (!string.IsNullOrEmpty(donation.donationID)) { donationsReceived[donation.donationID] = donation; } } #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed AsyncRunner.RunAsyncBackground(this.BackgroundDonationCheck, this.cancellationTokenSource.Token, 60000); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed this.TrackServiceTelemetry("ExtraLife"); return(new Result()); } return(new Result("Could not get Team/Participant data")); }
public async Task <Result> Connect() { try { this.IsConnected = false; ChannelSession.Settings.EnableOverlay = false; foreach (var kvp in this.AllOverlayNameAndPorts) { if (!await this.AddOverlay(kvp.Key, kvp.Value)) { await this.Disconnect(); return(new Result(string.Format(Resources.OverlayAddFailed, kvp.Key))); } } #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed AsyncRunner.RunAsyncBackground(this.WidgetsBackgroundUpdate, this.backgroundThreadCancellationTokenSource.Token, 1000); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed this.IsConnected = true; ChannelSession.Settings.EnableOverlay = true; ChannelSession.Services.Telemetry.TrackService("Overlay"); return(new Result()); } catch (Exception ex) { Logger.Log(ex); return(new Result(ex.ToString())); } }
protected override async Task <Result> InitializeInternal() { this.cancellationTokenSource = new CancellationTokenSource(); this.user = await this.GetCurrentUser(); if (this.user != null) { this.Campaign = await this.GetCampaign(); if (this.Campaign != null) { try { this.members = new List <PatreonCampaignMember>(await this.GetCampaignMembers()); foreach (PatreonCampaignMember member in this.members) { this.currentMembersAndTiers[member.UserID] = member.TierID; } } catch (Exception ex) { Logger.Log(ex); } #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed AsyncRunner.RunAsyncBackground(this.BackgroundDonationCheck, this.cancellationTokenSource.Token, 60000); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed this.TrackServiceTelemetry("Patreon"); return(new Result()); } return(new Result(Resources.PatreonCampaignDataFailed)); } return(new Result(Resources.PatreonUserDataFailed)); }
private void RestartTossTime() { if (this.lastHitCancellationTokenSource != null) { this.lastHitCancellationTokenSource.Cancel(); this.lastHitCancellationTokenSource = null; } this.lastHitCancellationTokenSource = new CancellationTokenSource(); #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed AsyncRunner.RunAsyncBackground(async(token) => { await DelayNoThrow(1000 * RandomHelper.GenerateRandomNumber(this.LowerTimeLimit, this.UpperTimeLimit), token); if (this.gameActive && !token.IsCancellationRequested) { this.gameActive = false; this.SetGameWinners(this.lastTossParameters, new List <CommandParametersModel>() { this.lastTossParameters }); await this.RunSubCommand(this.PotatoExplodeCommand, this.lastTossParameters); await this.PerformCooldown(this.lastTossParameters); this.ClearData(); } }, this.lastHitCancellationTokenSource.Token); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed }
public async Task <Result> ConnectUser() { if (ChannelSession.TwitchUserConnection != null) { return(await this.AttemptConnect((Func <Task <Result> >)(async() => { try { this.cancellationTokenSource = new CancellationTokenSource(); this.userClient = new ChatClient(ChannelSession.TwitchUserConnection.Connection); if (ChannelSession.AppSettings.DiagnosticLogging) { this.userClient.OnSentOccurred += Client_OnSentOccurred; } this.initialUserLogins.Clear(); this.userClient.OnPacketReceived += Client_OnPacketReceived; this.userClient.OnDisconnectOccurred += UserClient_OnDisconnectOccurred; this.userClient.OnPingReceived += UserClient_OnPingReceived; this.userClient.OnUserJoinReceived += UserClient_OnUserJoinReceived; this.userClient.OnUserLeaveReceived += UserClient_OnUserLeaveReceived; this.userClient.OnUserStateReceived += UserClient_OnUserStateReceived; this.userClient.OnUserNoticeReceived += UserClient_OnUserNoticeReceived; this.userClient.OnChatClearReceived += UserClient_OnChatClearReceived; this.userClient.OnMessageReceived += UserClient_OnMessageReceived; this.userClient.OnUserListReceived += UserClient_OnUserListReceived; await this.userClient.Connect(); await Task.Delay(1000); await this.userClient.AddCommandsCapability(); await this.userClient.AddTagsCapability(); await this.userClient.AddMembershipCapability(); await Task.Delay(1000); await this.userClient.Join((UserModel)ChannelSession.TwitchUserNewAPI); #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed AsyncRunner.RunAsyncBackground(this.ChatterJoinLeaveBackground, this.cancellationTokenSource.Token, 2500); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed await Task.Delay(3000); return new Result(); } catch (Exception ex) { Logger.Log(ex); return new Result(ex); } }))); } return(new Result(Resources.TwitchConnectionFailed)); }
public void BackgroundConnect() { AsyncRunner.RunAsyncBackground(async(cancellationToken) => { Result result = await this.Connect(); if (!result.Success) { SignalRConnection_Disconnected(this, new Exception()); } }, new CancellationToken()); }
public async Task Initialize() { if (!this.isInitialized) { this.isInitialized = true; GlobalEvents.OnChatMessageReceived += GlobalEvents_OnChatMessageReceived; await this.RebuildTimerGroups(); #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed AsyncRunner.RunAsyncBackground(this.TimerCommandsBackground, this.backgroundThreadCancellationTokenSource.Token, 60000); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed } }
public override async Task CustomRun(CommandParametersModel parameters) { this.TotalAmount += this.GetPrimaryBetAmount(parameters); parameters.SpecialIdentifiers[GameCommandModelBase.GameTotalAmountSpecialIdentifier] = this.TotalAmount.ToString(); if (this.TotalAmount >= this.Stage3MinimumAmount) { if (this.GenerateProbability() <= this.PayoutProbability) { this.collectUsers.Add(parameters.User); int payout = this.GenerateRandomNumber(this.TotalAmount, this.PayoutMinimumPercentage / 100.0d, this.PayoutMaximumPercentage / 100.0d); this.PerformPrimarySetPayout(parameters.User, payout); this.SetGameWinners(parameters, new List <CommandParametersModel>() { parameters }); parameters.SpecialIdentifiers[GameCommandModelBase.GamePayoutSpecialIdentifier] = payout.ToString(); #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed AsyncRunner.RunAsyncBackground(async(cancellationToken) => { this.collectActive = true; await DelayNoThrow(this.CollectTimeLimit * 1000, cancellationToken); this.ClearData(); }, new CancellationToken()); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed await this.RunSubCommand(this.PayoutCommand, parameters); } else { await this.RunSubCommand(this.Stage3DepositCommand, parameters); } } else if (this.TotalAmount >= this.Stage2MinimumAmount) { await this.RunSubCommand(this.Stage2DepositCommand, parameters); } else { await this.RunSubCommand(this.Stage1DepositCommand, parameters); } await this.PerformCooldown(parameters); ChannelSession.Settings.Commands.ManualValueChanged(this.ID); }
protected override async Task <Result> InitializeInternal() { this.cancellationTokenSource = new CancellationTokenSource(); this.user = await this.GetUser(); if (this.user != null) { #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed AsyncRunner.RunAsyncBackground(this.BackgroundDonationCheck, this.cancellationTokenSource.Token, 60000); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed this.TrackServiceTelemetry("Tiltify"); return(new Result()); } return(new Result(Resources.TiltifyUserDataFailed)); }
public static async Task ProcessDownloadedCommunityCommand(CommunityCommandDetailsViewModel command) { if (bool.Equals(await DialogHelper.ShowCustom(new CommandImporterDialogControl(command.PrimaryCommand)), true)) { if (!CommunityCommandsControl.downloadedCommandsCache.Contains(command.ID)) { CommunityCommandsControl.downloadedCommandsCache.Add(command.ID); #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed AsyncRunner.RunAsyncBackground(async(cancellationToken) => { await ChannelSession.Services.CommunityCommandsService.DownloadCommand(command.ID); }, new CancellationToken()); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed } } }
public void AddAmount(UserDataModel user, int amount) { if (!user.IsCurrencyRankExempt && amount > 0) { int currentLevel = this.GetLevel(user); this.SetAmount(user, this.GetAmount(user) + amount); int newLevel = this.GetLevel(user); if (newLevel > currentLevel) { for (int level = (currentLevel + 1); level <= newLevel; level++) { Dictionary <string, string> specialIdentifiers = new Dictionary <string, string>() { { this.UserLevelSpecialIdentifier, level.ToString() } }; CommandModelBase command = null; if (this.CustomLevelUpCommands.ContainsKey(level)) { command = ChannelSession.Settings.GetCommand(this.CustomLevelUpCommands[level]); } if (command == null && this.DefaultLevelUpCommand != null && this.DefaultLevelUpCommand.IsEnabled) { command = this.DefaultLevelUpCommand; } if (command != null) { UserViewModel userViewModel = ChannelSession.Services.User.GetActiveUserByID(user.ID); if (userViewModel == null) { userViewModel = new UserViewModel(user); } AsyncRunner.RunAsyncBackground((cancellationToken) => ChannelSession.Services.Command.Queue(command, new CommandParametersModel(userViewModel, specialIdentifiers: specialIdentifiers)), new CancellationToken()); } } } } }
protected override async Task <bool> ValidateRequirements(CommandParametersModel parameters) { if (this.gameActive) { return(await base.ValidateRequirements(parameters)); } else { if (parameters.User.HasPermissionsTo(this.StarterRole)) { this.gameActive = true; this.lastBidAmount = this.GetPrimaryCurrencyRequirement().GetAmount(parameters); this.runParameters = parameters; this.runParameters.SpecialIdentifiers[GameCommandModelBase.GameBetSpecialIdentifier] = this.lastBidAmount.ToString(); #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed AsyncRunner.RunAsyncBackground(async(cancellationToken) => { await DelayNoThrow(this.TimeLimit * 1000, cancellationToken); if (this.lastBidParameters != null) { await this.GameCompleteCommand.Perform(this.lastBidParameters); } else { await this.NotEnoughPlayersCommand.Perform(this.runParameters); } await this.PerformCooldown(this.runParameters); this.ClearData(); }, new CancellationToken()); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed await this.StartedCommand.Perform(this.runParameters); return(false); } await ChannelSession.Services.Chat.SendMessage(string.Format(MixItUp.Base.Resources.RoleErrorInsufficientRole, this.StarterRole)); } return(false); }
public override async Task <Result> CustomValidation(CommandParametersModel parameters) { if (!this.gameActive) { if (parameters.User.HasPermissionsTo(this.StarterRole)) { this.gameActive = true; this.lastBidAmount = this.GetPrimaryCurrencyRequirement()?.GetAmount(parameters) ?? 0; this.runParameters = parameters; this.runParameters.SpecialIdentifiers[GameCommandModelBase.GameBetSpecialIdentifier] = this.lastBidAmount.ToString(); #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed AsyncRunner.RunAsyncBackground(async(cancellationToken) => { await DelayNoThrow(this.TimeLimit * 1000, cancellationToken); if (this.lastBidParameters != null) { this.SetGameWinners(this.lastBidParameters, new List <CommandParametersModel>() { this.lastBidParameters }); await this.RunSubCommand(this.GameCompleteCommand, this.lastBidParameters); } else { await this.RunSubCommand(this.NotEnoughPlayersCommand, this.runParameters); } await this.PerformCooldown(this.runParameters); this.ClearData(); }, new CancellationToken()); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed await this.RunSubCommand(this.StartedCommand, this.runParameters); return(new Result(success: false)); } return(new Result(string.Format(MixItUp.Base.Resources.RoleErrorInsufficientRole, this.StarterRole))); } return(new Result()); }
public Command Run(Guid commandID, [FromBody] IEnumerable <string> arguments) { CommandModelBase selectedCommand = FindCommand(commandID, out string category); if (selectedCommand == null) { var resp = new HttpResponseMessage(HttpStatusCode.NotFound) { Content = new ObjectContent <Error>(new Error { Message = $"Unable to find command: {commandID.ToString()}." }, new JsonMediaTypeFormatter(), "application/json"), ReasonPhrase = "Command ID not found" }; throw new HttpResponseException(resp); } AsyncRunner.RunAsyncBackground((cancellationToken) => ChannelSession.Services.Command.Queue(selectedCommand, new CommandParametersModel(user: null, arguments)), new CancellationToken()); return(CommandFromCommandBase(selectedCommand, category)); }
protected override async Task <Result> InitializeInternal() { this.channel = await this.GetCurrentChannel(); if (this.channel != null) { foreach (StreamElementsDonation seDonation in await this.GetDonations()) { donationsReceived[seDonation._id] = seDonation; } #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed AsyncRunner.RunAsyncBackground(this.BackgroundDonationCheck, this.cancellationTokenSource.Token, 60000); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed this.TrackServiceTelemetry("StreamElements"); return(new Result()); } return(new Result("Failed to get user information")); }
public override async Task CustomRun(CommandParametersModel parameters) { await this.RefundCooldown(parameters); await this.SetSelectedUser(this.PlayerSelectionType, parameters); if (parameters.TargetUser != null) { if (await this.ValidateTargetUserPrimaryBetAmount(parameters)) { this.runParameters = parameters; this.runCancellationTokenSource = new CancellationTokenSource(); #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed AsyncRunner.RunAsyncBackground(async(cancellationToken) => { await DelayNoThrow(this.TimeLimit * 1000, cancellationToken); if (this.gameActive && cancellationToken != null && !cancellationToken.IsCancellationRequested) { this.gameActive = false; await this.RunSubCommand(this.NotAcceptedCommand, parameters); await this.Requirements.Refund(parameters); await this.PerformCooldown(parameters); } this.ClearData(); }, this.runCancellationTokenSource.Token); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed this.gameActive = true; await this.RunSubCommand(this.StartedCommand, parameters); return; } } else { await ChannelSession.Services.Chat.SendMessage(MixItUp.Base.Resources.GameCommandCouldNotFindUser); } await this.Requirements.Refund(parameters); }
public override async Task Enable() { if (this.FollowBonus > 0.0) { GlobalEvents.OnFollowOccurred += GlobalEvents_OnFollowOccurred; } if (this.HostBonus > 0.0) { GlobalEvents.OnHostOccurred += GlobalEvents_OnHostOccurred; } if (this.RaidBonus > 0.0) { GlobalEvents.OnRaidOccurred += GlobalEvents_OnRaidOccurred; } if (this.SubscriberBonus > 0.0) { GlobalEvents.OnSubscribeOccurred += GlobalEvents_OnSubscribeOccurred; GlobalEvents.OnResubscribeOccurred += GlobalEvents_OnResubscribeOccurred; GlobalEvents.OnSubscriptionGiftedOccurred += GlobalEvents_OnSubscriptionGiftedOccurred; } if (this.DonationBonus > 0.0) { GlobalEvents.OnDonationOccurred += GlobalEvents_OnDonationOccurred; } if (this.BitsBonus > 0.0) { GlobalEvents.OnBitsOccurred += GlobalEvents_OnBitsOccurred; } this.timeLeft = 0; this.stackedTime = 0; this.backgroundThreadCancellationTokenSource = new CancellationTokenSource(); #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed AsyncRunner.RunAsyncBackground(this.TimerBackground, this.backgroundThreadCancellationTokenSource.Token, 1000); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed await base.Enable(); }
public async Task Initialize(ITwitchChatService twitchChatService) { this.RebuildCommandTriggers(); await ChannelSession.Services.FileService.CreateDirectory(ChatEventLogDirectoryName); this.currentChatEventLogFilePath = Path.Combine(ChatEventLogDirectoryName, string.Format(ChatEventLogFileNameFormat, DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss", CultureInfo.InvariantCulture))); if (twitchChatService != null) { this.TwitchChatService = twitchChatService; this.TwitchChatService.OnMessageOccurred += TwitchChatService_OnMessageOccurred; this.TwitchChatService.OnUsersJoinOccurred += TwitchChatService_OnUsersJoinOccurred; this.TwitchChatService.OnUsersLeaveOccurred += TwitchChatService_OnUsersLeaveOccurred; await this.TwitchChatService.Initialize(); } #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed AsyncRunner.RunAsyncBackground(this.ProcessHoursCurrency, this.cancellationTokenSource.Token, 60000); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed }
private async Task <T> OBSCommandTimeoutWrapper <T>(Func <CancellationToken, T> function, int timeout = CommandTimeoutInMilliseconds) { CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); Task <T> task = AsyncRunner.RunAsyncBackground(function, cancellationTokenSource.Token); Task delay = Task.Delay(timeout); await Task.WhenAny(new Task[] { task, delay }); if (task.IsCompleted) { return(task.Result); } else { cancellationTokenSource.Cancel(); #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed AsyncRunner.RunAsyncBackground((cancellationToken) => { this.OBSWebsocket_Disconnected(this, new EventArgs()); return(true); }, new CancellationToken()); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed return(default(T)); } }
public static async Task <bool> InitializeSession() { try { TwitchNewAPI.Users.UserModel twitchChannelNew = await ChannelSession.TwitchUserConnection.GetNewAPICurrentUser(); TwitchV5API.Channel.ChannelModel twitchChannelv5 = await ChannelSession.TwitchUserConnection.GetCurrentV5APIChannel(); if (twitchChannelNew != null && twitchChannelv5 != null) { try { ChannelSession.TwitchUserNewAPI = twitchChannelNew; ChannelSession.TwitchChannelV5 = twitchChannelv5; ChannelSession.TwitchStreamNewAPI = await ChannelSession.TwitchUserConnection.GetStream(ChannelSession.TwitchUserNewAPI); ChannelSession.TwitchStreamV5 = await ChannelSession.TwitchUserConnection.GetV5LiveStream(ChannelSession.TwitchChannelV5); if (ChannelSession.Settings == null) { IEnumerable <SettingsV3Model> currentSettings = await ChannelSession.Services.Settings.GetAllSettings(); if (currentSettings.Any(s => !string.IsNullOrEmpty(s.StreamingPlatformAuthentications[StreamingPlatformTypeEnum.Twitch].ChannelID) && string.Equals(s.StreamingPlatformAuthentications[StreamingPlatformTypeEnum.Twitch].ChannelID, twitchChannelNew.id))) { GlobalEvents.ShowMessageBox(string.Format(Resources.TwitchAccountExists, twitchChannelNew.login)); return(false); } ChannelSession.Settings = await ChannelSession.Services.Settings.Create(twitchChannelNew.display_name); } else if (ChannelSession.Settings.StreamingPlatformAuthentications.ContainsKey(StreamingPlatformTypeEnum.Twitch) && !string.IsNullOrEmpty(ChannelSession.Settings.StreamingPlatformAuthentications[StreamingPlatformTypeEnum.Twitch].UserID) && !string.Equals(ChannelSession.TwitchUserNewAPI.id, ChannelSession.Settings.StreamingPlatformAuthentications[StreamingPlatformTypeEnum.Twitch].UserID)) { Logger.Log(LogLevel.Error, $"Signed in account does not match settings account: {ChannelSession.TwitchUserNewAPI.login} - {ChannelSession.TwitchUserNewAPI.id} - {ChannelSession.Settings.StreamingPlatformAuthentications[StreamingPlatformTypeEnum.Twitch].UserID}"); GlobalEvents.ShowMessageBox(Resources.TwitchAccountMismatch); ChannelSession.Settings.StreamingPlatformAuthentications[StreamingPlatformTypeEnum.Twitch].UserOAuthToken = null; return(false); } await ChannelSession.Services.Settings.Initialize(ChannelSession.Settings); ChannelSession.Settings.Name = ChannelSession.TwitchUserNewAPI.display_name; ChannelSession.Settings.StreamingPlatformAuthentications[StreamingPlatformTypeEnum.Twitch].UserID = ChannelSession.TwitchUserNewAPI.id; ChannelSession.Settings.StreamingPlatformAuthentications[StreamingPlatformTypeEnum.Twitch].ChannelID = ChannelSession.TwitchUserNewAPI.id; if (ChannelSession.TwitchBotNewAPI != null) { ChannelSession.Settings.StreamingPlatformAuthentications[StreamingPlatformTypeEnum.Twitch].BotID = ChannelSession.TwitchBotNewAPI.id; } } catch (Exception ex) { Logger.Log(ex); Logger.Log(LogLevel.Error, "Initialize Settings - " + JSONSerializerHelper.SerializeToString(ex)); await DialogHelper.ShowMessage(Resources.FailedToInitializeSettings + Environment.NewLine + Environment.NewLine + Resources.ErrorDetailsHeader + " " + ex.Message); return(false); } try { await ChannelSession.Services.Telemetry.Connect(); ChannelSession.Services.Telemetry.SetUserID(ChannelSession.Settings.TelemetryUserID); TwitchChatService twitchChatService = new TwitchChatService(); TwitchEventService twitchEventService = new TwitchEventService(); List <Task <Result> > twitchPlatformServiceTasks = new List <Task <Result> >(); twitchPlatformServiceTasks.Add(twitchChatService.ConnectUser()); twitchPlatformServiceTasks.Add(twitchEventService.Connect()); await Task.WhenAll(twitchPlatformServiceTasks); if (twitchPlatformServiceTasks.Any(c => !c.Result.Success)) { string errors = string.Join(Environment.NewLine, twitchPlatformServiceTasks.Where(c => !c.Result.Success).Select(c => c.Result.Message)); GlobalEvents.ShowMessageBox(Resources.TwitchFailed + Environment.NewLine + Environment.NewLine + errors); return(false); } await ChannelSession.Services.Chat.Initialize(twitchChatService); await ChannelSession.Services.Events.Initialize(twitchEventService); } catch (Exception ex) { Logger.Log(ex); Logger.Log(LogLevel.Error, "Twitch Services - " + JSONSerializerHelper.SerializeToString(ex)); await DialogHelper.ShowMessage(Resources.FailedToConnectToTwitch + Environment.NewLine + Environment.NewLine + Resources.ErrorDetailsHeader + " " + ex.Message); return(false); } Result result = await ChannelSession.InitializeBotInternal(); if (!result.Success) { await DialogHelper.ShowMessage(Resources.FailedToInitializeBotAccount); return(false); } try { // Connect External Services Dictionary <IExternalService, OAuthTokenModel> externalServiceToConnect = new Dictionary <IExternalService, OAuthTokenModel>(); if (ChannelSession.Settings.StreamlabsOAuthToken != null) { externalServiceToConnect[ChannelSession.Services.Streamlabs] = ChannelSession.Settings.StreamlabsOAuthToken; } if (ChannelSession.Settings.StreamElementsOAuthToken != null) { externalServiceToConnect[ChannelSession.Services.StreamElements] = ChannelSession.Settings.StreamElementsOAuthToken; } if (ChannelSession.Settings.RainMakerOAuthToken != null) { externalServiceToConnect[ChannelSession.Services.Rainmaker] = ChannelSession.Settings.RainMakerOAuthToken; } if (ChannelSession.Settings.TipeeeStreamOAuthToken != null) { externalServiceToConnect[ChannelSession.Services.TipeeeStream] = ChannelSession.Settings.TipeeeStreamOAuthToken; } if (ChannelSession.Settings.TreatStreamOAuthToken != null) { externalServiceToConnect[ChannelSession.Services.TreatStream] = ChannelSession.Settings.TreatStreamOAuthToken; } if (ChannelSession.Settings.StreamlootsOAuthToken != null) { externalServiceToConnect[ChannelSession.Services.Streamloots] = ChannelSession.Settings.StreamlootsOAuthToken; } if (ChannelSession.Settings.TiltifyOAuthToken != null) { externalServiceToConnect[ChannelSession.Services.Tiltify] = ChannelSession.Settings.TiltifyOAuthToken; } if (ChannelSession.Settings.JustGivingOAuthToken != null) { externalServiceToConnect[ChannelSession.Services.JustGiving] = ChannelSession.Settings.JustGivingOAuthToken; } if (ChannelSession.Settings.IFTTTOAuthToken != null) { externalServiceToConnect[ChannelSession.Services.IFTTT] = ChannelSession.Settings.IFTTTOAuthToken; } if (ChannelSession.Settings.ExtraLifeTeamID > 0) { externalServiceToConnect[ChannelSession.Services.ExtraLife] = new OAuthTokenModel(); } if (ChannelSession.Settings.PatreonOAuthToken != null) { externalServiceToConnect[ChannelSession.Services.Patreon] = ChannelSession.Settings.PatreonOAuthToken; } if (ChannelSession.Settings.DiscordOAuthToken != null) { externalServiceToConnect[ChannelSession.Services.Discord] = ChannelSession.Settings.DiscordOAuthToken; } if (ChannelSession.Settings.TwitterOAuthToken != null) { externalServiceToConnect[ChannelSession.Services.Twitter] = ChannelSession.Settings.TwitterOAuthToken; } if (ChannelSession.Settings.PixelChatOAuthToken != null) { externalServiceToConnect[ChannelSession.Services.PixelChat] = ChannelSession.Settings.PixelChatOAuthToken; } if (ChannelSession.Settings.VTubeStudioOAuthToken != null) { externalServiceToConnect[ChannelSession.Services.VTubeStudio] = ChannelSession.Settings.VTubeStudioOAuthToken; } if (ChannelSession.Settings.EnableVoicemodStudio) { externalServiceToConnect[ChannelSession.Services.Voicemod] = null; } if (ChannelSession.Services.OBSStudio.IsEnabled) { externalServiceToConnect[ChannelSession.Services.OBSStudio] = null; } if (ChannelSession.Services.StreamlabsOBS.IsEnabled) { externalServiceToConnect[ChannelSession.Services.StreamlabsOBS] = null; } if (ChannelSession.Services.XSplit.IsEnabled) { externalServiceToConnect[ChannelSession.Services.XSplit] = null; } if (!string.IsNullOrEmpty(ChannelSession.Settings.OvrStreamServerIP)) { externalServiceToConnect[ChannelSession.Services.OvrStream] = null; } if (ChannelSession.Settings.EnableOverlay) { externalServiceToConnect[ChannelSession.Services.Overlay] = null; } if (ChannelSession.Settings.EnableDeveloperAPI) { externalServiceToConnect[ChannelSession.Services.DeveloperAPI] = null; } if (externalServiceToConnect.Count > 0) { Dictionary <IExternalService, Task <Result> > externalServiceTasks = new Dictionary <IExternalService, Task <Result> >(); foreach (var kvp in externalServiceToConnect) { Logger.Log(LogLevel.Debug, "Trying automatic OAuth service connection: " + kvp.Key.Name); try { if (kvp.Key is IOAuthExternalService && kvp.Value != null) { externalServiceTasks[kvp.Key] = ((IOAuthExternalService)kvp.Key).Connect(kvp.Value); } else { externalServiceTasks[kvp.Key] = kvp.Key.Connect(); } } catch (Exception sex) { Logger.Log(LogLevel.Error, "Error in external service initial connection: " + kvp.Key.Name); Logger.Log(sex); } } try { await Task.WhenAll(externalServiceTasks.Values); } catch (Exception sex) { Logger.Log(LogLevel.Error, "Error in batch external service connection"); Logger.Log(sex); } List <IExternalService> failedServices = new List <IExternalService>(); foreach (var kvp in externalServiceTasks) { try { if (kvp.Value.Result != null && !kvp.Value.Result.Success && kvp.Key is IOAuthExternalService) { Logger.Log(LogLevel.Debug, "Automatic OAuth token connection failed, trying manual connection: " + kvp.Key.Name); result = await kvp.Key.Connect(); if (!result.Success) { failedServices.Add(kvp.Key); } } } catch (Exception sex) { Logger.Log(LogLevel.Error, "Error in external service failed re-connection: " + kvp.Key.Name); Logger.Log(sex); failedServices.Add(kvp.Key); } } if (failedServices.Count > 0) { Logger.Log(LogLevel.Debug, "Connection failed for services: " + string.Join(", ", failedServices.Select(s => s.Name))); StringBuilder message = new StringBuilder(); message.AppendLine("The following services could not be connected:"); message.AppendLine(); foreach (IExternalService service in failedServices) { message.AppendLine(" - " + service.Name); } message.AppendLine(); message.Append("We will attempt to re-connect with the service when possible. If this continues, please go to the Services page to reconnect them manually."); await DialogHelper.ShowMessage(message.ToString()); } } } catch (Exception ex) { Logger.Log(ex); Logger.Log(LogLevel.Error, "External Services - " + JSONSerializerHelper.SerializeToString(ex)); await DialogHelper.ShowMessage(Resources.FailedToInitializeExternalServices + Environment.NewLine + Environment.NewLine + Resources.ErrorDetailsHeader + " " + ex.Message); return(false); } try { ChannelSession.Services.WebhookService.BackgroundConnect(); foreach (CurrencyModel currency in ChannelSession.Settings.Currency.Values) { if (currency.ShouldBeReset()) { await currency.Reset(); } } if (ChannelSession.Settings.ModerationResetStrikesOnLaunch) { foreach (UserDataModel userData in ChannelSession.Settings.UserData.Values) { if (userData.ModerationStrikes > 0) { userData.ModerationStrikes = 0; ChannelSession.Settings.UserData.ManualValueChanged(userData.ID); } } } await ChannelSession.Services.Command.Initialize(); await ChannelSession.Services.Timers.Initialize(); await ChannelSession.Services.Moderation.Initialize(); IEnumerable <TwitchV5API.Users.UserModel> channelEditors = await ChannelSession.TwitchUserConnection.GetV5APIChannelEditors(ChannelSession.TwitchChannelV5); if (channelEditors != null) { foreach (TwitchV5API.Users.UserModel channelEditor in channelEditors) { ChannelSession.TwitchChannelEditorsV5.Add(channelEditor.id); } } } catch (Exception ex) { Logger.Log(ex); Logger.Log(LogLevel.Error, "Streamer Services - " + JSONSerializerHelper.SerializeToString(ex)); await DialogHelper.ShowMessage(Resources.FailedToInitializeStreamerBasedServices + Environment.NewLine + Environment.NewLine + Resources.ErrorDetailsHeader + " " + ex.Message); return(false); } try { ChannelSession.Services.Statistics.Initialize(); ChannelSession.Services.InputService.HotKeyPressed += InputService_HotKeyPressed; foreach (RedemptionStoreProductModel product in ChannelSession.Settings.RedemptionStoreProducts.Values) { product.ReplenishAmount(); } foreach (RedemptionStorePurchaseModel purchase in ChannelSession.Settings.RedemptionStorePurchases.ToList()) { if (purchase.State != RedemptionStorePurchaseRedemptionState.ManualRedeemNeeded) { ChannelSession.Settings.RedemptionStorePurchases.Remove(purchase); } } ChannelSession.Services.Telemetry.TrackLogin(ChannelSession.Settings.TelemetryUserID, ChannelSession.TwitchUserNewAPI?.broadcaster_type); await ChannelSession.SaveSettings(); await ChannelSession.Services.Settings.SaveLocalBackup(ChannelSession.Settings); if (!await ChannelSession.Services.Settings.PerformAutomaticBackupIfApplicable(ChannelSession.Settings)) { await DialogHelper.ShowMessage(Resources.AutomaticBackupFailedToCreate); } #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed AsyncRunner.RunAsyncBackground(SessionBackgroundTask, sessionBackgroundCancellationTokenSource.Token, 60000); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed } catch (Exception ex) { Logger.Log(ex); Logger.Log(LogLevel.Error, "Finalize Initialization - " + JSONSerializerHelper.SerializeToString(ex)); await DialogHelper.ShowMessage(Resources.FailedToFinalizeInitialization + Environment.NewLine + Environment.NewLine + Resources.ErrorDetailsHeader + " " + ex.Message); return(false); } return(true); } } catch (Exception ex) { Logger.Log(ex); Logger.Log(LogLevel.Error, "Channel Information - " + JSONSerializerHelper.SerializeToString(ex)); await DialogHelper.ShowMessage(Resources.FailedToGetChannelInformation + Environment.NewLine + Environment.NewLine + Resources.ErrorDetailsHeader + " " + ex.Message); } return(false); }
public override async Task CustomRun(CommandParametersModel parameters) { await this.RefundCooldown(parameters); var lastTargetUser = this.lastTossParameters?.TargetUser; if (this.gameActive && lastTargetUser != parameters.User) { // The game is underway and it's not the user's turn await ChannelSession.Services.Chat.SendMessage(MixItUp.Base.Resources.GameCommandAlreadyUnderway); await this.Requirements.Refund(parameters); return; } await this.SetSelectedUser(this.PlayerSelectionType, parameters); if (parameters.TargetUser != null) { if (this.startParameters == null) { this.gameActive = true; this.startParameters = parameters; if (this.ResetTimeOnToss) { this.RestartTossTime(); } else { #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed AsyncRunner.RunAsyncBackground(async(token) => { await DelayNoThrow(1000 * RandomHelper.GenerateRandomNumber(this.LowerTimeLimit, this.UpperTimeLimit), token); this.gameActive = false; this.SetGameWinners(this.lastTossParameters, new List <CommandParametersModel>() { this.lastTossParameters }); await this.RunSubCommand(this.PotatoExplodeCommand, this.lastTossParameters); await this.PerformCooldown(this.startParameters); this.ClearData(); }, new CancellationToken()); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed } await this.RunSubCommand(this.StartedCommand, parameters); } else { if (this.ResetTimeOnToss) { this.RestartTossTime(); } await this.RunSubCommand(this.TossPotatoCommand, parameters); } this.lastTossParameters = parameters; return; } else { await ChannelSession.Services.Chat.SendMessage(MixItUp.Base.Resources.GameCommandCouldNotFindUser); } await this.Requirements.Refund(parameters); }
public async Task <Result> Connect() { this.IsConnected = false; if (ChannelSession.TwitchUserConnection != null) { return(await this.AttemptConnect((Func <Task <Result> >)(async() => { try { this.pubSub = new PubSubClient(ChannelSession.TwitchUserConnection.Connection); if (ChannelSession.AppSettings.DiagnosticLogging) { this.pubSub.OnSentOccurred += PubSub_OnSentOccurred; this.pubSub.OnTextReceivedOccurred += PubSub_OnTextReceivedOccurred; this.pubSub.OnMessageReceived += PubSub_OnMessageReceived; } this.pubSub.OnReconnectReceived += PubSub_OnReconnectReceived; this.pubSub.OnDisconnectOccurred += PubSub_OnDisconnectOccurred; this.pubSub.OnPongReceived += PubSub_OnPongReceived; this.pubSub.OnResponseReceived += PubSub_OnResponseReceived; this.pubSub.OnWhisperReceived += PubSub_OnWhisperReceived; this.pubSub.OnBitsV2Received += PubSub_OnBitsV2Received; this.pubSub.OnSubscribedReceived += PubSub_OnSubscribedReceived; this.pubSub.OnSubscriptionsGiftedReceived += PubSub_OnSubscriptionsGiftedReceived; this.pubSub.OnChannelPointsRedeemed += PubSub_OnChannelPointsRedeemed; await this.pubSub.Connect(); await Task.Delay(1000); List <PubSubListenTopicModel> topics = new List <PubSubListenTopicModel>(); foreach (PubSubTopicsEnum topic in TwitchEventService.topicTypes) { topics.Add(new PubSubListenTopicModel(topic, (string)ChannelSession.TwitchUserNewAPI.id)); } await this.pubSub.Listen(topics); await Task.Delay(1000); await this.pubSub.Ping(); this.cancellationTokenSource = new CancellationTokenSource(); #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed AsyncRunner.RunAsyncBackground(this.BackgroundEventChecks, this.cancellationTokenSource.Token, 60000); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed this.IsConnected = true; return new Result(); } catch (Exception ex) { Logger.Log(ex); return new Result(ex); } }))); } return(new Result("Twitch connection has not been established")); }
public async Task PerformTradeCommand(UserViewModel user, IEnumerable <string> arguments = null, StreamingPlatformTypeEnum platform = StreamingPlatformTypeEnum.None) { try { if (ChannelSession.Services.Chat != null && arguments != null) { if (this.tradeReceiver == null && arguments.Count() >= 2) { UserViewModel targetUser = await SpecialIdentifierStringBuilder.GetUserFromArgument(arguments.First(), platform); if (targetUser == null) { await ChannelSession.Services.Chat.SendMessage("The specified user does not exist"); return; } int amount = 1; IEnumerable <string> itemArgs = arguments.Skip(1); InventoryItemModel item = this.GetItem(string.Join(" ", itemArgs)); if (item == null && itemArgs.Count() > 1) { itemArgs = itemArgs.Take(itemArgs.Count() - 1); item = this.GetItem(string.Join(" ", itemArgs)); if (item != null) { if (!int.TryParse(arguments.Last(), out amount) || amount <= 0) { await ChannelSession.Services.Chat.SendMessage("A valid amount greater than 0 must be specified"); return; } } } if (item == null) { await ChannelSession.Services.Chat.SendMessage("The item you specified does not exist"); return; } if (!this.HasAmount(user.Data, item, amount)) { await ChannelSession.Services.Chat.SendMessage(string.Format("You do not have the required {0} {1} to trade", amount, item.Name)); return; } this.tradeSender = new InventoryTradeModel() { User = user, Item = item, Amount = amount }; this.tradeReceiver = new InventoryTradeModel() { User = targetUser }; this.tradeTimeCheckToken = new CancellationTokenSource(); #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed AsyncRunner.RunAsyncBackground(async(token) => { await Task.Delay(60000); if (!token.IsCancellationRequested) { this.tradeSender = null; this.tradeReceiver = null; this.tradeTimeCheckToken = null; await ChannelSession.Services.Chat.SendMessage("The trade could not be completed in time and was cancelled..."); } }, this.tradeTimeCheckToken.Token); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed await ChannelSession.Services.Chat.SendMessage(string.Format("@{0} has started a trade with @{1} for {2} {3}. Type {4} <ITEM NAME> [AMOUNT] in chat to reply back with your offer in the next 60 seconds.", this.tradeSender.User.Username, this.tradeReceiver.User.Username, this.tradeSender.Amount, this.tradeSender.Item.Name, this.TradeCommand)); return; } else if (this.tradeSender != null && this.tradeReceiver != null && this.tradeReceiver.User.Equals(user) && this.tradeReceiver.Amount == 0 && arguments.Count() >= 1) { int amount = 1; IEnumerable <string> itemArgs = arguments.ToList(); InventoryItemModel item = this.GetItem(string.Join(" ", itemArgs)); if (item == null && itemArgs.Count() > 1) { itemArgs = itemArgs.Take(itemArgs.Count() - 1); item = this.GetItem(string.Join(" ", itemArgs)); if (item != null) { if (!int.TryParse(arguments.Last(), out amount) || amount <= 0) { await ChannelSession.Services.Chat.SendMessage("A valid amount greater than 0 must be specified"); return; } } } if (item == null) { await ChannelSession.Services.Chat.SendMessage("The item you specified does not exist"); return; } if (!this.HasAmount(user.Data, item, amount)) { await ChannelSession.Services.Chat.SendMessage(string.Format("You do not have the required {0} {1} to trade", amount, item.Name)); return; } this.tradeReceiver.Item = item; this.tradeReceiver.Amount = amount; await ChannelSession.Services.Chat.SendMessage(string.Format("@{0} has replied back to the offer by @{1} with {2} {3}. Type {4} in chat to accept the trade.", this.tradeReceiver.User.Username, this.tradeSender.User.Username, this.tradeReceiver.Amount, this.tradeReceiver.Item.Name, this.TradeCommand)); return; } else if (this.tradeSender != null && this.tradeReceiver != null && this.tradeReceiver.Amount > 0 && this.tradeSender.User.Equals(user)) { int senderItemMaxAmount = (this.tradeReceiver.Item.HasMaxAmount) ? this.tradeReceiver.Item.MaxAmount : this.DefaultMaxAmount; if ((this.GetAmount(this.tradeSender.User.Data, this.tradeReceiver.Item) + this.tradeReceiver.Amount) > senderItemMaxAmount) { await ChannelSession.Services.Chat.SendMessage(string.Format("You can only have {0} {1} in total", senderItemMaxAmount, this.tradeReceiver.Item.Name)); return; } int receiverItemMaxAmount = (this.tradeSender.Item.HasMaxAmount) ? this.tradeSender.Item.MaxAmount : this.DefaultMaxAmount; if ((this.GetAmount(this.tradeReceiver.User.Data, this.tradeSender.Item) + this.tradeSender.Amount) > receiverItemMaxAmount) { await ChannelSession.Services.Chat.SendMessage(string.Format("You can only have {0} {1} in total", receiverItemMaxAmount, this.tradeSender.Item.Name)); return; } this.SubtractAmount(this.tradeSender.User.Data, this.tradeSender.Item, this.tradeSender.Amount); this.AddAmount(this.tradeReceiver.User.Data, this.tradeSender.Item, this.tradeSender.Amount); this.SubtractAmount(this.tradeReceiver.User.Data, this.tradeReceiver.Item, this.tradeReceiver.Amount); this.AddAmount(this.tradeSender.User.Data, this.tradeReceiver.Item, this.tradeReceiver.Amount); if (this.ItemsTradedCommand != null) { Dictionary <string, string> specialIdentifiers = new Dictionary <string, string>(); specialIdentifiers["itemtotal"] = this.tradeSender.Amount.ToString(); specialIdentifiers["itemname"] = this.tradeSender.Item.Name; specialIdentifiers["targetitemtotal"] = this.tradeReceiver.Amount.ToString(); specialIdentifiers["targetitemname"] = this.tradeReceiver.Item.Name; await this.ItemsTradedCommand.Perform(new CommandParametersModel(user, arguments : new string[] { this.tradeReceiver.User.Username }, specialIdentifiers : specialIdentifiers)); } this.tradeSender = null; this.tradeReceiver = null; this.tradeTimeCheckToken.Cancel(); this.tradeTimeCheckToken = null; return; } else if (this.tradeSender != null && this.tradeReceiver != null && !this.tradeReceiver.User.Equals(user)) { await ChannelSession.Services.Chat.SendMessage("A trade is already underway, please wait until it is completed"); return; } } await ChannelSession.Services.Chat.SendMessage(this.TradeCommand + " <USERNAME> <ITEM NAME> [AMOUNT] = Trades 1 or the amount specified of the item to the specified user"); } catch (Exception ex) { Logger.Log(ex); } }
public override async Task CustomRun(CommandParametersModel parameters) { await this.RefundCooldown(parameters); if (string.IsNullOrEmpty(this.runWord)) { this.runWord = await this.GetRandomWord(this.CustomWordsFilePath); this.runBetAmount = this.GetPrimaryBetAmount(parameters); this.runParameters = parameters; this.runUsers[parameters.User] = parameters; this.GetPrimaryCurrencyRequirement()?.SetTemporaryAmount(this.runBetAmount); this.runCancellationTokenSource = new CancellationTokenSource(); #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed AsyncRunner.RunAsyncBackground(async(cancellationToken) => { await DelayNoThrow(this.TimeLimit * 1000, cancellationToken); if (cancellationToken != null && cancellationToken.IsCancellationRequested) { return; } this.runParameters.SpecialIdentifiers[WordScrambleGameCommandModel.GameWordScrambleAnswerSpecialIdentifier] = this.runWord; this.runParameters.SpecialIdentifiers[WordScrambleGameCommandModel.GameWordScrambleWordSpecialIdentifier] = this.runWordScrambled = this.runWord.Shuffle(); if (this.runUsers.Count < this.MinimumParticipants) { await this.RunSubCommand(this.NotEnoughPlayersCommand, this.runParameters); foreach (var kvp in this.runUsers.ToList()) { await this.Requirements.Refund(kvp.Value); } await this.PerformCooldown(this.runParameters); this.ClearData(); return; } await this.RunSubCommand(this.WordScramblePrepareCommand, this.runParameters); await DelayNoThrow(5000, cancellationToken); if (cancellationToken != null && cancellationToken.IsCancellationRequested) { return; } GlobalEvents.OnChatMessageReceived += GlobalEvents_OnChatMessageReceived; await this.RunSubCommand(this.WordScrambleBeginCommand, this.runParameters); await DelayNoThrow(this.WordScrambleTimeLimit * 1000, cancellationToken); if (cancellationToken != null && cancellationToken.IsCancellationRequested) { return; } GlobalEvents.OnChatMessageReceived -= GlobalEvents_OnChatMessageReceived; if (!string.IsNullOrEmpty(this.runWord)) { await this.RunSubCommand(this.UserFailureCommand, this.runParameters); await this.PerformCooldown(this.runParameters); } this.ClearData(); }, this.runCancellationTokenSource.Token); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed await this.RunSubCommand(this.StartedCommand, this.runParameters); await this.RunSubCommand(this.UserJoinCommand, this.runParameters); return; } else if (!this.runUsers.ContainsKey(parameters.User)) { this.runUsers[parameters.User] = parameters; await this.RunSubCommand(this.UserJoinCommand, parameters); return; } else { await ChannelSession.Services.Chat.SendMessage(MixItUp.Base.Resources.GameCommandAlreadyUnderway); } await this.Requirements.Refund(parameters); }
public override async Task CustomRun(CommandParametersModel parameters) { await this.RefundCooldown(parameters); if (this.runParameters == null) { this.runBetAmount = this.GetPrimaryBetAmount(parameters); this.runParameters = parameters; this.runUsers[parameters.User] = parameters; this.GetPrimaryCurrencyRequirement()?.SetTemporaryAmount(this.runBetAmount); #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed AsyncRunner.RunAsyncBackground(async(cancellationToken) => { await DelayNoThrow(this.TimeLimit * 1000, cancellationToken); if (this.runUsers.Count < this.MinimumParticipants) { await this.RunSubCommand(this.NotEnoughPlayersCommand, this.runParameters); foreach (var kvp in this.runUsers.ToList()) { await this.Requirements.Refund(kvp.Value); } await this.PerformCooldown(this.runParameters); this.ClearData(); return; } IEnumerable <CommandParametersModel> shuffledParticipants = this.runUsers.Values.Shuffle(); this.runUserTypes[shuffledParticipants.ElementAt(0).User] = WinLosePlayerType.King; double thiefDecimalPercentage = ((double)this.ThiefPlayerPercentage) / 100.0; int totalThieves = (int)Math.Ceiling(thiefDecimalPercentage * (double)shuffledParticipants.Count()); foreach (CommandParametersModel participant in shuffledParticipants.Skip(1).Take(totalThieves)) { this.runUserTypes[participant.User] = WinLosePlayerType.Thief; } foreach (CommandParametersModel participant in shuffledParticipants.Skip(1 + totalThieves)) { this.runUserTypes[participant.User] = WinLosePlayerType.Knight; } foreach (CommandParametersModel participant in shuffledParticipants) { if (this.runUserTypes[participant.User] == WinLosePlayerType.Thief) { await this.RunSubCommand(this.ThiefUserCommand, participant); } else if (this.runUserTypes[participant.User] == WinLosePlayerType.Thief) { await this.RunSubCommand(this.ThiefUserCommand, participant); } } await this.RunSubCommand(this.KingUserCommand, shuffledParticipants.ElementAt(0)); await DelayNoThrow(this.KingTimeLimit * 1000, cancellationToken); if (this.gameActive && this.runParameters != null) { await this.PerformCooldown(this.runParameters); this.ClearData(); } this.gameActive = false; }, new CancellationToken()); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed this.gameActive = true; await this.RunSubCommand(this.StartedCommand, this.runParameters); await this.RunSubCommand(this.UserJoinCommand, this.runParameters); return; } else if (this.runParameters != null) { if (this.runUserTypes.Count > 0 && this.runUserTypes[parameters.User] == WinLosePlayerType.King) { await parameters.SetTargetUser(); if (parameters.TargetUser != null && this.runUserTypes.ContainsKey(parameters.TargetUser)) { this.gameActive = false; WinLosePlayerType selectedType = (this.runUserTypes[parameters.TargetUser] == WinLosePlayerType.Knight) ? WinLosePlayerType.Knight : WinLosePlayerType.Thief; var winners = (selectedType == WinLosePlayerType.Knight) ? this.runUserTypes.Where(kvp => kvp.Value != WinLosePlayerType.Thief) : this.runUserTypes.Where(kvp => kvp.Value == WinLosePlayerType.Thief); IEnumerable <CommandParametersModel> winnerParameters = winners.Select(kvp => this.runUsers[kvp.Key]); int payout = this.runBetAmount * this.runUsers.Count; int individualPayout = payout / winnerParameters.Count(); foreach (CommandParametersModel winner in winnerParameters) { this.PerformPrimarySetPayout(winner.User, individualPayout); } parameters.SpecialIdentifiers[GameCommandModelBase.GamePayoutSpecialIdentifier] = individualPayout.ToString(); parameters.SpecialIdentifiers[GameCommandModelBase.GameAllPayoutSpecialIdentifier] = payout.ToString(); this.SetGameWinners(this.runParameters, winnerParameters); if (selectedType == WinLosePlayerType.Knight) { await this.RunSubCommand(this.KnightSelectedCommand, parameters); } else { await this.RunSubCommand(this.ThiefSelectedCommand, parameters); } await this.PerformCooldown(this.runParameters); this.ClearData(); } else { await ChannelSession.Services.Chat.SendMessage(MixItUp.Base.Resources.GameCommandCouldNotFindUser); } } else if (!this.runUsers.ContainsKey(parameters.User)) { this.runUsers[parameters.User] = parameters; await this.RunSubCommand(this.UserJoinCommand, parameters); return; } } else { await ChannelSession.Services.Chat.SendMessage(MixItUp.Base.Resources.GameCommandAlreadyUnderway); } await this.Requirements.Refund(parameters); }
public override async Task <Result> CustomValidation(CommandParametersModel parameters) { this.SetPrimaryCurrencyRequirementArgumentIndex(argumentIndex: 1); if (this.gameActive) { if (this.betsClosed) { if (parameters.User.HasPermissionsTo(this.StarterRole)) { // At least to arguments // 1st must be "answer" // 2nd must be a number from 1 to option count if (parameters.Arguments.Count == 2 && string.Equals(parameters.Arguments[0], MixItUp.Base.Resources.Answer, StringComparison.CurrentCultureIgnoreCase) && int.TryParse(parameters.Arguments[1], out int answer) && answer > 0 && answer <= this.BetOptions.Count) { this.gameActive = false; this.betsClosed = false; GameOutcomeModel winningOutcome = this.BetOptions[answer - 1]; List <CommandParametersModel> winners = new List <CommandParametersModel>(this.runUserSelections.Where(kvp => kvp.Value == answer).Select(kvp => this.runUsers[kvp.Key])); this.SetGameWinners(this.runParameters, winners); this.runParameters.SpecialIdentifiers[BetGameCommandModel.GameBetWinningOptionSpecialIdentifier] = winningOutcome.Name; await this.RunSubCommand(this.GameCompleteCommand, this.runParameters); foreach (CommandParametersModel winner in winners) { winner.SpecialIdentifiers[BetGameCommandModel.GameBetWinningOptionSpecialIdentifier] = winningOutcome.Name; await this.RunOutcome(winner, winningOutcome); } await this.PerformCooldown(this.runParameters); this.ClearData(); return(new Result(success: false)); } else { string trigger = this.GetFullTriggers().FirstOrDefault() ?? "!bet"; return(new Result(string.Format(MixItUp.Base.Resources.GameCommandBetAnswerExample, trigger))); } } else { return(new Result(string.Format(MixItUp.Base.Resources.RoleErrorInsufficientRole, this.StarterRole))); } } else if (parameters.Arguments.Count == 0 || !int.TryParse(parameters.Arguments[0], out int choice) || choice <= 0 || choice > this.BetOptions.Count) { return(new Result(string.Format(MixItUp.Base.Resources.GameCommandBetInvalidSelection, parameters.User.Username))); } } else { if (parameters.User.HasPermissionsTo(this.StarterRole)) { this.gameActive = true; this.runParameters = parameters; int i = 1; List <string> betOptions = new List <string>(); foreach (GameOutcomeModel betOption in this.BetOptions) { betOptions.Add($"{i}) {betOption.Name}"); i++; } this.runParameters.SpecialIdentifiers[BetGameCommandModel.GameBetOptionsSpecialIdentifier] = string.Join(", ", betOptions); #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed AsyncRunner.RunAsyncBackground(async(cancellationToken) => { await DelayNoThrow(this.TimeLimit * 1000, cancellationToken); if (this.runUsers.Count < this.MinimumParticipants) { await this.RunSubCommand(this.NotEnoughPlayersCommand, this.runParameters); foreach (var kvp in this.runUsers.ToList()) { await this.Requirements.Refund(kvp.Value); } await this.PerformCooldown(this.runParameters); this.ClearData(); return; } this.betsClosed = true; await this.RunSubCommand(this.BetsClosedCommand, this.runParameters); }, new CancellationToken()); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed await this.RunSubCommand(this.StartedCommand, parameters); return(new Result(success: false)); } return(new Result(string.Format(MixItUp.Base.Resources.RoleErrorInsufficientRole, this.StarterRole))); } return(new Result()); }
public override async Task CustomRun(CommandParametersModel parameters) { this.runParameters = parameters; bool useCustomQuestion = (RandomHelper.GenerateProbability() >= 50); if (this.CustomQuestions.Count > 0 && !this.UseRandomOnlineQuestions) { useCustomQuestion = true; } else if (this.CustomQuestions.Count == 0 && this.UseRandomOnlineQuestions) { useCustomQuestion = false; } if (!useCustomQuestion) { using (AdvancedHttpClient client = new AdvancedHttpClient()) { OpenTDBResults openTDBResults = await client.GetAsync <OpenTDBResults>(OpenTDBUrl); if (openTDBResults != null && openTDBResults.results != null && openTDBResults.results.Count > 0) { List <string> answers = new List <string>(); answers.Add(HttpUtility.HtmlDecode(openTDBResults.results[0].correct_answer)); answers.AddRange(openTDBResults.results[0].incorrect_answers.Select(a => HttpUtility.HtmlDecode(a))); this.question = new TriviaGameQuestionModel() { Question = HttpUtility.HtmlDecode(openTDBResults.results[0].question), Answers = answers, }; } } } if (this.CustomQuestions.Count > 0 && (useCustomQuestion || this.question == null)) { this.question = this.CustomQuestions.Random(); } if (this.question == null) { this.question = FallbackQuestion; } int i = 1; foreach (string answer in this.question.Answers.Shuffle()) { this.numbersToAnswers[i] = answer; i++; } int correctAnswerNumber = 0; foreach (var kvp in this.numbersToAnswers) { if (kvp.Value.Equals(this.question.CorrectAnswer)) { correctAnswerNumber = kvp.Key; break; } } this.runParameters.SpecialIdentifiers[TriviaGameCommandModel.GameTriviaQuestionSpecialIdentifier] = this.question.Question; foreach (var kvp in this.numbersToAnswers) { this.runParameters.SpecialIdentifiers[TriviaGameCommandModel.GameTriviaSpecificAnswerHeaderSpecialIdentifier + kvp.Key] = kvp.Value; } this.runParameters.SpecialIdentifiers[TriviaGameCommandModel.GameTriviaAnswersSpecialIdentifier] = string.Join(", ", this.numbersToAnswers.OrderBy(a => a.Key).Select(a => $"{a.Key}) {a.Value}")); this.runParameters.SpecialIdentifiers[TriviaGameCommandModel.GameTriviaCorrectAnswerSpecialIdentifier] = this.question.CorrectAnswer; #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed AsyncRunner.RunAsyncBackground(async(cancellationToken) => { GlobalEvents.OnChatMessageReceived += GlobalEvents_OnChatMessageReceived; await this.DelayNoThrow(this.TimeLimit * 1000, cancellationToken); GlobalEvents.OnChatMessageReceived -= GlobalEvents_OnChatMessageReceived; List <CommandParametersModel> winners = new List <CommandParametersModel>(); foreach (var kvp in this.runUserSelections.ToList()) { CommandParametersModel participant = this.runUsers[kvp.Key]; if (kvp.Value == correctAnswerNumber) { winners.Add(participant); this.PerformPrimarySetPayout(participant.User, this.WinAmount); participant.SpecialIdentifiers[GameCommandModelBase.GamePayoutSpecialIdentifier] = this.WinAmount.ToString(); await this.RunSubCommand(this.UserSuccessCommand, participant); } else { await this.RunSubCommand(this.UserFailureCommand, participant); } } this.SetGameWinners(this.runParameters, winners); this.runParameters.SpecialIdentifiers[GameCommandModelBase.GamePayoutSpecialIdentifier] = this.WinAmount.ToString(); this.runParameters.SpecialIdentifiers[GameCommandModelBase.GameAllPayoutSpecialIdentifier] = (this.WinAmount * winners.Count).ToString(); await this.RunSubCommand(this.CorrectAnswerCommand, this.runParameters); await this.PerformCooldown(this.runParameters); this.ClearData(); }, new CancellationToken()); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed await this.RunSubCommand(this.StartedCommand, this.runParameters); }
public override async Task CustomRun(CommandParametersModel parameters) { await this.RefundCooldown(parameters); if (this.runParameters == null) { this.runBetAmount = this.GetPrimaryBetAmount(parameters); this.runParameters = parameters; this.runUsers[parameters.User] = parameters; this.GetPrimaryCurrencyRequirement()?.SetTemporaryAmount(this.runBetAmount); #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed AsyncRunner.RunAsyncBackground(async(cancellationToken) => { await DelayNoThrow(this.TimeLimit * 1000, cancellationToken); if (this.runUsers.Count < this.MinimumParticipants) { await this.RunSubCommand(this.NotEnoughPlayersCommand, this.runParameters); foreach (var kvp in this.runUsers.ToList()) { await this.Requirements.Refund(kvp.Value); } await this.PerformCooldown(this.runParameters); this.ClearData(); return; } List <CommandParametersModel> participants = new List <CommandParametersModel>(this.runUsers.Values); int payout = this.runBetAmount * participants.Count; int individualPayout = payout / this.MaxWinners; List <CommandParametersModel> winners = new List <CommandParametersModel>(); for (int i = 0; i < this.MaxWinners; i++) { CommandParametersModel winner = participants.Random(); winners.Add(winner); participants.Remove(winner); } foreach (CommandParametersModel loser in participants) { await this.RunSubCommand(this.UserFailureCommand, loser); } foreach (CommandParametersModel winner in winners) { this.PerformPrimarySetPayout(winner.User, individualPayout); winner.SpecialIdentifiers[GameCommandModelBase.GamePayoutSpecialIdentifier] = individualPayout.ToString(); await this.RunSubCommand(this.UserSuccessCommand, winner); } this.SetGameWinners(this.runParameters, winners); this.runParameters.SpecialIdentifiers[GameCommandModelBase.GamePayoutSpecialIdentifier] = individualPayout.ToString(); this.runParameters.SpecialIdentifiers[GameCommandModelBase.GameAllPayoutSpecialIdentifier] = payout.ToString(); await this.RunSubCommand(this.GameCompleteCommand, this.runParameters); await this.PerformCooldown(this.runParameters); this.ClearData(); }, new CancellationToken()); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed await this.RunSubCommand(this.StartedCommand, this.runParameters); await this.RunSubCommand(this.UserJoinCommand, this.runParameters); return; } else if (this.runParameters != null && !this.runUsers.ContainsKey(parameters.User)) { this.runUsers[parameters.User] = parameters; await this.RunSubCommand(this.UserJoinCommand, parameters); return; } else { await ChannelSession.Services.Chat.SendMessage(MixItUp.Base.Resources.GameCommandAlreadyUnderway); } await this.Requirements.Refund(parameters); }