Пример #1
0
        private void OnTimer2MinTick(object sender, EventArgs e)
        {
            var posts = Instagram.GetPosts();

            if (posts.Count > 0)
            {
                bool petsExist = File.Exists($"{BotTools.BasePath}\\resources\\raz_pets.json");
                var  pastPets  = petsExist ? BotTools.ReadFromJson <List <string> >("resources\\raz_pets") : new List <string>();

                try
                {
                    var newPets = posts.Where(p => !pastPets.Contains(p["permalink"]));
                    if (newPets.Count() > 0)
                    {
                        foreach (var post in newPets)
                        {
                            BotTools.LogLine($"Saw new Raz pet -> {post["permalink"]}");
                            DiscordBot.PostToPetsChannel(post);
                            pastPets.Add(post["permalink"]);

                            using (var webClient = new System.Net.WebClient())
                            {
                                webClient.DownloadFile(post["media_url"], $"{BotTools.BasePath}\\datasources\\raz.jpg");
                            }
                        }
                        BotTools.WriteToJson(pastPets, "resources\\raz_pets");
                    }
                }
                catch (Exception petsException)
                {
                    BotTools.LogToSessionLogFile(petsException.ToString());
                    BotTools.LogLine("There was a problem loading past Raz Pets! See the session log for details.");
                }
            }
        }
Пример #2
0
        public static List <Dictionary <string, dynamic> > GetPosts()
        {
            string url = $"{RootUrl}/{UserId}/media?access_token={AccessToken}&fields=permalink,caption,media_url";

            var response = WebTools.GetJObjectResponse(url);

            try
            {
                if (response != null && response.HasValues && response["data"].Any())
                {
                    return(response["data"].ToObject <List <Dictionary <string, dynamic> > >());
                }
                else
                {
                    return(new List <Dictionary <string, dynamic> >()
                    {
                    });
                }
            }
            catch (Exception e)
            {
                BotTools.LogToSessionLogFile(e.ToString());
                return(new List <Dictionary <string, dynamic> >()
                {
                });
            }
        }
Пример #3
0
        public static string FillSongRequest(string requestBody, string songRequestor = "RazBot", bool bypassVet = false)
        {
            SongData songData = YTE.GetSongData(requestBody, requestor: songRequestor);

            if (songData.Duration <= TimeSpan.FromMinutes(10))
            {
                if (BotTools.Settings["vet_requests"] && !bypassVet)
                {
                    DiscordBot.PostVetRequestToDJChannel(songData);
                    return($"@{songData.Requestor}, Your request has been submitted for review! razBot");
                }
                else
                {
                    try
                    {
                        Music.GetPlaylist("request").AddSong(songData);
                        var placement = Music.GetPlaylist("request").Songs.Count;
                        if (DownloadedSong != null && placement == 1)
                        {
                            if (DownloadedSong.IsRequest)
                            {
                                placement++;
                            }
                            else
                            {
                                DownloadedSong = null;
                                GetPlaylist(LoadedPlaylist).CycleBack();
                            }
                        }
                        var placementWord = BotTools.GetPlacementWord(placement);

                        Music.SavePlaylists();
                        return($"@{songData.Requestor}, Your request is {placementWord} in the queue! razCool");
                    }
                    catch (ArgumentException)
                    {
                        BotTools.LogLine($"{songRequestor}'s request rejected: Already in queue");
                        return($"Sorry @{songRequestor}, that request is already queued!");
                    }
                    catch (FormatException e)
                    {
                        BotTools.LogToSessionLogFile(e.ToString());
                        BotTools.LogLine($"{songRequestor}'s request rejected: Bad url");
                        return($"Sorry @{songRequestor}, I can't access a YouTube video from that link! It may not be available in my region, or the url may not be properly formatted.");
                    }
                }
            }
            else
            {
                return($"{songData.Requestor}'s request was rejected: The audio was over 10 minutes long! razS");
            }
        }
Пример #4
0
        public async static Task <SongData> DownloadAudio(SongData songData, IProgress <double> myProgress)
        {
            string playlistName = songData.Requestor == "RazBot" ? Music.LoadedPlaylist : "request";

            Directory.CreateDirectory($"{BotTools.BasePath}\\playlists\\{playlistName}");
            string relativePath = $"playlists\\{playlistName}\\{songData.ID}";
            string newPath      = $"{BotTools.BasePath}\\{relativePath}.mp4";

            if (!File.Exists(newPath))
            {
                try
                {
                    var streamManifest = await youtube.Videos.Streams.GetManifestAsync(songData.ID);

                    var streamInfo = streamManifest.GetAudioOnly().Where(s => s.Container == YoutubeExplode.Videos.Streams.Container.Mp4).WithHighestBitrate();
                    if (streamInfo != null)
                    {
                        var stream = await Task.Run(() => youtube.Videos.Streams.GetAsync(streamInfo)).ConfigureAwait(false);

                        await Task.Run(async() => {
                            await youtube.Videos.Streams.DownloadAsync(streamInfo, newPath, progress: myProgress);
                        });
                    }
                }
                catch (YoutubeExplode.Exceptions.VideoUnplayableException e)
                {
                    BotTools.LogToSessionLogFile(e.ToString());
                    BotTools.LogLine($"Downloading \"{Music.QueuedSong.Title}\" failed: Video unavailable");
                    if (Music.QueuedSong.IsRequest)
                    {
                        TwitchBot.SendMessage($"Sorry @{Music.QueuedSong.Requestor}, there was a problem retreiving that video!");
                    }
                }
                catch (Exception e)
                {
                    BotTools.LogToSessionLogFile(e.ToString());
                    BotTools.LogLine($"The requested audio couldn't be downloaded from YouTube");
                    Music.QueuedSong = null;
                }
            }
            else
            {
                myProgress.Report(1.0d);
            }
            return(Music.QueuedSong);
        }
Пример #5
0
        public static SongData GetSongData(string url, string requestor = "RazBot")
        {
            songDataCache = null;
            try
            {
                GetVideoMetaDataAsync(url, requestor);
            }
            catch (Exception e)
            {
                BotTools.LogToSessionLogFile($"YTE::GetSongData -> \n{e}");
            }

            while (songDataCache == null)
            {
                ;
            }
            return(songDataCache);
        }
Пример #6
0
        public static void Start()
        {
            Client.Initialize(Credentials);

            Client.OnConnected     += Client_OnConnected;
            Client.OnDisconnected  += Client_OnDisconnected;
            Client.OnJoinedChannel += Client_OnJoinedChannel;
            Client.OnLeftChannel   += Client_OnLeftChannel;

            Client.OnMessageReceived    += Client_OnMessageReceived;
            Client.OnWhisperReceived    += Client_OnWhisperReceived;
            Client.OnModeratorsReceived += Client_OnModeratorsReceived;

            PubSub.OnPubSubServiceConnected += Pubsub_OnPubSubServiceConnected;
            PubSub.OnListenResponse         += PubSub_OnListenResponse;
            PubSub.OnStreamUp   += PubSub_OnStreamUp;
            PubSub.OnStreamDown += PubSub_OnStreamDown;
            PubSub.ListenToVideoPlayback("maerictv");

            Client.OnHostingStarted   += Client_OnHostingStarted;
            Client.OnHostingStopped   += Client_OnHostingStopped;
            Client.OnBeingHosted      += Client_OnBeingHosted;
            Client.OnRaidNotification += Client_OnRaidNotification;

            Client.OnNewSubscriber         += Client_OnNewSubscriber;
            Client.OnReSubscriber          += Client_OnReSubscriber;
            Client.OnCommunitySubscription += Client_OnCommunitySubscription;
            Client.OnGiftedSubscription    += Client_OnGiftedSubscription;

            for (int i = 0; i < 99; i++)
            {
                try
                {
                    Client.Connect();
                    PubSub.Connect();
                }
                catch (Exception e)
                {
                    BotTools.LogToSessionLogFile(e.ToString());
                }
            }

            StreamStatus = GetStreamOnline() ? StreamState.Online : StreamState.Offline;
        }
Пример #7
0
        private async static void GetVideoMetaDataAsync(string url, string requestor)
        {
            if (VideoExists(url))
            {
                for (int attempts = 3; attempts > 0; attempts--)
                {
                    try
                    {
                        var video = await youtube.Videos.GetAsync(url);

                        attempts      = 0;
                        songDataCache = new SongData(video, requestor);
                    }
                    catch (YoutubeExplode.Exceptions.VideoUnavailableException e)
                    {
                        if (attempts == 1)
                        {
                            BotTools.LogLine($"Failed to get video data from YouTube");
                            BotTools.LogToSessionLogFile(e.ToString());
                            songDataCache    = new SongData();
                            Music.LoadedSong = null;
                        }
                        else
                        {
                            BotTools.LogLine($"Failed to get video data from YouTube. Retrying {attempts-1} more times...");
                            continue;
                        }
                    }
                    catch (Exception e)
                    {
                        BotTools.LogLine($"Failed to get a video from ({url}), make sure the url is properly formatted!");
                        BotTools.LogToSessionLogFile(e.ToString());
                        songDataCache = new SongData();
                        attempts      = 0;
                    }
                }
            }
            else
            {
                songDataCache = new SongData();
            }
        }
Пример #8
0
        public async static void FillPlaylistFromYoutube(string url, string playlistName)
        {
            for (int attempts = 2; attempts > 0; attempts--)
            {
                try
                {
                    // Get playlist metadata
                    var playlist = await youtube.Playlists.GetAsync(url);

                    attempts = 0;

                    var title  = playlist.Title;
                    var author = playlist.Author;

                    // Enumerate through playlist videos
                    foreach (var video in await youtube.Playlists.GetVideosAsync(playlist.Id))
                    {
                        try
                        {
                            Music.GetPlaylist(playlistName).AddSong(new SongData(video, "RazBot"));
                        }
                        catch (ArgumentException)
                        {
                            continue;
                        }
                    }
                }
                catch (Exception e)
                {
                    if (attempts == 0)
                    {
                        BotTools.LogLine($"Failed to set playlist data");
                        BotTools.LogToSessionLogFile(e.ToString());
                    }
                    else
                    {
                        BotTools.LogLine($"Failed to get playlist data from YouTube. Retrying {attempts} more times...");
                    }
                }
            }
        }
Пример #9
0
        public static Dictionary <string, dynamic> GetIntent(string text)
        {
            string baseUrl     = "https://api.wit.ai/message?v=20200730&q=";
            string encodedText = HttpUtility.UrlEncode(text);
            var    url         = baseUrl + encodedText;
            var    headers     = new WebHeaderCollection()
            {
                $"Authorization: Bearer {appToken}"
            };

            JObject response = WebTools.GetJObjectResponse(url, headers: headers);

            Console.WriteLine(response);
            try
            {
                if (response.HasValues && response["intents"].Any())
                {
                    var    responseDict = response.ToObject <Dictionary <string, dynamic> >();
                    var    mainIntent   = responseDict["intents"].First;
                    string description  = mainIntent["name"].ToString();
                    double confidence   = double.Parse(mainIntent["confidence"].ToString(), System.Globalization.CultureInfo.InvariantCulture);
                    return(new Dictionary <string, dynamic>()
                    {
                        ["description"] = description,
                        ["confidence"] = confidence
                    });
                }
                else
                {
                    return(new Dictionary <string, dynamic>());
                }
            }
            catch (Exception e)
            {
                BotTools.LogToSessionLogFile(e.ToString());
                return(new Dictionary <string, dynamic>());
            }
        }
