Advertisement
Guest User

Untitled

a guest
Jan 4th, 2019
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.50 KB | None | 0 0
  1. import praw
  2. import asyncio
  3. import traceback
  4.  
  5. from datetime import timedelta
  6. from time import time
  7. from collections import OrderedDict
  8.  
  9. try:
  10.     from asyncio import ensure_future
  11. except ImportError:
  12.     ensure_future = asyncio.async
  13.  
  14.  
  15. username = "USERNAME"
  16. password = "PASSWORD"
  17. subreddit_name = "mod"
  18.  
  19.  
  20. '''
  21. `sleep time` : time (in seconds) the bot sleeps before performing a new check
  22. `time_until_message` : time (in seconds) a person has to add flair before a initial message is sent
  23. `time_until_remove` : time (in seconds) after a message is sent that a person has to add flair before the post is removed and they have to resubmit it
  24. `h_time_intil_remove` : Human Readable Version of time_until_remove
  25. `post_grab_limit` : how many new posts to check at a time.
  26. `add_flair_subject_line`, `add_flair_message` : Initial Message that tells a user that they need to flair their post
  27. `remove_post_subject_line`, `remove_post_message`: Second message telling them to resubmit their post since they have not flaired in time
  28. `no_flair` : Posts that still have a grace period to add a flair`
  29. '''
  30.  
  31. sleep_time = 10
  32. time_until_message = 180
  33. time_until_remove = 600
  34. h_time_until_remove = str(timedelta(seconds=time_until_remove))
  35. post_grab_limit = 20
  36. post_memory_limit = 100
  37. posts_to_forget = post_memory_limit - post_grab_limit
  38.  
  39. add_flair_subject_line = "You have not tagged your post."
  40. add_flair_message = ("[Your recent post]({post_url}) does not have any flair and will soon be removed.\n\n"
  41.                      "Please add flair to your post. "
  42.                      "If you do not add flair within **" + h_time_until_remove + "**, you will have to resubmit your post. "
  43.                      "Don't know how to flair your post? Click [here](http://imgur.com/a/m3FI3) to view this helpful guide on how to flair your post. "
  44.                      "If you are using the mobile version of the site click the hamburger menu in the top right of the screen and switch to the desktop site and then follow the instructions as you would on desktop.")
  45.  
  46. remove_post_subject_line = "You have not tagged your post within the allotted amount of time."
  47. remove_post_message = "[Your recent post]({post_url}) still does not have any flair and will remain removed, feel free to resubmit your post and remember to flair it once it is posted.*"
  48.  
  49. no_flair = OrderedDict()
  50. user_agent = ("Auto flair moderator for reddit created by /u/kooldawgstar") # tells reddit the bot's purpose.
  51. session = praw.Reddit(user_agent=user_agent)
  52. session.login(username=username, password=password, disable_warning=True)
  53. subreddit = session.get_subreddit(subreddit_name)
  54.  
  55.  
  56. @asyncio.coroutine
  57. def get_subreddit_settings(name):
  58.     raise NotImplementedError("TODO: Subreddit settings")
  59.  
  60.  
  61. @asyncio.coroutine
  62. def refresh_sesison():
  63.     '''Re-logs in every n seconds'''
  64.     while True:
  65.         try:
  66.             yield from asyncio.sleep(300)
  67.             session.login(username=username, password=password, disable_warning=True)
  68.             print("Session refreshed")
  69.         except Exception as e:
  70.             print(traceback.format_exc())
  71.             print("{0}: {1}".format(type(e).__name__, str(e)))
  72.  
  73.     yield from refresh_sesison()
  74.  
  75.  
  76. @asyncio.coroutine
  77. def inbox_stuff():
  78.     # For lack of a better name
  79.     '''Looks for mod invites, or if users have replied to the bot's message with a selected flair
  80.    Refreshes every n seconds
  81.    '''
  82.     while True:
  83.         try:
  84.             for message in session.get_unread():
  85.                 if message.body.startswith('**gadzooks!'):
  86.                     print("Checking out possible mod invite")
  87.                     try:
  88.                         print("Accepted Invite")
  89.                         sr = session.get_info(thing_id=message.subreddit.fullname)
  90.                         sr.accept_moderator_invite()
  91.                     except AttributeError:  # I cant rememver why I put this here but
  92.                         print("Tried to parse an invalid invite")
  93.                         continue
  94.                     except praw.errors.InvalidInvite:
  95.                         print("Tried to parse an invalid invite")
  96.                         continue
  97.                     message.mark_as_read()
  98.  
  99.                 if message.parent_id:
  100.                     if message.parent_id[3:] in no_flair:
  101.                         flaired = False
  102.                         post = session.get_submission(submission_id=no_flair[message.parent_id[3:]])
  103.                         choices = post.get_flair_choices()['choices']
  104.                         for ch in choices:
  105.                             if message.body == ch['flair_text']:
  106.                                 new_flair = ch['flair_text']
  107.                                 post.set_flair(new_flair)
  108.                                 flaired = True
  109.                                 break
  110.                         if flaired:
  111.                             message.reply("Set Flair: **{}**".format(new_flair))
  112.                         else:
  113.                             message.reply("Flair **{}** not found".format(message.body))
  114.                     message.mark_as_read()
  115.  
  116.         except Exception as e:
  117.             print(traceback.format_exc())
  118.             print("{0}: {1}".format(type(e).__name__, str(e)))
  119.  
  120.         yield from asyncio.sleep(sleep_time)
  121.  
  122.     yield from inbox_stuff()
  123.  
  124.  
  125. @asyncio.coroutine
  126. def main():
  127.     '''
  128.    Checks to see if a post has a flair, sends the user a message after
  129.    `time_until_message seconds`, and removes it if there is no flair after
  130.    `time_until_remove` seonds. Approves post if a flair is added. Refreshes every n seconds.
  131.    '''
  132.     while True:
  133.         # Checks to see if storing too much messages
  134.         if len(no_flair) >= post_memory_limit:
  135.             i = 0
  136.             while i < posts_to_forget:
  137.                 no_flair.popitem(0)
  138.                 i += 1
  139.  
  140.         try:
  141.             for submission in subreddit.get_new(limit=post_grab_limit):
  142.                 # If message has no flair
  143.                 if (submission.link_flair_text is None):
  144.                     if((time() - submission.created_utc) > time_until_message) and submission.id not in no_flair.values():
  145.                         final_add_flair_message = add_flair_message.format(post_url=submission.short_link)
  146.                         print("Sent Message to : {}".format(submission.author))
  147.                         session.send_message(submission.author, add_flair_subject_line, final_add_flair_message)
  148.                         for msg in session.get_sent():
  149.                             if msg.body == final_add_flair_message:
  150.                                 no_flair[msg.id] = submission.id
  151.                                 continue
  152.  
  153.                     if((time() - submission.created_utc) > time_until_remove):
  154.                         final_remove_post_message = remove_post_message.format(post_url=submission.short_link)
  155.                         session.send_message(submission.author, remove_post_subject_line, final_remove_post_message)
  156.                         print("Removed {0.short_link} of {0.author}'s".format(submission))
  157.                         for k in list(no_flair.keys()):
  158.                             if no_flair[k] == submission.id:
  159.                                 no_flair.pop(k)
  160.                         submission.remove()
  161.                         continue
  162.                         # Keeps track of how many posts the bot removed
  163.                         f = open('NumberRemoved','a')
  164.                         f.write('1\n')
  165.                         f.close()
  166.                 #
  167.                 if submission.id in no_flair.values() and submission.link_flair_text:
  168.                     submission.approve()
  169.                     print("Approved {0.short_link} of {0.author}'s".format(submission))
  170.                     for k in list(no_flair.keys()):
  171.                         if no_flair[k] == submission.id:
  172.                             no_flair.pop(k)
  173.                     continue
  174.         except Exception as e:
  175.             print(traceback.format_exc())
  176.             print("{0}: {1}".format(type(e).__name__, str(e)))
  177.  
  178.         yield from asyncio.sleep(sleep_time)
  179.  
  180.     yield from main()
  181.  
  182. if __name__ == "__main__":
  183.     # Puts main func into a loop and runs forever
  184.     loop = asyncio.get_event_loop()
  185.  
  186.     print("Registering session refresh\n")
  187.     ensure_future(refresh_sesison())
  188.  
  189.     print("Registering Mod Invites\n")
  190.     ensure_future(inbox_stuff())
  191.  
  192.     print("Registering Main\n")
  193.     ensure_future(main())
  194.  
  195.     print("\nStarting...\n")
  196.     loop.run_forever()
  197.  
  198.     loop.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement