Last active
January 4, 2016 06:59
-
-
Save ryanvalentin/8585404 to your computer and use it in GitHub Desktop.
Get Disqus popular threads using C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Newtonsoft.Json; | |
using Newtonsoft.Json.Linq; | |
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.Net; | |
using System.Net.Http; | |
using System.Threading.Tasks; | |
namespace Example | |
{ | |
public class ExampleClass | |
{ | |
// | |
// TODO enter the Disqus shortname that the threads belong to | |
private const string _disqusShortname = "YOUR_DISQUS_SHORTNAME"; | |
public async Task YourFunctionAsync() | |
{ | |
// | |
// Variables to pass into API call | |
string interval = "7d"; // Options are 1h, 6h, 12h, 1d, 3d, 7d, 30d, 90d | |
int limit = 10; // Maximum number of threads in response | |
DisqusApi dsqApi = new DisqusApi(); | |
try | |
{ | |
var response = await dsqApi.GetDisqusThreadArrayAsync(_disqusShortname, interval, limit); | |
foreach (var thread in response.DisqusPopularThreads) | |
{ | |
// | |
// Do something with the thread object here | |
} | |
// | |
// Log if nothing was found. This would happen if there were no comments on your site within a given interval | |
if (response.DisqusPopularThreads.Count == 0) | |
{ | |
System.Diagnostics.Debug.WriteLine(String.Format("No comments on any threads within the {0} interval on the shortname {1}.", interval, _disqusShortname)); | |
} | |
} | |
catch (DsqApiException e) | |
{ | |
// | |
// Handle error | |
} | |
} | |
} | |
public class DisqusApi | |
{ | |
private const string _disqusSecretKey = "YOUR_SECRET_KEY"; | |
private const string _disqusPublicKey = "YOUR_PUBLIC_KEY"; | |
public async Task<DisqusPopularThreadsResponse> GetDisqusThreadArrayAsync(string shortname, string interval, int limit) | |
{ | |
// | |
// The Disqus threads endpoint documented here: http://disqus.com/api/docs/threads/listPopular/ | |
string endpoint = "https://disqus.com/api/3.0/threads/listPopular.json"; | |
// | |
// TODO: Comment out this line to hide your secret key if this is running client-side | |
string arguments = String.Format("?api_secret={0}&forum={1}&interval={2}&limit={3}", _disqusSecretKey, shortname, interval, limit.ToString()); | |
// | |
// TODO: Un-comment to use your public key if this is running client-side | |
//string arguments = String.Format("?api_key={0}&forum={1}&interval={2}&limit={3}", _disqusPublicKey, shortname, interval, limit.ToString()); | |
// The Disqus API supports gzip requests | |
HttpClientHandler gzipHandler = new HttpClientHandler(); | |
if (gzipHandler.SupportsAutomaticDecompression) | |
gzipHandler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; | |
HttpClient httpClient = new HttpClient(gzipHandler); | |
// | |
// TODO: Enter your website information in the headers | |
httpClient.DefaultRequestHeaders.Referrer = new Uri("http://yourdomain.com/", UriKind.Absolute); // Only required when using public key. Must match one of the domains in your application's domain list. | |
httpClient.DefaultRequestHeaders.Host = "yourdomain.com"; // Only required when using public key. Must match one of the domains in your application's domain list. | |
httpClient.DefaultRequestHeaders.Add("User-Agent", "Disqus SDK for .NET"); // Only required when using public key | |
httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); | |
// | |
// Make the request | |
var response = await httpClient.GetAsync(endpoint + arguments); | |
httpClient.Dispose(); | |
if (response.IsSuccessStatusCode) | |
{ | |
using (StreamReader sr = new StreamReader(await response.Content.ReadAsStreamAsync())) | |
{ | |
// | |
// Deserialize and return | |
using (JsonReader reader = new JsonTextReader(sr)) | |
{ | |
JsonSerializer serializer = new JsonSerializer(); | |
// | |
// Return serialized JSON | |
return serializer.Deserialize<DisqusPopularThreadsResponse>(reader); | |
} | |
} | |
} | |
else | |
{ | |
string rawResponse = await response.Content.ReadAsStringAsync(); | |
try | |
{ | |
JObject json = JObject.Parse(rawResponse); | |
throw new DsqApiException((string)json["response"], (int)json["code"]); | |
} | |
catch (Exception ex) | |
{ | |
throw new DsqApiException("There was an error making this request: " + ex.Message + "; " + response.Content.ReadAsStringAsync(), 99); | |
} | |
} | |
} | |
} | |
public class DisqusThread | |
{ | |
/// <summary> | |
/// RSS feed URL of the latest comments | |
/// </summary> | |
[JsonProperty(PropertyName = "feed")] | |
public string Feed { get; set; } | |
/// <summary> | |
/// Category ID number | |
/// </summary> | |
[JsonProperty(PropertyName = "category")] | |
public string Category { get; set; } | |
/// <summary> | |
/// Author ID number | |
/// </summary> | |
[JsonProperty(PropertyName = "author")] | |
public string Author { get; set; } | |
/// <summary> | |
/// Disqus shortname the thread belongs to | |
/// </summary> | |
[JsonProperty(PropertyName = "forum")] | |
public string Forum { get; set; } | |
/// <summary> | |
/// Saved title of the thread | |
/// </summary> | |
[JsonProperty(PropertyName = "title")] | |
public string Title { get; set; } | |
/// <summary> | |
/// The score the authenticated user gave to the thread. This is where "starring" is stored | |
/// </summary> | |
[JsonProperty(PropertyName = "userScore")] | |
public int UserScore { get; set; } | |
/// <summary> | |
/// The custom identifiers stored with this thread. Corresponds with 'var disqus_identifier' | |
/// </summary> | |
[JsonProperty(PropertyName = "identifiers")] | |
public List<string> Identifiers { get; set; } | |
/// <summary> | |
/// The number of dislikes the thread has received. Not currently used. | |
/// </summary> | |
[JsonProperty(PropertyName = "dislikes")] | |
public int Dislikes { get; set; } | |
/// <summary> | |
/// When the thread was created in Disqus | |
/// </summary> | |
[JsonProperty(PropertyName = "createdAt")] | |
public string CreatedAt { get; set; } | |
/// <summary> | |
/// The unique slug given to the thread | |
/// </summary> | |
[JsonProperty(PropertyName = "slug")] | |
public string Slug { get; set; } | |
/// <summary> | |
/// Whether the thread is closed to new comments | |
/// </summary> | |
[JsonProperty(PropertyName = "isClosed")] | |
public bool IsClosed { get; set; } | |
/// <summary> | |
/// Number of total approved comments in the thread | |
/// </summary> | |
[JsonProperty(PropertyName = "posts")] | |
public int Posts { get; set; } | |
/// <summary> | |
/// Number of comments within the interval you passed | |
/// </summary> | |
[JsonProperty(PropertyName = "postsInInterval")] | |
public int PostsInInterval { get; set; } | |
/// <summary> | |
/// Whether the authenticated user is subscribed to email notifications | |
/// </summary> | |
[JsonProperty(PropertyName = "userSubscription")] | |
public bool UserSubscription { get; set; } | |
/// <summary> | |
/// The URL stored with the thread. Corresponds to 'var disqus_url' | |
/// </summary> | |
[JsonProperty(PropertyName = "link")] | |
public string Link { get; set; } | |
/// <summary> | |
/// Number of likes (stars) received by the thread | |
/// </summary> | |
[JsonProperty(PropertyName = "likes")] | |
public int Likes { get; set; } | |
/// <summary> | |
/// The content body of the thread. Not populated by default | |
/// </summary> | |
[JsonProperty(PropertyName = "message")] | |
public string Message { get; set; } | |
/// <summary> | |
/// Unique Disqus ID of this thread | |
/// </summary> | |
[JsonProperty(PropertyName = "id")] | |
public string Id { get; set; } | |
/// <summary> | |
/// Whether the thread has been deleted | |
/// </summary> | |
[JsonProperty(PropertyName = "isDeleted")] | |
public bool IsDeleted { get; set; } | |
} | |
public class DisqusPopularThreadsResponse | |
{ | |
[JsonProperty(PropertyName = "code")] | |
public int Code { get; set; } | |
[JsonProperty(PropertyName = "response")] | |
public List<DisqusThread> DisqusPopularThreads { get; set; } | |
} | |
public class DsqApiException : Exception | |
{ | |
public DsqApiException(string message, int code) : base(message) | |
{ | |
this.Code = code; | |
} | |
public int Code { get; set; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment