Browse Source

Added webexception handling for modules that create a connection. Fixes #8

tags/3.0.4
Teknikode 4 years ago
parent
commit
0605e2bdeb
3 changed files with 204 additions and 129 deletions
  1. 34
    17
      Modules/Search/Search.cs
  2. 108
    74
      Modules/Weather Information/Weather_Information.cs
  3. 62
    38
      Modules/YouTube/YouTube.cs

+ 34
- 17
Modules/Search/Search.cs View File

@@ -35,31 +35,48 @@ namespace Combot.Modules.Plugins
Uri searchUrl = new Uri(string.Format(urlTemplate, command.Arguments["Query"]));
WebClient web = new WebClient();
web.Encoding = Encoding.UTF8;
string page = web.DownloadString(searchUrl);

JObject parsed = (JObject)JsonConvert.DeserializeObject(page);
int responseCode = parsed.Value<int>("responseStatus");
if (responseCode < 300 && responseCode >= 200)
try
{
if (parsed["responseData"]["results"].Any())
string page = web.DownloadString(searchUrl);

JObject parsed = (JObject) JsonConvert.DeserializeObject(page);
int responseCode = parsed.Value<int>("responseStatus");
if (responseCode < 300 && responseCode >= 200)
{
var result = parsed["responseData"]["results"][0];
string url = result.Value<string>("unescapedUrl");
string title = HttpUtility.HtmlDecode(HttpUtility.UrlDecode(StripTagsCharArray(result.Value<string>("titleNoFormatting"))));
string content = HttpUtility.HtmlDecode(HttpUtility.UrlDecode(StripTagsCharArray(result.Value<string>("content"))));
string resultMessage = string.Format("[{0}] \u0002{1}\u000F: {2}.", url, title, content);
SendResponse(command.MessageType, command.Location, command.Nick.Nickname, resultMessage);
if (parsed["responseData"]["results"].Any())
{
var result = parsed["responseData"]["results"][0];
string url = result.Value<string>("unescapedUrl");
string title = HttpUtility.HtmlDecode(HttpUtility.UrlDecode(StripTagsCharArray(result.Value<string>("titleNoFormatting"))));
string content = HttpUtility.HtmlDecode(HttpUtility.UrlDecode(StripTagsCharArray(result.Value<string>("content"))));
string resultMessage = string.Format("[{0}] \u0002{1}\u000F: {2}.", url, title, content);
SendResponse(command.MessageType, command.Location, command.Nick.Nickname, resultMessage);
}
else
{
string noResults = string.Format("No results found for \u0002{0}\u000F.", command.Arguments["Query"]);
SendResponse(command.MessageType, command.Location, command.Nick.Nickname, noResults);
}
}
else
{
string noResults = string.Format("No results found for \u0002{0}\u000F.", command.Arguments["Query"]);
SendResponse(command.MessageType, command.Location, command.Nick.Nickname, noResults);
string errorCode = string.Format("Unable to search for \u0002{0}\u000F. Google returned status code \u0002{1}\u000F.", command.Arguments["Query"], responseCode);
SendResponse(command.MessageType, command.Location, command.Nick.Nickname, errorCode);
}
}
else
catch (WebException ex)
{
string errorCode = string.Format("Unable to search for \u0002{0}\u000F. Google returned status code \u0002{1}\u000F.", command.Arguments["Query"], responseCode);
SendResponse(command.MessageType, command.Location, command.Nick.Nickname, errorCode);
if (ex.Response != null)
{
int code = (int)((HttpWebResponse)ex.Response).StatusCode;
string errorCode = string.Format("Unable to search for \u0002{0}\u000F. Google returned status code \u0002{1}\u000F.", command.Arguments["Query"], code);
SendResponse(command.MessageType, command.Location, command.Nick.Nickname, errorCode);
}
else
{
string errorCode = string.Format("Unable to search for \u0002{0}\u000F.", command.Arguments["Query"]);
SendResponse(command.MessageType, command.Location, command.Nick.Nickname, errorCode);
}
}
}


+ 108
- 74
Modules/Weather Information/Weather_Information.cs View File

@@ -1,4 +1,5 @@
using System;
using System.Net;
using System.Xml;

namespace Combot.Modules.Plugins
@@ -37,22 +38,29 @@ namespace Combot.Modules.Plugins
XmlDocument doc2 = new XmlDocument();

// Load data
doc2.Load("http://api.wunderground.com/auto/wui/geo/WXCurrentObXML/index.xml?query=" + command.Arguments["Location"]);

// Get forecast with XPath
XmlNodeList nodes2 = doc2.SelectNodes("/current_observation");
try
{
doc2.Load("http://api.wunderground.com/auto/wui/geo/WXCurrentObXML/index.xml?query=" + command.Arguments["Location"]);
}
catch { }

