The easy to use and full featured Irc Bot everyone is talking about!
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

YouTube.cs 6.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. using System;
  2. using System.Linq;
  3. using System.Net;
  4. using System.Text;
  5. using System.Text.RegularExpressions;
  6. using Combot.IRCServices.Messaging;
  7. using Newtonsoft.Json;
  8. using Newtonsoft.Json.Linq;
  9. namespace Combot.Modules.Plugins
  10. {
  11. public class YouTube : Module
  12. {
  13. public override void Initialize()
  14. {
  15. Bot.CommandReceivedEvent += HandleCommandEvent;
  16. }
  17. public override void ParseCommand(CommandMessage command)
  18. {
  19. Command foundCommand = Commands.Find(c => c.Triggers.Contains(command.Command));
  20. switch (foundCommand.Name)
  21. {
  22. case "YouTube Search":
  23. YoutubeSearch(command);
  24. break;
  25. }
  26. }
  27. private void YoutubeSearch(CommandMessage command)
  28. {
  29. string urlTemplate = "https://www.googleapis.com/youtube/v3/search?part=snippet&q={0}&key={1}";
  30. Uri searchUrl = new Uri(string.Format(urlTemplate, command.Arguments["Query"], GetOptionValue("API Key")));
  31. WebClient web = new WebClient();
  32. web.Encoding = Encoding.UTF8;
  33. try
  34. {
  35. string page = web.DownloadString(searchUrl);
  36. JObject parsed = (JObject) JsonConvert.DeserializeObject(page);
  37. if (parsed["items"].Any())
  38. {
  39. string videoID = parsed["items"].First()["id"].Value<string>("videoId");
  40. string vidDescription = GetYoutubeDescription(videoID);
  41. string youtubeMessage = string.Format("{0} - {1}", vidDescription, string.Format("http://youtu.be/{0}", videoID));
  42. SendResponse(command.MessageType, command.Location, command.Nick.Nickname, youtubeMessage);
  43. }
  44. else
  45. {
  46. string noResults = string.Format("No results found for \u0002{0}\u000F.", command.Arguments["Query"]);
  47. SendResponse(command.MessageType, command.Location, command.Nick.Nickname, noResults);
  48. }
  49. }
  50. catch (WebException ex)
  51. {
  52. if (ex.Response != null)
  53. {
  54. int code = (int)((HttpWebResponse)ex.Response).StatusCode;
  55. string errorCode = string.Format("Unable to search for \u0002{0}\u000F. Youtube returned status code \u0002{1}\u000F.", command.Arguments["Query"], code);
  56. SendResponse(command.MessageType, command.Location, command.Nick.Nickname, errorCode);
  57. }
  58. else
  59. {
  60. string errorCode = string.Format("Unable to search for \u0002{0}\u000F.", command.Arguments["Query"]);
  61. SendResponse(command.MessageType, command.Location, command.Nick.Nickname, errorCode);
  62. }
  63. }
  64. }
  65. private string GetYoutubeDescription(string ID)
  66. {
  67. string description = string.Empty;
  68. string urlTemplate = "https://www.googleapis.com/youtube/v3/videos?part=snippet,statistics,contentDetails&id={0}&key={1}";
  69. Uri searchUrl = new Uri(string.Format(urlTemplate, ID, GetOptionValue("API Key")));
  70. WebClient web = new WebClient();
  71. web.Encoding = Encoding.UTF8;
  72. try
  73. {
  74. string page = web.DownloadString(searchUrl);
  75. JObject parsed = (JObject)JsonConvert.DeserializeObject(page);
  76. var data = parsed["items"].First();
  77. description = string.Format("\u0002{0}\u000F", data["snippet"]["title"]);
  78. if (data["contentDetails"]["duration"] == null)
  79. {
  80. return description;
  81. }
  82. string length = data["contentDetails"]["duration"].Value<string>();
  83. Regex lengthRegex = new Regex(@"PT((?<Days>[0-9]+)D)?((?<Hours>[0-9]+)H)?((?<Minutes>[0-9]+)M)?((?<Seconds>[0-9]+)S)?");
  84. Match lengthMatch = lengthRegex.Match(length);
  85. double totalTime = 0;
  86. if (lengthMatch.Groups["Days"].Success)
  87. totalTime += 86400.0 * Convert.ToDouble(lengthMatch.Groups["Days"].Value);
  88. if (lengthMatch.Groups["Hours"].Success)
  89. totalTime += 3600.0 * Convert.ToDouble(lengthMatch.Groups["Hours"].Value);
  90. if (lengthMatch.Groups["Minutes"].Success)
  91. totalTime += 60.0 * Convert.ToDouble(lengthMatch.Groups["Minutes"].Value);
  92. if (lengthMatch.Groups["Seconds"].Success)
  93. totalTime += Convert.ToDouble(lengthMatch.Groups["Seconds"].Value);
  94. TimeSpan duration = TimeSpan.FromSeconds(totalTime);
  95. description += string.Format(" | Length: \u0002{0}\u000F", duration.ToString("g"));
  96. if (data["statistics"] != null)
  97. {
  98. JToken stats = data["statistics"];
  99. int likes = (stats["likeCount"] != null) ? stats["likeCount"].Value<int>() : 0;
  100. string pluralLikes = (likes > 1) ? "s" : string.Empty;
  101. int dislikes = (stats["dislikeCount"] != null) ? stats["dislikeCount"].Value<int>() : 0;
  102. string pluralDislikes = (dislikes > 1) ? "s" : string.Empty;
  103. double percent = 100.0 * ((double)likes / (likes + dislikes));
  104. description += string.Format(" | Rating: {0} Like{1}, {2} Dislike{3} (\u0002{4}\u000F%)", likes, pluralLikes, dislikes, pluralDislikes, Math.Round(percent, 1));
  105. description += string.Format(" | Views: \u0002{0}\u000F", data["statistics"]["viewCount"].Value<int>());
  106. }
  107. DateTime uploadDate = Convert.ToDateTime(data["snippet"]["publishedAt"].Value<string>());
  108. description += string.Format(" | Uploaded By: \u0002{0}\u000F on \u0002{1}\u000F", data["snippet"]["channelTitle"].Value<string>(), uploadDate.ToString("R"));
  109. if (data["contentDetails"]["contentRating"] != null)
  110. {
  111. description += " | \u0002NSFW\u000F";
  112. }
  113. }
  114. catch (WebException ex)
  115. {
  116. description = string.Empty;
  117. }
  118. return description;
  119. }
  120. }
  121. }