Пример #10
0
        private async void BackgroundCycleAudioQueue(object sender, DoWorkEventArgs e)
        {
            // Priority 1: Load downloaded song
            try
            {
                if (Music.DownloadedSong != null && Music.LoadedSong == null)
                {
                    Music.LoadedSong     = Music.DownloadedSong;
                    Music.DownloadedSong = null;
                    //windowsMP.URL = Music.LoadedSong.URL;
                    //BotTools.LogLine($"Loaded {Music.LoadedSong.Title}");

                    try
                    {
                        string songID       = Music.LoadedSong.ID;
                        string playlistName = Music.LoadedSong.Requestor == "RazBot" ? Music.LoadedPlaylist : "request";
                        string filePathNorm = $"{BotTools.BasePath}\\playlists\\{playlistName}\\{songID}_Normalized.wav";
                        string filePath     = $"{BotTools.BasePath}\\playlists\\{playlistName}\\{songID}.mp4";

                        windowsMP.URL = File.Exists(filePathNorm) ? filePathNorm : filePath;
                    }
                    catch (NullReferenceException)
                    {
                        BotTools.LogLine($"Failed to play song, skipping...");
                        Music.QueueNextSong();
                    }

                    if (windowsMP.playState != WMPLib.WMPPlayState.wmppsPlaying && !playerStopped && windowsMP.playState != WMPLib.WMPPlayState.wmppsPaused)
                    {
                        try
                        {
                            windowsMP.Ctlcontrols.play();
                        }
                        catch (Exception playErr)
                        {
                            BotTools.LogToSessionLogFile(playErr.ToString());
                        }
                    }
                    else if (windowsMP.playState != WMPLib.WMPPlayState.wmppsPaused)
                    {
                        // Force stop since I can't get autoplay to stay disabled
                        windowsMP.Ctlcontrols.stop();
                    }
                }
                // Priority 2: Downloaded next song
                else if (Music.DownloadedSong == null && !downloadingAudio)
                {
                    if (BotTools.Settings["random_play"] == true)
                    {
                        Random rand = new Random();
                        var    playlistCandidates = Music.Playlists.Where(p => p.Value.Songs.Count > 0);
                        Music.LoadedPlaylist = playlistCandidates.ElementAt(rand.Next(playlistCandidates.Count())).Key;
                        BotTools.Settings["loaded_playlist"] = Music.LoadedPlaylist;
                    }

                    SongData nextSong = Music.GetPlaylist("request").Songs.Count > 0 ?
                                        Music.GetPlaylist("request").GetNext() :
                                        Music.GetPlaylist(Music.LoadedPlaylist).GetNext();

                    if (nextSong != null)
                    {
                        Music.QueuedSong = YTE.GetSongData(nextSong.URL, requestor: nextSong.Requestor);

                        downloadProgress = 0.0;
                        downloadingAudio = true;
                        var progress = new Progress <double>(percent =>
                        {
                            downloadProgress = percent;
                        });

                        Music.DownloadedSong = await YTE.DownloadAudio(Music.QueuedSong, progress);

                        Music.QueuedSong = null;
                        downloadingAudio = false;
                        while (bgwAudioNormalizer.IsBusy)
                        {
                            ;
                        }
                        if (cbNormalize.Checked && Music.DownloadedSong != null)
                        {
                            bgwAudioNormalizer.RunWorkerAsync();
                        }
                    }
                }
            }
            catch (Exception comExc)
            {
                BotTools.LogLine("Exception written to session log file");
                BotTools.LogToSessionLogFile(comExc.ToString());
            }
        }
