#!/usr/bin/env python

import sys,requests,json

REDDIT=sys.argv[1]
CHANNEL=sys.argv[2]
FEED=sys.argv[3]
# Test mode:
if len(sys.argv) == 5:
  print "running in test mode"
  data = json.loads(open(sys.argv[4]).read())
  writer=sys.stdout
else:
  req = requests.get("http://www.reddit.com/r/%s/%s.json" %(REDDIT,FEED), headers={'User-agent': 'iibot/irc-reddit'})
  if req.status_code != 200:
    print "Kabloom!"
    print req.text
    sys.exit(1)
  data = req.json()
  writer=open("/home/ircbot/irc/irc.mozilla.org/%s/in"%CHANNEL, "a")

STATEFILE="/home/ircbot/state/reddit-%s-%s-storyids"%(CHANNEL,REDDIT)
sf = open(STATEFILE)
seen = set(sf.read().split("\n"))
sf.close()
print "Previously seen %d posts"%len(seen)

new=[]
for post in data["data"]["children"]:
  post = post['data']
  if not post["id"] in seen:
    print "New post", post
    writer.write(post["title"]+"\n")
    if post["domain"] == "self.%s" % REDDIT:
      writer.write(post["url"]+"\n")
    else:
      writer.write(post["url"]+" https://reddit.com"+post["permalink"]+"\n")
    new.append(post["id"])
if len(new) != 0:
  f = open(STATEFILE, "a")
  for new in new:
    f.write(new+"\n")
  f.close()

@@ -14,16 +14,17 @@
 v python
+3
 %0A%0Aimport
@@ -137,22 +137,33 @@
 == 5:%0A  
-print 
+sys.stderr.write(
 %22running
@@ -175,17 +175,20 @@
 est mode
-%22
+%5Cn%22)
 %0A  data 
@@ -230,28 +230,8 @@
 ())%0A
-  writer=sys.stdout%0A
 else
@@ -392,29 +392,31 @@
 rint
- %22Kabloom!%22%0A    print
+(%22mcpherrin: Kabloom!%22,
  req
@@ -420,16 +420,17 @@
 req.text
+)
 %0A    sys
@@ -461,77 +461,8 @@
 on()
-%0A  writer=open(%22/home/ircbot/irc/irc.mozilla.org/%25s/in%22%25CHANNEL, %22a%22)
 %0A%0AST
@@ -599,58 +599,8 @@
 e()%0A
-print %22Previously seen %25d posts%22%25len(seen)%0A%0Anew=%5B%5D
 %0Afor
@@ -608,16 +608,25 @@
 post in 
+reversed(
 data%5B%22da
@@ -641,16 +641,17 @@
 ildren%22%5D
+)
 :%0A  post
@@ -703,67 +703,132 @@
     
-print %22New post%22, post
+id = post%5B%22id%22%5D%0A    with open(STATEFILE, %22a%22) as f:
 %0A    
+  f.
 write
-r.write(post%5B%22title%22%5D+%22%5Cn%22)
+(id + %22%5Cn%22)%0A    title = post%5B%22title%22%5D%0A    url = post%5B%22url%22%5D
 %0A   
@@ -879,246 +879,149 @@
     
-writer.write(post%5B%22url%22%5D+%22%5Cn%22)%0A    else:%0A      writer.write(post%5B%22url%22%5D+%22
+print(%22/r/%25s %25s http://redd.it/%25s/%5Cn%22 %25 (REDDIT, title, id))%0A    else:%0A      print(%22/r/%25s %25s %25s
  http
-s
 ://redd
+.
 it
-.com%22+post%5B%22permalink%22%5D+%22%5Cn%22)%0A    new.append(post%5B%22id%22%5D)%0Aif len(new) != 0:%0A  f = open(STATEFILE, %22a%22)%0A  for new in new:%0A    f.write(new+%22%5Cn%22)%0A  f.close(
+/%25s%5Cn%22 %25 (REDDIT, title, url, id)
 )%0A

Fix all the unicode bugs ... by switching to py3