Advertisement
Guest User

flairbot

a guest
Apr 2nd, 2019
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.75 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.  
  10. username = "UmbrellaCorpBot"
  11. password = "ResidentEvil"
  12. subreddit_name = "automodtest1243"
  13.  
  14.  
  15. '''
  16. `sleep time` : time (in seconds) the bot sleeps before performing a new check
  17. `time_until_message` : time (in seconds) a person has to add flair before a initial message is sent
  18. `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
  19. `h_time_intil_remove` : Human Readable Version of time_until_remove
  20. `post_grab_limit` : how many new posts to check at a time.
  21. `add_flair_subject_line`, `add_flair_message` : Initial Message that tells a user that they need to flair their post
  22. `remove_post_subject_line`, `remove_post_message`: Second message telling them to resubmit their post since they have not flaired in time
  23. `no_flair` : Posts that still have a grace period to add a flair`
  24. '''
  25.  
  26. sleep_time = 10
  27. time_until_message = 300
  28. time_until_remove = 1800
  29. h_time_until_remove = str(timedelta(seconds=time_until_remove))
  30. post_grab_limit = 30
  31. post_memory_limit = 300
  32. posts_to_forget = post_memory_limit - post_grab_limit
  33.  
  34. add_flair_subject_line = "You have not tagged your post."
  35.  
  36. add_flair_message = ("Hello {author}, **[your submission]({url}) in /r/Rainbow6 does not have any flair** and will soon be removed.\n\n"
  37.                      "Please add flair to your post. "
  38.                      "If you do not add flair within **" + h_time_until_remove + "**, you will have to resubmit your post. "
  39.                      "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. "
  40.                      "If you are using the mobile version of the site, feel free to reply to this message and I'll flair it for you!")
  41.  
  42. remove_post_subject_line = "You have not tagged your post within the allotted amount of time."
  43. remove_post_message = "Hello {author}, **[your submission]({url}) in /r/Rainbow6 has been removed for it still does not have any flair.** It will remain removed but feel free to resubmit your post and remember to flair it once it is posted."
  44.  
  45. no_flair = OrderedDict()
  46. user_agent = ("/r/Rainbow6 Flair Bot")
  47. session = praw.Reddit(user_agent=username)
  48. session.login(username=username, password=password, disable_warning=True)
  49. subreddit = session.get_subreddit(subreddit_name)
  50.  
  51.  
  52. @asyncio.coroutine
  53. def get_subreddit_settings(name):
  54.     raise NotImplementedError("TODO: Subreddit settings")
  55.  
  56.  
  57. @asyncio.coroutine
  58. def refresh_sesison():
  59.     '''Re-logs in every n seconds'''
  60.     while True:
  61.         try:
  62.             yield from asyncio.sleep(300)
  63.             session.login(username=UmbrellaCorpBot, password=ResidentEvil, disable_warning=True)
  64.             print("Session refreshed")
  65.         except Exception as e:
  66.             print(traceback.format_exc())
  67.             print("{0}: {1}".format(type(e).__name__, str(e)))
  68.  
  69.     yield from refresh_sesison()
  70.  
  71.  
  72. @asyncio.coroutine
  73. def inbox_stuff():
  74.     # For lack of a better name
  75.     '''Looks to see if users have replied to the bot's message with a selected flair
  76.    Refreshes every n seconds
  77.    '''
  78.     while True:
  79.         try:
  80.             for message in session.get_unread():
  81.                 if message.parent_id:
  82.                     if message.parent_id[3:] in no_flair:
  83.                         flaired = False
  84.                         post = session.get_submission(submission_id=no_flair[message.parent_id[3:]])
  85.                         choices = post.get_flair_choices()['choices']
  86.                         for ch in choices:
  87.                             if message.body == ch['flair_text']:
  88.                                 new_flair = ch['flair_text']
  89.                                 post.set_flair(new_flair)
  90.                                 flaired = True
  91.                                 break
  92.                         if flaired:
  93.                             message.reply("Set Flair: **{}**".format(new_flair))
  94.                     message.mark_as_read()
  95.  
  96.         except Exception as e:
  97.             print(traceback.format_exc())
  98.             print("{0}: {1}".format(type(e).__name__, str(e)))
  99.  
  100.         yield from asyncio.sleep(sleep_time)
  101.  
  102.     await inbox_stuff()
  103.  
  104.  
  105. @asyncio.coroutine
  106. def main():
  107.     '''
  108.    Checks to see if a post has a flair, sends the user a message after
  109.    `time_until_message seconds`, and removes it if there is no flair after
  110.    `time_until_remove` seonds. Approves post if a flair is added. Refreshes every n seconds.
  111.    '''
  112.     while True:
  113.         # Checks to see if storing too much messages
  114.         if len(no_flair) >= post_memory_limit:
  115.             i = 0
  116.             while i < posts_to_forget:
  117.                 no_flair.popitem(0)
  118.                 i += 1
  119.  
  120.         try:
  121.             for submission in subreddit.get_new(limit=post_grab_limit):
  122.                 # If message has no flair
  123.                 if (submission.link_flair_text is None):
  124.                     if((time() - submission.created_utc) > time_until_message) and submission.id not in no_flair.values():
  125.                         final_add_flair_message = add_flair_message.format(post_url=submission.short_link)
  126.                         print("Sent Message to : {}".format(submission.author))
  127.                         session.send_message(submission.author, add_flair_subject_line, final_add_flair_message)
  128.                         for msg in session.get_sent():
  129.                             if msg.body == final_add_flair_message:
  130.                                 no_flair[msg.id] = submission.id
  131.                                 continue
  132.  
  133.                     if((time() - submission.created_utc) > time_until_remove):
  134.                         final_remove_post_message = remove_post_message.format(post_url=submission.short_link)
  135.                         session.send_message(submission.author, remove_post_subject_line, final_remove_post_message)
  136.                         print("Removed {0.short_link} of {0.author}'s".format(submission))
  137.                         for k in list(no_flair.keys()):
  138.                             if no_flair[k] == submission.id:
  139.                                 no_flair.pop(k)
  140.                         submission.remove()
  141.                         continue
  142.                         # Keeps track of how many posts the bot removed
  143.                         f = open('NumberRemoved','a')
  144.                         f.write('1\n')
  145.                         f.close()
  146.                 #
  147.                 if submission.id in no_flair.values() and submission.link_flair_text:
  148.                     submission.approve()
  149.                     print("Approved {0.short_link} of {0.author}'s".format(submission))
  150.                     for k in list(no_flair.keys()):
  151.                         if no_flair[k] == submission.id:
  152.                             no_flair.pop(k)
  153.                     continue
  154.         except Exception as e:
  155.             print(traceback.format_exc())
  156.             print("{0}: {1}".format(type(e).__name__, str(e)))
  157.  
  158.         yield from asyncio.sleep(sleep_time)
  159.  
  160.     yield from main()
  161.  
  162. if __name__ == "__main__":
  163.     # Puts main func into a loop and runs forever
  164.     loop = asyncio.get_event_loop()
  165.  
  166.     print("Registering session refresh\n")
  167.     asyncio.ensure_future(refresh_sesison())
  168.  
  169.     print("Registering Mod Invites\n")
  170.     asyncio.ensure_future(inbox_stuff())
  171.  
  172.     userAgent = "/r/Rainbow6 Flair Bot"
  173.     clientId = '***********'
  174.     clientSecret = '********************'
  175.     r = praw.Reddit(user_agent=userAgent, client_id=clientId, client_secret=clientSecret)
  176.  
  177.     print("Registering Main\n")
  178.     asyncio.ensure_future(main())
  179.  
  180.     print("\nStarting...\n")
  181.     loop.run_forever()
  182.  
  183.     loop.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement