public TypingGame(ITextChannel channel) { _log = LogManager.GetCurrentClassLogger(); this.channel = channel; IsActive = false; sw = new Stopwatch(); finishedUserIds = new List<ulong>(); }
public RepeatRunner(Repeater repeater, ITextChannel channel = null) { _log = LogManager.GetCurrentClassLogger(); this.Repeater = repeater; this.Channel = channel ?? NadekoBot.Client.GetGuild(repeater.GuildId)?.GetTextChannel(repeater.ChannelId); if (Channel == null) return; Task.Run(Run); }
public TriviaGame(IGuild guild, ITextChannel channel, bool showHints, int winReq = 10) { _log = LogManager.GetCurrentClassLogger(); ShowHints = showHints; this.guild = guild; this.channel = channel; WinRequirement = winReq; Task.Run(async () => { try { await StartGame().ConfigureAwait(false); } catch { } }); }
private static async Task<bool> IsAnimeListAuthorized(ITextChannel e) { if ((DateTime.Now - Storage.anilistAuthorizationCreated).TotalMinutes > 50) { if (!await AuthorizeAnilistAsync()) { await e.SendMessageAsync($"Something went wrong authorizing Anilist, please try again!"); return false; } } return true; }
public AnimalRace(ulong serverId, ITextChannel ch) { this._log = LogManager.GetCurrentClassLogger(); this.serverId = serverId; this.raceChannel = ch; if (!AnimalRaces.TryAdd(serverId, this)) { Fail = true; return; } using (var uow = DbHandler.UnitOfWork()) { animals = new ConcurrentQueue<string>(uow.BotConfig.GetOrCreate().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.SendMessageAsync($"🏁`Race is starting in 20 seconds or when the room is full. Type {NadekoBot.ModulePrefixes[typeof(Gambling).Name]}jr to join the race.`"); } 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.SendMessageAsync("🏁`Race full, starting right now!`"); } catch (Exception ex) { _log.Warn(ex); } } else if (participants.Count > 1) { try { await raceChannel.SendMessageAsync("🏁`Game starting with " + participants.Count + " participants.`"); } catch (Exception ex) { _log.Warn(ex); } } else { try { await raceChannel.SendMessageAsync("🏁`Race failed to start since there was not enough participants.`"); } 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 { } }); }
public async Task ChannelInfo(IUserMessage msg, ITextChannel channel = null) { var ch = channel ?? (ITextChannel)msg.Channel; if (ch == null) return; var createdAt = new DateTime(2015, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(ch.Id >> 22); var toReturn = $@"__`Name:`__ **#{ch.Name}** __`ID:`__ **{ch.Id}** __`Created At:`__ **{createdAt.ToString("dd.MM.yyyy HH:mm")}** __`Topic:`__ {ch.Topic} __`Users:`__ **{(await ch.GetUsersAsync()).Count()}**"; await msg.Reply(toReturn).ConfigureAwait(false); }
public MusicPlayer(IVoiceChannel startingVoiceChannel, ITextChannel outputChannel, float?defaultVolume) { if (startingVoiceChannel == null) { throw new ArgumentNullException(nameof(startingVoiceChannel)); } _log = LogManager.GetCurrentClassLogger(); OutputTextChannel = outputChannel; Volume = defaultVolume ?? 1.0f; PlaybackVoiceChannel = startingVoiceChannel; SongCancelSource = new CancellationTokenSource(); cancelToken = SongCancelSource.Token; Task.Run(async() => { try { while (!destroyed) { try { Action action; if (actionQueue.TryDequeue(out action)) { action(); } } finally { await Task.Delay(100).ConfigureAwait(false); } } } catch (Exception ex) { _log.Warn("Action queue crashed"); _log.Warn(ex); } }).ConfigureAwait(false); var t = new Thread(async() => { while (!destroyed) { try { CurrentSong = GetNextSong(); if (CurrentSong == null) { continue; } if (audioClient != null) { try { await audioClient.DisconnectAsync().ConfigureAwait(false); } catch { } } audioClient = await PlaybackVoiceChannel.ConnectAsync().ConfigureAwait(false); var index = _playlist.IndexOf(CurrentSong); if (index != -1) { RemoveSongAt(index, true); } OnStarted(this, CurrentSong); try { await CurrentSong.Play(audioClient, cancelToken); } catch (OperationCanceledException) { } finally { OnCompleted(this, CurrentSong); } if (RepeatPlaylist & !RepeatSong) { AddSong(CurrentSong, CurrentSong.QueuerName); } if (RepeatSong) { AddSong(CurrentSong, 0); } } catch (Exception ex) { _log.Warn("Music thread almost crashed."); _log.Warn(ex); await Task.Delay(3000).ConfigureAwait(false); } finally { if (!cancelToken.IsCancellationRequested) { SongCancelSource.Cancel(); } SongCancelSource = new CancellationTokenSource(); cancelToken = SongCancelSource.Token; CurrentSong = null; await Task.Delay(300).ConfigureAwait(false); } } }); t.Start(); }
public override async void Execute(ITextChannel Channel, MessageEventArgs e, MatchCollection args) { await Channel.TriggerTypingIndicator(); await Channel.CreateMessage("pong"); }
public async Task SetGambleChannel([Remainder] ITextChannel gambleChannel) { await _guildRepo.ModifyAsync(Context.DbGuild, x => x.GambleChannelId = gambleChannel.Id); await ReplyAsync($"You have successfully set the gamble channel to {gambleChannel.Mention}."); }
public async Task DelTxtChanl([Remainder] ITextChannel toDelete) { await toDelete.DeleteAsync().ConfigureAwait(false); await Context.Channel.SendConfirmAsync($"🗑 Removed text channel **{toDelete.Name}**. ID: `{toDelete.Id}`").ConfigureAwait(false); }
public async Task MakeConfessionChannelAsync([Remainder] ITextChannel channel = null) => await this.SetConfessionChannelAsync(channel, ConfessionType.LoveConfession).ConfigureAwait(true);
private string GetText(ITextChannel ch, string key, params object[] rep) => _strings.GetText(key, ch.GuildId, "Games".ToLowerInvariant(), rep);
private string GetEnableString(ITextChannel chan) { if (chan == null) return ("X"); return (chan.Id.ToString()); }
public static IPagedEnumerable <IThreadChannel> EnumeratePrivateArchivedThreads(this ITextChannel channel, int limit, DateTimeOffset?startFromDate = null, IRestRequestOptions options = null) { var client = channel.GetRestClient(); return(client.EnumeratePrivateArchivedThreads(channel.Id, limit, startFromDate, options)); }
private void GuildTracker() { Client.JoinedGuild += async(guild) => { using (BotDBContext DBContext = DBFactory.Create <BotDBContext>()) { DBContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; var existingGuild = DBContext.Guilds.FromSql("SELECT * FROM Guilds WHERE Id = {0} LIMIT 1", guild.Id.ToString()).AsNoTracking().FirstOrDefault(); var newGuild = new DiscordGuild(guild.Id, guild.Name, guild.OwnerId, guild.CreatedAt, guild.IconUrl, guild.SplashUrl); if (existingGuild == null) { await DBContext.AddAsync(newGuild); ConsoleEx.WriteColoredLine($"Joined new Guild $[[DarkCyan]]${guild.Name}$[[Gray]]$!"); foreach (ITextChannel channel in guild.TextChannels) { var newChannel = new DiscordTextChannel(channel.Id.ToString(), channel.GuildId.ToString(), channel.Name, channel.Topic, channel.CreatedAt, ((channel as ISocketPrivateChannel) != null)); ConsoleEx.WriteColoredLine($"Joined new Channel $[[DarkCyan]]${channel.Name}$[[Gray]]$ within the Guild $[[DarkCyan]]${guild.Name}$[[Gray]]$!"); } } else { DBContext.DetachLocal(newGuild, existingGuild.Id); ConsoleEx.WriteColoredLine($"Joined existing Guild $[[DarkCyan]]${guild.Name}$[[Gray]]$, updating data."); await ProcessTextChannels(guild); await ProcessUsers(guild); } await DBContext.SaveChangesAsync(); } }; Client.GuildUpdated += async(oldGuild, newGuild) => { using (BotDBContext DBContext = DBFactory.Create <BotDBContext>()) { DBContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; DiscordGuild foundGuild = DBContext.Guilds.FromSql("SELECT * FROM Guilds WHERE Id = {0} LIMIT 1", oldGuild.Id.ToString()).AsNoTracking().First(); var addedGuild = new DiscordGuild(newGuild.Id, newGuild.Name, newGuild.OwnerId, newGuild.CreatedAt, newGuild.IconUrl, newGuild.SplashUrl); if (foundGuild == null) { await DBContext.AddAsync(addedGuild); await ProcessTextChannels(newGuild); await ProcessUsers(newGuild); } else { DBContext.DetachLocal(addedGuild, oldGuild.Id.ToString()); ConsoleEx.WriteColoredLine($"Updating existing Guild $[[DarkCyan]]${oldGuild.Name}$[[Gray]]$, adjusting record."); } await DBContext.SaveChangesAsync(); } }; Client.ChannelCreated += async(channel) => { ITextChannel textChannel = channel as ITextChannel; if (textChannel == null) { return; } using (BotDBContext DBContext = DBFactory.Create <BotDBContext>()) { DBContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; var existingTextChannel = DBContext.TextChannels.FromSql("SELECT * FROM TextChannels WHERE Id = {0} LIMIT 1", channel.Id.ToString()).AsNoTracking().FirstOrDefault(); if (existingTextChannel == null) { var newChannel = new DiscordTextChannel(textChannel.Id.ToString(), textChannel.GuildId.ToString(), textChannel.Name, textChannel.Topic, textChannel.CreatedAt, ((textChannel as ISocketPrivateChannel) != null)); await DBContext.AddAsync(newChannel); ConsoleEx.WriteColoredLine($"Added new TextChannel $[[DarkCyan]]${textChannel.Name}$[[Gray]]$!"); } else { DBContext.DetachLocal(existingTextChannel, existingTextChannel.Id); ConsoleEx.WriteColoredLine($"Channel already exists somehow, $[[DarkCyan]]${textChannel.Name}$[[Gray]]$, updating records."); } await DBContext.SaveChangesAsync(); } }; Client.ChannelUpdated += async(oldChan, newChan) => { ITextChannel oldTextChannel = oldChan as ITextChannel; ITextChannel newTextChannel = newChan as ITextChannel; if (oldTextChannel == null || newTextChannel == null) { return; } using (BotDBContext DBContext = DBFactory.Create <BotDBContext>()) { DBContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; var existingChannel = DBContext.TextChannels.FromSql("SELECT * FROM TextChannels WHERE Id = {0} LIMIT 1", oldChan.Id.ToString()).FirstOrDefault(); var newChannel = new DiscordTextChannel(newTextChannel.Id.ToString(), newTextChannel.GuildId.ToString(), newTextChannel.Name, newTextChannel.Topic, newTextChannel.CreatedAt, ((newTextChannel as ISocketPrivateChannel) != null)); if (existingChannel == null) { await DBContext.AddAsync(newChannel); ConsoleEx.WriteColoredLine($"Added new TextChannel $[[DarkCyan]]${newTextChannel.Name}$[[Gray]]$ that $[[Red]]$should$[[Gray]]$ have existed!"); } else { DBContext.DetachLocal(newChannel, newTextChannel.Id.ToString()); ConsoleEx.WriteColoredLine($"Updating existing TextChannel $[[DarkCyan]]${oldTextChannel.Name}$[[Gray]]$, adjusting record."); } await DBContext.SaveChangesAsync(); } }; }
public Task GameListAsync(ITextChannel lobbyChannel) { return(GameListAsync(lobbyChannel.Id)); }
public Task ShowGameAsync(ITextChannel lobbyChannel, int gameNumber) { return(ShowGameAsync(lobbyChannel.Id, gameNumber)); }
public static string GetLocalText(ITextChannel channel, string key, params object[] replacements) => NadekoTopLevelModule.GetTextStatic(key, NadekoBot.Localization.GetCultureInfo(channel.GuildId), typeof(Games).Name.ToLowerInvariant(), replacements);
public Task ClearGResAsync(ITextChannel lobbyChannel, int gameNumber) { return(ClearGResAsync(lobbyChannel.Id, gameNumber)); }
public static IPagedEnumerable <IThreadChannel> EnumerateJoinedPrivateArchivedThreads(this ITextChannel channel, int limit, Snowflake?startFromId = null, IRestRequestOptions options = null) { var client = channel.GetRestClient(); return(client.EnumerateJoinedPrivateArchivedThreads(channel.Id, limit, startFromId, options)); }
public static async Task<bool> ValidateQuery(ITextChannel ch, string query) { if (!string.IsNullOrEmpty(query.Trim())) return true; await ch.SendMessageAsync("Please specify search parameters.").ConfigureAwait(false); return false; }
public static Task <IReadOnlyList <IThreadChannel> > FetchJoinedPrivateArchivedThreadsAsync(this ITextChannel channel, int limit = Discord.Limits.Rest.FetchThreadsPageSize, Snowflake?startFromId = null, IRestRequestOptions options = null, CancellationToken cancellationToken = default) { var client = channel.GetRestClient(); return(client.FetchJoinedPrivateArchivedThreadsAsync(channel.Id, limit, startFromId, options, cancellationToken)); }
public InterviewRoom GetRoom(ITextChannel chnl) => InterviewRooms.FirstOrDefault(x => x.Channel.Id == chnl.Id);
public static async Task <IMessage> SendLogAsync( this ITextChannel channel, string title, string description, Color color, IApiService apiService, string thumbnailUrl = null) { var embed = new EmbedBuilder() .WithTitle(title) .WithDescription(description) .WithColor(color) .WithCurrentTimestamp(); if (thumbnailUrl != null) { embed.WithThumbnailUrl(thumbnailUrl); } IMessage message = null; try { message = await channel.SendMessageAsync(embed : embed.Build()); } catch (Discord.Net.HttpException) { // The bot does not have access to the logging channel, WUT SHOULD WE DO? // We don't really have any good options, the only thing we can send a message // to is the channel we don't have access to. // So for now I think we will just eat the exception... YUMMY! } ServerLogItemCreateDto serverLogItem = new ServerLogItemCreateDto { Guild = new GuildCreateDto { GuildId = channel.Guild.Id, GuildName = channel.Guild.Name }, Channel = new ChannelCreateDto { ChannelId = channel.Id, ChannelName = channel.Name }, Title = title, Description = description, ThumbnailUrl = thumbnailUrl, Date = DateTimeOffset.UtcNow }; if (apiService != null && apiService.ApiIsEnabled) { try { await apiService.ServerLogItemApi.SaveServerLogItem(serverLogItem); } catch (Exception e) { Log.Warning(e, "An exception occured while trying to contact the API"); } } else if (apiService == null) { throw new ArgumentNullException(nameof(apiService)); } return(message); }
private static Task UserUpdatedEventHandler(SocketUser iuser, SocketVoiceState before, SocketVoiceState after) { var user = (iuser as SocketGuildUser); var guild = user?.Guild; if (guild == null) { return(Task.CompletedTask); } var botUserPerms = guild.CurrentUser.GuildPermissions; if (before.VoiceChannel == after.VoiceChannel) { return(Task.CompletedTask); } if (!_voicePlusTextCache.Contains(guild.Id)) { return(Task.CompletedTask); } var _ = Task.Run(async() => { try { if (!botUserPerms.ManageChannels || !botUserPerms.ManageRoles) { try { await guild.Owner.SendErrorAsync( GetTextStatic("vt_exit", NadekoBot.Localization.GetCultureInfo(guild), typeof(Administration).Name.ToLowerInvariant(), Format.Bold(guild.Name))).ConfigureAwait(false); } catch { // ignored } using (var uow = DbHandler.UnitOfWork()) { uow.GuildConfigs.For(guild.Id, set => set).VoicePlusTextEnabled = false; _voicePlusTextCache.TryRemove(guild.Id); await uow.CompleteAsync().ConfigureAwait(false); } return; } var semaphore = _guildLockObjects.GetOrAdd(guild.Id, (key) => new SemaphoreSlim(1, 1)); try { await semaphore.WaitAsync().ConfigureAwait(false); var beforeVch = before.VoiceChannel; if (beforeVch != null) { var beforeRoleName = GetRoleName(beforeVch); var beforeRole = guild.Roles.FirstOrDefault(x => x.Name == beforeRoleName); if (beforeRole != null) { try { _log.Info("Removing role " + beforeRoleName + " from user " + user.Username); await user.RemoveRolesAsync(beforeRole).ConfigureAwait(false); await Task.Delay(200).ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); } } } var afterVch = after.VoiceChannel; if (afterVch != null && guild.AFKChannel?.Id != afterVch.Id) { var roleName = GetRoleName(afterVch); var roleToAdd = guild.Roles.FirstOrDefault(x => x.Name == roleName) ?? (IRole)await guild.CreateRoleAsync(roleName, GuildPermissions.None).ConfigureAwait(false); ITextChannel textChannel = guild.TextChannels .FirstOrDefault(t => t.Name == GetChannelName(afterVch.Name).ToLowerInvariant()); if (textChannel == null) { var created = (await guild.CreateTextChannelAsync(GetChannelName(afterVch.Name).ToLowerInvariant()).ConfigureAwait(false)); try { await guild.CurrentUser.AddRolesAsync(roleToAdd).ConfigureAwait(false); } catch { /*ignored*/ } await Task.Delay(50).ConfigureAwait(false); await created.AddPermissionOverwriteAsync(roleToAdd, new OverwritePermissions( readMessages: PermValue.Allow, sendMessages: PermValue.Allow)) .ConfigureAwait(false); await Task.Delay(50).ConfigureAwait(false); await created.AddPermissionOverwriteAsync(guild.EveryoneRole, new OverwritePermissions( readMessages: PermValue.Deny, sendMessages: PermValue.Deny)) .ConfigureAwait(false); await Task.Delay(50).ConfigureAwait(false); } _log.Warn("Adding role " + roleToAdd.Name + " to user " + user.Username); await user.AddRolesAsync(roleToAdd).ConfigureAwait(false); } } finally { semaphore.Release(); } } catch (Exception ex) { _log.Warn(ex); } }); return(Task.CompletedTask); }
public void TellVideo(ITextChannel channel) { DiscordUtil.SendMessage(channel, LastVideo.Author + " uploaded a video! " + LastVideo.Title + " " + LastVideo.URL); }
public async Task MakeVentingLoggingChannelAsync([Remainder] ITextChannel channel = null) => await this.SetLoggingChannelAsync(channel, ConfessionType.VentConfession).ConfigureAwait(true);
public async Task SetModLogChannel(ITextChannel modLogChannel) { GuildRepository.Modify(DEABot.GuildUpdateBuilder.Set(x => x.ModLogId, modLogChannel.Id), Context.Guild.Id); await ReplyAsync($"{Context.User.Mention}, You have successfully set the moderator log channel to {modLogChannel.Mention}!"); }
public async Task SetModLogChannel([Remainder] ITextChannel modLogChannel) { await _guildRepo.ModifyAsync(Context.DbGuild, x => x.ModLogChannelId = modLogChannel.Id); await ReplyAsync($"You have successfully set the moderator log channel to {modLogChannel.Mention}."); }
public async Task SetDetailedLogsChannel(ITextChannel detailedLogsChannel) { GuildRepository.Modify(DEABot.GuildUpdateBuilder.Set(x => x.DetailedLogsId, detailedLogsChannel.Id), Context.Guild.Id); await ReplyAsync($"{Context.User.Mention}, You have successfully set the detailed logs channel to {detailedLogsChannel.Mention}!"); }
public async Task SetUpdateChannel([Remainder] ITextChannel channel) { await _guildRepo.ModifyAsync(Context.DbGuild, x => x.UpdateChannelId = channel.Id); await ReplyAsync($"You have successfully set the DEA update channel to {channel.Mention}."); }
public async Task SetGambleChannel(ITextChannel gambleChannel) { GuildRepository.Modify(DEABot.GuildUpdateBuilder.Set(x => x.GambleId, gambleChannel.Id), Context.Guild.Id); await ReplyAsync($"{Context.User.Mention}, You have successfully set the gamble channel to {gambleChannel.Mention}!"); }
public async Task Promote(PickupQueue queue, ITextChannel pickupChannel, IGuildUser user) { var guild = (SocketGuild)user.Guild; var activity = await _activitiesRepository.Find(user); activity.PickupPromote += 1; await _activitiesRepository.Update(activity); if (queue?.MaxInQueue <= queue?.Subscribers.Count) { await pickupChannel.SendMessageAsync("Queue is full, why the spam?").AutoRemoveMessage(10); return; } var role = guild.Roles.FirstOrDefault(w => w.Name == RoleNames.PickupPromote); if (role == null) { return; //Failed to get role; } var users = guild.Users.Where(w => w.Roles.Any(r => r.Id == role.Id)).ToList(); if (!users.Any()) { await pickupChannel.SendMessageAsync("No users have subscribed using the `!subscribe` command.") .AutoRemoveMessage(10); return; } using (pickupChannel.EnterTypingState()) { if (queue == null) { var queues = await _queueRepository.AllQueues(user.GuildId.ToString()); var filtered = queues.Where(q => q.MaxInQueue > q.Subscribers.Count).ToArray(); if (filtered.Any()) { await pickupChannel.SendMessageAsync($"There are {filtered.Length} pickup queues with spots left, check out the `!list`! - {role.Mention}") .AutoRemoveMessage(); } } else { var sb = BuildPromoteMessage(queue, pickupChannel); var embed = new EmbedBuilder { Title = $"Pickup queue {queue.Name} needs more players", Description = sb.ToString(), Author = new EmbedAuthorBuilder { Name = "pickup-bot" }, Color = Color.Orange }.Build(); foreach (var u in users) { await u.SendMessageAsync(embed : embed); await Task.Delay(TimeSpan.FromMilliseconds(200)); } } } }
private async Task TrackStream(ITextChannel channel, string username, FollowedStream.FollowedStreamType type) { username = username.ToLowerInvariant().Trim(); var stream = new FollowedStream { GuildId = channel.Guild.Id, ChannelId = channel.Id, Username = username, Type = type, }; bool exists; using (var uow = DbHandler.UnitOfWork()) { exists = uow.GuildConfigs.For(channel.Guild.Id).FollowedStreams.Where(fs => fs.ChannelId == channel.Id && fs.Username.ToLowerInvariant().Trim() == username).Any(); } if (exists) { await channel.SendMessageAsync($":anger: I am already following `{username}` ({type}) stream on this channel.").ConfigureAwait(false); return; } StreamStatus data; try { data = await GetStreamStatus(stream).ConfigureAwait(false); } catch { await channel.SendMessageAsync(":anger: Stream probably doesn't exist.").ConfigureAwait(false); return; } var msg = $"Stream is currently **{(data.IsLive ? "ONLINE" : "OFFLINE")}** with **{data.Views}** viewers"; if (data.IsLive) if (type == FollowedStream.FollowedStreamType.Hitbox) msg += $"\n`Here is the Link:`【 http://www.hitbox.tv/{stream.Username}/ 】"; else if (type == FollowedStream.FollowedStreamType.Twitch) msg += $"\n`Here is the Link:`【 http://www.twitch.tv/{stream.Username}/ 】"; else if (type == FollowedStream.FollowedStreamType.Beam) msg += $"\n`Here is the Link:`【 https://beam.pro/{stream.Username}/ 】"; using (var uow = DbHandler.UnitOfWork()) { uow.GuildConfigs.For(channel.Guild.Id).FollowedStreams.Add(stream); await uow.CompleteAsync(); } msg = $":ok: I will notify this channel when status changes.\n{msg}"; await channel.SendMessageAsync(msg).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 SingleBattleEnvironment(string Name, ITextChannel lobbyChannel, bool isPersistent, ITextChannel BattleChannel, BattleDifficulty diff) : base(Name, lobbyChannel, isPersistent, BattleChannel) { internalDiff = diff; _ = Reset("init"); }
private string GetText(IGuild server, ITextChannel channel, IGuildUser user, IUserMessage message) => $"**{server.Name} | {channel.Name}** `{user.Username}`: " + message.Content;
public static async Task <IReadOnlyCollection <RestWebhook> > GetWebhooksAsync(ITextChannel channel, BaseDiscordClient client, RequestOptions options) { var models = await client.ApiClient.GetChannelWebhooksAsync(channel.Id, options).ConfigureAwait(false); return(models.Select(x => RestWebhook.Create(client, channel, x)) .ToImmutableArray()); }
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.SendMessageAsync("💢 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).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.SendMessageAsync($"🎵`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} `Vol: {(int)(sender.Volume * 100)}%`"; try { playingMessage = await textCh.SendMessageAsync(msgTxt).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.SendMessageAsync($"🎵 `Queue is full at {musicPlayer.MaxQueueSize}/{musicPlayer.MaxQueueSize}.` "); } catch { } throw; } if (!silent) { try { var queuedMessage = await textCh.SendMessageAsync($"🎵`Queued`{resolvedSong.PrettyName} **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 } }
//News public static async Task <RestWebhook> CreateNewsWebhookAsync(BaseDiscordClient client, SocketNewsChannel source, ITextChannel target, RequestOptions options) { API.WebhookJson model = await client.ApiClient.CreateFollowWebhookAsync(source.Id, new CreateWebhookNews(target.Id), options).ConfigureAwait(false); return(RestWebhook.Create(client, target, model)); }