Here is a simple and easy to use C# wrapper for the Reddit API.
If implements all of the major functionality of the API in C#.
Documentation
To get started you’d, as one would expect, simply drop Reddit.cs into your project and setup a RedditAPI object with your username and password.
RedditAPI reddit = new RedditAPI(“username”,”password”);
There needs to be a file to store the Reddit login cookie in, as the API doesn’t like you logging in too often, it’ll just give you an error. As such we need to store the cookie. By default it uses the file “cookie” so make sure you create an empty file in your exe’s directory. Alternatively you can use a different file by constructing like so:
RedditAPI reddit = new RedditAPI(“username”,”password”,”different/file/name”);
Then it’s a simple task to post links, comments, self-posts, upvote, downvote, rescind your vote and check if you have mail.
reddit.HasMail();
To post a comment you just call PostComment with the “thing” ID of the thing you want to comment on and the comment content. Regarding the “thing” IDs, see the glossary here.
reddit.PostComment(“t1_c263usp”, “The narwhal bacons at midnight, ha!”);
To post a link is simple, too. Just call PostLink with the URL, title and subreddit:
reddit.PostLink(“http://z3rb.net”,”AWEZOME WEBSITE BROS [NSFW]“, “SPACEDICKS”);
Self posts are pretty much the same, but replace the URL with the text of the post:
reddit.PostSelf(“It went \*okay\*”,”I can hear my roommate…”,”AskReddit”);
Voting is simple too, just pop the “thing” ID into the various methods:
reddit.Upvote(“t1_c263usp”);
reddit.Downvote(“t1_c263usp”);
reddit.UnVote(“t1_c263usp”);
That’s the main methods of the class. There’s another, though, called GetMeCache(). It returns the contents of me.json as a Hashtable, so it’s easy enough to get any of the data from there like so:
Hashtable me = GetMeCache();
double mykarma = (double)me["link_karma"];
I will soon create LinkKarma(), CommentKarma() and HasModMail() methods. As for now you can use the above way of getting this data.
Also, the class will soon be available as a DLL if there’s any demand for it.
TODO
- Proper error handling for every method
- Methods for handling info.json
- Methods for handling mine.json
- Decent way of handling me.json information
- Impliment save/unsave and hide/unhide methods
- Build as a DLL
- Implement LinkKarma(), CommentKarma() and HasModMail() methods.
Download
You can get the Reddit.cs file here or as a zip file here.
Licence
I’m giving it away under the zlib licence.
Copyright (c) 2011 Ruairidh Barnes This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution.
So you can use it freely and without restriction, but a credit would be nice.
The code includes a JSON parser which is available freely here.
Pingback: Reddit C# API wrapper | z3rb.net
Hello,
thank you so much for implementing this. I just have a problem (stack trace attached below).
I used your .cs file and created new RedditAPI instance with my credentials. During the runtime the following exception is raised:
System.Runtime.Serialization.SerializationException was unhandled
Message=Attempting to deserialize an empty stream.
Source=mscorlib
StackTrace:
at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream, HeaderHandler handler, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream)
at AutomaticSubmitter.RedditAPI.Loadcookie(String filename) in D:\My projects\AutomaticSubmitter\AutomaticSubmitter\Reddit.cs:line 318
at AutomaticSubmitter.RedditAPI..ctor(String user, String pswd, String cookiefilename) in D:\My projects\AutomaticSubmitter\AutomaticSubmitter\Reddit.cs:line 72
at AutomaticSubmitter.Program.TestRedditApi() in D:\My projects\AutomaticSubmitter\AutomaticSubmitter\Program.cs:line 26
at AutomaticSubmitter.Program.Main(String[] args) in D:\My projects\AutomaticSubmitter\AutomaticSubmitter\Program.cs:line 17
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
Any idea what might help?
Thank you in advance!
I recently started playing around with this code, and I might be able to help. However, I would need to see your specific use of the code to be of any use. Ruairidh might be able to diagnose your problem without the need to review your code, in which case you might want to wait for his reply. If you do want me to take a look, upload the project file somewhere and reply with the link.
In adding this API to one of my projects I encountered a couple of problems. The first was an error occurring in the RedditAPI constructor. Your code tries to call Loadcookie() before Savecookie() was ever called, resulting in an error as a result of Loadcookie() not being able to load the file. My simple fix was to call Savecookie() right before the code:
redditCookie = Loadcookie(cookiefilename);
Of course, that’s only necessary on the first run, as after that the cookie file has already been created.
The second problem, and thus far the only other one, took place in the HasMail() function. In the if statement your code reads:
if ((string)me["has_mail"] == "true")
However, at least in .NET 4.0.30319, this results in the error “Cannot cast ‘me["has_mail"]‘ (which has an actual type of ‘bool’) to ‘string’ “. I changed the if statement to read:
if (Convert.ToString(me["has_mail"]) == "true")
That did the trick for my version of .NET.
Despite my two minor complaints (which would be even less minor for someone that wasn’t a C# novice), this API wrapper is fantastic. I actually plan on writing my own in the next week or so, just as practice. I will likely fall back on yours though, as your code is much better than mine. Anyway, I’d be interested to know if the problems I encountered aren’t applicable for you, for whatever reason.
I apologize for apparently not reading your original post. I see that you addressed my first issue, though if you don’t want to have to leave Visual Studio, or whatever IDE you’re using, my solution still works. Unless of course there is a valid reason not to, which is likely the case.
Creating the empty file beforehand didn’t seem to correct the first issue for me at all, I simply got a SerializationException; however, your suggestion worked.
Any idea why? I’m assuming it is because running the SaveCookie method first saves the serialized CookieContainer object that has been initialized to redditCookie into the file before LoadCookie attempts to read data out of it. Simply creating an empty file and not calling SaveCookie first means that LoadCookie has nothing to read.
Is there a way to get an rss feed from the articles I’ve liked? I’d like to have that feed… feed my twitter account so when I LIKE something, it’s automatically tweeted for me.
ah… found it… https://ssl.reddit.com/prefs/feeds/
now onto the code… thanks anyways.