Пример #11
0
        public static void FetchInventoryData()
        {
            try
            {
                // Fetch NA item data
                var inventoryData = new Dictionary <string, Dictionary <string, dynamic> >()
                {
                    ["na"] = new Dictionary <string, dynamic>(),
                    ["eu"] = new Dictionary <string, dynamic>()
                };

                List <string> naCharacterNames = GetCharacters("na").ToObject <List <string> >();

                foreach (var characterName in naCharacterNames)
                {
                    string encodedCharacterName = characterName.Replace(" ", "%20");

                    JObject upperInventoryData = WebTools.GetJObjectResponse($"{BaseURL}/characters/{encodedCharacterName}/inventory", DefaultHeaders("na"));
                    if (upperInventoryData != null && upperInventoryData.HasValues)
                    {
                        JToken bags = upperInventoryData["bags"];
                        inventoryData["na"][characterName] = new List <Dictionary <string, dynamic> >();

                        foreach (JToken bag in bags)
                        {
                            if (bag.HasValues)
                            {
                                JToken bagContents = bag["inventory"];
                                foreach (JToken item in bagContents)
                                {
                                    inventoryData["na"][characterName].Add(item.ToObject <Dictionary <string, dynamic> >());
                                }
                            }
                        }
                    }
                }

                JArray naSharedBankData      = WebTools.GetJArrayResponse($"{BaseURL}/account/bank", DefaultHeaders("na"));
                JArray naSharedInventoryData = WebTools.GetJArrayResponse($"{BaseURL}/account/inventory", DefaultHeaders("na"));
                JArray naMaterialsData       = WebTools.GetJArrayResponse($"{BaseURL}/account/materials", DefaultHeaders("na"));
                JArray naWalletData          = WebTools.GetJArrayResponse($"{BaseURL}/account/wallet", DefaultHeaders("na"));

                inventoryData["na"]["Shared Bank"]      = naSharedBankData.ToObject <List <Dictionary <string, dynamic> > >();
                inventoryData["na"]["Shared Inventory"] = naSharedInventoryData.ToObject <List <Dictionary <string, dynamic> > >();
                inventoryData["na"]["Materials"]        = naMaterialsData.ToObject <List <Dictionary <string, dynamic> > >();
                inventoryData["na"]["Wallet"]           = naWalletData.ToObject <List <Dictionary <string, dynamic> > >();

                // Fetch EU item data
                List <string> euCharacterNames = GetCharacters("eu").ToObject <List <string> >();

                foreach (var characterName in euCharacterNames)
                {
                    string encodedCharacterName = characterName.Replace(" ", "%20");

                    JObject upperInventoryData = WebTools.GetJObjectResponse($"{BaseURL}/characters/{encodedCharacterName}/inventory", DefaultHeaders("eu"));
                    if (upperInventoryData != null && upperInventoryData.HasValues)
                    {
                        JToken bags = upperInventoryData["bags"];
                        inventoryData["eu"][characterName] = new List <Dictionary <string, dynamic> >();

                        foreach (JToken bag in bags)
                        {
                            if (bag.HasValues)
                            {
                                JToken bagContents = bag["inventory"];
                                foreach (JToken item in bagContents)
                                {
                                    inventoryData["eu"][characterName].Add(item.ToObject <Dictionary <string, dynamic> >());
                                }
                            }
                        }
                    }
                }

                JArray euSharedBankData      = WebTools.GetJArrayResponse($"{BaseURL}/account/bank", DefaultHeaders("eu"));
                JArray euSharedInventoryData = WebTools.GetJArrayResponse($"{BaseURL}/account/inventory", DefaultHeaders("eu"));
                JArray euMaterialsData       = WebTools.GetJArrayResponse($"{BaseURL}/account/materials", DefaultHeaders("eu"));
                JArray euWalletData          = WebTools.GetJArrayResponse($"{BaseURL}/account/wallet", DefaultHeaders("eu"));

                inventoryData["eu"]["Shared Bank"]      = euSharedBankData.ToObject <List <Dictionary <string, dynamic> > >();
                inventoryData["eu"]["Shared Inventory"] = euSharedInventoryData.ToObject <List <Dictionary <string, dynamic> > >();
                inventoryData["eu"]["Materials"]        = euMaterialsData.ToObject <List <Dictionary <string, dynamic> > >();
                inventoryData["eu"]["Wallet"]           = euWalletData.ToObject <List <Dictionary <string, dynamic> > >();

                BotTools.WriteToJson(inventoryData, "resources\\inventory_data");
            }
            catch (NullReferenceException e)
            {
                BotTools.LogToSessionLogFile(e.ToString());
            }
        }