gavin19

Sidebar 'top 3' table

Feb 14th, 2016
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.75 KB | None | 0 0
  1. #!/usr/bin/python3
  2. import praw
  3. import sys
  4. import html.parser
  5. from datetime import datetime as time
  6. import OAuth2Util
  7.  
  8.  
  9. def main():
  10.     subr = "Everton"
  11.     start = '[](/start)'
  12.     end = '[](/end)'
  13.     ua = 'Sidebar updater for /r/Everton'
  14.     top = []
  15.     tbl_top = '|Top recent discussions|[](/comm "No. of comments")\n:-:|:-:\n'
  16.     tbl_row = '|[{0}]({1})|[{2}]({3})\n'
  17.     content = start + '\n\n'
  18.  
  19.     # login
  20.     r = praw.Reddit(user_agent=ua)
  21.     o = OAuth2Util.OAuth2Util(r)
  22.     o.refresh()
  23.     target_sub = r.get_subreddit(subr)
  24.  
  25.     # get top 30 posts from 'new'
  26.     listing = r.get_subreddit(subr).get_new(limit=30)
  27.     for post in listing:
  28.         top.append(post)
  29.  
  30.     # sort submission objects by number of comments (most first)
  31.     top.sort(key=lambda x: x.num_comments, reverse=True)
  32.     listing = []
  33.  
  34.     for i in range(3):
  35.         top[i].title = top[i].title.replace('|', '|')
  36.         top[i].url = top[i].url.replace('|', '|')
  37.         listing.append([top[i].title,
  38.                         top[i].url,
  39.                         top[i].num_comments,
  40.                         top[i].short_link])
  41.         print(top[i].title)
  42.         print(top[i].url)
  43.  
  44.     # build markdown table and populate with post info
  45.     content += tbl_top
  46.  
  47.     for i in listing:
  48.         content += tbl_row.format(i[0], i[1], i[2], i[3])
  49.  
  50.     print(content)
  51.     print(time.now().strftime('%Y-%m-%d %H:%M:%S'))
  52.  
  53.     desc = target_sub.get_settings()['description']
  54.     desc = html.parser.HTMLParser().unescape(desc)
  55.     before = desc.split(start)
  56.     after = desc.split(end)
  57.  
  58.     new_desc = before[0] + content + end + after[1]
  59.     target_sub.update_settings(description=new_desc)
  60.     sys.exit()
  61.  
  62. if __name__ == '__main__':
  63.     main()
Advertisement
Add Comment
Please, Sign In to add comment