Advertisement
Guest User

Untitled

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