Added to Inbox, allows sending messages

This commit is contained in:
2010-03-18 14:20:07 +00:00
parent 3f2c4445a7
commit 2005131a4e

View File

@@ -3,6 +3,9 @@ import urllib2
import urllib import urllib
from datetime import datetime from datetime import datetime
class NotLoggedIn(Exception):
pass
class Message(dict): class Message(dict):
""" Reddit Message """ """ Reddit Message """
@@ -26,23 +29,32 @@ class Inbox():
REDDIT = "http://www.reddit.com" REDDIT = "http://www.reddit.com"
REDDIT_API_LOGIN = "%s/api/login" % REDDIT REDDIT_API_LOGIN = "%s/api/login" % REDDIT
REDDIT_API_INBOX = "%s/message/inbox/.json?mark=false" % REDDIT REDDIT_API_INBOX = "%s/message/inbox/.json?mark=false" % REDDIT
REDDIT_API_COMPOSE = "%s/api/compose/" % REDDIT
def __init__(self, username, password): def __init__(self, username=None, password=None):
self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
urllib2.install_opener(self.opener) urllib2.install_opener(self.opener)
if username and password:
self.login(username, password)
def login(self, username, password):
data = { 'user': username, data = { 'user': username,
'passwd': password, 'passwd': password,
'api_type': 'json' } 'api_type': 'json' }
url = "%s/%s" % (self.REDDIT_API_LOGIN, username) url = "%s/%s" % (self.REDDIT_API_LOGIN, username)
req = urllib2.Request( url, urllib.urlencode(data)) req = urllib2.Request( url, urllib.urlencode(data))
jsondoc = json.load(self.opener.open(req)) jsondoc = json.load(self.opener.open(req))
self.login_cookie = jsondoc['json']['data']['cookie'] self.login_cookie = jsondoc['json']['data']['cookie']
self.modhash = jsondoc['json']['data']['modhash']
if self.login_cookie:
return True
return False
@property @property
def _inbox_data(self): def _inbox_data(self):
@@ -56,6 +68,10 @@ class Inbox():
return self.__inbox_cache return self.__inbox_cache
def _url_request(self, url, data):
req = urllib2.Request( url, urllib.urlencode(data))
return self.opener.open(req)
def __len__(self): def __len__(self):
return len(self._inbox_data) return len(self._inbox_data)
@@ -65,3 +81,18 @@ class Inbox():
def __iter__(self): def __iter__(self):
return self._inbox_data.__iter__() return self._inbox_data.__iter__()
def send(self, to, subject, text):
if not self.login_cookie:
raise NotLoggedIn
print self.login_cookie
data = { 'to': to,
'subject': subject,
'text': 'text',
'uh': self.modhash,
'thing_id': '' }
url = "%s" % (self.REDDIT_API_COMPOSE)
jsondoc = json.load(self._url_request(url, data))
print jsondoc