string location = "";
if (nodes2 != null && nodes2.Count > 0)
string location = string.Empty;
if (doc2.HasChildNodes)
{
foreach (XmlNode node2 in nodes2)
// Get forecast with XPath
XmlNodeList nodes2 = doc2.SelectNodes("/current_observation");

if (nodes2 != null && nodes2.Count > 0)
{
XmlNodeList sub_node2 = doc2.SelectNodes("/current_observation/display_location");
if (sub_node2 != null)
foreach (XmlNode node2 in nodes2)
{
foreach (XmlNode xn2 in sub_node2)
XmlNodeList sub_node2 = doc2.SelectNodes("/current_observation/display_location");
if (sub_node2 != null)
{
location = xn2["full"].InnerText;
foreach (XmlNode xn2 in sub_node2)
{
location = xn2["full"].InnerText;
}
}
}
}
@@ -60,56 +68,68 @@ namespace Combot.Modules.Plugins

XmlDocument doc = new XmlDocument();
// Load data
doc.Load("http://api.wunderground.com/auto/wui/geo/ForecastXML/index.xml?query=" + command.Arguments["Location"]);

// Get forecast with XPath
XmlNodeList nodes = doc.SelectNodes("/forecast/simpleforecast");
try
{
doc.Load("http://api.wunderground.com/auto/wui/geo/ForecastXML/index.xml?query=" + command.Arguments["Location"]);
}
catch { }

string weekday = string.Empty;
string highf = string.Empty;
string lowf = string.Empty;
string highc = string.Empty;
string lowc = string.Empty;
string conditions = string.Empty;
if (location != ", " && !String.IsNullOrEmpty(location))
if (doc.HasChildNodes)
{
if (nodes != null && nodes.Count > 0)
// Get forecast with XPath
XmlNodeList nodes = doc.SelectNodes("/forecast/simpleforecast");

string weekday = string.Empty;
string highf = string.Empty;
string lowf = string.Empty;
string highc = string.Empty;
string lowc = string.Empty;
string conditions = string.Empty;
if (location != ", " && !String.IsNullOrEmpty(location))
{
string startMsg = string.Format("{0} day forecast for {1}", days, command.Arguments["Location"]);
if (command.MessageType == MessageType.Channel || command.MessageType == MessageType.Notice)
if (nodes != null && nodes.Count > 0)
{
Bot.IRC.Command.SendNotice(command.Nick.Nickname, startMsg);
}
else
{
Bot.IRC.Command.SendPrivateMessage(command.Nick.Nickname, startMsg);
}
int index = 0;
foreach (XmlNode node in nodes)
{
foreach (XmlNode sub_node in node)
string startMsg = string.Format("{0} day forecast for {1}", days, command.Arguments["Location"]);
if (command.MessageType == MessageType.Channel || command.MessageType == MessageType.Notice)
{
if (index < days)
Bot.IRC.Command.SendNotice(command.Nick.Nickname, startMsg);
}
else
{
Bot.IRC.Command.SendPrivateMessage(command.Nick.Nickname, startMsg);
}
int index = 0;
foreach (XmlNode node in nodes)
{
foreach (XmlNode sub_node in node)
{
weekday = sub_node["date"].SelectSingleNode("weekday").InnerText;
highf = sub_node["high"].SelectSingleNode("fahrenheit").InnerText;
highc = sub_node["high"].SelectSingleNode("celsius").InnerText;
lowf = sub_node["low"].SelectSingleNode("fahrenheit").InnerText;
lowc = sub_node["low"].SelectSingleNode("celsius").InnerText;
conditions = sub_node["conditions"].InnerText;
string forecastMsg = string.Format("{0}: {1} with a high of {2} F ({3} C) and a low of {4} F ({5} C).", weekday, conditions, highf, highc, lowf, lowc);
if (command.MessageType == MessageType.Channel || command.MessageType == MessageType.Notice)
if (index < days)
{
Bot.IRC.Command.SendNotice(command.Nick.Nickname, forecastMsg);
}
else
{
Bot.IRC.Command.SendPrivateMessage(command.Nick.Nickname, forecastMsg);
weekday = sub_node["date"].SelectSingleNode("weekday").InnerText;
highf = sub_node["high"].SelectSingleNode("fahrenheit").InnerText;
highc = sub_node["high"].SelectSingleNode("celsius").InnerText;
lowf = sub_node["low"].SelectSingleNode("fahrenheit").InnerText;
lowc = sub_node["low"].SelectSingleNode("celsius").InnerText;
conditions = sub_node["conditions"].InnerText;
string forecastMsg = string.Format("{0}: {1} with a high of {2} F ({3} C) and a low of {4} F ({5} C).", weekday, conditions, highf, highc, lowf, lowc);
if (command.MessageType == MessageType.Channel || command.MessageType == MessageType.Notice)
{
Bot.IRC.Command.SendNotice(command.Nick.Nickname, forecastMsg);
}
else
{
Bot.IRC.Command.SendPrivateMessage(command.Nick.Nickname, forecastMsg);
}
}
index++;
}
index++;
}
}
else
{
string noWeather = string.Format("No weather information available for \u0002{0}\u000F", command.Arguments["Location"]);
SendResponse(command.MessageType, command.Location, command.Nick.Nickname, noWeather);
}
}
else
{
@@ -127,37 +147,51 @@ namespace Combot.Modules.Plugins
private void getWeather(CommandMessage command)
{
XmlDocument doc = new XmlDocument();
string weatherMsg = string.Empty;

// Load data
doc.Load("http://api.wunderground.com/auto/wui/geo/WXCurrentObXML/index.xml?query=" + command.Arguments["Location"]);
try
{
doc.Load("http://api.wunderground.com/auto/wui/geo/WXCurrentObXML/index.xml?query=" + command.Arguments["Location"]);
}
catch (WebException ex)
{
}

// Get forecast with XPath
XmlNodeList nodes = doc.SelectNodes("/current_observation");
string weatherMsg = string.Empty;
string location = string.Empty;
string temp = string.Empty;
string weather = string.Empty;
string humidity = string.Empty;
string wind_dir = string.Empty;
string wind_mph = string.Empty;
if (nodes != null && nodes.Count > 0)
if (doc.HasChildNodes)
{
foreach (XmlNode node in nodes)
// Get forecast with XPath
XmlNodeList nodes = doc.SelectNodes("/current_observation");
string location = string.Empty;
string temp = string.Empty;
string weather = string.Empty;
string humidity = string.Empty;
string wind_dir = string.Empty;
string wind_mph = string.Empty;
if (nodes != null && nodes.Count > 0)
{
XmlNodeList sub_node = doc.SelectNodes("/current_observation/display_location");
foreach (XmlNode xn in sub_node)
foreach (XmlNode node in nodes)
{
location = xn["full"].InnerText;
XmlNodeList sub_node = doc.SelectNodes("/current_observation/display_location");
foreach (XmlNode xn in sub_node)
{
location = xn["full"].InnerText;
}
temp = node["temperature_string"].InnerText;
weather = node["weather"].InnerText;
humidity = node["relative_humidity"].InnerText;
wind_dir = node["wind_dir"].InnerText;
wind_mph = node["wind_mph"].InnerText;
}
if (location != ", ")
{
weatherMsg = string.Format("{0} is currently {1} with a temperature of {2}. The humidity is {3} with winds blowing {4} at {5} mph", location, weather, temp, humidity, wind_dir, wind_mph);
}
else
{
weatherMsg = string.Format("No weather information available for \u0002{0}\u000F", command.Arguments["Location"]);
}
temp = node["temperature_string"].InnerText;
weather = node["weather"].InnerText;
humidity = node["relative_humidity"].InnerText;
wind_dir = node["wind_dir"].InnerText;
wind_mph = node["wind_mph"].InnerText;
}
if (location != ", ")
{
weatherMsg = string.Format("{0} is currently {1} with a temperature of {2}. The humidity is {3} with winds blowing {4} at {5} mph", location, weather, temp, humidity, wind_dir, wind_mph);
}
else
{

+ 62
- 38
Modules/YouTube/YouTube.cs View File

@@ -54,20 +54,37 @@ namespace Combot.Modules.Plugins
Uri searchUrl = new Uri(string.Format(urlTemplate, command.Arguments["Query"]));
WebClient web = new WebClient();
web.Encoding = Encoding.UTF8;
string page = web.DownloadString(searchUrl);

JObject parsed = (JObject)JsonConvert.DeserializeObject(page);
if (parsed["data"]["totalItems"].Value<int>() > 0)
try
{
string videoID = parsed["data"]["items"].First().Value<string>("id");
string vidDescription = GetYoutubeDescription(videoID);
string youtubeMessage = string.Format("{0} - {1}", vidDescription, string.Format("http://youtu.be/{0}", videoID));
SendResponse(command.MessageType, command.Location, command.Nick.Nickname, youtubeMessage);
string page = web.DownloadString(searchUrl);

JObject parsed = (JObject) JsonConvert.DeserializeObject(page);
if (parsed["data"]["totalItems"].Value<int>() > 0)
{
string videoID = parsed["data"]["items"].First().Value<string>("id");
string vidDescription = GetYoutubeDescription(videoID);
string youtubeMessage = string.Format("{0} - {1}", vidDescription, string.Format("http://youtu.be/{0}", videoID));
SendResponse(command.MessageType, command.Location, command.Nick.Nickname, youtubeMessage);
}
else
{
string noResults = string.Format("No results found for \u0002{0}\u000F.", command.Arguments["Query"]);
SendResponse(command.MessageType, command.Location, command.Nick.Nickname, noResults);
}
}
else
catch (WebException ex)
{
string noResults = string.Format("No results found for \u0002{0}\u000F.", command.Arguments["Query"]);
SendResponse(command.MessageType, command.Location, command.Nick.Nickname, noResults);
if (ex.Response != null)
{
int code = (int)((HttpWebResponse)ex.Response).StatusCode;
string errorCode = string.Format("Unable to search for \u0002{0}\u000F. Youtube returned status code \u0002{1}\u000F.", command.Arguments["Query"], code);
SendResponse(command.MessageType, command.Location, command.Nick.Nickname, errorCode);
}
else
{
string errorCode = string.Format("Unable to search for \u0002{0}\u000F.", command.Arguments["Query"]);
SendResponse(command.MessageType, command.Location, command.Nick.Nickname, errorCode);
}
}
}

@@ -79,43 +96,50 @@ namespace Combot.Modules.Plugins
Uri searchUrl = new Uri(string.Format(urlTemplate, ID));
WebClient web = new WebClient();
web.Encoding = Encoding.UTF8;
string page = web.DownloadString(searchUrl);
try
{
string page = web.DownloadString(searchUrl);

JObject parsed = (JObject)JsonConvert.DeserializeObject(page);
var data = parsed["data"];
JObject parsed = (JObject) JsonConvert.DeserializeObject(page);
var data = parsed["data"];

description = string.Format("\u0002{0}\u000F", data["title"]);
description = string.Format("\u0002{0}\u000F", data["title"]);

if (data["duration"] == null)
{
return description;
}
if (data["duration"] == null)
{
return description;
}

TimeSpan duration = TimeSpan.FromSeconds(data["duration"].Value<double>());
description += string.Format(" | Length: \u0002{0}\u000F", duration.ToString("g"));
TimeSpan duration = TimeSpan.FromSeconds(data["duration"].Value<double>());
description += string.Format(" | Length: \u0002{0}\u000F", duration.ToString("g"));

if (data["ratingCount"] != null)
{
int likes = data["likeCount"].Value<int>();
string pluralLikes = (likes > 1) ? "s" : string.Empty;
int dislikes = data["ratingCount"].Value<int>() - likes;
string pluralDislikes = (dislikes > 1) ? "s" : string.Empty;
double percent = 100.0 * ((double)likes / data["ratingCount"].Value<int>());
description += string.Format(" | Rating: {0} Like{1}, {2} Dislike{3} (\u0002{4}\u000F%)", likes, pluralLikes, dislikes, pluralDislikes, Math.Round(percent, 1));
}
if (data["ratingCount"] != null)
{
int likes = data["likeCount"].Value<int>();
string pluralLikes = (likes > 1) ? "s" : string.Empty;
int dislikes = data["ratingCount"].Value<int>() - likes;
string pluralDislikes = (dislikes > 1) ? "s" : string.Empty;
double percent = 100.0*((double) likes/data["ratingCount"].Value<int>());
description += string.Format(" | Rating: {0} Like{1}, {2} Dislike{3} (\u0002{4}\u000F%)", likes, pluralLikes, dislikes, pluralDislikes, Math.Round(percent, 1));
}

if (data["viewCount"] != null)
{
description += string.Format(" | Views: \u0002{0}\u000F", data["viewCount"].Value<int>());
}
if (data["viewCount"] != null)
{
description += string.Format(" | Views: \u0002{0}\u000F", data["viewCount"].Value<int>());
}

DateTime uploadDate = Convert.ToDateTime(data["uploaded"].Value<string>());
DateTime uploadDate = Convert.ToDateTime(data["uploaded"].Value<string>());

description += string.Format(" | Uploaded By: \u0002{0}\u000F on \u0002{1}\u000F", data["uploader"].Value<string>(), uploadDate.ToString("R"));
description += string.Format(" | Uploaded By: \u0002{0}\u000F on \u0002{1}\u000F", data["uploader"].Value<string>(), uploadDate.ToString("R"));

if (data["contentRating"] != null)
if (data["contentRating"] != null)
{
description += " | \u0002NSFW\u000F";
}
}
catch (WebException ex)
{
description += " | \u0002NSFW\u000F";
description = string.Empty;
}

return description;

Loading…
Cancel
Save