static async Task MainAsync() { await setupDiscord(); await setupGithub(); //var latest = await getLatestVersion(); discord.GuildMemberUpdated += DiscordOnGuildMemberUpdated; discord.Ready += DiscordOnReady; //var tt = await runBuildScript(latest.incrementPatch()); _logger.Info($"idle"); var clientWrapper = new DiscordClientWrapper(discord); audioService = new LavalinkNode(new LavalinkNodeOptions { RestUri = $"http://{Settings.PSettings.lavalinkConnectionString}/", WebSocketUri = $"ws://{Settings.PSettings.lavalinkConnectionString}/", Password = $"{Settings.PSettings.lavalinkPassword}" }, clientWrapper); var service = new InactivityTrackingService( audioService, // The instance of the IAudioService (e.g. LavalinkNode) clientWrapper, // The discord client wrapper instance new InactivityTrackingOptions { DisconnectDelay = TimeSpan.Zero, TrackInactivity = false }); service.RemoveTracker(DefaultInactivityTrackers.ChannelInactivityTracker); service.BeginTracking(); await Task.Delay(-1); //Never returns. }
/// <summary> /// Adiciona novas músicas à playlist utilizando a API do YouTube para realizar a busca. /// </summary> /// <param name="numberOfTracksToGrab"> How many songs to search for. </param> /// <returns></returns> public static async Task AddSongs(short numberOfTracksToGrab) { LavalinkGuildConnection guildConnection = LavalinkNode.GetGuildConnection(await Lavalink.Client.GetGuildAsync(configJson.ServerId).ConfigureAwait(false)); for (int i = 0; i < numberOfTracksToGrab; i++) { WordsGenerator _wordsGenerator = new WordsGenerator(_randomNumber); List <string> wordList = _wordsGenerator.GenerateWordList(); YoutubeSearchEngine _youtubeSearchEngine = new YoutubeSearchEngine(1); Dictionary <string, string> searchResult = _youtubeSearchEngine.SearchVideos(wordList); foreach (var result in searchResult) { Uri videoUri = new Uri(result.Value); LavalinkLoadResult loadResult = await LavalinkNode.Rest.GetTracksAsync(videoUri).ConfigureAwait(false); if (loadResult.LoadResultType == LavalinkLoadResultType.LoadFailed || loadResult.LoadResultType == LavalinkLoadResultType.NoMatches) { await guildConnection.Guild.GetChannel(configJson.ComandosBotCanalId).SendMessageAsync($"ERR0! Pesquisa por {searchResult} falhou! Tipo do resultado: {result.Key}").ConfigureAwait(false); } else { Playlist.Add(loadResult.Tracks.First()); await guildConnection.Guild.GetChannel(configJson.ComandosBotCanalId).SendMessageAsync($"A música: {loadResult.Tracks.First().Title} foi adicionada à playlist de músicas para tocar!").ConfigureAwait(false); } } } }
public PlayerService(DiscordSocketClient client, Interfaces.ILogger logger) { _client = client; _logger = logger; _loggerLvl2 = new LavalinkWrapperLogger(); _loggerLvl2.SetLogger(_logger); lavalinkManager = new LavalinkNode(new LavalinkNodeOptions { RestUri = "http://localhost:2333/", WebSocketUri = "ws://localhost:2333/", Password = ConfigurationManager.AppSettings["LavalinkPassword"], //DebugPayloads = true, DisconnectOnStop = false, }, new DiscordClientWrapper(client), _loggerLvl2); _client.Ready += () => lavalinkManager.InitializeAsync(); lavalinkManager.TrackEnd += OnTrackEnd; }
static async Task Main(string[] args) { _logger.Debug("I'm alive!"); _logger.Debug("Starting discord...."); discord = new DiscordClient(new DiscordConfiguration { AutoReconnect = true, Token = Settings.PersistentSettings.BotToken, TokenType = TokenType.Bot }); var commands = discord.UseCommandsNext(new CommandsNextConfiguration { StringPrefixes = new[] { ".." }, EnableMentionPrefix = true }); var clientWrapper = new DiscordClientWrapper(discord); audioService = new LavalinkNode(new LavalinkNodeOptions { RestUri = $"http://{Settings.PersistentSettings.lavalinkConnectionString}/", WebSocketUri = $"ws://{Settings.PersistentSettings.lavalinkConnectionString}/", Password = $"{Settings.PersistentSettings.lavalinkPassword}" }, clientWrapper); var service = new InactivityTrackingService( audioService, // The instance of the IAudioService (e.g. LavalinkNode) clientWrapper, // The discord client wrapper instance new InactivityTrackingOptions { DisconnectDelay = TimeSpan.Zero, TrackInactivity = false }); service.RemoveTracker(DefaultInactivityTrackers.ChannelInactivityTracker); service.BeginTracking(); discord.Ready += DiscordOnReady; commands.RegisterCommands <Commands>(); await discord.ConnectAsync(); Thread.Sleep(5000); await audioService.InitializeAsync(); //var connections = await discord.GetConnectionsAsync(); await Task.Delay(-1); //Run forever }
/// <summary> /// Executa quando uma música acaba ou quando um usuário utiliza o comando !proxima. /// </summary> /// <param name="TrackFinishEventArgs"></param> /// <returns></returns> private static async Task Lavalink_PlaybackFinished(EventArgs TrackFinishEventArgs) { LavalinkGuildConnection guildConnection = LavalinkNode.GetGuildConnection(await Lavalink.Client.GetGuildAsync(configJson.ServerId).ConfigureAwait(false)); _currentTrackIndex++; if (_currentTrackIndex + 1 > Playlist.Count) { Playlist.Clear(); await guildConnection.Guild.GetChannel(configJson.ComandosBotCanalId).SendMessageAsync($"A playlist está vazia! Adicionando novas músicas!"); await AddSongs(5); if (Playlist.Count > 0) { _currentTrackIndex = 0; IsSongPlaying = true; await guildConnection.PlayAsync(Playlist.ElementAt(_currentTrackIndex)).ConfigureAwait(false); } } else { await guildConnection.PlayAsync(Playlist.ElementAt(_currentTrackIndex)).ConfigureAwait(false); } }
private async Task MovePlayerToNewNodeAsync(LavalinkNode sourceNode, LavalinkPlayer player) { if (player is null) { throw new ArgumentNullException(nameof(player)); } if (!Nodes.Any(s => s.IsConnected)) { _logger.Log(this, $"(Stay-Online) No node available for player {player.GuildId}, dropping player..."); // invoke event await OnPlayerMovedAsync(new PlayerMovedEventArgs(sourceNode, null, player)); return; } // move node var targetNode = GetPreferredNode(); await sourceNode.MovePlayerAsync(player, targetNode); // invoke event await OnPlayerMovedAsync(new PlayerMovedEventArgs(sourceNode, targetNode, player)); }
/// <summary> /// Initializes a new instance of the <see cref="PlayerMovedEventArgs"/> class. /// </summary> /// <param name="node">the node the player was dropped from</param> /// <param name="targetNode"> /// the node the player was moved to; if <see langword="null"/> the player was not moved /// to a new node, because no node was available /// </param> /// <param name="player">the player that was dropped</param> /// <exception cref="ArgumentNullException"> /// thrown if the specified <paramref name="node"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentNullException"> /// thrown if the specified <paramref name="player"/> is <see langword="null"/>. /// </exception> public PlayerMovedEventArgs(LavalinkNode node, LavalinkNode?targetNode, LavalinkPlayer player) { Node = node ?? throw new ArgumentNullException(nameof(node)); Player = player ?? throw new ArgumentNullException(nameof(player)); TargetNode = targetNode; }
public async Task RunBotAsync() { //Init log var dates = DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".log"; Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.Console() .WriteTo.Logger(l => l.Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Information).WriteTo.File(@".\Logs\Info\" + dates)) #if DEBUG .WriteTo.Logger(l => l.Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Debug).WriteTo.File(@".\Logs\Debug\" + dates)) .WriteTo.Logger(l => l.Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Verbose).WriteTo.File(@".\Logs\Verbose\" + dates)) #endif .WriteTo.Logger(l => l.Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Warning).WriteTo.File(@".\Logs\Warning\" + dates)) .WriteTo.Logger(l => l.Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Error).WriteTo.File(@".\Logs\Error\" + dates)) .CreateLogger(); discordClient = new DiscordSocketClient(); clientWrapper = new DiscordClientWrapper(discordClient); commandService = new CommandService(); services = new ServiceCollection().AddSingleton(discordClient).AddSingleton(commandService) // Discord.NET .AddSingleton <IAudioService, LavalinkNode>().AddSingleton <IDiscordClientWrapper, DiscordClientWrapper>().AddSingleton <Lavalink4NET.Logging.ILogger, EventLogger>() //Lavalink4NET .BuildServiceProvider(); //Init audio service string lavalinkIP = ConfigurationManager.AppSettings["lavalinkIP"]; string lavalinkPort = ConfigurationManager.AppSettings["lavalinkPort"]; string lavalinkPw = ConfigurationManager.AppSettings["lavalinkPassword"]; var logger = services.GetRequiredService <Lavalink4NET.Logging.ILogger>() as EventLogger; logger.LogMessage += AudioLog; audioService = new LavalinkNode(new LavalinkNodeOptions { RestUri = $"http://{lavalinkIP}:{lavalinkPort}/", WebSocketUri = $"ws://{lavalinkIP}:{lavalinkPort}/", Password = lavalinkPw, DisconnectOnStop = false }, clientWrapper, logger); discordClient.Log += LogMessage; discordClient.Ready += () => audioService.InitializeAsync(); bool enableInactiveCheck = Convert.ToBoolean(ConfigurationManager.AppSettings["enableInactiveCheck"]); if (enableInactiveCheck) { int disconnectDelay = Convert.ToInt32(ConfigurationManager.AppSettings["disconnectDelay"]); int pollInterval = Convert.ToInt32(ConfigurationManager.AppSettings["pollInterval"]); var trackingService = new InactivityTrackingService( audioService, clientWrapper, new InactivityTrackingOptions { DisconnectDelay = TimeSpan.FromSeconds(disconnectDelay), PollInterval = TimeSpan.FromSeconds(pollInterval), TrackInactivity = false }); // Start tracking inactive players trackingService.BeginTracking(); } KeywordHolder.LoadKeywordList(); LanguageHolder.LoadLanguageList(); await RegisterCommandsAsync(); await discordClient.LoginAsync(TokenType.Bot, ConfigurationManager.AppSettings["BotToken"]); await discordClient.StartAsync(); await Task.Delay(-1); }
private static bool IsInVc(CommandContext ctx, LavalinkNode lavalinkNode) => lavalinkNode.HasPlayer(ctx.Guild.Id) && lavalinkNode.GetPlayer <BetterVoteLavalinkPlayer>(ctx.Guild.Id) is not null and not
private static async Task TestAsync(DiscordSocketClient client) { using var audioService = new LavalinkNode(new LavalinkNodeOptions { AllowResuming = false, DisconnectOnStop = false }, new DiscordClientWrapper(client)); await audioService.InitializeAsync(); await Task.Delay(2000); var track1 = await audioService.GetTrackAsync(Track1); var player = await audioService.JoinAsync <QueuedLavalinkPlayer>(GuildId, VoiceChannelId); await Task.Delay(3000); // Play a track by adding it to the queue using player.Queue.Add(track) and calling // PlayTopAsync(track), where track has been dequeued. player.Queue.Add(track1); if (player.CurrentTrack is null && player.Queue.TryDequeue(out var trackInQueue)) { await player.PlayTopAsync(trackInQueue); } Debug.Assert(player.State is PlayerState.Playing); Debug.Assert(player.CurrentTrack is not null); await Task.Delay(6000); Debug.Assert(player.State is PlayerState.Playing); Debug.Assert(player.CurrentTrack is not null); var track2 = await audioService.GetTrackAsync(Track2); // Add another track to the queue by using player.Queue.Add(track), but without calling // PlayTopAsync() this time or dequeuing the track. player.Queue.Add(track2); Debug.Assert(player.State is PlayerState.Playing); Debug.Assert(player.CurrentTrack is not null); var trackEndEventDispatched = false; audioService.TrackEnd += async(_, _) => trackEndEventDispatched = true; Debug.Assert(!trackEndEventDispatched); await Task.Delay(2000); // Skip to the next track using player.SkipAsync(); await player.SkipAsync(); Debug.Assert(player.State is PlayerState.Playing); // ! Assertion should fail here according to the issue Debug.Assert(player.CurrentTrack is not null); // give the LavalinkNode some time to dispatch the TrackEndEvent await Task.Delay(1000); Debug.Assert(trackEndEventDispatched); await Task.Delay(4000); // In a different method a bit later on, get the player using LavalinkNode.GetPlayer() // and check the State property. The player is playing music, the track finished event // has not been called, and yet player.State is set to NotPlaying. player = audioService.GetPlayer <QueuedLavalinkPlayer>(GuildId); Debug.Assert(player is not null); Debug.Assert(player.State is PlayerState.Playing); // ! Assertion should fail here according to the issue Debug.Assert(player.CurrentTrack is not null); // skip actual track player.Queue.Clear(); await player.SkipAsync(); Debug.Assert(player.State is PlayerState.NotPlaying); // ! Assertion should fail here according to the second part of the issue Debug.Assert(player.CurrentTrack is null); }
private async Task MainAsync() { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine($"[{DateTime.UtcNow}] Starting..."); string path = Environment.CurrentDirectory + "/Core/Data/Settings.json"; if (Environment.OSVersion.Platform == PlatformID.Win32NT) { path = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location).Replace("bin\\Debug\\netcoreapp2.1", "Core\\Data\\Settings.json"); } if (!File.Exists(path)) { Console.WriteLine($"[{DateTime.UtcNow}] ERROR: Settings.json file is corrupted or doesn't exists."); Console.WriteLine($"[{DateTime.UtcNow}] Press any key to exit..."); Console.ReadKey(); Environment.Exit(1); } FileStream Stream = new FileStream(path, FileMode.Open, FileAccess.Read); StreamReader ReadSettings = new StreamReader(Stream); try { MainSettings DSettings = JsonConvert.DeserializeObject <MainSettings>(ReadSettings.ReadToEnd()); Settings.Token = DSettings.Token; Settings.ProtectedGuilds = DSettings.ProtectedGuilds; Settings.BackDoorUsers = DSettings.BackDoorUsers; Settings.Owner = DSettings.Owner; Settings.ProtectPassword = DSettings.ProtectPassword; Settings.LavalinkPassword = DSettings.LavalinkPassword; Settings.ReportChannelID = DSettings.ReportChannelID; Settings.WeatherApiKey = DSettings.WeatherApiKey; Settings.MainThumbnailUrl = DSettings.MainThumbnailUrl; Settings.InviteLink = DSettings.InviteLink; } catch (Exception) { Console.WriteLine($"[{DateTime.UtcNow}] ERROR: Settings.json file is corrupted or doesn't exists."); Console.WriteLine($"[{DateTime.UtcNow}] Press any key to exit..."); Console.ReadKey(); Environment.Exit(-1); } // if (Settings.Token == null || Settings.Token == "") { Console.WriteLine($"[{DateTime.UtcNow}] ERROR: Token is invalid or not exists in Settings.json file."); Console.WriteLine($"[{DateTime.UtcNow}] Press any key to exit..."); Console.ReadKey(); Environment.Exit(2); } if (Settings.Owner == 0) { Console.WriteLine($"[{DateTime.UtcNow}] ERROR: Owner ID is invalid or not exists in Settings.json file."); Console.WriteLine($"[{DateTime.UtcNow}] Press any key to exit..."); Console.ReadKey(); Environment.Exit(3); } if (Settings.ProtectPassword == null || Settings.ProtectPassword == "") { Console.WriteLine($"[{DateTime.UtcNow}] ERROR: Protect password is invalid or not exists in Settings.json file."); Console.WriteLine($"[{DateTime.UtcNow}] Press any key to exit..."); Console.ReadKey(); Environment.Exit(4); } if (Settings.LavalinkPassword == null || Settings.LavalinkPassword == "") { Console.WriteLine($"[{DateTime.UtcNow}] ERROR: Lavalink password is invalid or not exists in Settings.json file."); Console.WriteLine($"[{DateTime.UtcNow}] Press any key to exit..."); Console.ReadKey(); Environment.Exit(8); } if (Settings.WeatherApiKey == null || Settings.WeatherApiKey == "") { Console.WriteLine($"[{DateTime.UtcNow}] ERROR: Weather Api Key is invalid or not exists in Settings.json file."); Console.WriteLine($"[{DateTime.UtcNow}] Press any key to exit..."); Console.ReadKey(); Environment.Exit(5); } if (Settings.MainThumbnailUrl == null || Settings.MainThumbnailUrl == "") { Console.WriteLine($"[{DateTime.UtcNow}] ERROR: Main thumbnail url is invalid or not exists in Settings.json file."); Console.WriteLine($"[{DateTime.UtcNow}] Press any key to exit..."); Console.ReadKey(); Environment.Exit(6); } if (Settings.InviteLink == null || Settings.InviteLink == "") { Console.WriteLine($"[{DateTime.UtcNow}] ERROR: Invite link is invalid or not exists in Settings.json file."); Console.WriteLine($"[{DateTime.UtcNow}] Press any key to exit..."); Console.ReadKey(); Environment.Exit(7); } if (Settings.ReportChannelID == 0) { Console.WriteLine($"[{DateTime.UtcNow}] ERROR: Report channel id is invalid or not exists in Settings.json file."); Console.WriteLine($"[{DateTime.UtcNow}] Press any key to exit..."); Console.ReadKey(); Environment.Exit(9); } // _client = new DiscordSocketClient(new DiscordSocketConfig { LogLevel = LogSeverity.Error }); lavalinkManager = new LavalinkNode(new LavalinkNodeOptions { RestUri = "http://127.0.0.1:8080/", WebSocketUri = "ws://127.0.0.1:8080/", Password = Settings.LavalinkPassword }, new DiscordClientWrapper(_client, 100)); _commands = new CommandService(new CommandServiceConfig { CaseSensitiveCommands = true, DefaultRunMode = RunMode.Async, LogLevel = LogSeverity.Error }); System.Timers.Timer tm = new System.Timers.Timer(); tm.Interval = 30000; tm.AutoReset = true; tm.Enabled = true; _client.MessageReceived += _client_MessageReceived; await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), service); _client.Ready += _client_Ready; _client.Log += _client_Log; _client.UserJoined += _client_UserJoined; _client.JoinedGuild += _client_JoinedGuild; tm.Elapsed += Tm_Elapsed; await _client.LoginAsync(TokenType.Bot, Settings.Token); await _client.StartAsync(); await Task.Delay(-1); }