private static void Client_OnGiftedSubscription(object sender, OnGiftedSubscriptionArgs e) { string giftee = e.GiftedSubscription.MsgParamRecipientDisplayName; string gifter = e.GiftedSubscription.DisplayName; BotTools.LogLine($"{gifter} gifted a sub to {giftee}"); }
private void OnPlaylistBoxDoubleClick(object sender, EventArgs e) { if (!InPlaylist()) { var selected = $"{listBoxPlaylist.SelectedItem}"; var playlist = Music.Playlists[selected]; if (playlist != null) { listBoxPlaylist.DataSource = playlist.Songs.Select(s => s.Title).ToList <string>(); enteredPlaylist = selected; btnLoad.Text = "SHUFFLE"; btnRemove.Enabled = listBoxPlaylist.Items.Count > 0; } } else { var selected = $"{listBoxPlaylist.SelectedItem}"; var playlist = Music.GetPlaylist(enteredPlaylist); var selectedSong = playlist.GetSong(selected); if (selectedSong != null) { Music.FillSongRequest(selectedSong.URL, songRequestor: "MaericTV", bypassVet: true); BotTools.LogLine($"Added to request Queue: {selectedSong.Title}"); } } }
private static void Client_OnModeratorsReceived(object sender, OnModeratorsReceivedArgs e) { var mods = String.Join(", ", e.Moderators); BotTools.LogLine($"Channel Moderators: {mods}"); BotTools.WriteToJson(e.Moderators, "resources\\moderators"); }
private static void Client_OnReSubscriber(object sender, OnReSubscriberArgs e) { int monthCount = e.ReSubscriber.Months; string monthWord = monthCount > 1 ? "months" : "month"; BotTools.LogLine($"{e.ReSubscriber.DisplayName} subscribed ({monthCount} {monthWord})"); }
private void OnAddButtonClick(object sender, EventArgs e) { if (!Music.Playlists["default"].ContainsSongWithID(Music.LoadedSong.ID)) { var playlist = Music.Playlists["default"]; var songCopy = new SongData(Music.LoadedSong); try { playlist.AddSong(songCopy); BotTools.LogLine("Added current song to default playlist"); btnAddToDefault.Enabled = false; } catch (ArgumentException) { BotTools.LogLine($"Couldn't add current song: Already in default playlist"); } catch (FormatException) { BotTools.LogLine($"Couldn't add current song: Bad url"); } } else { BotTools.LogLine("Song already in default playlist!"); } }
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."); } } }
private static bool GetStreamOnline() { for (int i = 20; i > 0; i--) { string url = "https://decapi.me/twitch/uptime/maerictv"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) using (Stream stream = response.GetResponseStream()) using (StreamReader reader = new StreamReader(stream)) { string result = reader.ReadToEnd(); if (result.Contains("offline")) { BotTools.LogLine($"Stream reported as offline"); return(false); } else if (result.Contains("seconds") || result.Contains("minutes") || result.Contains("hours")) { BotTools.LogLine($"Stream reported as online"); return(true); } } BotTools.LogLine($"Failed to fetch stream status. Retrying {i} more times..."); } BotTools.LogLine($"Failed to fetch stream status. Treating stream as offline."); return(false); }
private static void Client_OnWhisperReceived(object sender, OnWhisperReceivedArgs e) { if (e.WhisperMessage.Username == CurrentChannel || BotTools.ReadFromJson <List <string> >("resources\\moderators").Contains(e.WhisperMessage.Username)) { BotTools.LogLine($"○ {e.WhisperMessage.DisplayName}: {e.WhisperMessage.Message.Trim()}"); } }
private static void PubSub_OnListenResponse(object sender, OnListenResponseArgs e) { if (!e.Successful) { BotTools.LogLine($"Failed to listen! Response: {e.Response.Error}"); } }
private static void Client_OnCommunitySubscription(object sender, OnCommunitySubscriptionArgs e) { int giftAmount = e.GiftedSubscription.MsgParamMassGiftCount; string subWords = giftAmount > 1 ? $"{giftAmount} subscriptions" : "a subscription"; BotTools.LogLine($"{e.GiftedSubscription.DisplayName} gifted {subWords} " + $"({e.GiftedSubscription.MsgParamSenderCount} total)"); }
public static void PostToDJChannel(string postContent) { if (BotTools.Settings["announce_songs"] && !BotTools.Settings["debug_output"]) { DJChannelWebhook.SendMessageAsync(text: postContent); } else { BotTools.LogLine("[D] RazBot: " + postContent); } }
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"); } }
private string[] SkipSong(TwitchMessage message) { if (message.HasModPrivileges && CooldownDone("skip", 2)) { MainWindow.SkipSong(); BotTools.LogLine($"Song skipped by {message.DisplayName}"); return(new string[] { }); } else { return(null); } }
public string[] TryInvoke(string token, TwitchMessage message) { if (Map.ContainsKey(token)) { string invokeReport = $"{message.DisplayName} invoked \"{token}\" ->"; if (message.HasInvokation) { invokeReport += $"\n\t|| TOKEN: {message.Token}"; } if (message.HasQuestion) { invokeReport += $"\n\t|| QUESTION: {message.Message}"; } if (message.Intent != null) { invokeReport += $"\n\t|| INTENT: {message.Intent}"; } if (message.Args != null && message.Args.Length > 0) { invokeReport += $"\n\t|| ARGS: [{String.Join(", ", message.Args)}]"; } BotTools.LogLine(invokeReport); return(Map[token](message)); } else if (CustomMap.ContainsKey(token)) { string invokeReport = $"{message.DisplayName} invoked \"{token}\" ->"; if (message.HasInvokation) { invokeReport += $"\n\t|| TOKEN: {message.Token}"; } if (message.HasQuestion) { invokeReport += $"\n\t|| QUESTION: {message.Message}"; } if (message.Intent != null) { invokeReport += $"\n\t|| INTENT: {message.Intent}"; } if (message.Args != null && message.Args.Length > 0) { invokeReport += $"\n\t|| ARGS: [{String.Join(", ", message.Args)}]"; } BotTools.LogLine(invokeReport); return(new string[] { TwitchBot.Commands.CustomMap[token].Replace("{user}", message.DisplayName) }); } else { return(null); } }
public static void SendMessage(string message) { if (Client.IsConnected) { if (BotTools.Settings["debug_output"] == true) { BotTools.LogLine($"[T] RazBot: {message}"); } else { Client.SendMessage(CurrentChannel, $"/me ~ {message}"); } } }
public void RemoveSong(SongData songData) { var idx = Songs.FindIndex(s => s.ID == songData.ID); if (idx >= 0) { BotTools.LogLine($"Removing \"{songData.Title}\" from \"{Name}\""); RemoveSong(idx); } else { BotTools.LogLine($"\"{songData.Title}\" doesn't exist in \"{Name}\""); } }
private void RemoveSongFromPlaylist() { var loadedPlaylist = Music.Playlists[Music.LoadedPlaylist]; if (loadedPlaylist.ContainsSong(Music.LoadedSong)) { loadedPlaylist.RemoveSong(Music.LoadedSong); } if (!loadedPlaylist.Songs.Any()) { BotTools.LogLine("Loaded playlist is empty, loading default"); Music.LoadedPlaylist = "default"; BotTools.Settings["loaded_playlist"] = Music.LoadedPlaylist; BotTools.SaveSettings(); } SkipSong(); }
private void NormalizeDownloadedAudio(object sender, DoWorkEventArgs e) { normalizingAudio = true; string songID = Music.DownloadedSong.ID; string playlistName = Music.DownloadedSong.IsRequest ? "request" : Music.LoadedPlaylist; NAudioTools.Mp4ToWav($"playlists\\{playlistName}\\{songID}"); NAudioTools.Normalize($"playlists\\{playlistName}\\{songID}"); File.Delete($"{BotTools.BasePath}\\playlists\\{playlistName}\\{songID}.wav"); if (unloadPath != null) { File.Delete(unloadPath); unloadPath = null; } normalizingAudio = false; BotTools.LogLine($"Normalized {Music.DownloadedSong.Title}"); }
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); }
public static int GetCauliflowerCount(string region = "na") { var inventoryData = LoadInventoryData(); if (inventoryData.Count > 0) { int cf_total = 0; foreach (var characterName in inventoryData[region].Keys) { try { List <Dictionary <string, dynamic> > items = inventoryData[region][characterName]; int cf_count = 0; foreach (var item in items.Where(i => i != null && i.ContainsKey("id") && i["id"] == 12532)) { cf_count += item["count"]; } if (cf_count > 0) { cf_total += cf_count; } } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException) { JArray items = inventoryData[region][characterName]; int cf_count = 0; foreach (var item in items.ToObject <List <Dictionary <string, dynamic> > >().Where(i => i != null && i.ContainsKey("id") && i["id"] == 12532)) { cf_count += item["count"]; } if (cf_count > 0) { cf_total += cf_count; BotTools.LogLine($"{characterName}: {cf_count}"); } } } return(cf_total); } else { return(-1); } }
private static async Task Client_OnReactionAdded(Cacheable <IUserMessage, ulong> cache, ISocketMessageChannel channel, SocketReaction reaction) { var message = await cache.GetOrDownloadAsync(); if (!reaction.User.Value.IsBot && RequestMap.ContainsKey(message.Id)) { SongData songData = RequestMap[message.Id]; if (reaction.Emote.Name == "👍") { BotTools.LogLine($"{songData.Requestor}'s request was approved by {reaction.User.Value.Username}"); await DJVettingChannelWebhook.SendMessageAsync($"*{songData.Requestor}'s request was approved by {reaction.User.Value.Username}*"); RequestMap.Remove(message.Id); try { Music.GetPlaylist("request").AddSong(songData); var placement = Music.GetPlaylist("request").Songs.Count; var placementWord = BotTools.GetPlacementWord(placement); TwitchBot.SendMessage($"@{songData.Requestor}, Your request is {placementWord} in the queue! razCool"); Music.QueuedSong = Music.DownloadedSong = null; Music.SavePlaylists(); await message.RemoveAllReactionsAsync(); } catch (ArgumentException) { BotTools.LogLine($"{songData.Requestor}'s request rejected: Already in queue"); TwitchBot.SendMessage($"Sorry @{songData.Requestor}, that request is already queued!"); } catch (FormatException) { BotTools.LogLine($"{songData.Requestor}'s request rejected: Bad url"); TwitchBot.SendMessage($"Sorry @{songData.Requestor}, I can't access any video with that url!"); } } else if (reaction.Emote.Name == "👎") { BotTools.LogLine($"{RequestMap[message.Id].Requestor}'s request was declined by {reaction.User.Value.Username}"); await DJVettingChannelWebhook.SendMessageAsync($"*{RequestMap[message.Id].Requestor}'s request was declined by {reaction.User.Value.Username}*"); TwitchBot.SendMessage($"@{songData.Requestor}, Your request was declined! razHands"); RequestMap.Remove(message.Id); await message.RemoveAllReactionsAsync(); } } }
private static async Task Client_OnMessageReceived(SocketMessage message) { var user = message.Author as SocketGuildUser; var requiredRole = (user as IGuildUser).Guild.Roles.FirstOrDefault(x => x.Name == "~Moderator~"); if (user.Roles.Contains(requiredRole)) { var messageSend = new TwitchMessage(message.Author.Username, message.Content); if (messageSend.BotResponse != null && messageSend.BotResponse.Length > 0) { if (!BotTools.Settings["debug_output"]) { await message.Channel.SendMessageAsync(String.Join("\n", messageSend.BotResponse)); } else { BotTools.LogLine("[D] RazBot: " + String.Join("\n", messageSend.BotResponse)); } } else if (messageSend.WitResponse != null && messageSend.WitResponse.Length > 0) { if (!BotTools.Settings["debug_output"]) { await message.Channel.SendMessageAsync(String.Join("\n", messageSend.WitResponse)); } else { BotTools.LogLine("[D] RazBot: " + String.Join("\n", messageSend.WitResponse)); } } } while (RequestPosting) { ; } if (RequestMap.ContainsKey(message.Id)) { foreach (var emoji in new[] { "👍", "👎" }) // "✅" "▶️" // "👍" "👎" // "⛔" "⏏️" { await message.AddReactionAsync(new Emoji(emoji)); } } }
public static void TrainUtterance(string utteranceIn, string intentIn) { string url = "https://api.wit.ai/utterances?v=20200730"; var dataList = new List <dynamic>() { new { text = utteranceIn, intent = intentIn, entities = new List <Dictionary <string, string> >(), traits = new List <string>() } }; var httpWebRequest = (HttpWebRequest)WebRequest.Create(url); httpWebRequest.ContentType = "application/json"; httpWebRequest.Method = "POST"; httpWebRequest.Headers.Add("Authorization", $"Bearer {appToken}"); using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { var json = Newtonsoft.Json.JsonConvert.SerializeObject(dataList); streamWriter.Write(json); } var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { var result = streamReader.ReadToEnd(); if (result.Contains("\"sent\":true")) { BotTools.LogLine($"Asked WitAi to train: \"{utteranceIn}\" -> {intentIn}"); } else { BotTools.LogLine("Failed to send training to WitAi"); } } }
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(); } }
public static void PostToPetsChannel(Dictionary <string, dynamic> post) { if (!BotTools.Settings["debug_output"]) { var builder = new EmbedBuilder { Title = "RAZ PETS!", Description = post["caption"], Color = Color.Purple, ImageUrl = post["media_url"], Url = post["permalink"] }; builder.AddField("Instagram", post["permalink"]); RazChannelWebhook.SendMessageAsync(text: "", embeds: new[] { builder.Build() }); } else { BotTools.LogLine($"[D] RazBot: NEW RAZ PETS! -> {post["permalink"]}"); } }
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..."); } } } }
private bool CooldownDone(string token, int cooldown = 1) { if (LastCall.ContainsKey(token)) { int cooldownTimeRemaining = cooldown - (int)(DateTime.Now - LastCall[token]).TotalSeconds; if (cooldownTimeRemaining <= 0) { LastCall[token] = DateTime.Now; return(true); } else { BotTools.LogLine($"Invocation of \"{token}\" was blocked: {cooldownTimeRemaining}s cooldown remaining"); return(false); } } else { LastCall[token] = DateTime.Now; return(true); } }
private static void Client_OnNewSubscriber(object sender, OnNewSubscriberArgs e) { if (e.Subscriber.SubscriptionPlan == SubscriptionPlan.Prime) { BotTools.LogLine($"{e.Subscriber.DisplayName} subscribed with Twitch Prime"); } else if (e.Subscriber.SubscriptionPlan == SubscriptionPlan.Tier1) { BotTools.LogLine($"{e.Subscriber.DisplayName} subscribed at Tier 1"); } else if (e.Subscriber.SubscriptionPlan == SubscriptionPlan.Tier2) { BotTools.LogLine($"{e.Subscriber.DisplayName} subscribed at Tier 2"); } else if (e.Subscriber.SubscriptionPlan == SubscriptionPlan.Tier3) { BotTools.LogLine($"{e.Subscriber.DisplayName} subscribed at Tier 3"); } else { BotTools.LogLine($"{e.Subscriber.DisplayName} subscribed"); } }
public static string GetTwitchEndpointResponse(string endpoint) { for (int i = 3; i > 0; i--) { string url = $"https://decapi.me/twitch/{endpoint}"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) using (Stream stream = response.GetResponseStream()) using (StreamReader reader = new StreamReader(stream)) { string result = reader.ReadToEnd(); if (!String.IsNullOrEmpty(result)) { return(result); } } BotTools.LogLine($"Failed to fetch data from \"{endpoint}\" endpoint. Retrying {i} more times..."); } BotTools.LogLine($"Failed to fetch data from \"{endpoint}\" endpoint."); return(null); }
private static void Client_OnLeftChannel(object sender, OnLeftChannelArgs e) { string onlineMessage = $"RazBot has disconnected from Twitch [{e.Channel}]"; BotTools.LogLine($"RazBot: {onlineMessage}"); }