public async Task ConnectAsync(CommandContext ctx, [Description("Channel.")] DiscordChannel channel = null) { VoiceNextExtension vnext = ctx.Client.GetVoiceNext(); if (vnext == null) { throw new CommandFailedException("VNext is not enabled or configured."); } VoiceNextConnection vnc = vnext.GetConnection(ctx.Guild); if (vnc != null) { throw new CommandFailedException("Already connected in this guild."); } DiscordVoiceState vstat = ctx.Member?.VoiceState; if ((vstat == null || vstat.Channel == null) && channel == null) { throw new CommandFailedException("You are not in a voice channel."); } if (channel == null) { channel = vstat.Channel; } vnc = await vnext.ConnectAsync(channel); await this.InformAsync(ctx, StaticDiscordEmoji.Headphones, $"Connected to {Formatter.Bold(channel.Name)}.", important : false); }
public Task DisconnectAsync(CommandContext ctx) { VoiceNextExtension vnext = ctx.Client.GetVoiceNext(); if (vnext == null) { throw new CommandFailedException("VNext is not enabled or configured."); } VoiceNextConnection vnc = vnext.GetConnection(ctx.Guild); if (vnc == null) { throw new CommandFailedException("Not connected in this guild."); } if (MusicPlayers.ContainsKey(ctx.Guild.Id)) { MusicPlayers[ctx.Guild.Id].Stop(); MusicPlayers.TryRemove(ctx.Guild.Id, out _); } // TODO check await Task.Delay(500); vnc.Disconnect(); return(this.InformAsync(ctx, StaticDiscordEmoji.Headphones, "Disconnected.", important: false)); }
public Bot() { Instance = this; //DownloadAudioClips(); DiscordConfiguration discordConfiguration = new DiscordConfiguration() { AutoReconnect = true, Token = Config.Instance.Token, TokenType = TokenType.Bot, UseInternalLogHandler = true, LogLevel = LogLevel.Info, DateTimeFormat = "MM/dd/yyyy hh:mm:ss tt" }; discord = new DiscordClient(discordConfiguration); discord.DebugLogger.LogMessageReceived += LogMessageReceived; interactivity = discord.UseInteractivity(new InteractivityConfiguration()); voice = discord.UseVoiceNext(); commands = discord.UseCommandsNext(new CommandsNextConfiguration() { StringPrefixes = new[] { Config.Instance.Prefix }, CaseSensitive = false }); commands.RegisterCommands <GeneralCommands>(); commands.RegisterCommands <AudioModule>(); commands.RegisterCommands <MinecraftCommands>(); commands.CommandErrored += CommandErrored; commands.CommandExecuted += CommandExecuted; //discord.MessageCreated += MessageCreated; discord.Ready += Ready; }
public async Task Join(CommandContext ctx, DiscordChannel chn = null) { _vnext = ctx.Client.GetVoiceNext(); if (_vnext == null) { await ctx.RespondAsync(":x: VNext is not enabled or configured."); return; } VoiceNextConnection vnc = _vnext.GetConnection(ctx.Guild); if (vnc != null) { await ctx.RespondAsync("Already connected."); return; } DiscordVoiceState vstat = ctx.Member?.VoiceState; if (vstat?.Channel == null && chn == null) { await ctx.RespondAsync("You are not in a voice channel."); return; } if (chn == null) { chn = vstat.Channel; } await chn.ConnectAsync(); await ctx.RespondAsync($"Connected to `{chn.Name}`"); }
public async Task Leave(CommandContext ctx) { DiscordMessage tmp = await ctx.RespondAsync("DC"); VoiceNextExtension vnext = ctx.Client.GetVoiceNext(); await tmp.DeleteAsync(); tmp = await ctx.RespondAsync("DC: GVNC"); VoiceNextConnection vnc = vnext.GetConnection(ctx.Guild); await tmp.DeleteAsync(); tmp = await ctx.RespondAsync("DC: CVNC"); if (vnc == null) { throw new InvalidOperationException("Not connected in this guild."); } await tmp.DeleteAsync(); tmp = await ctx.RespondAsync("DC: DCXC"); vnc.Disconnect(); await tmp.DeleteAsync(); await ctx.RespondAsync("👌"); }
private async Task ConnectAndAddToQueueAsync(CommandContext ctx, SongInfo si) { VoiceNextExtension vnext = ctx.Client.GetVoiceNext(); if (vnext == null) { throw new CommandFailedException("VNext is not enabled or configured."); } VoiceNextConnection vnc = vnext.GetConnection(ctx.Guild); if (vnc == null) { await this.ConnectAsync(ctx); vnc = vnext.GetConnection(ctx.Guild); } if (MusicPlayers.ContainsKey(ctx.Guild.Id)) { MusicPlayers[ctx.Guild.Id].Enqueue(si); await ctx.RespondAsync("Added to queue:", embed : si.ToDiscordEmbed(this.ModuleColor)); } else { if (!MusicPlayers.TryAdd(ctx.Guild.Id, new MusicPlayer(ctx.Client, ctx.Channel, vnc))) { throw new ConcurrentOperationException("Failed to initialize music player!"); } MusicPlayers[ctx.Guild.Id].Enqueue(si); var t = Task.Run(() => MusicPlayers[ctx.Guild.Id].StartAsync()); } }
public AudioPlayerModule(ILogger <AudioPlayerModule> logger, IBotCoreModule botCoreModule, AudioPlayer config) { // These dlls are imported via DllImportAttribute which does not trigger BotRunner's assembly resolve functionality string opus = "libopus.dll", sodium = "libsodium.dll"; CopyNativeLib(opus); CopyNativeLib(sodium); _logger = logger; _botCoreModule = botCoreModule; _botCoreModule.CommandHandler.RegisterCommands <AudioPlayerCommands>(); _botCoreModule.DiscordClient.VoiceStateUpdated += VoiceStateUpdated; _config = config; _voiceNextExtension = _botCoreModule.DiscordClient.UseVoiceNext(new VoiceNextConfiguration { EnableIncoming = false }); foreach (Track track in config.Tracks) { if (track.FileName != null && track.FileNames != null) { _logger.LogWarning($"Track \"{track.Name}\" has a file name and a list of file names, if the file name is not also included in the list it will not be used as a trigger!"); } } }
private async Task Client_MessageCreatedAsync(DSharpPlus.EventArgs.MessageCreateEventArgs e) { if (e.Message.Content.Contains(":foodReview:")) { VoiceNextExtension voiceNextClient = Program.Client.GetVoiceNext(); VoiceNextConnection voiceNextCon = voiceNextClient.GetConnection(e.Guild); if (voiceNextCon == null) { foreach (DiscordVoiceState vs in e.Guild.VoiceStates) { if (vs.User.Username.Equals(e.Author.Username)) { voiceNextCon = await voiceNextClient.ConnectAsync(vs.Channel); } } } if (voiceNextCon == null) { // user wasnt in a voice channel return; } else { // await PlayAudio(voiceNextCon, @"AudioFiles\foodReview.mp3"); voiceNextCon.Disconnect(); } } }
public JosephineBot(JosephineConfig cfg, int shardid) { Config = cfg; var dcfg = new DiscordConfiguration { AutoReconnect = true, LargeThreshold = 250, LogLevel = LogLevel.Debug, Token = Config.Token, TokenType = TokenType.Bot, UseInternalLogHandler = false, ShardId = shardid, ShardCount = Config.ShardCount, MessageCacheSize = 2048, DateTimeFormat = "dd-MM-yyyy HH:mm:ss zzz" }; debugMode = Config.debug; Discord = new DiscordClient(dcfg); Discord.DebugLogger.LogMessageReceived += this.DebugLogger_LogMessageRecieved; Discord.Ready += this.Client_Ready; Discord.ClientErrored += this.Client_ClientError; Discord.GuildUpdated += this.Discord_GuildUpdated; Discord.ChannelDeleted += this.Discord_ChannelDeleted; Discord.MessageCreated += this.Client_Chat; Discord.MessageUpdated += this.MessageUpdated; //Discord.GuildMemberAdded += this.Join_Chat; var vcfg = new VoiceNextConfiguration { AudioFormat = AudioFormat.Default, EnableIncoming = true }; VoiceService = Discord.UseVoiceNext(vcfg); var depco = new ServiceCollection(); // commandsnext config and the commandsnext service itself var cncfg = new CommandsNextConfiguration { StringPrefixes = Config.CommandPrefixes, EnableDms = false, EnableMentionPrefix = true, CaseSensitive = false, Services = depco.BuildServiceProvider(true), IgnoreExtraArguments = false, UseDefaultCommandHandler = true, }; this.CommandsNextService = Discord.UseCommandsNext(cncfg); this.CommandsNextService.CommandErrored += this.CommandsNextService_CommandErrored; this.CommandsNextService.CommandExecuted += this.Commands_CommandExecuted; this.CommandsNextService.RegisterCommands(typeof(JosephineBot).GetTypeInfo().Assembly); this.CommandsNextService.SetHelpFormatter <HelpFormatter>(); }
/// <summary> /// Connect to a Voicechannel /// </summary> /// <param name="channel"></param> /// <param name="voiceNext"></param> /// <returns>true when successfuly connected, false if not</returns> public async Task <bool> ConnectToChannel(DiscordChannel channel, VoiceNextExtension voiceNext) { if (channel.Type == DSharpPlus.ChannelType.Voice) { Vnc = await voiceNext.ConnectAsync(channel); return(true); } return(false); }
public async Task RunAsync() { var json = string.Empty; using (var fs = File.OpenRead("config.json")) using (var sr = new StreamReader(fs, new UTF8Encoding(false))) json = await sr.ReadToEndAsync().ConfigureAwait(false); var configJson = JsonConvert.DeserializeObject <ConfigJson>(json); var config = new DiscordConfiguration { Token = configJson.Token, TokenType = TokenType.Bot, AutoReconnect = true, LogLevel = LogLevel.Debug, UseInternalLogHandler = true, }; Client = new DiscordClient(config); Client.Ready += OnClientReady; Client.UseInteractivity(new InteractivityConfiguration { Timeout = TimeSpan.FromMinutes(1) }); var commandsConfig = new CommandsNextConfiguration { StringPrefixes = new string[] { configJson.Prefix }, EnableDms = false, EnableMentionPrefix = true, }; Commands = Client.UseCommandsNext(commandsConfig); Commands.RegisterCommands <TestCommands>(); Commands.RegisterCommands <MusicCommands>(); var voiceConfiguration = new VoiceNextConfiguration { //configuration of voice }; Voice = Client.UseVoiceNext(voiceConfiguration); await Client.ConnectAsync(); await Task.Delay(-1); //fix for premature disconnect, delays eternally }
public static async Task Main(string[] args) { Globals.BotSettings = JsonConvert.DeserializeObject <Settings>(File.ReadAllText(Path.Combine(Globals.AppPath, "config.json"))); try { if (Directory.Exists(Path.Combine(Globals.AppPath, "Queue"))) { Directory.Delete(Path.Combine(Globals.AppPath, "Queue"), true); } } catch { // Consume "Directory not empty" error } discord = new DiscordClient(new DiscordConfiguration { Token = Globals.BotSettings.Token, TokenType = TokenType.Bot, UseInternalLogHandler = true, LogLevel = LogLevel.Debug, AutoReconnect = true }); commands = discord.UseCommandsNext(new CommandsNextConfiguration { StringPrefixes = new [] { "=" }, EnableMentionPrefix = true, EnableDms = false }); commands.RegisterCommands(Assembly.GetExecutingAssembly()); commands.CommandExecuted += Commands_CommandExecuted; commands.CommandErrored += Commands_CommandErrored; interactivity = discord.UseInteractivity(new InteractivityConfiguration { }); voice = discord.UseVoiceNext(new VoiceNextConfiguration { VoiceApplication = VoiceApplication.Music }); discord.MessageCreated += Discord_MessageCreated; AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit; await discord.ConnectAsync(); await Task.Delay(-1); }
public async Task Play(CommandContext ctx, [RemainingText] string queryString) { VoiceNextExtension vnext = ctx.Client.GetVoiceNext(); VoiceNextConnection vnc = vnext.GetConnection(ctx.Guild); if (vnc == null) { DiscordChannel chn = ctx.Member?.VoiceState?.Channel; if (chn == null) { throw new OutputException("You need to be in a voice channel."); } await vnext.ConnectAsync(chn); } if (!string.IsNullOrWhiteSpace(queryString)) { await this.Queue(ctx, queryString); if (!GuildMusicStatuses.TryGetValue(ctx.Guild.Id, out MusicStatus musicStatus)) { GuildMusicStatuses.Add(ctx.Guild.Id, new MusicStatus { Skip = false }); if (ctx.Client.GetVoiceNext().GetConnection(ctx.Guild) != null) { PlayMusic(ctx); } } else { if (!musicStatus.Skip && ctx.Client.GetVoiceNext().GetConnection(ctx.Guild) != null) { PlayMusic(ctx); } } return; } if (!GuildMusicStatuses.TryGetValue(ctx.Guild.Id, out MusicStatus _)) { GuildMusicStatuses.Add(ctx.Guild.Id, new MusicStatus { Skip = false }); } PlayMusic(ctx); }
public async Task RunAsync() { var json = string.Empty; await using (var fs = File.OpenRead("config.json")) { using var sr = new StreamReader(fs, new UTF8Encoding(false)); json = await sr.ReadToEndAsync().ConfigureAwait(false); } var configJson = JsonConvert.DeserializeObject <ConfigJson>(json); var config = new DiscordConfiguration { Token = configJson.Token, TokenType = TokenType.Bot, AutoReconnect = true, MinimumLogLevel = LogLevel.Debug }; Client = new DiscordClient(config); Client.Ready += OnClientReady; Client.GuildAvailable += OnGuildAvailable; Client.ClientErrored += Client_ClientError; Client.UseInteractivity(new InteractivityConfiguration { Timeout = TimeSpan.FromMinutes(1) }); var commandsConfig = new CommandsNextConfiguration { StringPrefixes = new [] { configJson.Prefix }, EnableDms = false, EnableMentionPrefix = true, }; Commands = Client.UseCommandsNext(commandsConfig); Commands.CommandExecuted += Commands_CommandExecuted; Commands.CommandErrored += Commands_CommandErrored; Commands.RegisterCommands <LolCommands>(); Commands.RegisterCommands <TeamCommands>(); Commands.RegisterCommands <PolcrazCommands>(); Voices = Client.UseVoiceNext(); await Client.ConnectAsync(); await Task.Delay(-1); }
public async Task RunAsync() { var json = string.Empty; using (var fs = File.OpenRead("config.json")) using (var sr = new StreamReader(fs, new UTF8Encoding(false))) json = await sr.ReadToEndAsync().ConfigureAwait(false); configJson = JsonConvert.DeserializeObject <Dictionary <string, string> >(json); var config = new DiscordConfiguration { Token = configJson["Token"], TokenType = TokenType.Bot, AutoReconnect = true, LogLevel = LogLevel.Debug, UseInternalLogHandler = true }; Client = new DiscordClient(config); Client.Ready += OnClientReady; Client.MessageDeleted += MessageLogger; Client.UseInteractivity(new InteractivityConfiguration { }); var commandsConfig = new CommandsNextConfiguration { StringPrefixes = new string[] { configJson["Prefix"] }, CaseSensitive = false, EnableDms = false, EnableMentionPrefix = true, EnableDefaultHelp = false, IgnoreExtraArguments = true }; Commands = Client.UseCommandsNext(commandsConfig); Commands.RegisterCommands <ModerationCommands>(); Commands.RegisterCommands <OsuCommands>(); Commands.RegisterCommands <UtilityCommands>(); Commands.RegisterCommands <ImageCommands>(); Commands.RegisterCommands <VoiceCommands>(); Commands.CommandErrored += OnCommandError; Voice = Client.UseVoiceNext(); await Client.ConnectAsync(); await Task.Delay(-1); }
/// <summary> /// Plays music through the music process /// </summary> /// <param name="vnext">VoiceNext instance</param> /// <param name="guild">Guild reference</param> /// <param name="song_path">Path to MP3 music file</param> /// <returns></returns> public async Task PlayFromMemory(VoiceNextExtension vnext, DiscordGuild guild, DiscordMember requested_by, string song_path) { var vnc = vnext.GetConnection(guild); if (vnc == null) { throw new InvalidOperationException($"I'm not connected to any voice channel! {DiscordEmoji.FromName(vnext.Client, ":thinking:")}"); } if (!File.Exists(song_path)) { throw new FileNotFoundException($"Music file not found! {DiscordEmoji.FromName(vnext.Client, ":(")}"); } if (!this.MusicChannels.TryGetValue(guild.Id, out GuildMusicChannel channel)) { throw new InvalidOperationException("No music channel associated with this guild!"); } this.EnqueueSong(channel, new MusicData { Source = song_path, Channel = channel, RequestedBy = requested_by, MusicType = MusicTypes.MEMORY }); // Something it's being already played, limit to just enqueueing if (channel.IsPlaying) { return; } var txStream = vnc.GetTransmitStream(); txStream.VolumeModifier = channel.Volume / 100f; // Start speaking channel.IsPlaying = true; channel.MusicProc = new MusicProcess(song_path, ProcessStartMode.OUTPUT); var ffout = channel.MusicProc.FFMpeg.StandardOutput.BaseStream; await ffout.CopyToAsync(txStream); await txStream.FlushAsync().ConfigureAwait(false); await vnc.WaitForPlaybackFinishAsync(); // Stop speaking (also sets IsPlaying to false) await this.TryDequeueSong(channel); }
private void BuildClient() { __discord = new DiscordClient(new DiscordConfiguration { Token = __config.GetValue <string>("discord:token"), TokenType = TokenType.Bot, MinimumLogLevel = Microsoft.Extensions.Logging.LogLevel.Error }); __interactivity = __discord.UseInteractivity(); __voice = __discord.UseVoiceNext(); __lavalink = __discord.UseLavalink(); }
public async Task RunAsync() { var json = string.Empty; using (var fs = File.OpenRead("config.json")) using (var sr = new StreamReader(fs, new UTF8Encoding(false))) json = await sr.ReadToEndAsync().ConfigureAwait(false); var configJson = JsonConvert.DeserializeObject <ConfigJson>(json); var config = new DiscordConfiguration { Token = configJson.Token, TokenType = TokenType.Bot, AutoReconnect = true, MinimumLogLevel = Microsoft.Extensions.Logging.LogLevel.Debug, }; Client = new DiscordClient(config); Client.Ready += Client_Ready; Client.UseInteractivity(new InteractivityConfiguration { Timeout = TimeSpan.FromMinutes(2) }); var commandsConfig = new CommandsNextConfiguration { StringPrefixes = new string[] { configJson.Prefix }, EnableMentionPrefix = true, EnableDms = false, DmHelp = true, }; Commands = Client.UseCommandsNext(commandsConfig); Commands.RegisterCommands <FunCommands>(); Commands.RegisterCommands <TeamCommands>(); Commands.RegisterCommands <UtilitaryCommands>(); Commands.RegisterCommands <SpecialCommands>(); voice = Client.UseVoiceNext(); await Client.ConnectAsync(); await Task.Delay(-1); }
public async Task StopListen(CommandContext ctx) { if (await IsClientConnected(ctx)) { VoiceNextExtension voiceNextClient = ctx.Client.GetVoiceNext(); VoiceNextConnection voiceNextCon = ctx.Client.GetVoiceNext().GetConnection(ctx.Guild); if (voiceNextClient.IsIncomingEnabled) { this.ssrcMap = new ConcurrentDictionary <uint, ulong>(); this.ssrcFilemap = new ConcurrentDictionary <uint, FileStream>(); voiceNextCon.VoiceReceived += null; voiceNextCon.UserSpeaking += null; } } }
public async Task StartListen(CommandContext ctx) { await JoinIfNotConnected(ctx); VoiceNextExtension voiceNextClient = ctx.Client.GetVoiceNext(); VoiceNextConnection voiceNextCon = voiceNextClient.GetConnection(ctx.Guild); if (voiceNextClient.IsIncomingEnabled) { this.ssrcMap = new ConcurrentDictionary <uint, ulong>(); this.ssrcFilemap = new ConcurrentDictionary <uint, FileStream>(); voiceNextCon.VoiceReceived += this.OnVoiceReceived; voiceNextCon.UserSpeaking += this.OnUserSpeaking; } }
} //To play music public async Task RunAsync() { //Read config from JSON file var json = string.Empty; using (var fs = File.OpenRead("config.json")) using (var sr = new StreamReader(fs, new UTF8Encoding(false))) json = sr.ReadToEnd(); var configJson = JsonConvert.DeserializeObject <ConfigJson>(json); var config = new DiscordConfiguration { Token = configJson.Token, TokenType = TokenType.Bot, AutoReconnect = true, LogLevel = LogLevel.Debug, UseInternalLogHandler = true, }; Client = new DiscordClient(config); Client.Ready += OnClientReady; Client.UseInteractivity(new InteractivityConfiguration { Timeout = TimeSpan.FromMinutes(2) }); var commandsConfig = new CommandsNextConfiguration { StringPrefixes = new string[] { configJson.Prefix }, EnableDms = false, EnableMentionPrefix = true, DmHelp = false //Bot will send you private message with help command }; Commands = Client.UseCommandsNext(commandsConfig); //To use commands Voice = Client.UseVoiceNext(); //To play msucic //Register our own commands Commands.RegisterCommands <NetworkCommands>(); Commands.RegisterCommands <MusicCommands>(); //Commands that will take care of playing music await Client.ConnectAsync(); await Task.Delay(-1); //this is to prevent the bot to quit unexpectedly }
public async Task PlayFileAsync(CommandContext ctx, [RemainingText, Description("Full path to the file to play.")] string filename) { VoiceNextExtension vnext = ctx.Client.GetVoiceNext(); if (vnext == null) { throw new CommandFailedException("VNext is not enabled or configured."); } VoiceNextConnection vnc = vnext.GetConnection(ctx.Guild); if (vnc == null) { await this.ConnectAsync(ctx); vnc = vnext.GetConnection(ctx.Guild); } if (!File.Exists(filename)) { throw new CommandFailedException($"File {Formatter.InlineCode(filename)} does not exist."); } var si = new SongInfo() { Title = filename, Provider = "Server file system", Query = ctx.Client.CurrentUser.AvatarUrl, Queuer = ctx.User.Mention, Uri = filename }; if (MusicPlayers.ContainsKey(ctx.Guild.Id)) { MusicPlayers[ctx.Guild.Id].Enqueue(si); await ctx.RespondAsync("Added to queue:", embed : si.ToDiscordEmbed(this.ModuleColor)); } else { if (!MusicPlayers.TryAdd(ctx.Guild.Id, new MusicPlayer(ctx.Client, ctx.Channel, vnc))) { throw new ConcurrentOperationException("Failed to initialize music player!"); } MusicPlayers[ctx.Guild.Id].Enqueue(si); await MusicPlayers[ctx.Guild.Id].StartAsync(); } }
public async Task RunAsync() { var json = string.Empty; using (var fs = File.OpenRead("config.json")) using (var sr = new StreamReader(fs, new UTF8Encoding(false))) json = await sr.ReadToEndAsync().ConfigureAwait(false); var configJson = JsonConvert.DeserializeObject <ConfigJson>(json); var config = new DiscordConfiguration { Token = configJson.Token, TokenType = TokenType.Bot, AutoReconnect = true, LogLevel = LogLevel.Debug, UseInternalLogHandler = true }; Client = new DiscordClient(config); Client.Ready += ClientReady; Client.VoiceStateUpdated += SeriousCommands.MemberJoin; Client.UseInteractivity(new InteractivityConfiguration { Timeout = TimeSpan.FromMinutes(2) });; var commandsConfig = new CommandsNextConfiguration { StringPrefixes = new string[] { configJson.Prefix }, EnableDms = true, EnableMentionPrefix = true, DmHelp = true }; Commands = Client.UseCommandsNext(commandsConfig); Commands.RegisterCommands <FunCommands>(); Commands.RegisterCommands <SeriousCommands>(); voice = Client.UseVoiceNext(); await Client.ConnectAsync(); await Task.Delay(-1); }
/// <summary> /// Stops any currently playing music but does not disconnect from the voice channel /// </summary> /// <param name="vnext">VoiceNext instance</param> /// <param name="guild">Guild reference</param> /// <returns></returns> public async Task Stop(VoiceNextExtension vnext, DiscordGuild guild) { var vnc = vnext.GetConnection(guild); if (vnc == null) { throw new InvalidOperationException($"I'm not connected to any voice channel! {DiscordEmoji.FromName(vnext.Client, ":thinking:")}"); } if (!this.MusicChannels.TryGetValue(guild.Id, out GuildMusicChannel channel)) { throw new InvalidOperationException("No music channel associated with this guild!"); } await this.TryDequeueSong(channel); }
private async void AudioPlayingThread() { while (true) { try { PlayQueueElement elementToPlay = playQueue.Take(); Program.Client.DebugLogger.Info($"Took [{elementToPlay.Filepath}] off the queue"); // Connect if not already VoiceNextExtension voiceNextClient = Program.Client.GetVoiceNext(); VoiceNextConnection voiceNextCon = voiceNextClient.GetConnection(elementToPlay.GuildToJoin); if (voiceNextCon == null) { Program.Client.DebugLogger.Info($"Not currently connected"); Task <VoiceNextConnection> voiceNextConTask = voiceNextClient.ConnectAsync(elementToPlay.ChannelToJoin); voiceNextConTask.Wait(new TimeSpan(0, 0, 3)); if (voiceNextConTask.IsCompletedSuccessfully) { voiceNextCon = voiceNextConTask.Result; Program.Client.DebugLogger.Info($"Joined: {voiceNextCon.Channel}"); } else { Program.Client.DebugLogger.Error($"Could not join: {elementToPlay.ChannelToJoin.Name}"); continue; } } await PlayAudio(voiceNextCon, elementToPlay.Filepath); if (playQueue.Count == 0) { voiceNextCon.Disconnect(); Program.Client.DebugLogger.Info($"Leaving: {voiceNextCon.Channel}"); } } catch (Exception ex) { Program.Client.DebugLogger.Critical($"Exception was caught in the Audio Thread: {ex}"); } } }
public async Task RunAsync() { var json = string.Empty; using (var fs = File.OpenRead("config.json")) using (var sr = new StreamReader(fs, new UTF8Encoding(false))) json = await sr.ReadToEndAsync().ConfigureAwait(false); var configJson = JsonConvert.DeserializeObject <Config>(json); var config = new DiscordConfiguration() { Token = configJson.Token, TokenType = TokenType.Bot, AutoReconnect = true, LogLevel = LogLevel.Debug, UseInternalLogHandler = true }; Client = new DiscordClient(config); Client.Ready += OnClientReady; var commandsConfig = new CommandsNextConfiguration { StringPrefixes = new string[] { configJson.Prefix }, EnableMentionPrefix = true, EnableDms = false, DmHelp = true, }; Commands = Client.UseCommandsNext(commandsConfig); Commands.RegisterCommands <TestCommands>(); Voice = Client.UseVoiceNext(new VoiceNextConfiguration { AudioFormat = AudioFormat.Default, EnableIncoming = true }); await Client.ConnectAsync(); await Task.Delay(-1); }
/// <summary> /// Joins a voice channel /// </summary> /// <param name="vnext">VoiceNext instance</param> /// <param name="voiceChannel">Voice channel to join</param> /// <returns></returns> public async Task <GuildMusicChannel> JoinVoiceChannel(VoiceNextExtension vnext, DiscordChannel voiceChannel) { var vnc = vnext.GetConnection(voiceChannel.Guild); var channel = new GuildMusicChannel(voiceChannel.Guild); if (!this.MusicChannels.TryAdd(voiceChannel.GuildId, channel)) { // If the add fails, it means there is already a channel for this guild, recover it this.MusicChannels.TryGetValue(voiceChannel.GuildId, out channel); } channel.IsConnected = true; if (vnc != null) { return(channel); } vnc = await vnext.ConnectAsync(voiceChannel); return(channel); }
/// <summary> /// Leaves the voice channel where the bot is currently connected for a given guild /// </summary> /// <param name="vnext">VoiceNext instance</param> /// <param name="guild">Guild reference</param> public async Task LeaveVoiceChannel(VoiceNextExtension vnext, DiscordGuild guild) { var vnc = vnext.GetConnection(guild); if (vnc == null) { throw new InvalidOperationException($"I'm not connected to any voice channel! {DiscordEmoji.FromName(vnext.Client, ":thinking:")}"); } if (!this.MusicChannels.TryGetValue(guild.Id, out GuildMusicChannel channel)) { throw new InvalidOperationException("No music channel associated with this guild!"); } if (await this.TryDequeueSong(channel) && !channel.Queue.IsEmpty) { channel.Queue.Clear(); } channel.IsConnected = false; vnc.Dispose(); }
public async Task Join(CommandContext ctx) { VoiceNextExtension vnext = ctx.Client.GetVoiceNext(); VoiceNextConnection vnc = vnext.GetConnection(ctx.Guild); if (vnc != null) { throw new OutputException("Already connected in this guild."); } DiscordChannel chn = ctx.Member?.VoiceState?.Channel; if (chn == null) { throw new OutputException("You need to be in a voice channel."); } vnc = await vnext.ConnectAsync(chn); await ctx.RespondAsync($"Connected to channel {vnc.Channel.Name} successfully."); }
public async Task Join(CommandContext ctx) { DiscordMessage tmp = await ctx.RespondAsync("JN: GVNC"); VoiceNextExtension vnext = ctx.Client.GetVoiceNext(); await tmp.DeleteAsync(); tmp = await ctx.RespondAsync("JN: GGLD"); VoiceNextConnection vnc = vnext.GetConnection(ctx.Guild); await tmp.DeleteAsync(); tmp = await ctx.RespondAsync("JN: CVNC"); if (vnc != null) { throw new InvalidOperationException("Already connected in this guild."); } await tmp.DeleteAsync(); tmp = await ctx.RespondAsync("JN: CCHN"); DiscordChannel chn = ctx.Member?.VoiceState?.Channel; if (chn == null) { throw new InvalidOperationException("You need to be in a voice channel."); } await tmp.DeleteAsync(); tmp = await ctx.RespondAsync("JN: CTXC"); vnc = await vnext.ConnectAsync(chn); await tmp.DeleteAsync(); await ctx.RespondAsync("👌Connected"); }