Skip to content

Instantly share code, notes, and snippets.

@ryanvalentin
Last active January 2, 2016 21:09
Show Gist options
  • Select an option

  • Save ryanvalentin/8361277 to your computer and use it in GitHub Desktop.

Select an option

Save ryanvalentin/8361277 to your computer and use it in GitHub Desktop.
How to make a Disqus API call to threads/set to get an unsorted array of threads you specified
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()
{
string[] threadIdentifiers = { "ident:YOUR_IDENTIFIER_1", "ident:YOUR_IDENTIFIER_2", "ident:YOUR_IDENTIFIER_3" };
DisqusApi dsqApi = new DisqusApi();
try
{
var response = await dsqApi.GetDisqusThreadArrayAsync(_disqusShortname, new List<string>(threadIdentifiers));
foreach (var thread in response.DisqusThreadSet)
{
int commentCount = thread.Posts;
//
// Do something with comment counts here
}
//
// Log if nothing was found
if (response.DisqusThreadSet.Count == 0)
{
System.Diagnostics.Debug.WriteLine("No threads found for threads: " + threadIdentifiers);
}
}
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<DisqusThreadSetResponse> GetDisqusThreadArrayAsync(string shortname, List<string> threads)
{
//
// The Disqus threads endpoint documented here: http://disqus.com/api/docs/threads/set/
string endpoint = "https://disqus.com/api/3.0/threads/set.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}", _disqusSecretKey, shortname);
//
// TODO: Un-comment to use your public key if this is running client-side
//string arguments = String.Format("?api_key={0}&forum={1}", _disqusPublicKey, shortname);
//
// Build the rest of the arguments using the threads in the list
// NOTE: If you're looking up by identifier, the string must look like "ident:YOUR_DISQUS_IDENTIFIER", and if by URL "link:http://yoursite.com/path-to-article/"
foreach (string t in threads)
{
arguments += "&thread=" + t;
}
// 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<DisqusThreadSetResponse>(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 approved comments in the thread
/// </summary>
[JsonProperty(PropertyName = "posts")]
public int Posts { 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 DisqusThreadSetResponse
{
[JsonProperty(PropertyName = "code")]
public int Code { get; set; }
[JsonProperty(PropertyName = "response")]
public List<DisqusThread> DisqusThreadSet { 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