Advertisement
Guest User

Untitled

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