public async Task Join() { var queue = Queues.GetOrCreateService(Context.Guild.Id); if (!queue.HasEntries()) { await ReplyAsync("The queue is empty!"); return; } SocketGuild guild = Context.Guild; if (!IsInVoiceChannel(guild, Context.Message.Author)) { await ReplyAsync("You are not in a channel!"); return; } SocketVoiceChannel channel = FindVoiceChannel(guild, Context.Message.Author); if (channel.Users.Any(x => x.Id == Context.Client.CurrentUser.Id)) { await ReplyAsync("I'm already in your channel!"); return; } await JoinAndPlay(queue, channel); }
public async Task <string> GetUserList(SocketVoiceChannel room) { StringBuilder output = new StringBuilder(); TVroom currentRoom = await GetRoom(room); if (currentRoom != null) { output.AppendLine($"{currentRoom.TvChannel.Name}"); output.AppendLine("Admins:"); foreach (SocketUser user in currentRoom.Admins) { output.AppendLine($"{user.Username}"); } output.AppendLine("Allowed:"); foreach (SocketUser user in currentRoom.Allowed) { output.AppendLine($"{user.Username}"); } output.AppendLine("Muted:"); foreach (SocketUser user in currentRoom.Muted) { output.AppendLine($"{user.Username}"); } } else { output.AppendLine("No tv rooms in this channel"); } return(output.ToString()); }
public static async Task <bool> JoinChannel(string server, string channel) { SocketVoiceChannel chan = null; foreach (SocketVoiceChannel vchannel in getSocketChannels(server)) { if (vchannel.Name == channel) { chan = vchannel; } } if (chan != null) { try { audioClient = await chan.ConnectAsync(); Log?.Invoke("Joined channel: " + chan.Name); } catch (Exception ex) { Log?.Invoke("Error joining channel."); Log?.Invoke(ex.Message); return(false); } } return(true); }
private void UpdateChannel(ulong voiceChannel, bool isLocked) { if (GuildHandler.Plugins.IsPluginActive(_autoVoiceNamePluginName)) { SendMessage(_autoVoiceNamePluginName, "UpdateChannel", voiceChannel); } else { DisablePluginIfPermissionMissing(Discord.GuildPermission.ManageChannels, true); SocketVoiceChannel channel = GuildHandler.FindVoiceChannel(voiceChannel); if (channel != null) { if (isLocked) { if (!channel.Name.StartsWith(_lockEmoji)) { channel.ModifyAsync(x => x.Name = _lockEmoji + x.Name).ConfigureAwait(false); } } else { if (channel.Name.StartsWith(_lockEmoji)) { channel.ModifyAsync(x => x.Name = x.Name.Value.Substring(_lockEmoji.Length)).ConfigureAwait(false); } } } } }
public async Task ServerStats() { int memberCount = Context.Guild.MemberCount; DateTimeOffset date = Context.Guild.CreatedAt; string name = Context.Guild.Name; string owner = Context.Guild.Owner.Username; ServerConfig serverConfig = ServerConfigs.GetConfig(Context.Guild); bool reqV = serverConfig.RequiresVerification; string verification = string.Format("\nRequires Verification: **{0}**", reqV); if (reqV) { SocketRole vRole = Context.Guild.GetRole(serverConfig.VerificationRoleID); verification += string.Format("\nVerified Role: **{0}**", vRole.Name); } string configs = "\nBot Prefix: **" + serverConfig.Prefix + "**" + verification + "\nAFK Channel: **" + Context.Guild.GetVoiceChannel(serverConfig.AFKChannelID).Name + "**\nAFK Timeout: **" + serverConfig.AFKTimeout + "**\nAntispam Mute Time: **" + serverConfig.AntiSpamTime + "**\nAntispam Warn Ban: **" + serverConfig.AntiSpamWarn; string msg = "Server Name: **" + name + "**\nOwner: **" + owner + "**\nMember Count: **" + memberCount + "**\nDate Created: **" + date.ToString("MM/dd/yyyy hh:mm:ss") + "**" + configs + "**\n\n__Roles__\n**" + getAllRoles((SocketGuildUser)Context.User) + "**"; var result = from s in Context.Guild.VoiceChannels where s.Name.Contains("Member Count") select s; await PrintEmbedMessage("Server Stats", msg, iconUrl : Context.Guild.IconUrl); SocketVoiceChannel memberChan = result.FirstOrDefault(); await memberChan.ModifyAsync(m => { m.Name = "Member Count: " + Context.Guild.MemberCount; }); DataStorage.AddPairToStorage(memberChan.Guild.Name + " MemberChannel", memberChan.Id.ToString()); }
private SocketVoiceChannel GetVoiceChannel(SocketUser user, SocketVoiceState oldState, SocketVoiceState newState) { SocketVoiceChannel channel = oldState.VoiceChannel ?? newState.VoiceChannel; SocketGuildUser botUser = channel.Guild.CurrentUser; if (oldState.VoiceChannel != botUser.VoiceChannel && newState.VoiceChannel != botUser.VoiceChannel) { return(null); } switch (newState.VoiceChannel) { case null: if (oldState.VoiceChannel != null && user.Id != this._baseSocketClient.CurrentUser.Id) { return(oldState.VoiceChannel); } break; default: if (user.Id == this._baseSocketClient.CurrentUser.Id) { return(newState.VoiceChannel); } if (botUser.VoiceChannel == newState.VoiceChannel) { return(newState.VoiceChannel); } break; } return(channel); }
private async Task ConnectToVoice(SocketVoiceChannel voiceChannel, string sound, string id) { if (voiceChannel == null) { return; } try { Console.WriteLine($"Connecting to channel {voiceChannel.Id}"); var connection = await voiceChannel.ConnectAsync(); Console.WriteLine($"Connected to channel {voiceChannel.Id}"); Tuple <IAudioClient, Process> t = new Tuple <IAudioClient, Process>(connection, null); _connections[voiceChannel.Guild.Id] = t; await Task.Delay(3000); await Say(connection, sound, voiceChannel); await Task.Delay(1000); await voiceChannel.DisconnectAsync(); File.Delete($"prank/{id}.37"); } catch (Exception ex) { // Oh no, error Console.WriteLine(ex.Message); Console.WriteLine($"- {ex.StackTrace}"); } }
private static async Task UpdatePermissionsAsync(SocketUser user, SocketVoiceChannel channel, bool allow) { var textChannel = channel.Guild.TextChannels.FirstOrDefault(t => t.Topic?.EndsWith("for:" + channel.Name) == true); if (textChannel == null) { return; } if (allow) { var overwrite = textChannel.GetPermissionOverwrite(user) ?? new OverwritePermissions(); overwrite = overwrite.Modify(viewChannel: PermValue.Allow); await textChannel.AddPermissionOverwriteAsync(user, overwrite); await channel.Guild.GetUser(user.Id).AddRoleAsync(channel.Guild.GetRole(DiscordSettings.VoiceRole)); return; } await textChannel.RemovePermissionOverwriteAsync(user); await channel.Guild.GetUser(user.Id).RemoveRoleAsync(channel.Guild.GetRole(DiscordSettings.VoiceRole)); return; }
public async Task SendAudioAsync(SocketVoiceChannel voiceChannel, SocketUserMessage userMessage, string fileName) { var lavaLinkPlayer = await this.ConnectAudio(voiceChannel); if (!fileName.Contains(' ')) { ; var url = BASE_AUDIOS_URL + ChatService.RemoveDiacritics(fileName) + ".mp3"; if (await this.IsBotMemeFile(url)) { var tracks = await this._audioService.GetTracksAsync(url); foreach (var track in tracks) { await lavaLinkPlayer.PlayAsync(track); await lavaLinkPlayer.SetVolumeAsync(0.30f); } return; } } var ytTrack = (await this._audioService.GetTracksAsync(fileName, SearchMode.YouTube)).FirstOrDefault(); if (ytTrack == null) { await userMessage.AddReactionAsync(new Emoji("❓")); return; } await lavaLinkPlayer.PlayAsync(ytTrack); await lavaLinkPlayer.SetVolumeAsync(0.30f); }
async Task Handle(TTTGame game, SocketGuildUser user, SocketVoiceChannel before, SocketVoiceChannel gameVc) { var position = int.Parse(gameVc.Name.Split('-')[1]); var coords = game.GetCoords(position); await Handle(game, user, coords); }
public async Task OnGuildReady(SocketGuild guild) { if (guild.CurrentUser.VoiceChannel != null && guild.VoiceChannels.Count > 1) { // seems like the bot died during VC, this'll cause issue such as the bot being slient and stuffs so let's force it out Log.Information("Seems like the bot died while in a voice chat, forcing disconnect..."); await audioService.JoinVoiceChannel(guild, guild.CurrentUser.VoiceChannel); await audioService.LeaveVoiceChannel(guild); Log.Information($"Successfully disconnected the bot from the VC in {guild.Id}!"); } // shhhh this is not a proper fix, i'm aware await Task.Delay(200); if (RossConfig.Root.Binding.BindedChannel > 0 && RossConfig.Root.Binding.BindedServer == guild.Id) { Binding bindingConfig = RossConfig.Root.Binding; Log.Information($"Joining {bindingConfig.BindedChannel} in {guild.Id} due to binding."); SocketVoiceChannel voiceChannel = guild.GetVoiceChannel(RossConfig.Root.Binding.BindedChannel); await audioService.JoinVoiceChannel(guild, voiceChannel); var playlist = audioService.GetPlaylist(guild); playlist.AddFromPlaylistDirectory(RossConfig.Root.Binding.PlaylistName); playlist.Loop = bindingConfig.Loop; await Task.Run(() => playlist.StartPlaylist(audioService, guild, this.client)).ConfigureAwait(false); } }
//creates a new channel and inserts the values into a NOSQL database private async Task InsertChannel(SocketVoiceChannel voiceChannel) { ITextChannel textChannel = await voiceChannel.Guild.CreateTextChannelAsync($"{voiceChannel.Name} - Voice"); await textChannel.ModifyAsync(channel => channel.Topic = $" {voiceChannel.Name} -> {textChannel.Name}"); Log($"Created new Text Channel in {textChannel.GuildId}: {voiceChannel.Id} -> {textChannel.Id}"); string insert = @"INSERT INTO Mappings (VoiceID, TextID, Guild) VALUES ($VoiceID, $TextID, $Guild);"; SQLiteCommand command = new SQLiteCommand(insert, dbConnection); command.Parameters.Add(new SQLiteParameter("$VoiceID")); command.Parameters.Add(new SQLiteParameter("$TextID")); command.Parameters.Add(new SQLiteParameter("$Guild")); command.Parameters["$VoiceID"].Value = voiceChannel.Id; command.Parameters["$TextID"].Value = textChannel.Id; command.Parameters["$Guild"].Value = voiceChannel.Guild.Id; dbConnection.Open(); command.ExecuteScalar(); dbConnection.Close(); OverwritePermissions overwrite = new OverwritePermissions(readMessages: PermValue.Deny); await textChannel.AddPermissionOverwriteAsync(voiceChannel.Guild.EveryoneRole, overwrite); }
public async Task <string> PlayTrack(IGuild guild, SocketVoiceChannel voiceChannel, ITextChannel textChannel, LavaTrack track) { if (voiceChannel == null) { return(GuildUtils.Locate("PlayerError", textChannel)); } if (!LavaNode.TryGetPlayer(guild, out var player) || player == null) { await LavaNode.JoinAsync(voiceChannel, textChannel); player = LavaNode.GetPlayer(guild); } if (track == null) { return(GuildUtils.Locate("InvalidTrack", textChannel)); } if (player.PlayerState == PlayerState.Playing) { player.Queue.Enqueue(track); await _logService.LogAsync(new LogMessage(LogSeverity.Info, "Victoria", $"Added {track.Title} ({track.Url}) to the queue in {textChannel.Guild.Name}/{textChannel.Name}")); return(string.Format(GuildUtils.Locate("PlayerTrackAdded", textChannel), track.ToTrackLink())); } await player.PlayAsync(track); await _logService.LogAsync(new LogMessage(LogSeverity.Info, "Victoria", $"Now playing: {track.Title} ({track.Url}) in {textChannel.Guild.Name}/{textChannel.Name}")); return(string.Format(GuildUtils.Locate("PlayerNowPlaying", textChannel), track.ToTrackLink())); }
public async Task Skip() { var guild = Context.Guild; var user = Context.Message.Author; var queue = Queues.GetOrCreateService(guild.Id); if (!IsInVoiceChannel(Context.Guild, Context.Message.Author)) { await ReplyAsync("You are not in any channel!"); return; } SocketVoiceChannel channel = FindVoiceChannel(guild, user); if (!channel.Users.Any(x => x.Id == Context.Client.CurrentUser.Id)) { await ReplyAsync("You are not in the same channel as me!"); return; } int requests = queue.RequestSkip(user.Id, channel); int usercount = channel.Users.Count(x => !x.IsBot); float part = (float)requests / usercount; await base.ReplyAsync($"Skip requested ({requests} of {usercount}, {(int)Math.Round(part * 100)}%). " + $"{(int)Math.Round(Config.MinSkipQuota * 100)}% needed."); if (part > Config.MinSkipQuota) { queue.Skip(); await ReplyAsync("Skipping current song."); } }
private async Task ConnectToVoice(SocketVoiceChannel voiceChannel) { if (voiceChannel == null) { return; } try { Console.WriteLine($"Connecting to channel {voiceChannel.Id}"); var connection = await voiceChannel.ConnectAsync(); Console.WriteLine($"Connected to channel {voiceChannel.Id}"); _connections[voiceChannel.Guild.Id] = connection; await Task.Delay(1000); _lastZapped[voiceChannel.Guild.Id] = DateTime.Now; await Say(connection, ZapSound.Hello); } catch (Exception ex) { // Oh no, error Console.WriteLine(ex.Message); Console.WriteLine($"- {ex.StackTrace}"); } }
public async Task PlaySoundByNameOnAllMostPopulatedAudioChannels(string fileName) { try { foreach (var sGuild in this._discord.Guilds) { SocketVoiceChannel vcWithMorePeople = null; foreach (var vc in sGuild.VoiceChannels) { if (vcWithMorePeople == null) { vcWithMorePeople = vc; continue; } if (vc.Users.Count > vcWithMorePeople.Users.Count) { vcWithMorePeople = vc; } } if (vcWithMorePeople == null || vcWithMorePeople.Users.Count <= 0) { continue; } await this.SendAudioAsync(vcWithMorePeople, null, fileName); } } catch (Exception e) { await this._log.Error(e.ToString()); } }
public static void HandleUserJoin(SocketVoiceChannel vc) { if (unjoined.Contains(vc.Id)) { unjoined.Remove(vc.Id); } }
private bool EqualVoiceChannel(SocketVoiceChannel x, SocketVoiceChannel y) { if (x == null) { if (y == null) { throw new Exception(); } else { return(false); } } else { if (y == null) { return(false); } else { return(x.Equals(y)); } } }
public static void RemoveLeftoverChannels(SocketGuild server) { List <SocketVoiceChannel> toDelete = new List <SocketVoiceChannel> (); foreach (SocketVoiceChannel channel in server.VoiceChannels) { if (!defaultChannels.ContainsKey(channel.Id) && channel.Users.Count() == 0) { toDelete.Add(channel); } } for (int i = IsDefaultFull() ? 1 : 0; i < toDelete.Count; i++) { SocketVoiceChannel channel = toDelete [i]; string channelName = allVoiceChannels [channel.Id].name; if (channelName != postRebootChannelName && nameQueue.ContainsKey(channelName)) { nameQueue [channelName] = false; } temporaryChannels.Remove(channel); allVoiceChannels.Remove(channel.Id); channel.DeleteAsync(); } ResetVoiceChannelPositions(server); }
public bool ConnectToVoice(ISocketMessageChannel requester, SocketVoiceChannel channel) { if (m_playbackThread == null) { m_playbackThread = Task.Factory.StartNew(PlaybackThread, m_playbackCancellationSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default); } if (m_loadedPlaylists == false && m_loadingPlaylists == false) { Utilities.Execute(async() => await LoadPlaylists(requester)); } if (m_connectedChannel != null && m_audioClient?.ConnectionState == ConnectionState.Connected) { if (channel.Id == m_connectedChannel.Id) { return(true); } } m_audioClient = m_guild.ConnectToVoice(channel); if (m_audioClient == null) { Logging.LogError(LogType.Bot, $"Audio client is not connected on server {m_guild.Name}."); return(false); } m_connectedChannel = channel; return(true); }
private async Task Say(IAudioClient connection, string sound, SocketVoiceChannel channel) { try { await connection.SetSpeakingAsync(true); // send a speaking indicator var psi = new ProcessStartInfo { FileName = "ffmpeg", Arguments = $@"-re -i ""audio/{sound}.wav"" -ac 2 -f s16le -ar 48000 pipe:1", RedirectStandardOutput = true, UseShellExecute = false }; var ffmpeg = Process.Start(psi); var output = ffmpeg.StandardOutput.BaseStream; Tuple <IAudioClient, Process> t = new Tuple <IAudioClient, Process>(connection, ffmpeg); _connections[channel.Guild.Id] = t; var discord = connection.CreatePCMStream(AudioApplication.Voice); await output.CopyToAsync(discord); await discord.FlushAsync(); Tuple <IAudioClient, Process> te = new Tuple <IAudioClient, Process>(connection, null); _connections[channel.Guild.Id] = te; await connection.SetSpeakingAsync(false); // we're not speaking anymore } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine($"- {ex.StackTrace}"); } }
private async Task <bool> IsCustomVC(SocketVoiceChannel voiceChannel) { using MySqlConnection connection = MySQL.MySQL.getConnection(); string query = $"SELECT COUNT(1) FROM CustomVCs WHERE ChannelID={voiceChannel.Id}"; return(await connection.ExecuteScalarAsync <bool>(query)); }
public async Task Connect(SocketVoiceChannel voiceChannel) { if (this.audioClient != null) { await this.Disconnect(); } // TRANSLATORS: Log message. In AudioManager. Logger.Log(T._("* Connect to voice channel")); try { // LOCK STREAMS await st_lock_sem.WaitAsync().ConfigureAwait(false); // stop recording and close audio stream this.CloseRecordStream(); // TRANSLATORS: Log message. In AudioManager. Logger.Log(T._("- join voice channel ...")); this.audioClient = await voiceChannel.ConnectAsync(); this.bitrate = voiceChannel.Bitrate; // create audio stream and start recording this.CreateRecordStream(); // TRANSLATORS: Log message. In AudioManager. Logger.Log(T._("... Done!")); } catch (Exception e) { Logger.DebugLog(e.ToString()); // TRANSLATORS: Error message. In AudioManager. throw new Exception(T._("Could not connect to voice channel."), e); } finally { st_lock_sem.Release(); // RELEASE STREAMS } }
public async Task AFKChannel([Remainder] string chanName) { IReadOnlyCollection <SocketVoiceChannel> vChans = Context.Guild.VoiceChannels; SocketVoiceChannel selectedChan = null; foreach (SocketVoiceChannel chan in vChans) { if (chan.Name.ToLower() == chanName.ToLower()) { selectedChan = chan; break; } } if (selectedChan == null) { await Context.Channel.SendMessageAsync("Voice channel does not exist! Make sure you type it out correctly!\n(not case sensitive)"); } ServerConfig config = ServerConfigs.GetConfig(Context.Guild); config.AFKChannelID = selectedChan.Id; config.AFKChannelName = selectedChan.Name; await Context.Guild.ModifyAsync(m => { m.AfkChannel = selectedChan; }); ServerConfigs.UpdateServerConfig(Context.Guild, config); await PrintEmbedMessage("AFK Channel Set", string.Format("**{0}** is now the AFK Channel!\nUsers will be sent there after **{1}mins**", selectedChan.Name, config.AFKTimeout / 60), iconUrl : config.IconURL); }
public async Task PlayAsync([Remainder] string query) { // Ensure voice SocketVoiceChannel voiceChannel = (Context.User as SocketGuildUser)?.VoiceChannel; if (voiceChannel is null) { await ReplyAsync("You r not in a voice channel"); return; } SocketVoiceChannel selfVoiceChannel = (Context.Guild.CurrentUser as SocketGuildUser)?.VoiceChannel; if (selfVoiceChannel is null) { await audioService.JoinChannel(voiceChannel, Context.Guild); } AudioTrack loadedTrack = await audioService.LoadAndPlay(query, Context.Guild); if (loadedTrack != null) { await ReplyAsync($":musical_note: Added to queue {loadedTrack.Info.Title}"); } else { await ReplyAsync($"Not found anything with {query}"); } }
public async Task <bool> ConnectVoiceChannel(SocketVoiceChannel voiceChannel) { await DisconnectCurrentVoiceChannel(); if (voiceChannel == null) { throw new ArgumentNullException("VoiceChannel is null"); } CurrentVoiceChannel = voiceChannel; // ボイスチャンネルへの接続を開始 // 音声の送信はConnectedイベント後 // 受信はStreamCreatedイベント後に行われます using (var releaser = await _VoiceChannelLock.LockAsync()) { await voiceChannel.ConnectAsync((client) => { _CurrentVoiceAudioClient = client; client.Connected += VoiceChannelConnected; client.Disconnected += VoiceChannelDisconnected; client.LatencyUpdated += VoiceChannelLatencyUpdated; client.SpeakingUpdated += VoiceChannelSpeakingUpdated; client.StreamCreated += VoiceChannelAudioStreamCreated; client.StreamDestroyed += VoiceChannelAudioStreamDestroyed; }); CurrentVoiceChannel = voiceChannel; ConnectState = UncordChannelConnectState.Connected; } return(true); }
private void UserLeftVoiceChannel(SocketGuildUser user, SocketVoiceChannel channel) { var key = $"{_creds.RedisKey()}_user_xp_vc_join_{user.Id}"; var value = _cache.Redis.GetDatabase().StringGet(key); _cache.Redis.GetDatabase().KeyDelete(key); // Allow for if this function gets called multiple times when a user leaves a channel. if (value.IsNull) { return; } if (!value.TryParse(out long startUnixTime)) { return; } var dateStart = DateTimeOffset.FromUnixTimeSeconds(startUnixTime); var dateEnd = DateTimeOffset.UtcNow; var minutes = (dateEnd - dateStart).TotalMinutes; var xp = _bc.BotConfig.VoiceXpPerMinute * minutes; var actualXp = (int)Math.Floor(xp); if (actualXp > 0) { _addMessageXp.Enqueue(new UserCacheItem { Guild = channel.Guild, User = user, XpAmount = actualXp }); } }
private async Task <bool> TryRenameChannel(SocketVoiceChannel voiceChannel) { if (voiceChannel.Users.Count == 0 && !voiceChannel.Name.Equals(DEFAULT_DYNAMIC_CHANNEL_NAME)) { string oldName = voiceChannel.Name; await voiceChannel.ModifyAsync(x => x.Name = DEFAULT_DYNAMIC_CHANNEL_NAME); log.Debug("Reverted channel: " + voiceChannel.Id + " - \"" + oldName + "\""); return(true); } else if (voiceChannel.Users.Count == 1) { if (!await TryUpdateToTopGame(voiceChannel)) { await TryRenameVoiceChannelToUser(voiceChannel, voiceChannel.Users.First()); } return(true); } else if (!await TryUpdateToTopGame(voiceChannel) && !voiceChannel.Name.Equals(DEFAULT_DYNAMIC_CHANNEL_NAME) && voiceChannel.Users.Any(x => voiceChannel.Name.Contains(x.Username) || voiceChannel.Name.Contains(x.Nickname))) { var user = voiceChannel.Users.First(); log.Debug("No top game in channel: " + voiceChannel.Id + " - \"" + voiceChannel.Name + "\""); await TryRenameVoiceChannelToUser(voiceChannel, user); return(true); } else { return(false); } }
protected static void VoiceChannelConnectedValidation(SocketVoiceChannel channel) { if (channel == null) { throw new InvalidOperationException("You are not connected to a voice channel"); } }
public VoiceChannelWorker(SocketVoiceChannel voiceChannel, MetadataManager metadataManager, PlayHistoryManager playHistoryManager, WitAiClient witAiClient) { _voiceChannel = voiceChannel; _metadataManager = metadataManager; _playHistoryManager = playHistoryManager; _witAiClient = witAiClient; }