daily pastebin goal
15%
SHARE
TWEET

Untitled

a guest Jun 8th, 2017 154 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # -*- coding: utf-8 -*-
  2. import sys
  3. reload(sys)
  4. sys.setdefaultencoding("utf-8")
  5. import praw
  6. from termcolor import colored
  7. import time
  8. #Log into PRAW with script credentials
  9.  
  10. r = praw.Reddit(client_id='<your id>',
  11.                      client_secret='<your secret>',
  12.                      password='<your password>',
  13.                      user_agent='Advanced Flair Moderation Bot',
  14.                      username='FlairTimeBot')
  15.  
  16. print(colored('Logged in as: ' + str(r.user.me()), 'green'))
  17.                      
  18.  
  19. #Generate comment for a subreddit    
  20. #Using their flairs and wiki settings
  21. def generateComment(subm, mins):
  22.     template = '''This post has automatically been removed for not being flaired within {mins} minutes. When the post receives a flair it will automatically be restored. If you are on mobile, reply to this comment with one of the following commands and the bot will flair it accordingly.\n\n
  23. Flair | Command
  24. ---|---
  25. {flairs}
  26. \n\n
  27. If you believe that this removal was a mistake, please [contact the moderators.](https://www.reddit.com/message/compose?to=%2Fr%2F{subr})'''.format(mins=mins, flairs=getChoices(subm, True), subr=subm.subreddit)
  28.     return template
  29.    
  30. def generateWiki(sub):
  31.     print('GENNNERRATTTINGGG')
  32.     r.subreddit(sub).wiki.create('FlairTimeBot', '''#This is the configuration page for /u/FlairTimeBot. Do not adjust any of the text, only the values!
  33.                                               \n\n**Time until posts without flair are removed (minutes):** 10
  34.                                               \n\n**Time users have to add flair after post is removed (hours; max is 72):** 24
  35.                                              ''', reason='Initializing Flair Time Bot')
  36.  
  37.  
  38. def getSettings(subr):
  39.     wiki = r.subreddit(subr).wiki['FlairTimeBot']
  40.     wCon = str(wiki.content_md).split('values!')[1]
  41.     mins = int(round(float(str(wCon.split(':')[1])[0:8].strip('**').strip(' ').replace(' ','').replace('\n','').replace('\r',''))))
  42.     hrs = int(round(float(str(wCon.split(':')[2])[:].strip('**').strip(' ').replace(' ','').replace('\n','').replace('\r',''))))
  43.     return mins, hrs
  44.        
  45.  
  46. def getChoices(subm, isReport):
  47.     if isReport:
  48.         return '\n'.join([flair['flair_text'].encode('utf-8') + ' | -' + flair['flair_text'].encode('utf-8') for flair in subm.flair.choices()])
  49.     else:
  50.         flist =  [flair['flair_text'].encode('utf-8') for flair in subm.flair.choices()]
  51.         fclist = [flair['flair_css_class'].encode('utf-8') for flair in subm.flair.choices()]  
  52.         mdict = dict(zip([x.encode('utf-8').lower().rstrip() for x in flist], fclist))
  53.         return flist, mdict
  54.    
  55. #Initialize Database
  56.  
  57. import sqlite3
  58. conn = sqlite3.connect('genposts.db');
  59. c = conn.cursor()
  60. c.execute('''CREATE TABLE IF NOT EXISTS rposts (id TEXT, created TEXT, parentId TEXT, isremoved TEXT);''')
  61.  
  62. #rposts --> id, created, isremoved
  63.  
  64.  
  65. #get id, time created, and removal status from post if it exists
  66. #otherwise, return False
  67. def getInfo(ident):
  68.     t = (ident,)
  69.     for row in c.execute('''SELECT * FROM rposts WHERE id=?''', t):
  70.         postId = row[0]
  71.         time_created = row[1]
  72.         isRemoved = row[2]
  73.         return [postId, time_created, isRemoved]
  74.     return False
  75.  
  76. #list all posts in the database
  77. def listAll():
  78.     for row in c.execute('''SELECT * FROM rposts'''):
  79.         print(row)
  80.  
  81. #add a post for the first time when removing it    
  82. def addPost(ident, timec, parId, isRem):
  83.     ident = "'" + ident + "'"
  84.     timec = "'" + timec + "'"
  85.     parId = "'" + parId + "'"
  86.     isRem = "'" + isRem + "'"
  87.     c.execute('''INSERT INTO rposts VALUES ({}, {}, {}, {})'''.format(ident, timec, parId ,isRem))
  88.    
  89.  
  90. #delete all posts (only used for bugfixing)
  91. def deleteAll():
  92.     c.execute('''DELETE FROM rposts''')
  93.  
  94. #delete post with specific id from database
  95. def deleteSpec(ident):
  96.      t = (ident,)
  97.      c.execute('''DELETE FROM rposts WHERE id=?''', t)
  98.  
  99.  
  100. #return the age of a post in minutes
  101. def checkAge(post):
  102.     print('Started age check')
  103.     ctime = time.time() + 28800
  104.     difference =  float(ctime) - post.created
  105.     print('Checked age')
  106.     return difference/60
  107.    
  108. #second main function; check for old, unflaired posts
  109.  
  110. def checkForOld(post, qmins):
  111.     if checkAge(post)>qmins and post.link_flair_text == None and getInfo(post.id) == False:
  112.         myComment = post.reply(generateComment(post, qmins))
  113.         myComment.mod.distinguish(how='yes', sticky=True)
  114.         post.mod.remove()
  115.         addPost(post.id, str(post.created), myComment.id, 'true')
  116.     print('Checked for old')
  117. #third main function; database checker/complex question checking
  118.  
  119. def checkDatabase():
  120.     for row in c.execute('''SELECT * FROM rposts'''):
  121.         postId = row[0]
  122.         postCreated = row[1]
  123.         parId = row[2]
  124.         postRemoved = row[3]
  125.         actualPost = r.submission(id=postId)
  126.         qmins, fmins = getSettings(str(actualPost.subreddit))
  127.         fmins *= 60
  128.         if str(actualPost.author) == 'None':
  129.             deleteSpec(actualPost.id)
  130.             r.comment(id=parId).edit('This post has been deleted and can no longer be restored.')
  131.         elif postRemoved == 'true':
  132.             if checkAge(actualPost) > fmins:
  133.                 r.comment(id=parId).edit('This post is older than {} hours and can no longer be reapproved. Please resubmit and flair in time.'.format(fmins/60))
  134.                 deleteSpec(actualPost.id)
  135.             elif actualPost.link_flair_text != None:
  136.                 r.comment(id=parId).delete()
  137.                 actualPost.mod.approve()
  138.                 deleteSpec(actualPost.id)
  139.  
  140. def correctPerms(subr):
  141.     for moderator in r.subreddit(subr).moderator():
  142.         if str(moderator).lower() == 'flairtimebot':
  143.             mperms = moderator.mod_permissions
  144.             if 'all' in mperms:
  145.                 return True
  146.             elif 'wiki' not in mperms or 'posts' not in mperms or 'flair' not in mperms:
  147.                 return False
  148.             else:
  149.                 return True
  150.  
  151. def checkInvites():
  152.     for message in r.inbox.unread(limit=5):
  153.         message.mark_read()
  154.         if message.body.startswith('**gadzooks!') and message.subreddit != None:
  155.             try:
  156.                 r.subreddit(str(message.subreddit)).mod.accept_invite()
  157.                 if not correctPerms(str(message.subreddit)):
  158.                     r.subreddit(str(message.subreddit)).moderator.leave()
  159.                     message.reply('Error: Incorrect permissions. This bot requires the wiki, post, and flair permissions to function properly. Please re-invite it accordingly.')
  160.                 else:
  161.                     generateWiki(str(message.subreddit))
  162.                     print('GenXd Page')
  163.                     message.reply('Setup successful. Thank you for using /u/FlairTimeBot! You can access the configuration here: https://www.reddit.com/r/{}/wiki/flairtimebot\n\nAny complaints or bug reports should be sent to /u/--Nylon.'.format(str(message.subreddit)))
  164.             except:
  165.                 message.reply('There was an error joining the subreddit. Please try again or contact /u/--Nylon for support.')
  166.                 try:
  167.                     r.subreddit(str(message.subreddit)).moderator.leave()
  168.                 except:
  169.                     pass
  170.         elif message.body.startswith('**gadzooks!')  and message.subreddit == None:
  171.             message.reply('Nice try, I\'m uncrashable ;)')
  172.        
  173.  
  174. def checkComments():
  175.     for comment in r.inbox.comment_replies(limit=30):
  176.         if comment.id not in open('dcomments.txt', 'r').read().split('\n') and comment.body.encode('utf-8')[0] == '-' and str(comment.author).lower() == str(comment.parent().parent().author).lower():
  177.             if  'older than' in comment.parent().body.encode('utf-8'):
  178.                 r.redditor(str(comment.author)).message('Unable to assign flair to post.', '**Error:** Post is no longer eligible to be flaired (too old).')
  179.                 return False
  180.             subm = comment.parent().parent()
  181.             pflair = comment.body.encode('utf-8').strip('-').rstrip()
  182.             print(pflair.lower())
  183.             flair_list, fdict = getChoices(subm, False)
  184.             if pflair.lower() in [x.encode('utf-8').lower().rstrip() for x in flair_list]:
  185.                 subm.mod.flair(text=flair_list[[x.encode('utf-8').lower().rstrip() for x in flair_list].index(pflair.encode('utf-8').lower())], css_class=fdict[pflair.lower().rstrip()])
  186.                 comment.mod.remove()
  187.                 open('dcomments.txt','a').write(comment.id + '\n')
  188.             else:
  189.                 r.redditor(str(comment.author)).message('Unable to assign flair to your post.', '**Error:** Invalid flair option ({}).'.format(pflair))
  190.  
  191. def checkInbox():
  192.     checkInvites()
  193.     checkComments()
  194.  
  195. def runTimeBot():
  196.     cmdict = {}
  197.     x = 0
  198.     for post in [y for y in r.subreddit('mod').new(limit=50) if y.link_flair_text == None]:
  199.         print(colored('Going for time {}'.format(x), 'green'))
  200.         x+=1
  201.         try:
  202.             mlist = cmdict[str(post.subreddit)]
  203.         except:
  204.             print('Nope')
  205.             mlist = [str(mod) for mod in r.subreddit(str(post.subreddit)).moderator]
  206.             cmdict[str(post.subreddit)] = mlist
  207.         print('Got moderators')
  208.         if str(post.author).lower() != "automoderator" and str(post.author) not in mlist and post.link_flair_text == None:
  209.             mins, hrs = getSettings(str(post.subreddit))
  210.             checkForOld(post, mins)
  211.     checkInbox()
  212.     checkDatabase()
  213.     conn.commit()
  214.    
  215.  
  216.  
  217. while True:
  218.     try:
  219.         runTimeBot()
  220.     except Exception as e:
  221.         print(str(e))
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top