public async Task <AudioPlayer> JoinAsync(IVoiceChannel voiceChannel, ISocketMessageChannel textChannel) { await voiceChannel.ConnectAsync(true); await voiceChannel.DisconnectAsync(); var client = await voiceChannel.ConnectAsync(true); var player = new AudioPlayer(voiceChannel.GuildId, textChannel, voiceChannel, client, this, _client); players.Add(player); return(player); }
public async Task Play(IVoiceChannel vc, Audio audio, CancellationToken cancellationToken) { using var s3object = await s3Client.GetObjectAsync("quotebot-audio-post", audio.Path, cancellationToken); using var ffmpeg = CreateStream(); using var output = ffmpeg.StandardOutput.BaseStream; var inputTask = Task.Run(async() => { using var input = ffmpeg.StandardInput.BaseStream; await s3object.ResponseStream.CopyToAsync(input, cancellationToken); }, cancellationToken); using var audioClient = await vc.ConnectAsync(); using var discord = audioClient.CreatePCMStream(AudioApplication.Mixed, bufferMillis: 1); try { await output.CopyToAsync(discord, cancellationToken); await inputTask; } finally { await discord.FlushAsync(cancellationToken); } await vc.DisconnectAsync(); }
public async Task JoinChannelAndPlayAudio(IVoiceChannel channel = null) { string downloadedFileName = null; // Attempt to download the attachment if it exists if (Context.Message.Attachments != null && Context.Message.Attachments.Count > 0) { downloadedFileName = this.downloadAttachedFiles(Context.Message); } else { await Context.Channel.SendMessageAsync("You must attach a valid audio file to be played."); return; } if (downloadedFileName == null) { return; } // Get the audio channel channel = channel ?? (Context.User as IGuildUser)?.VoiceChannel; if (channel == null) { await Context.Channel.SendMessageAsync("User must be in a voice channel, or a voice channel must be passed as an argument."); return; } var audioClient = await channel.ConnectAsync(true, false); await this.SendAsync(audioClient, PlayAudioFileCommand.downloadedFileDir + downloadedFileName); }
public async Task Join() { IVoiceChannel vc = (Context.User as IGuildUser)?.VoiceChannel; if (vc == null) { await Context.Channel.SendMessageAsync("**:x: You have to be in a voice channel to use this command**"); return; } try { AudioService.Dispose(); Initialize(await vc.ConnectAsync(), Context.Channel); } catch (Exception e) { Console.WriteLine(e.Message); } finally { await Context.Channel.SendMessageAsync($"**:thumbsup: Joined `{vc.Name}` and bound to {(Context.Channel as SocketTextChannel).Mention}**"); } }
/// <summary> /// Joins audio channel /// </summary> /// <param name="guild">The guild the bot is connected to</param> /// <param name="target">The target voice channel</param> /// <param name="mChannel">The message channel that allows sending messages etc.</param> public async Task JoinAudio(IGuild guild, IVoiceChannel target, IMessageChannel mChannel = null) { if (target == null) { if (mChannel != null) { await mChannel.SendMessageAsync("You must be connected to a channel for me to join!"); } return; } if (ConnectedChannels.TryGetValue(guild.Id, out _)) { return; } if (target.Guild.Id != guild.Id) { return; } var audioClient = await target.ConnectAsync(); if (ConnectedChannels.TryAdd(guild.Id, audioClient)) { _logger.LogInfo($"Connected to a voice channel in: { guild.Name }"); } }
public async Task JoinAsync(IVoiceChannel voiceChannel, IMessageChannel channel) { if (voiceChannel == null) { await channel.SendMessageAsync("<Mention> __User must be in a voice channel__"); return; } var guildId = voiceChannel.Guild.Id; if (_container.TryGetValue(guildId, out _)) { return; } var Container = new AudioContainer { AudioClient = await voiceChannel.ConnectAsync(), CancellationTokenSource = new CancellationTokenSource(), QueueManager = new QueueManager(), }; Container.AudioOutStream = Container.AudioClient.CreatePCMStream(AudioApplication.Music, bitrate: 128000); _container.TryAdd(guildId, Container); }
public async Task <JoinChannelResult> JoinChannelAsync(SocketCommandContext context, IVoiceChannel voiceChannel) { if (entries.TryGetValue(context.Guild.Id, out MusicEntry entry)) { return(JoinChannelResult.ALREADY_CONNECTED); } if (context.Guild.Id != voiceChannel.GuildId) { return(JoinChannelResult.DIFFERENT_GUILD); } var audioClient = await voiceChannel.ConnectAsync(); MusicEntry newentry = new MusicEntry(context.Guild.Id, voiceChannel, audioClient, context.Channel, database.GetStreams()); if (entries.TryAdd(context.Guild.Id, newentry)) { // Register event handlers newentry.MusicPlayer.PlayerStarted += Player_PlayerStarted; newentry.MusicPlayer.PlayerStopped += Player_PlayerStopped; newentry.MusicPlayer.SongQueued += Player_SongQueued; newentry.MusicPlayer.PlaylistQueued += Player_PlaylistQueued; newentry.StreamPlayer.PlayerStarted += StreamPlayer_PlayerStarted; newentry.StreamPlayer.PlayerStopped += StreamPlayer_PlayerStopped; return(JoinChannelResult.JOINED); } return(JoinChannelResult.NONE); }
//public async Task JoinAudio(IGuild guild, IVoiceChannel target) //{ // AudioChannelInfo info; // if (ConnectedChannels.TryGetValue(guild.Id, out info) && info.AudioClient != null) // { // return; // } // if (target.Guild.Id != guild.Id) // { // return; // } // var audioClient = await target.ConnectAsync(); // if (info == null) // { // info = new AudioChannelInfo(); // } // info.AudioClient = audioClient; // if (ConnectedChannels.TryAdd(guild.Id, info)) // { // // If you add a method to log happenings from this service, // // you can uncomment these commented lines to make use of that. // //await Log(LogSeverity.Info, $"Connected to voice on {guild.Name}."); // Console.WriteLine($"Connected to voice on {guild.Name}."); // } //} //public async Task LeaveAudio(IGuild guild) //{ // AudioChannelInfo info; // if (ConnectedChannels.ContainsKey(guild.Id)) // { // info = ConnectedChannels[guild.Id]; // await info.AudioClient.StopAsync(); // ConnectedChannels.Remove(guild.Id, out info); // //await Log(LogSeverity.Info, $"Disconnected from voice on {guild.Name}."); // } //} public async Task JoinAudio(IVoiceChannel target) { UsingAudioClient = await target.ConnectAsync(); UsingVoiceChannel = target; //Console.WriteLine($"Connected to voice on {guild.Name}."); }
public async Task JoinChannelAsync(IVoiceChannel channel, ulong guildID) { _audioClient = await channel.ConnectAsync(); var lol = _audioClient.ConnectionState; // _audioClients.TryAdd(guildID, audioClient); }
public async Task Radio() { IVoiceChannel channel = (Context.Message.Author as IGuildUser).VoiceChannel; if (channel == null) { await Context.Channel.SendMessageAsync("Please join a voice channel before requesting radio! :)"); return; } if (ChannelTrackList.Keys.Contains(channel) == false) { AudioPlayer NewPlayer = new AudioPlayer() { MessageClient = Context.Message.Channel }; NewPlayer.SendMessage_Raised += (Message, x) => x.SendMessageAsync(Message); ChannelTrackList.Add(channel, NewPlayer); } AudioPlayer Player = ChannelTrackList[channel]; var IsInVoiceChannel = await channel.GetUserAsync(Context.Client.CurrentUser.Id); if (IsInVoiceChannel == null || Player.DiscordOutStream == null) { IAudioClient audioClient = await channel.ConnectAsync(); Player.EngageOutStream(audioClient); } await Player.PlayRadio(); }
public async Task deneme() { IVoiceChannel channel = (Context.User as IVoiceState).VoiceChannel; IAudioClient client = await channel.ConnectAsync(); var stream = client.CreatePCMStream(AudioApplication.Music); }
public async Task JoinAudio(IVoiceChannel channel = null) { // Get the audio channel channel = channel ?? (Context.Message.Author as IGuildUser)?.VoiceChannel; if (channel == null) { await Context.Channel.SendMessageAsync("You must be in a voice channel."); return; } var userList = channel.GetUserAsync(307798617522044929); //if bot is not in channel, then join the channel if (userList.Result == null) { // For the next step with transmitting audio, you would want to pass this Audio Client in to a service. DiscordBot.AudioClient = await channel.ConnectAsync(); } else { await Context.Channel.SendMessageAsync("Bot is already in a channel"); } }
private async Task JoinAudio(EduardoContext context) { // Get connected voice channel of requesting user IVoiceChannel target = (context.User as IVoiceState)?.VoiceChannel; // Don't join audio if not correct guild. if (target?.Guild.Id != context.Guild.Id) { return; } // Leave current audio channel on guild (if any) if (_connectedChannels.ContainsKey(context.Guild.Id)) { await LeaveAudio(context.Guild); } // Connect to new audio channel IAudioClient audioClient = await target.ConnectAsync(); // Register connection in connected channels if (_connectedChannels.TryAdd(context.Guild.Id, audioClient)) { await Logger.Log($"Connected to voice channel on {context.Guild.Name}", LogSeverity.Info); } else { await Logger.Log($"Failed to join voice channel on {context.Guild.Name}", LogSeverity.Error); } }
public async Task QueueFileAsync(ITextChannel guildChannel, IVoiceChannel target, string path) { if (guildChannel == null) { return; } if (_connectedChannels.TryGetValue(guildChannel.Guild.Id, out var audio)) { audio.Queue.Enqueue(path); return; } if (target.Guild.Id != guildChannel.Guild.Id) { return; } var audioClient = await target.ConnectAsync().ConfigureAwait(false); audio = new GuildAudioInfo(guildChannel, audioClient); audio.Queue.Enqueue(path); if (_connectedChannels.TryAdd(guildChannel.Guild.Id, audio)) { #pragma warning disable CS4014 Task.Run(() => SendAudioAsync(guildChannel.Guild)); #pragma warning restore CS4014 } }
public async Task <TriviaServiceResult> StartQuiz() { if (_audioConnection == null || _audioConnection.ConnectionState != ConnectionState.Connected) { _audioConnection = await _channel.ConnectAsync(); } var channelMembers = await _channel.GetUsersAsync().FlattenAsync(); foreach (IGuildUser member in channelMembers) { if (!member.IsBot) { _mapPlayersToScores.Add(member.Id, 0); _mapIdsToUsernames.Add(member.Id, member.Username); } } EmbedBuilder builder = new EmbedBuilder(); builder.WithTitle("Starting Music Quiz!"); builder.WithColor(kEmbedColor); builder.WithDescription("Get ready! There are 15 songs, you have 30 seconds to guess either the singer/band or the name of the song. Good Luck! You can end the quiz using the end-trivia command"); await(_textChannel as ISocketMessageChannel).SendMessageAsync("", false, builder.Build()); PlaySnippet(_questions[0]); return(TriviaServiceResult.Success); }
public async Task ConnectAsync(IGuild guild, IVoiceChannel voice, IMessageChannel chan = null) { IAudioClient audioClient; if (ourGuilds.TryGetValue(guild.Id, out IAudioClient value)) { return; } if (voice.GuildId != guild.Id) { return; } if (chan != null) { await chan.SendMessageAsync("**Joining your voice channel!** :clap:"); audioClient = await voice.ConnectAsync(); } else { audioClient = await voice.ConnectAsync(); } if (ourGuilds.TryAdd(guild.Id, audioClient)) { return; } }
public async Task JoinChannel(IVoiceChannel channel, ulong guildID) { //for the next step with transmitting audio, you would want to pass this audio client in to a service var audioClient = await channel.ConnectAsync(); audioDict.TryAdd(guildID, audioClient); }
//On Bot ready private async void Ready() { Print("Ready!", ConsoleColor.Green); //"Playing Nothing :/" await _client.SetGameAsync("Nothing :/"); //Get Guilds / Servers try { //Server PrintServers(); SocketGuild guild = _client.Guilds.FirstOrDefault(g => g.Name == Information.ServerName); //Text Channel _textChannel = guild.TextChannels.FirstOrDefault(t => t.Name == Information.TextChannelName); Print($"Using Text Channel: \"#{_textChannel.Name}\"", ConsoleColor.Cyan); //Voice Channel _voiceChannel = guild.VoiceChannels.FirstOrDefault(t => t.Name == Information.VoiceChannelName); Print($"Using Voice Channel: \"{_voiceChannel.Name}\"", ConsoleColor.Cyan); _audio = await _voiceChannel.ConnectAsync(); } catch (Exception e) { Print("Could not join Voice/Text Channel (" + e.Message + ")", ConsoleColor.Red); } }
public async Task JoinAudioChannel(IGuild guild, IVoiceChannel target) { //TODO: Throw exceptions beside returns. IAudioClient client; if (ConnectedChannels.TryGetValue(guild.Id, out client)) { return; } if (target.Guild.Id != guild.Id) { return; } var audioClient = await target.ConnectAsync(); if (ConnectedChannels.TryAdd(guild.Id, audioClient)) { LogMessage logMessage = new LogMessage(LogSeverity.Info, "Audio", $"Connected to voice on {guild.Name}."); await _logHandler.Handle(logMessage); return; } else { //Something went wrong return; } }
public async Task JoinAudio(IGuild guild, IVoiceChannel target) { try { if (isGuildAdded(guild).Result) { if (connectedVChannel(guild).Result != null) { return; } ConnectedChannels.Clear(); } if (target.Guild.Id != guild.Id) { return; } var audioClient = await target.ConnectAsync(); if (ConnectedChannels.TryAdd(guild.Id, audioClient)) { DiscordWrapper.Log($"[info][{LogSeverity.Info}] Connected to voice on {guild.Name}."); } } catch (Exception ex) { DiscordWrapper.Log($"[log] {ex}"); } }
public async Task JoinVoiceChannel(IGuild guild, IVoiceChannel destination) { Console.WriteLine("Now joining a voice channel."); if (destination.Guild.Id != guild.Id) { return; } var audioClient = await destination.ConnectAsync(); if (CurrentChannels.TryGetValue(guild.Id, out IAudioClient client)) { Console.WriteLine("Audio client found."); if (CurrentChannels.TryUpdate(guild.Id, audioClient, client)) { Console.WriteLine("Updated voice channel location."); Console.WriteLine($"orikivo.cs\nvoice.updated('{guild.Name}')"); } return; } if (CurrentChannels.TryAdd(guild.Id, audioClient)) { Console.WriteLine("Connected to voice channel."); Console.WriteLine($"orikivo.cs\nvoice.connected('{guild.Name}')"); } }
public async Task JoinAudio(IGuild guild, IVoiceChannel target) { try { if (ConnectedChannels.TryGetValue(guild.Id, out IAudioClient client)) { return; } if (target.Guild.Id != guild.Id) { return; } var audioClient = await target.ConnectAsync(); if (ConnectedChannels.TryAdd(guild.Id, audioClient)) { // If you add a method to log happenings from this service, // you can uncomment these commented lines to make use of that. //await Log(LogSeverity.Info, $"Connected to voice on {guild.Name}."); } } catch (Exception ex) { Console.WriteLine($"JoinAudio error: {ex}"); } }
private Task UserVoiceStateUpdated(SocketUser arg1, SocketVoiceState oldState, SocketVoiceState newState) { if (arg1.Id == client.CurrentUser.Id) { return(Task.CompletedTask); } _ = Task.Run(async() => { IVoiceChannel channel = null; string audioClipPath = null; //disconnect if (newState.VoiceChannel == null && oldState.VoiceChannel != null) { channel = oldState.VoiceChannel; audioClipPath = ClipPaths[SoundClip.Disconnected]; } //connect if (newState.VoiceChannel != null && oldState.VoiceChannel == null) { channel = newState.VoiceChannel; audioClipPath = ClipPaths[SoundClip.Connected]; } //server muted if (newState.IsMuted && !oldState.IsMuted) { channel = newState.VoiceChannel; audioClipPath = ClipPaths[SoundClip.Muted]; } //un server muted if (!newState.IsMuted && oldState.IsMuted) { channel = newState.VoiceChannel; audioClipPath = ClipPaths[SoundClip.Unmuted]; } //move if (newState.VoiceChannel != null && oldState.VoiceChannel != null && newState.VoiceChannel.Id != oldState.VoiceChannel.Id) { channel = newState.VoiceChannel; audioClipPath = ClipPaths[SoundClip.Connected]; } if (channel != null && audioClipPath != null) { //if (channel.GuildId != 678781680638492672) // return; var audioClient = await channel.ConnectAsync(); await SendAsync(audioClient, audioClipPath); await channel.DisconnectAsync(); } }); return(Task.CompletedTask); }
public async Task stream(IVoiceChannel channel = null) { // Get the audio channel channel = channel ?? (Context.User as IGuildUser)?.VoiceChannel; if (channel == null) { await Context.Channel.SendMessageAsync("User must be in a voice channel, or a voice channel must be passed as an argument."); return; } // For the next step with transmitting audio, you would want to pass this Audio Client in to a service. var audioClient = await channel.ConnectAsync(); await audioClient.SetSpeakingAsync(true); var psi = new ProcessStartInfo { FileName = "ffmpeg", Arguments = $@"-f pulse -i default -ac 2 -f s16le -ar 48000 pipe:1", RedirectStandardOutput = true, UseShellExecute = false }; var ffmpeg = Process.Start(psi); var output = ffmpeg.StandardOutput.BaseStream; var discord = audioClient.CreatePCMStream(AudioApplication.Voice); await output.CopyToAsync(discord); await discord.FlushAsync(); }
public async Task Tts(string message) { var client = TextToSpeechClient.Create(); var input = new SynthesisInput { Text = message.ToLower() }; var voiceSelection = new VoiceSelectionParams { LanguageCode = "pl-PL", Name = "pl-PL-Standard-C", SsmlGender = SsmlVoiceGender.Female }; var audioConfig = new AudioConfig { AudioEncoding = AudioEncoding.Mp3, SpeakingRate = 0.85 }; var response = client.SynthesizeSpeech(input, voiceSelection, audioConfig); using (var output = File.Create(EnvVars.RoboMajkelTtsAudioFileLocation)) { response.AudioContent.WriteTo(output); } IVoiceChannel channel = (Context.User as IGuildUser)?.VoiceChannel; var audioClient = await channel.ConnectAsync(); await SendAsync(audioClient, EnvVars.RoboMajkelTtsAudioFileLocation); }
public async Task <bool> JoinAudio(IGuild guild, IVoiceChannel target) { if (this.IsConnected(guild.Id)) { return(false); } if (target.Guild.Id != guild.Id) { return(false); } AudioClient audioClient = new AudioClient(); audioClient.Client = await target.ConnectAsync(); if (this.connectedChannels.TryAdd(guild.Id, audioClient)) { FC.Log.Write($"Connected to voice on {guild.Name}.", "Bot - Audio"); // Leave audio if no music _ = Task.Run(async() => await IdleStreamStop()); return(true); } return(false); }
public async Task JoinAudio(IGuild guild, IVoiceChannel target) { IAudioClient client; if (ConnectedChannels.TryGetValue(guild.Id, out client)) { return; } if (target.Guild.Id != guild.Id) { return; } try { var audioClient = await target.ConnectAsync(); if (ConnectedChannels.TryAdd(guild.Id, audioClient)) { // // If you add a method to log happenings from this service, // // you can uncomment these commented lines to make use of that. Console.WriteLine($"Connected to voice on {guild.Name}."); } } catch (Exception ex) { Console.WriteLine("Could not connect to chat: " + ex.Message); } }
//[Command("come",RunMode =RunMode.Async)] //[Summary("Comes joins to the channel")] public async Task Come() { try { _audio?.Dispose(); _voiceChannel = Context.Guild.GetVoiceChannelsAsync(CacheMode.AllowDownload).Result.FirstOrDefault(x => x.Name.ToLower() == "Music".ToLower()); if (_voiceChannel == null) { await Context.Channel.SendMessageAsync("Create a Voice Channel with the name Music"); } _textChannel = Context.Guild.GetTextChannelsAsync(CacheMode.AllowDownload).Result.FirstOrDefault(x => x.Name.ToLower() == "Music".ToLower()); if (_textChannel == null) { await Context.Channel.SendMessageAsync("Create a Text Channel with the name Music"); } _audio = await _voiceChannel.ConnectAsync(); } catch (Exception ex) { CommonTools.ErrorReporting(ex); } }
public async Task <bool> TryToJoinAudioChannel(IGuild guild, IVoiceChannel target) { try { IAudioClient client; if (ConnectedChannels.TryGetValue(guild.Id, out client)) { return(false); } if (target.Guild.Id != guild.Id) { return(false); } var audioClient = await target.ConnectAsync(); if (ConnectedChannels.TryAdd(guild.Id, audioClient)) { return(true); // If you add a method to log happenings from this service, // you can uncomment these commented lines to make use of that. //await Log(LogSeverity.Info, $"Connected to voice on {guild.Name}."); } return(false); } catch (Exception ex) { Logger.Log(ex.ToString()); throw; } }
public async Task som() { // Get the audio channel IVoiceChannel channel = (Context.User as IGuildUser)?.VoiceChannel; if (channel == null) { await Context.Channel.SendMessageAsync("User must be in a voice channel, or a voice channel must be passed as an argument."); return; } // For the next step with transmitting audio, you would want to pass this Audio Client in to a service. var audioClient = await channel.ConnectAsync(); string path = "C:\\Users\\phili\\Music\\bateu.mp3"; string pathSite = "https://www.youtube.com/watch?v=IpMLYWb1G1w"; var processo = Process.Start(new ProcessStartInfo { FileName = "ffmpeg", Arguments = $"-hide_banner -loglevel panic -i \"{path}\" -ac 2 -f s16le -ar 48000 pipe:1", UseShellExecute = false, RedirectStandardOutput = true, }); // Create FFmpeg using the previous example using (var ffmpeg = processo) using (var output = ffmpeg.StandardOutput.BaseStream) //120, 240, 480, 960, 1920, or 2880 using (var discord = audioClient.CreatePCMStream(AudioApplication.Mixed)) { try { await output.CopyToAsync(discord); } finally { await discord.FlushAsync(); } } }
public MusicPlayer(IVoiceChannel startingVoiceChannel, float? defaultVolume) { if (startingVoiceChannel == null) throw new ArgumentNullException(nameof(startingVoiceChannel)); 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) { Console.WriteLine("Action queue crashed"); Console.WriteLine(ex); } }).ConfigureAwait(false); var t = new Thread(new ThreadStart(async () => { while (!Destroyed) { try { if (audioClient?.ConnectionState != ConnectionState.Connected) { if (audioClient != null) try { await audioClient.DisconnectAsync().ConfigureAwait(false); } catch { } audioClient = await PlaybackVoiceChannel.ConnectAsync().ConfigureAwait(false); continue; } CurrentSong = GetNextSong(); RemoveSongAt(0); if (CurrentSong == null) continue; OnStarted(this, CurrentSong); await CurrentSong.Play(audioClient, cancelToken); OnCompleted(this, CurrentSong); if (RepeatPlaylist) AddSong(CurrentSong, CurrentSong.QueuerName); if (RepeatSong) AddSong(CurrentSong, 0); } catch (OperationCanceledException) { } catch (Exception ex) { Console.WriteLine("Music thread almost crashed."); Console.WriteLine(ex); } finally { if (!cancelToken.IsCancellationRequested) { SongCancelSource.Cancel(); } SongCancelSource = new CancellationTokenSource(); cancelToken = SongCancelSource.Token; CurrentSong = null; await Task.Delay(300).ConfigureAwait(false); } } })); t.Start(); }
public Task MoveToVoiceChannel(IVoiceChannel voiceChannel) { if (audioClient?.ConnectionState != ConnectionState.Connected) throw new InvalidOperationException("Can't move while bot is not connected to voice channel."); PlaybackVoiceChannel = voiceChannel; return PlaybackVoiceChannel.ConnectAsync(); }