public async Task Start(IGuildUser user) { if (_phase == Phase.Started || _phase == Phase.Ended) { await _channel.SendErrorAsync(user.Mention + GetText("ttt_already_running")).ConfigureAwait(false); return; } else if (_users[0] == user) { await _channel.SendErrorAsync(user.Mention + GetText("ttt_against_yourself")).ConfigureAwait(false); return; } _users[1] = user; _phase = Phase.Started; _timeoutTimer = new Timer(async(_) => { await _moveLock.WaitAsync(); try { if (_phase == Phase.Ended) { return; } _phase = Phase.Ended; if (_users[1] != null) { _winner = _users[_curUserIndex ^= 1]; var del = _previousMessage?.DeleteAsync(); try { await _channel.EmbedAsync(GetEmbed(GetText("ttt_time_expired"))).ConfigureAwait(false); if (del != null) { await del.ConfigureAwait(false); } } catch { } } OnEnded?.Invoke(this); } catch { } finally { _moveLock.Release(); } }, null, _options.TurnTimer * 1000, Timeout.Infinite); _client.MessageReceived += Client_MessageReceived; _previousMessage = await _channel.EmbedAsync(GetEmbed(GetText("game_started"))).ConfigureAwait(false); }
public async Task Start(IGuildUser user) { if (_phase == Phase.Started || _phase == Phase.Ended) { await _channel.SendErrorAsync(user.Mention + " TicTacToe Game is already running in this channel.").ConfigureAwait(false); return; } else if (_users[0] == user) { await _channel.SendErrorAsync(user.Mention + " You can't play against yourself.").ConfigureAwait(false); return; } _users[1] = user; _log.Warn($"User {user} joined a TicTacToe game."); _phase = Phase.Started; timeoutTimer = new Timer(async(_) => { await moveLock.WaitAsync(); try { if (_phase == Phase.Ended) { return; } _phase = Phase.Ended; if (_users[1] != null) { _winner = _users[curUserIndex ^= 1]; var del = previousMessage?.DeleteAsync(); try { await _channel.EmbedAsync(GetEmbed("Time Expired!")).ConfigureAwait(false); await del.ConfigureAwait(false); } catch { } } OnEnded?.Invoke(this); } catch { } finally { moveLock.Release(); } }, null, 15000, Timeout.Infinite); NadekoBot.Client.MessageReceived += Client_MessageReceived; previousMessage = await _channel.EmbedAsync(GetEmbed("Game Started")).ConfigureAwait(false); }
public async Task Run() { NadekoBot.Client.MessageReceived += PotentialAcro; var embed = GetEmbed(); //SUBMISSIONS PHASE await _channel.EmbedAsync(embed).ConfigureAwait(false); try { await Task.Delay(_time * 1000, _source.Token).ConfigureAwait(false); phase = AcroPhase.Idle; } catch (OperationCanceledException) { return; } //var i = 0; if (_submissions.Count == 0) { await _channel.SendErrorAsync(GetText("acrophobia"), GetText("acro_ended_no_sub")); return; } if (_submissions.Count == 1) { await _channel.EmbedAsync(new EmbedBuilder().WithOkColor() .WithDescription( GetText("acro_winner_only", Format.Bold(_submissions.First().Value.ToString()))) .WithFooter(efb => efb.WithText(_submissions.First().Key.ToLowerInvariant().ToTitleCase()))) .ConfigureAwait(false); return; } var submissionClosedEmbed = GetEmbed(); await _channel.EmbedAsync(submissionClosedEmbed).ConfigureAwait(false); //VOTING PHASE phase = AcroPhase.Voting; try { //30 secondds for voting await Task.Delay(30000, _source.Token).ConfigureAwait(false); phase = AcroPhase.Idle; } catch (OperationCanceledException) { return; } await End().ConfigureAwait(false); }
public async Task Run() { NadekoBot.Client.MessageReceived += PotentialAcro; var embed = GetEmbed(); //SUBMISSIONS PHASE await channel.EmbedAsync(embed).ConfigureAwait(false); try { await Task.Delay(time * 1000, source.Token).ConfigureAwait(false); phase = AcroPhase.Idle; } catch (OperationCanceledException) { return; } //var i = 0; if (submissions.Count == 0) { await channel.SendErrorAsync("Acrophobia", "Game ended with no submissions."); return; } else if (submissions.Count == 1) { await channel.EmbedAsync(new EmbedBuilder().WithOkColor() .WithDescription($"{submissions.First().Value.Mention} is the winner for being the only user who made a submission!") .WithFooter(efb => efb.WithText(submissions.First().Key.ToLowerInvariant().ToTitleCase()))) .ConfigureAwait(false); return; } var submissionClosedEmbed = GetEmbed(); await channel.EmbedAsync(submissionClosedEmbed).ConfigureAwait(false); //VOTING PHASE this.phase = AcroPhase.Voting; try { //30 secondds for voting await Task.Delay(30000, source.Token).ConfigureAwait(false); this.phase = AcroPhase.Idle; } catch (OperationCanceledException) { return; } await End().ConfigureAwait(false); }
private async Task TrackStream(ITextChannel channel, string username, FollowedStream.FollowedStreamType type) { username = username.ToLowerInvariant().Trim(); var fs = new FollowedStream { GuildId = channel.Guild.Id, ChannelId = channel.Id, Username = username, Type = type, }; StreamStatus status; try { status = await GetStreamStatus(fs).ConfigureAwait(false); } catch { await channel.SendErrorAsync("Stream probably doesn't exist.").ConfigureAwait(false); return; } using (var uow = DbHandler.UnitOfWork()) { uow.GuildConfigs.For(channel.Guild.Id, set => set.Include(gc => gc.FollowedStreams)) .FollowedStreams .Add(fs); await uow.CompleteAsync().ConfigureAwait(false); } await channel.EmbedAsync(fs.GetEmbed(status).Build(), $"🆗 I will notify this channel when status changes.").ConfigureAwait(false); }
public async Task JoinRace(IGuildUser u, int amount = 0) { string animal; if (!animals.TryDequeue(out animal)) { await _raceChannel.SendErrorAsync(GetText("animal_race_no_race")).ConfigureAwait(false); return; } var p = new Participant(u, animal, amount); if (_participants.Contains(p)) { await _raceChannel.SendErrorAsync(GetText("animal_race_already_in")).ConfigureAwait(false); return; } if (Started) { await _raceChannel.SendErrorAsync(GetText("animal_race_already_started")).ConfigureAwait(false); return; } if (amount > 0) { if (!await CurrencyHandler.RemoveCurrencyAsync(u, "BetRace", amount, false).ConfigureAwait(false)) { await _raceChannel.SendErrorAsync(GetText("not_enough", CurrencySign)).ConfigureAwait(false); return; } } _participants.Add(p); string confStr; if (amount > 0) { confStr = GetText("animal_race_join_bet", u.Mention, p.Animal, amount + CurrencySign); } else { confStr = GetText("animal_race_join", u.Mention, p.Animal); } await _raceChannel.SendConfirmAsync(GetText("animal_race"), Format.Bold(confStr)).ConfigureAwait(false); }
public static async Task <bool> ValidateQuery(ITextChannel ch, string query) { if (!string.IsNullOrEmpty(query.Trim())) { return(true); } await ch.SendErrorAsync("Please specify search parameters.").ConfigureAwait(false); return(false); }
public async Task Start(IGuildUser user) { if (_phase == Phase.Started || _phase == Phase.Ended) { await _channel.SendErrorAsync(user.Mention + " TicTacToe Game is already running in this channel.").ConfigureAwait(false); return; } else if (_users[0] == user) { await _channel.SendErrorAsync(user.Mention + " You can't play against yourself.").ConfigureAwait(false); return; } _users[1] = user; _log.Warn($"User {user} joined a TicTacToe game."); _phase = Phase.Started; NadekoBot.Client.MessageReceived += Client_MessageReceived; previousMessage = await _channel.EmbedAsync(GetEmbed("Game Started")).ConfigureAwait(false); }
public async Task <MusicPlayer> GetOrCreatePlayer(ulong guildId, IVoiceChannel voiceCh, ITextChannel textCh) { string GetText(string text, params object[] replacements) => _strings.GetText(text, _localization.GetCultureInfo(textCh.Guild), "Music".ToLowerInvariant(), replacements); if (voiceCh == null || voiceCh.Guild != textCh.Guild) { if (textCh != null) { await textCh.SendErrorAsync(GetText("must_be_in_voice")).ConfigureAwait(false); } throw new NotInVoiceChannelException(); } return(MusicPlayers.GetOrAdd(guildId, _ => { var vol = GetDefaultVolume(guildId); if (!_musicSettings.TryGetValue(guildId, out var ms)) { ms = new MusicSettings(); } var mp = new MusicPlayer(this, ms, _google, voiceCh, textCh, vol); IUserMessage playingMessage = null; IUserMessage lastFinishedMessage = null; mp.OnCompleted += async(s, song) => { try { lastFinishedMessage?.DeleteAfter(0); try { lastFinishedMessage = await mp.OutputTextChannel.EmbedAsync(new EmbedBuilder().WithOkColor() .WithAuthor(eab => eab.WithName(GetText("finished_song")).WithMusicIcon()) .WithDescription(song.PrettyName) .WithFooter(ef => ef.WithText(song.PrettyInfo))) .ConfigureAwait(false); } catch { // ignored } var(Index, Current) = mp.Current; if (Current == null && !mp.RepeatCurrentSong && !mp.RepeatPlaylist && !mp.FairPlay && AutoDcServers.Contains(guildId)) { await DestroyPlayer(guildId).ConfigureAwait(false); } } catch { // ignored } }; mp.OnStarted += async(player, song) => { //try { await mp.UpdateSongDurationsAsync().ConfigureAwait(false); } //catch //{ // // ignored //} var sender = player; if (sender == null) { return; } try { playingMessage?.DeleteAfter(0); playingMessage = await mp.OutputTextChannel.EmbedAsync(new EmbedBuilder().WithOkColor() .WithAuthor(eab => eab.WithName(GetText("playing_song", song.Index + 1)).WithMusicIcon()) .WithDescription(song.Song.PrettyName) .WithFooter(ef => ef.WithText(mp.PrettyVolume + " | " + song.Song.PrettyInfo))) .ConfigureAwait(false); } catch { // ignored } }; mp.OnPauseChanged += async(player, paused) => { try { IUserMessage msg; if (paused) { msg = await mp.OutputTextChannel.SendConfirmAsync(GetText("paused")).ConfigureAwait(false); } else { msg = await mp.OutputTextChannel.SendConfirmAsync(GetText("resumed")).ConfigureAwait(false); } msg?.DeleteAfter(10); } catch { // ignored } }; _log.Info("Done creating"); return mp; })); }
public static async Task QueueSong(IGuildUser queuer, ITextChannel textCh, IVoiceChannel voiceCh, string query, bool silent = false, MusicType musicType = MusicType.Normal) { if (voiceCh == null || voiceCh.Guild != textCh.Guild) { if (!silent) { await textCh.SendErrorAsync($"💢 You need to be in a voice channel on this server.").ConfigureAwait(false); } throw new ArgumentNullException(nameof(voiceCh)); } if (string.IsNullOrWhiteSpace(query) || query.Length < 3) { throw new ArgumentException("💢 Invalid query for queue song.", nameof(query)); } var musicPlayer = MusicPlayers.GetOrAdd(textCh.Guild.Id, server => { float vol = 1;// SpecificConfigurations.Default.Of(server.Id).DefaultMusicVolume; using (var uow = DbHandler.UnitOfWork()) { vol = uow.GuildConfigs.For(textCh.Guild.Id, set => set).DefaultMusicVolume; } var mp = new MusicPlayer(voiceCh, textCh, vol); IUserMessage playingMessage = null; IUserMessage lastFinishedMessage = null; mp.OnCompleted += async(s, song) => { try { lastFinishedMessage?.DeleteAfter(0); try { lastFinishedMessage = await mp.OutputTextChannel.EmbedAsync(new EmbedBuilder().WithOkColor() .WithAuthor(eab => eab.WithName("Finished Song").WithMusicIcon()) .WithDescription(song.PrettyName) .WithFooter(ef => ef.WithText(song.PrettyInfo))) .ConfigureAwait(false); } catch { // ignored } if (mp.Autoplay && mp.Playlist.Count == 0 && song.SongInfo.ProviderType == MusicType.Normal) { var relatedVideos = (await NadekoBot.Google.GetRelatedVideosAsync(song.SongInfo.Query, 4)).ToList(); if (relatedVideos.Count > 0) { await QueueSong(await queuer.Guild.GetCurrentUserAsync(), textCh, voiceCh, relatedVideos[new NadekoRandom().Next(0, relatedVideos.Count)], true).ConfigureAwait(false); } } } catch { } }; mp.OnStarted += async(player, song) => { try { await mp.UpdateSongDurationsAsync().ConfigureAwait(false); } catch { // ignored } var sender = player as MusicPlayer; if (sender == null) { return; } try { playingMessage?.DeleteAfter(0); playingMessage = await mp.OutputTextChannel.EmbedAsync(new EmbedBuilder().WithOkColor() .WithAuthor(eab => eab.WithName("Playing Song").WithMusicIcon()) .WithDescription(song.PrettyName) .WithFooter(ef => ef.WithText(song.PrettyInfo))) .ConfigureAwait(false); } catch { } }; mp.OnPauseChanged += async(paused) => { try { IUserMessage msg; if (paused) { msg = await mp.OutputTextChannel.SendConfirmAsync("🎵 Music playback **paused**.").ConfigureAwait(false); } else { msg = await mp.OutputTextChannel.SendConfirmAsync("🎵 Music playback **resumed**.").ConfigureAwait(false); } msg?.DeleteAfter(10); } catch { } }; mp.SongRemoved += async(song, index) => { try { var embed = new EmbedBuilder() .WithAuthor(eab => eab.WithName("Removed song #" + (index + 1)).WithMusicIcon()) .WithDescription(song.PrettyName) .WithFooter(ef => ef.WithText(song.PrettyInfo)) .WithErrorColor(); await mp.OutputTextChannel.EmbedAsync(embed).ConfigureAwait(false); } catch { // ignored } }; return(mp); }); Song resolvedSong; try { musicPlayer.ThrowIfQueueFull(); resolvedSong = await SongHandler.ResolveSong(query, musicType).ConfigureAwait(false); if (resolvedSong == null) { throw new SongNotFoundException(); } musicPlayer.AddSong(resolvedSong, queuer.Username); } catch (PlaylistFullException) { try { await textCh.SendConfirmAsync($"🎵 Queue is full at **{musicPlayer.MaxQueueSize}/{musicPlayer.MaxQueueSize}**."); } catch { } throw; } if (!silent) { try { //var queuedMessage = await textCh.SendConfirmAsync($"🎵 Queued **{resolvedSong.SongInfo.Title}** at `#{musicPlayer.Playlist.Count + 1}`").ConfigureAwait(false); var queuedMessage = await textCh.EmbedAsync(new EmbedBuilder().WithOkColor() .WithAuthor(eab => eab.WithName("Queued Song #" + (musicPlayer.Playlist.Count + 1)).WithMusicIcon()) .WithDescription($"{resolvedSong.PrettyName}\nQueue ") .WithThumbnailUrl(resolvedSong.Thumbnail) .WithFooter(ef => ef.WithText(resolvedSong.PrettyProvider))) .ConfigureAwait(false); queuedMessage?.DeleteAfter(10); } catch { // ignored } // if queued message sending fails, don't attempt to delete it } }
public AnimalRace(ulong serverId, ITextChannel ch, string prefix) { _prefix = prefix; _log = LogManager.GetCurrentClassLogger(); _serverId = serverId; _raceChannel = ch; if (!AnimalRaces.TryAdd(serverId, this)) { Fail = true; return; } animals = new ConcurrentQueue <string>(NadekoBot.BotConfig.RaceAnimals.Select(ra => ra.Icon).Shuffle()); var cancelSource = new CancellationTokenSource(); var token = cancelSource.Token; var fullgame = CheckForFullGameAsync(token); Task.Run(async() => { try { try { await _raceChannel.SendConfirmAsync(GetText("animal_race"), GetText("animal_race_starting"), footer: GetText("animal_race_join_instr", _prefix)); } catch (Exception ex) { _log.Warn(ex); } var t = await Task.WhenAny(Task.Delay(20000, token), fullgame); Started = true; cancelSource.Cancel(); if (t == fullgame) { try { await _raceChannel.SendConfirmAsync(GetText("animal_race"), GetText("animal_race_full")); } catch (Exception ex) { _log.Warn(ex); } } else if (_participants.Count > 1) { try { await _raceChannel.SendConfirmAsync(GetText("animal_race"), GetText("animal_race_starting_with_x", _participants.Count)); } catch (Exception ex) { _log.Warn(ex); } } else { try { await _raceChannel.SendErrorAsync(GetText("animal_race"), GetText("animal_race_failed")); } catch (Exception ex) { _log.Warn(ex); } var p = _participants.FirstOrDefault(); if (p != null && p.AmountBet > 0) { await CurrencyHandler.AddCurrencyAsync(p.User, "BetRace", p.AmountBet, false).ConfigureAwait(false); } End(); return; } await Task.Run(StartRace); End(); } catch { try { End(); } catch { } } }); }
public static async Task QueueSong(IGuildUser queuer, ITextChannel textCh, IVoiceChannel voiceCh, string query, bool silent = false, MusicType musicType = MusicType.Normal) { if (voiceCh == null || voiceCh.Guild != textCh.Guild) { if (!silent) { await textCh.SendErrorAsync("💢 You need to be in a voice channel on this server.\n If you are already in a voice channel, try rejoining.").ConfigureAwait(false); } throw new ArgumentNullException(nameof(voiceCh)); } if (string.IsNullOrWhiteSpace(query) || query.Length < 3) { throw new ArgumentException("💢 Invalid query for queue song.", nameof(query)); } var musicPlayer = MusicPlayers.GetOrAdd(textCh.Guild.Id, server => { float vol = 1;// SpecificConfigurations.Default.Of(server.Id).DefaultMusicVolume; using (var uow = DbHandler.UnitOfWork()) { vol = uow.GuildConfigs.For(textCh.Guild.Id, set => set).DefaultMusicVolume; } var mp = new MusicPlayer(voiceCh, vol); IUserMessage playingMessage = null; IUserMessage lastFinishedMessage = null; mp.OnCompleted += async(s, song) => { if (song.PrintStatusMessage) { try { if (lastFinishedMessage != null) { await lastFinishedMessage.DeleteAsync().ConfigureAwait(false); } if (playingMessage != null) { await playingMessage.DeleteAsync().ConfigureAwait(false); } try { lastFinishedMessage = await textCh.SendConfirmAsync($"🎵 Finished {song.PrettyName}").ConfigureAwait(false); } catch { } if (mp.Autoplay && mp.Playlist.Count == 0 && song.SongInfo.Provider == "YouTube") { await QueueSong(queuer.Guild.GetCurrentUser(), textCh, voiceCh, (await NadekoBot.Google.GetRelatedVideosAsync(song.SongInfo.Query, 4)).ToList().Shuffle().FirstOrDefault(), silent, musicType).ConfigureAwait(false); } } catch { } } }; mp.OnStarted += async(s, song) => { if (song.PrintStatusMessage) { var sender = s as MusicPlayer; if (sender == null) { return; } var msgTxt = $"🎵 Playing {song.PrettyName}\t `Vol: {(int)(sender.Volume * 100)}%`"; try { playingMessage = await textCh.SendConfirmAsync(msgTxt).ConfigureAwait(false); } catch { } } }; mp.OnPauseChanged += async(paused) => { try { if (paused) { await textCh.SendConfirmAsync("🎵 Music playback **paused**.").ConfigureAwait(false); } else { await textCh.SendConfirmAsync("🎵 Music playback **resumed**.").ConfigureAwait(false); } } catch { } }; return(mp); }); Song resolvedSong; try { musicPlayer.ThrowIfQueueFull(); resolvedSong = await Song.ResolveSong(query, musicType).ConfigureAwait(false); if (resolvedSong == null) { throw new SongNotFoundException(); } musicPlayer.AddSong(resolvedSong, queuer.Username); } catch (PlaylistFullException) { try { await textCh.SendConfirmAsync($"🎵 Queue is full at **{musicPlayer.MaxQueueSize}/{musicPlayer.MaxQueueSize}**. "); } catch { } throw; } if (!silent) { try { var queuedMessage = await textCh.SendConfirmAsync($"🎵 Queued **{resolvedSong.SongInfo.Title.TrimTo(55)}** at `#{musicPlayer.Playlist.Count + 1}`").ConfigureAwait(false); var t = Task.Run(async() => { try { await Task.Delay(10000).ConfigureAwait(false); await queuedMessage.DeleteAsync().ConfigureAwait(false); } catch { } }).ConfigureAwait(false); } catch { } // if queued message sending fails, don't attempt to delete it } }