public async Task <string[]> download_audio(string url) { ///<summary> /// Documentation on how to use the libVideo /// https://github.com/jamesqo/libvideo/blob/master/docs/README.md ///</summary> var youtube = YouTube.Default; var video = youtube.GetAllVideos(url); //look at the video and now extract from all the url's the ones that are just audio //this way we dont have to do any extraction of video to audio var audio = video .Where(e => e.AudioFormat == AudioFormat.Aac && e.AdaptiveKind == AdaptiveKind.Audio) .ToList(); string workingDir = Directory.GetCurrentDirectory() + "\\cache\\"; string fileAAC = audio[0].FullName.Remove(audio[0].FullName.Length - 4) + ".aac"; // should remove the .mp4 from the filename and adds aac to the filename //string fileAAC = fileName + ".aac"; // string title = audio[0].Title.Remove(audio[0].Title.Length - 10); // removes the " - youtube" part of the string if (File.Exists(workingDir + fileAAC)) { // do nothing _logs.logMessage("Debug", "downloader.download_audio", "URL " + url + " was already downloaded, ignoring", "system"); } else { //download the file if (audio.Count > 0) { File.WriteAllBytes(workingDir + fileAAC, audio[0].GetBytes()); _logs.logMessage("Info", "downloader.download_audio", $"Downloaded {url} to cache.", "system"); } } string[] returnVar = { audio[0].Title, //pass the title back fileAAC, //pass the filename, not sure if we need to retain this workingDir + fileAAC, //pass the full path to the file to be played back audio[0].AudioBitrate.ToString() //pass the bitrate so we can return the value }; return(returnVar); }
/// <summary> /// Sends the flag to skip the current track /// </summary> /// <returns> /// return True if it worked /// return false if it failed /// </returns> public bool cmd_skip() { try { if (playingSong == true) { playingSong = false; return(true); } else { return(false); } } catch (Exception error) { _logs.logMessage("Error", "player.cmd_skip", error.ToString(), "system"); return(false); } }
public void saveUrbanTags() { try { string loc = Directory.GetCurrentDirectory() + "\\configs\\urbanTags.json"; string json = JsonConvert.SerializeObject(urbanTags); if (!File.Exists(loc)) { File.Create(loc).Close(); } File.WriteAllText(loc, json); } catch (Exception error) { _logs.logMessage("Error", "urban.saveUrbanTags", error.ToString(), "system"); } }
void IModule.Install(ModuleManager manager) { _manager = manager; _client = manager.Client; manager.CreateCommands("", group => { _client.GetService <CommandService>().CreateCommand("urbanDictionary") .Alias("ud") .Description("Requests a definition from UrbanDictionary.com.\rExample: !urbanDictionary 'cheesy ragu'\rPermissions: Everyone") .Parameter("tag", ParameterType.Optional) .MinPermissions((int)PermissionLevel.GroupUsers) .Do(async e => { try { string[] result = null; if (e.GetArg("tag") == "") { //request a random tag from what we have so far in the urban.json file.. to be built result = _urban.cmd_urbanFlow(null); } else { result = _urban.cmd_urbanFlow(e.GetArg("tag")); } if (result == null) { await e.Channel.SendMessage($"Ran into a error trying to process your request. The error has been saved to the log file."); } else if (result[0] == "No Value") { await e.Channel.SendMessage($"{e.User.Name},\rI searched for '{e.GetArg("tag")}' but nothing was found."); } else { string message = $"```\rUrbanDictionary Restult for '{result[2]}'\rDefinition: {result[0]}\rExample: {result[1]}\rTags: {result[3]}```"; //check to see if the message is longer then 2000 characters. Discord Limmit. int messageLength = message.Length; if (message.Length >= 2000) { //get the number of characters we need to remove int charTrim = message.Length - 2003; message.Substring(message.Length - charTrim); } await e.Channel.SendMessage(message); } } catch (Exception error) { _logs.logMessage("Error", "commandsWeb.urbanDictionary", error.ToString(), e.User.Name); } }); _client.GetService <CommandService>().CreateCommand("smut") .Alias("smut") .Description("Requests a picture from r34.xxx.\rExample: !smut 'overwatch'\rPermissions: Everyone") .Parameter("site", ParameterType.Optional) .Parameter("tag", ParameterType.Optional) .MinPermissions((int)PermissionLevel.GroupUsers) .Do(async e => { try { string[] result = null; switch (e.GetArg("site")) { case "dabooru": case "dan": result = _danbooru.danSearchTag(e.GetArg("tag")); if (result != null) { await e.Channel.SendMessage($"Result from {result[1]}\rURL: {result[0]}\rTags: {result[2]}"); } else { await e.Channel.SendMessage($"Unable to find anything with the tag: {e.GetArg("tag")}"); } break; case "rule34": case "r34": result = _rule34.rule34QuerrySite(e.GetArg("tag")); if (result != null) { } else { } break; default: result = _danbooru.danSearchTag(e.GetArg("site")); if (result != null) { await e.Channel.SendMessage($"Result from {result[1]}\rURL: {result[0]}\rTags: {result[2]}"); } else { await e.Channel.SendMessage($"Unable to find anything with the tag: {e.GetArg("site")}"); } break; } //await e.Channel.SendMessage("placeholder"); } catch (Exception error) { _logs.logMessage("Error", "commandsWeb.urbanDictionary", error.ToString(), e.User.Name); } }); }); }
void IModule.Install(ModuleManager manager) { _manager = manager; _client = manager.Client; _config = configuration.LoadFile(); manager.CreateCommands("", group => { _client.GetService <CommandService>().CreateCommand("rm") .Alias("rm") .Description("Removes messages from a text channel.\rExample: !rm 100\rPermissions: Everyone") .Parameter("count", ParameterType.Optional) .MinPermissions((int)PermissionLevel.GroupUsers) .Do(async e => { try { if (e.GetArg("count") == "") { await e.Channel.SendMessage($"{e.User.Name}, Please give me the number of lines you want to remove."); return; } //convert the arg from string to int int counter = int.Parse(e.GetArg("count")); int deleteCounter = 100; while (counter > 0) { if (counter >= 100) { deleteCounter = 100; } else { deleteCounter = counter; } //tell server to download messages to memory Message[] messagesToDelete = await e.Channel.DownloadMessages(deleteCounter); //tell bot to delete them from server await e.Channel.DeleteMessages(messagesToDelete); counter = counter - 100; } _logs.logMessage("Info", "commandsSystem.rm", $"User requested {e.GetArg("count")} lines to be removed from {e.Channel.Name}", e.User.Name); } catch (Exception error) { _logs.logMessage("Error", "commandsSystem.rm", error.ToString(), e.User.Name); } }); _client.GetService <CommandService>().CreateCommand("defaultRoom") .Alias("defaultRoom") .Description("Sets the bots default voice room.\rExample: !defaultRoom roomID\rPermission: Owner") .Parameter("roomID", ParameterType.Optional) .MinPermissions((int)PermissionLevel.BotOwner) .Do(async e => { try { if (e.GetArg("roomID") == null) { await e.Channel.SendMessage("Oops, you forgot to give me the room ID to make my home by default."); return; } ulong id = Convert.ToUInt64(e.GetArg("roomID")); _config.defaultRoomID = id; _config.SaveFile(); await e.Channel.SendMessage("I have updated the config file for you."); _logs.logMessage("Info", "commandsSystem.defaultRoom", $"defaultRoom was updated to {e.GetArg("roomID")}", e.User.Name); } catch (Exception error) { _logs.logMessage("Error", "commandsSystem.defaultRoom", error.ToString(), e.User.Name); } }); _client.GetService <CommandService>().CreateCommand("volume") .Alias("vol") .Description("Adjusts the default volume from the bot.\rExample: !vol +10\rPermission: Everyone") .Parameter("vol", ParameterType.Optional) .MinPermissions((int)PermissionLevel.GroupUsers) .Do(async e => { try { if (e.GetArg("vol") == null) { await e.Channel.SendMessage($"{e.User.Name},\rPlease give me the percent value you want me to change to.\rExample: {_config.Prefix}vol 50"); return; } //make sure we got a number value int intVol = 0; int.TryParse(e.GetArg("vol"), out intVol); if (intVol >= 1 && intVol <= 100) { //convert the value that we deam a percent value to a string to format it string stringVol = intVol.ToString(); string t = null; if (stringVol.Length == 1) { t = $".0{stringVol}"; } else { t = $".{stringVol}"; } //convert to float float newVol = float.Parse(t, System.Globalization.CultureInfo.InvariantCulture); if (newVol >= 0f && newVol <= 1f) { //valid number _config.volume = newVol; _config.SaveFile(); player.volume = newVol; //send the updated value to the var so we dont have to load the config file everytime in the loop. await e.Channel.SendMessage($"{e.User.Name},\rI have updated the volume to {e.GetArg("vol")}%."); _logs.logMessage("Info", "commandsSyste.Volume", $"Volume was changed to {newVol}%", e.User.Name); } } else if (intVol >= 101) { await e.Channel.SendMessage($"{e.User.Name},\rThe value you gave was higher then 100%, sorry."); } else if (intVol <= 0) { await e.Channel.SendMessage($"{e.User.Name},\rThe value can't go below 1, sorry."); } } catch (Exception error) { _logs.logMessage("Error", "commandsSystem.vol", error.ToString(), e.User.Name); } }); _client.GetService <CommandService>().CreateCommand("halt") .Alias("halt") .Description("Shuts down the bot.\rPermission: Owner") .MinPermissions((int)PermissionLevel.BotOwner) .Do(async e => { try { await e.Channel.SendMessage($":wave: :zzz:"); _logs.logMessage("Info", "commandsSystem.halt", $"Server was requested to shutdown.", e.User.Name); await e.Server.Client.Disconnect(); Environment.Exit(0); } catch (Exception error) { _logs.logMessage("Error", "commandsSystem.halt", error.ToString(), e.User.Name); } }); _client.GetService <CommandService>().CreateCommand("restart") .Alias("reboot") .Description("Shuts down the bot.\rPermission: Mods") .MinPermissions((int)PermissionLevel.GroupMods) .Do(async e => { try { //dump the current game playing _client.SetGame(null); //send a message out on the restart await e.Channel.SendMessage($":wave: :zzz:"); //check to see if she is in a voice room, if so disconnect var bot = e.Server.FindUsers(_client.CurrentUser.Name).FirstOrDefault().VoiceChannel; //check to see if the bot is in a room. if (bot != null) { //if she is, disconnect from the room. await bot.LeaveAudio(); } _logs.logMessage("Info", _config.Prefix + "restart", "Process was restarted by user", e.User.Name); var fileName = Assembly.GetExecutingAssembly().Location; System.Diagnostics.Process.Start(fileName); Environment.Exit(0); } catch (Exception error) { _logs.logMessage("Error", "commandsSystem.restart", error.ToString(), e.User.Name); } }); _client.GetService <CommandService>().CreateCommand("serverIds") .Alias("serverIds") .Description("Exports roles IDs.\rPermission: Owner") .MinPermissions((int)PermissionLevel.GroupAdmin) .Do(async e => { try { //extract the roles and id's from the server List <Role> serverRolesList = e.Server.Roles.ToList(); string result = null; for (int i = 0; i < serverRolesList.Count; i++) { result = result + $"{serverRolesList[i].Name} = {serverRolesList[i].Id}\r"; } Channel userPM = await e.User.CreatePMChannel(); await userPM.SendMessage($"```\r{result}\r```"); _logs.logMessage("Info", "commandsSystem.serverIds", "User requested the server role IDs.", e.User.Name); } catch (Exception error) { _logs.logMessage("Error", "commandsSystem.serverIds", error.ToString(), e.User.Name); } }); _client.GetService <CommandService>().CreateCommand("setGroup") .Alias("sg") .Description($"Sets the role group needed for basic commands.\r{_config.Prefix}setGroup default id\r{_config.Prefix}setGroup mods id\r{_config.Prefix}setGroup admins id\rPermission: Owner") .Parameter("role", ParameterType.Optional) .Parameter("id", ParameterType.Optional) .MinPermissions((int)PermissionLevel.BotOwner) .Do(async e => { try { ulong id = new ulong { }; try { id = Convert.ToUInt64(e.GetArg("id")); } catch { } if (e.GetArg("id") == null) { await e.Channel.SendMessage($"Please submit a role ID.\rExample: {_config.Prefix}setGroup default 139135090637668350"); return; } switch (e.GetArg("role")) { case "default": _config.idDefaultGroup = id; _config.SaveFile(); await e.Channel.SendMessage($"Permission Role has been updated."); _logs.logMessage("Info", "commandsSystem.setGroup default", $"Default role updated to {e.GetArg("id")}", e.User.Name); break; case "mods": _config.idModsGroup = id; _config.SaveFile(); await e.Channel.SendMessage($"Permission Role has been updated."); _logs.logMessage("Info", "commandsSystem.setGroup mods", $"Mods role updated to {e.GetArg("id")}", e.User.Name); break; case "admins": _config.idAdminGroup = id; _config.SaveFile(); await e.Channel.SendMessage($"Permission Role has been updated."); _logs.logMessage("Info", "commandsSystem.setGroup admins", $"Admins role updated to {e.GetArg("id")}", e.User.Name); break; default: await e.Channel.SendMessage($"Please submit a group level.\rAvailable args\rdefault\rmods\radmins\rExample: {_config.Prefix}setGroup default 139135090637668350"); break; } } catch (Exception error) { _logs.logMessage("Error", "commandsSystem.setGroup", error.ToString(), e.User.Name); } }); _client.GetService <CommandService>().CreateCommand("setPrefix") .Alias("sp") .Description("Changes the prefix that the bot will listen to.\rPermission: Owner") .Parameter("id", ParameterType.Optional) .MinPermissions((int)PermissionLevel.BotOwner) .Do(async e => { try { if (e.GetArg("id") == "#" || e.GetArg("id") == "/" || e.GetArg("id") == "@") { await e.Channel.SendMessage($"Please pick another command character that is not one of the following.\r'#' '/' '@'"); return; } else { _config.Prefix = e.GetArg("id")[0]; _config.SaveFile(); await e.Channel.SendMessage($"Character prefix has been changed to {e.GetArg("id")} and will be active on next restart."); _logs.logMessage("Info", "commandsSystem.setPrefix", $"Commands prefix was changed to {e.GetArg("id")}.", e.User.Name); } } catch (Exception error) { _logs.logMessage("Error", "commandsSystem.setPrefix", error.ToString(), e.User.Name); } }); _client.GetService <CommandService>().CreateCommand("about") .Alias("about") .Description("Returns with github infomation.\rPermission: Everyone") .Parameter("id", ParameterType.Optional) .MinPermissions((int)PermissionLevel.GroupUsers) .Do(async e => { try { await e.Channel.SendMessage($"Here is my current documentation.\rGetting Started: soon\rCommands: <https://github.com/luther38/DiscordMusicBot/wiki/Commands>"); _logs.logMessage("Info", "commandsSystem.about", "User requested help docs.", e.User.Name); } catch (Exception error) { _logs.logMessage("Error", "commandsSystem.about", error.ToString(), e.User.Name); } }); _client.GetService <CommandService>().CreateCommand("export") .Alias("export") .Description($"Exports current files based on given arg.\r{_config.Prefix}export playlist\r{_config.Prefix}export blacklist\r{_config.Prefix}export log = Running log file.\rPermission: Mods") .Parameter("file", ParameterType.Optional) .MinPermissions((int)PermissionLevel.GroupAdmin) .Do(async e => { try { string argFile = e.GetArg("file"); Channel userPM = await e.User.CreatePMChannel(); switch (argFile) { case "playlist": case "pl": bool plExport = _system.cmd_plExport(); if (plExport == true) { await userPM.SendFile(Directory.GetCurrentDirectory() + "\\configs\\playlist_export.json"); await e.Channel.SendMessage($"{e.User.Name},\rPlease check the PM that I sent you for your file request."); File.Delete(Directory.GetCurrentDirectory() + "\\configs\\playlist_export.json"); _logs.logMessage("Info", "commandsSystem.Export Playlist", "User requested the playlist file.", e.User.Name); } else { await e.Channel.SendMessage("Error generating file.\rPlease inform the server owner for more infomation."); } break; case "blacklist": case "bl": bool blExport = _system.cmd_blExport(); if (blExport == true) { await userPM.SendFile(Directory.GetCurrentDirectory() + "\\configs\\blacklist_export.json"); await e.Channel.SendMessage($"{e.User.Name},\rPlease check the PM that I sent you for your file request."); File.Delete(Directory.GetCurrentDirectory() + "\\configs\\blacklist_export.json"); _logs.logMessage("Info", "commandsSystem.Export Blacklist", "User requested the blacklist file.", e.User.Name); } else { await e.Channel.SendMessage("Error generating file.\rPlease inform the server owner for more infomation."); } break; case "log": await userPM.SendFile(Directory.GetCurrentDirectory() + "\\logs.txt"); await e.Channel.SendMessage($"{e.User.Name},\rPlease check the PM that I sent you for your file request."); _logs.logMessage("Info", "commandsSystem.Export log", "User requested the log file.", e.User.Name); break; case "config": await userPM.SendFile(Directory.GetCurrentDirectory() + "\\configs\\config.json"); await e.Channel.SendMessage($"{e.User.Name},\rPlease check the PM that I sent you for your file request."); _logs.logMessage("Info", "commandsSystem.Export config", "User requested the config file.", e.User.Name); break; default: await e.Channel.SendMessage($"Invalid arguemnt found!\rPlease use one of the following.\r{_config.Prefix}export pl = Playlist\r{_config.Prefix}export bl = Blacklist\r{_config.Prefix}export log = Running log file."); break; } } catch (Exception error) { _logs.logMessage("Error", "commandsSystem.export", error.ToString(), e.User.Name); } }); _client.GetService <CommandService>().CreateCommand("ping") .Alias("ping") .Description($"Exports current files based on given arg.\r{_config.Prefix}export playlist\r{_config.Prefix}export blacklist\r{_config.Prefix}export log = Running log file.\rPermission: Mods") .MinPermissions((int)PermissionLevel.GroupUsers) .Do(async e => { try { var t = e.Server.Region; long ping = _network.cmd_ping(t.Hostname); if (ping != -1) { await e.Channel.SendMessage($"{e.User.Name},\rDatacenter: {t.Name}\rPing: {ping}ms"); _logs.logMessage("Info", "commandSystem.ping", $"Datacenter: {t.Name} - Host IP: {t.Id} - Ping: {ping}ms", e.User.Name); } else { await e.Channel.SendMessage($"{e.User.Name}, Something happened and I was unable to ping the server. Please check the log for the dump info."); } } catch (Exception error) { _logs.logMessage("Error", "commandsSystem.ping", error.ToString(), e.User.Name); } }); _client.GetService <CommandService>().CreateCommand("maxSubmitted") .Alias("maxSub") .Description($"Changes the max number of tracks a user can submit to the queue.\r{_config.Prefix}maxSubmitted 10\rPermission: Admins") .Parameter("value", ParameterType.Optional) .MinPermissions((int)PermissionLevel.GroupAdmin) .Do(async e => { try { if (e.GetArg("value") == "") { await e.Channel.SendMessage($"{e.User.Name},\rMax Submitted: {_config.maxTrackSubmitted}"); } else { int value = -1; bool parseResult = int.TryParse(e.GetArg("value"), out value); if (parseResult == true) { if (value != -1) { _config.maxTrackSubmitted = value; _config.SaveFile(); await e.Channel.SendMessage($"{e.User.Name},\rI have adjusted the max number of submitted tracks to {e.GetArg("value")}."); } } else { await e.Channel.SendMessage($"{e.User.Name},\rPlease enter a number value to adjust the max number of tracks a user can submit."); } } } catch (Exception error) { _logs.logMessage("Error", "commandsSystem.maxSubmitted", error.ToString(), e.User.Name); } }); }); }
public void shuffleLibrary() { Stopwatch stopWatch = new Stopwatch(); //make the stopwatch so we can track how long it takes try { loadPlaylist(); //load the playlist to memory loadBlacklist(); //load the blacklist to memory _logs.logMessage("Info", "playlist.shuffleLibrary", $"Starting shuffle of {listLibrary.Count} tracks", "system"); Random rng = new Random(); List <ListPlaylist> tempLibrary = new List <ListPlaylist>(); tempLibrary.AddRange(listLibrary); stopWatch.Start(); //generate a temp lis for (int i = 0; i < listLibrary.Count; i++) { int counter = rng.Next(0, tempLibrary.Count); listAutoQueue.Add(new ListPlaylist { title = tempLibrary[counter].title, url = tempLibrary[counter].url, user = tempLibrary[counter].user, like = tempLibrary[counter].like, skips = tempLibrary[counter].skips, filename = tempLibrary[counter].filename }); //remove the item we just added to the queue tempLibrary.RemoveAt(counter); } stopWatch.Stop(); _logs.logMessage("Info", "playlist.shuffleLibrary", $"Finished shuffle of {listLibrary.Count} tracks in {stopWatch.Elapsed.TotalSeconds}s", "system"); } catch (Exception error) { stopWatch.Stop(); _logs.logMessage("Error", "playlist.shuffleLibrary", error.ToString(), "system"); } }
void IModule.Install(ModuleManager manager) { _manager = manager; _client = manager.Client; playlist _playlist = new playlist(); youtube _downloader = new youtube(); player _player = new player(); logs _logs = new logs(); system _system = new system(); manager.CreateCommands("", group => { //group.PublicOnly(); //get the config file _config = configuration.LoadFile(); _client.GetService <CommandService>().CreateCommand("test") .Alias("test") .Description("Placeholder for testing.") .Do(async e => { //await e.Channel.SendMessage("test"); }); _client.GetService <CommandService>().CreateCommand("play") .Alias("play") .Description("Adds the requested song to the queue.\rExample: !play url\rPermissions: Mods") .Parameter("url", ParameterType.Optional) .Parameter("title", ParameterType.Optional) .MinPermissions((int)PermissionLevel.GroupUsers) .Do(async e => { try { if (e.GetArg("url") == "") { await e.Channel.SendMessage($"{e.User.Mention}, Please give me a link so I can play the song for you."); return; } //if return in 0 the user can add a track int UserSubmit = _playlist.checkNumberOfTracksByUserSubmitted(e.User.Name); if (UserSubmit == 0) { //add the url to the listSubmitted if (e.GetArg("url").Contains("https://www.youtube.com/")) { string result = await _playlist.cmd_play(e.GetArg("url"), e.User.Name); if (result == null) { await e.Channel.SendMessage($"Sorry I wont add that url to the queue given someone blacklisted it already."); } else { await e.Channel.SendMessage(result); _logs.logMessage("Info", "commandsPlayer.play", $"URL:{e.GetArg("url")} was submitted to the queue.", e.User.Name); } } else { switch (e.GetArg("url").ToLower()) { case "title": string searchResult = _playlist.cmd_searchLibrary(e.GetArg("url"), e.GetArg("title"), e.User.Name); if (searchResult == null) { await e.Channel.SendMessage($"Sorry I ran into a error. Please check the log for more information."); } else if (searchResult.Contains("https://www.youtube.com/")) { string searchResultMessage = await _playlist.cmd_play(searchResult, e.User.Name); await e.Channel.SendMessage(searchResultMessage); } else { await e.Channel.SendMessage(searchResult); } break; default: await e.Channel.SendMessage($"{e.User.Name},\r Please enter a valid search mode."); break; } } } else if (UserSubmit == 1) { await e.Channel.SendMessage($"{e.User.Name},\rYou have submitted too many tracks to the queue. Please wait before you submit anymore."); } } catch (Exception error) { _logs.logMessage("Error", "commandsPlayer.play", error.ToString(), e.User.Name); } }); _client.GetService <CommandService>().CreateCommand("skip") .Alias("skip") .Description("Adds the requested song to the queue.\rPermissions: Everyone") .MinPermissions((int)PermissionLevel.GroupUsers) .Do(async e => { try { bool result = _player.cmd_skip(); if (result == true) { await e.Channel.SendMessage($"Skipping the track."); _logs.logMessage("Info", "commandsPlayer.skip", "Track skip was requested.", e.User.Name); } else { await e.Channel.SendMessage($"Nothing is currently playing, unable to skip."); } } catch (Exception error) { _logs.logMessage("Error", "commandsPlayer.skip", error.ToString(), e.User.Name); } }); _client.GetService <CommandService>().CreateCommand("stop") .Alias("stop") .Description("Stops the music from playing.\rPermissions: Everyone") .MinPermissions((int)PermissionLevel.GroupUsers) .Do(async e => { try { bool result = _player.cmd_stop(); if (result == true) { _client.SetGame(null); await e.Channel.SendMessage($"Music will be stopping."); _logs.logMessage("Info", "commandsPlayer.stop", "Player was requested to stop.", e.User.Name); } else { await e.Channel.SendMessage($"Nothing is currently playing, can't stop something that isnt moving."); } } catch (Exception error) { _logs.logMessage("Error", "commandsPlayer.stop", error.ToString(), e.User.Name); } }); _client.GetService <CommandService>().CreateCommand("resume") .Alias("resume") .Description("Starts the playlist again.\rPermissions: Everyone") .MinPermissions((int)PermissionLevel.GroupUsers) .Do(async e => { try { _player.cmd_resume(); await e.Channel.SendMessage($"Activating the playlist again."); _logs.logMessage("Info", "commandsPlayer.resume", "", e.User.Name); } catch (Exception error) { _logs.logMessage("Error", "commandsPlayer.resume", error.ToString(), e.User.Name); } }); _client.GetService <CommandService>().CreateCommand("summon") .Alias("summon") .Description("Summons bot to current voice channel and starts playing from the library.\rPermission: Everyone") .MinPermissions((int)PermissionLevel.GroupUsers) .Do(async e => { try { Channel voiceChan = e.User.VoiceChannel; await voiceChan.JoinAudio(); //await _playlist.startAutoPlayList(voiceChan, _client); await _playlist.playAutoQueue(voiceChan, _client); _logs.logMessage("Error", "commandsPlayer.summon", $"User has summoned the bot to room {voiceChan.ToString()}", e.User.Name); } catch (Exception error) { _logs.logMessage("Error", "commandsPlayer.summon", error.ToString(), e.User.Name); } }); }); }
void IModule.Install(ModuleManager manager) { _manager = manager; _client = manager.Client; playlist _playlist = new playlist(); player _player = new player(); system _system = new system(); youtube _downloader = new youtube(); logs _logs = new logs(); _config = configuration.LoadFile(); manager.CreateCommands("", group => { _client.GetService <CommandService>().CreateCommand("shuffle") .Alias("shuffle") .Description("Adds a url to the playlist file.\rPermissions: Everyone") .MinPermissions((int)PermissionLevel.GroupUsers) .Do(async e => { try { string result = _playlist.cmd_shuffle(); if (result == "empty") { await e.Channel.SendMessage($"@{e.User.Name}\rNo songs have been submitted to be shuffled."); } if (result == "true") { await e.Channel.SendMessage($"@{e.User.Name}\rThe current queue has been shuffled."); } if (result == "error") { await e.Channel.SendMessage($"{e.User.Name}\rError please check the console for more information."); } } catch (Exception error) { _logs.logMessage("Error", "commandsPlaylist.shuffle", error.ToString(), e.User.Name); } }); _client.GetService <CommandService>().CreateCommand("np") .Alias("np") .Description("Returns infomation of current playing track.\rPermissions: Everyone") .MinPermissions((int)PermissionLevel.GroupUsers) .Parameter("flag", ParameterType.Optional) .Do(async e => { try { switch (e.GetArg("flag")) { case "remove": case "r": //going to remove a track from the playlist with what is currently playing. bool npRemoveResult = _playlist.cmd_npRemove(); if (npRemoveResult == true) { _player.cmd_skip(); await e.Channel.SendMessage($"{e.User.Name}, the current playing track has been removed from the Library as requested."); _logs.logMessage("Info", "commandsPlaylist.np remove", $"URL: {playlist.npUrl} was removed from the Library", e.User.Name); } else { await e.Channel.SendMessage($"{e.User.Name}, I ran into a problem with your request. Please see the log for more details."); } break; default: string[] result = _playlist.cmd_np(); if (result[0] == null) { await e.Channel.SendMessage($"Sorry but a song is not currently playing."); } else { await e.Channel.SendMessage($"Track currently playing\rTitle: {result[0]} \rURL: {result[1]}\rUser: {result[2]}\rSource: {result[3]}"); _logs.logMessage("Info", "commandsPlaylist.np", $"Now playing infomation was requested. Title: {result[0]} URL: {result[1]} User: {result[2]} Source: {result[3]} ", e.User.Name); } break; } } catch (Exception error) { _logs.logMessage("Error", "commandsPlaylist.np", error.ToString(), e.User.Name); } }); _client.GetService <CommandService>().CreateCommand("queue") .Alias("queue") .Parameter("limit", ParameterType.Optional) .Description("Returns infomation of currently queued tacks.\rPermissions: Everyone") .MinPermissions((int)PermissionLevel.GroupUsers) .Do(async e => { try { int limit = 0; string result = null; if (e.GetArg("limit") == "") { limit = 5; result = _playlist.cmd_queue(limit); await e.Channel.SendMessage($"```\r{result}\r```"); } else { if (int.TryParse(e.GetArg("limit"), out limit)) { //true if (limit >= 20) { limit = 20; } result = _playlist.cmd_queue(limit); await e.Channel.SendMessage($"```{result}\r```"); } else { //false await e.Channel.SendMessage($"Sorry the arg you passed was not a number."); } } } catch (Exception error) { _logs.logMessage("Error", "commandsPlaylist.np", error.ToString(), e.User.Name); } }); _client.GetService <CommandService>().CreateCommand("playlist") .Alias("pl") .Description("Adds a url to the playlist file.\rPermissions: Mods") .Parameter("flag", ParameterType.Optional) .Parameter("url", ParameterType.Optional) .MinPermissions((int)PermissionLevel.GroupMods) .Do(async e => { try { if (e.GetArg("url") == "") { await e.Channel.SendMessage($"@{e.User.Name}, Unable to adjust the playlist if you dont give me a url."); return; } switch (e.GetArg("flag")) { case "add": case "a": string title = await _system.cmd_plAdd(e.User.Name, e.GetArg("url")); if (title == "dupe") { await e.Channel.SendMessage($"{e.User.Name},\rI found this url already in the list. :smile:\rNo change was made."); } else { await e.Channel.SendMessage($"{e.User.Name},\rTitle: {title}\rHas been added to the playlist file."); _logs.logMessage("Info", "commandsPlaylist.playlist add", $"Playlist was updated. Added {title} {e.GetArg("url")}", e.User.Name); } break; case "remove": case "r": string url = _system.cmd_plRemove(e.GetArg("url")); if (url == "match") { string[] urlTitle = await _downloader.returnYoutubeTitle(e.GetArg("url")); await e.Channel.SendMessage($"{e.User.Name},\rTitle: {urlTitle[0]}\rWas removed from the playlist."); _logs.logMessage("Info", "commandsPlaylist.playlist remove", $"Playlist was updated. Removed {urlTitle[0]} {e.GetArg("url")}", e.User.Name); } else { await e.Channel.SendMessage($"{e.User.Name},\rUnable to find the song in the playlist."); } break; default: await e.Channel.SendMessage($"Invalid Argument\r{_config.Prefix}playlist add url\r{_config.Prefix}playlist remove url"); break; } } catch (Exception error) { _logs.logMessage("Error", "commandsPlaylist.playlist", error.ToString(), e.User.Name); } }); _client.GetService <CommandService>().CreateCommand("blacklist") .Alias("bl") .Description("Adds a url to the blacklist file.\rPermissions: Mods") .Parameter("flag", ParameterType.Optional) .Parameter("url", ParameterType.Optional) .MinPermissions((int)PermissionLevel.GroupMods) .Do(async e => { try { if (e.GetArg("url") == "") { await e.Channel.SendMessage($"@{e.User.Name}, Unable to adjust the blacklist if you dont give me a url."); return; } switch (e.GetArg("flag")) { case "add": case "a": //parse the url and get the infomation then append to the blacklist.json string title = await _system.cmd_blAdd(e.User.Name, e.GetArg("url")); if (title == "dupe") { await e.Channel.SendMessage($"{e.User.Name},\rI found this url already in the list. :smile:\rNo change was made."); } else { //send the infomation back to the user letting them know we added it to the blacklist. await e.Channel.SendMessage($"{e.User.Name}\rTitle: {title}\rHas been added to the blacklist file."); _logs.logMessage("Info", "commandsPlaylist.blacklist add", $"Blacklist was updated. Added {title} {e.GetArg("url")}", e.User.Name); } break; case "remove": case "r": //parse the url and get the infomation then append to the blacklist.json string url = _system.cmd_blRemove(e.GetArg("url")); if (url == "match") { string[] urlTitle = await _downloader.returnYoutubeTitle(e.GetArg("url")); await e.Channel.SendMessage($"{e.User.Name}\rTitle: {urlTitle[0]}\rWas removed from the blacklist."); _logs.logMessage("Info", "commandsPlaylist.blacklist remove", $"Blacklist was updated. Removed {urlTitle[0]} {e.GetArg("url")}", e.User.Name); } else { await e.Channel.SendMessage($"{e.User.Name}\rUnable to find the song in the blacklist."); } break; default: await e.Channel.SendMessage($"Invalid Argument\r{_config.Prefix}blacklist add url\r{_config.Prefix}blacklist remove url"); break; } } catch (Exception error) { _logs.logMessage("Error", "commandsPlaylist.blacklist", error.ToString(), e.User.Name); } }); _client.GetService <CommandService>().CreateCommand("vote") .Alias("v") .Description("Adds a url to the blacklist file.\rPermissions: Mods") .Parameter("flag", ParameterType.Optional) .MinPermissions((int)PermissionLevel.GroupMods) .Do(async e => { try { bool result = false; switch (e.GetArg("flag")) { case "up": case "+": //parse the url and get the infomation then append to the blacklist.json result = _playlist.cmd_voteUp(e.User.Id.ToString()); if (result == true) { await e.Channel.SendMessage($"{e.User.Name},\rI have updated the record for the current track to note it was voted for."); _logs.logMessage("Info", "commandsPlaylist.vote up", $"User voted up for URL: {playlist.npUrl}", e.User.Name); } else { await e.Channel.SendMessage($"{e.User.Name},\rRan into a error... please check the log file for more infomation."); } break; case "down": case "-": //parse the url and get the infomation then append to the blacklist.json int intResult = _playlist.cmd_voteDown(e.User.Id.ToString()); switch (intResult) { case -1: await e.Channel.SendMessage($"{e.User.Name},\r The track was been skipped enough that it ws removed from the library."); _logs.logMessage("Info", "commandsPlaylist.vote down", $"URL: {playlist.npUrl} hit the treshhold and was removed from the library.", "System"); break; case 0: await e.Channel.SendMessage($"{e.User.Name},\rRan into a error... please check the log file for more infomation."); break; case 1: await e.Channel.SendMessage($"{e.User.Name},\rI have updated the record for the current track to note it was down voted for."); _logs.logMessage("Info", "commandsPlaylist.vote down", $"User voted down for URL: {playlist.npUrl}", e.User.Name); break; default: break; } break; default: await e.Channel.SendMessage($"Invalid Argument\r{_config.Prefix}vote up/+ \r{_config.Prefix}vote down/-"); break; } } catch (Exception error) { _logs.logMessage("Error", "commandsPlaylist.vote", error.ToString(), e.User.Name); } }); }); }
public void Start() { _startup.startupCheck(); _config = configuration.LoadFile(); _client = new DiscordClient(x => { x.AppName = "C# Music Bot"; x.AppUrl = "https://github.com/luther38/DiscordMusicBot"; x.AppVersion = "0.1.4"; x.UsePermissionsCache = true; //x.LogLevel = LogSeverity.Info; x.LogHandler = OnLogMessage; }) .UsingCommands(x => { x.PrefixChar = _config.Prefix; x.AllowMentionPrefix = true; x.HelpMode = HelpMode.Public; x.ExecuteHandler = OnCommandExecuted; x.ErrorHandler = OnCommandError; }) .UsingModules() .UsingAudio(x => { x.Mode = AudioMode.Outgoing; x.EnableEncryption = true; x.Bitrate = AudioServiceConfig.MaxBitrate; x.BufferLength = 10000; }) .UsingPermissionLevels(PermissionResolver); //this CommandsModule is tied behind discordMusicBot.src _client.AddModule <commandsPlayer>("commandsPlayer", ModuleFilter.ServerWhitelist); _client.AddModule <commandsSystem>("commandsSystem", ModuleFilter.ServerWhitelist); _client.AddModule <commandsPlaylist>("commandsPlaylist", ModuleFilter.ServerWhitelist); _client.AddModule <commandsWeb>("commandsWeb", ModuleFilter.ServerWhitelist); _client.GetService <AudioService>(); //check the playlist file _playlist.shuffleLibrary(); //this is used to force the bot the dc from the room if she is left alone. _client.UserUpdated += async(s, e) => { //gives us more infomation for like what room the bot is in var bot = e.Server.FindUsers(_client.CurrentUser.Name).FirstOrDefault().VoiceChannel; try { List <User> userCount = bot.Users.ToList(); if (userCount.Count <= 1) { _client.SetGame(null); _player.cmd_stop(); //double checking to make sure she isnt in a room. //Event shouldnt have flagged but reguardless double checking if (bot.ToString() != null) { await bot.LeaveAudio(); } //Console.WriteLine("Bot is left alone. Music is stopping."); } } catch { //this will catch if the bot isnt summoned given bot.user.tolist will pull a null } }; //turns the bot on and connects to discord. _client.ExecuteAndWait(async() => { while (true) { try { await _client.Connect(_config.Token, TokenType.Bot); _client.SetGame(null); _logs.logMessage("Info", "program.Start", "Connected to Discord", "system"); //Console.WriteLine("Connected to Discord."); //await _client.ClientAPI.Send(new Discord.API.Client.Rest.HealthRequest()); break; } catch (Exception ex) { _client.Log.Error($"Login Failed", ex); _logs.logMessage("Error", "program.Start", ex.ToString(), "system"); //await Task.Delay(_client.Config.FailedReconnectDelay); await Task.Delay(3000); } } }); }