NateNate60

Willard Points Bot v2.1

Mar 23rd, 2019
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 26.31 KB | None | 0 0
  1. import prawcore.exceptions as e
  2. while True :
  3.     try :
  4.         # NateNate60's Willard Points Bot
  5.         version = "2.1"
  6.  
  7.         print ("Starting Willard Points Bot version", version)
  8.  
  9.         # Module importation
  10.         print ("Importing modules...", end='')
  11.         import praw
  12.         import config4 as config
  13.         import time as t
  14.         import datetime
  15.         import os.path
  16.         print ('done')
  17.         print ("Loading features...", end='')
  18.  
  19.         # On or Off. You can still run it if off, but nothing will actually happen
  20.         on = True
  21.  
  22.         # Set the tick
  23.         tick = 0
  24.  
  25.         # Login function
  26.         def login() :
  27.             print ("Connecting to Reddit")
  28.             print ("Authenticating...", end='')
  29.             r = praw.Reddit(username = config.username,
  30.                             password = config.password,
  31.                             client_id = config.client_id,
  32.                             client_secret = config.client_secret,
  33.                             user_agent = "WillardPointsBot" + version)
  34.             print ('done')
  35.             return r
  36.  
  37.  
  38.         """
  39.        Core running functionality
  40.        """
  41.  
  42.  
  43.         # Retrieve the queue of transactions to be processed
  44.         def retrieve() :
  45.             with open ("transactions.txt", "r") as queuefile :
  46.                 queue = queuefile.read()
  47.                 queue = queue.split('\n')
  48.             open('transactions.txt', 'w').close()
  49.  
  50.             return queue
  51.  
  52.  
  53.         #Set the signature
  54.         signature = "\n \n ^NateNate60's ^Willard ^Points ^Bot ^v" + version + ". ^Don't ^have ^an ^account? ^Use ^!newaccount. ^!info ^for ^information"
  55.  
  56.  
  57.         # The acutal code
  58.         def run_bot(r, tick, timen, queue, replied_to, time, blacklist) :
  59.             if on == True :
  60.                 if tick%3 == 0:
  61.                     for trans in queue :
  62.                         trans = str(trans)
  63.                         if "~" in trans and "+" not in trans :
  64.                             trans = trans.split('~')
  65.                             user = trans[0]
  66.                             if os.path.isfile (user + ".txt") :
  67.                                 with open (user + ".txt", 'r') as u :
  68.                                     balance = u.read()
  69.                                 balance = int(balance) - int(trans[1])
  70.                                 if balance < 0 :
  71.                                     balance = balance + int(trans[1])
  72.                                     notify (r, user, balance, trans[1], 0)
  73.                                 with open (user + ".txt", 'w') as s :
  74.                                     s.write(str(balance))
  75.                                 with open ('log.txt', 'a') as log :
  76.                                     log.write ("\n" + time + ' ' + user + " paid " + trans[1] + " WP.")
  77.                                     print (time + ' ' + user + " paid " + trans[1] + " WP.")
  78.                                 notify(r, user, balance, trans[1], '~')
  79.  
  80.                         elif "+" in trans and "~" not in trans :
  81.                             trans = trans.split('+')
  82.                             user = trans[0]
  83.                             if os.path.isfile (user + ".txt") :
  84.                                 with open (user + ".txt", 'r') as u :
  85.                                     balance = u.read()
  86.                                 balance = int(balance) + int(trans[1])
  87.                                 with open (user + ".txt", 'w') as s :
  88.                                     s.write(str(balance))
  89.                                 with open ('log.txt', 'a') as log :
  90.                                     log.write ("\n" + time + ' ' + user + " gained " + trans[1] + " WP.")
  91.                                     print (time + ' ' + user + " gained " + trans[1] + " WP.")
  92.                                 notify(r, user, balance, trans[1], '+')
  93.                 if tick%2 == 0 :
  94.                     for message in r.inbox.unread(limit = 5) :
  95.                         #For blacklisting
  96.                         if "!black" in message.body.lower() or "unsub" in message.body.lower() or "ignore" in message.body.lower() :
  97.                             message.reply ("Sorry to see you go. You have been temporarily blacklisted. Due to a technical problem, the bot cannot permanently blacklist you automatically." +
  98.                                            " Pinging u/NateNate60 for permanent blacklisting. This ping WILL NOT WORK if this command was issued in a PM, so please contact NateNate60 yourself." + signature)
  99.                             blacklist.append(message.author)
  100.                             print (time, message.author, "requested to be blacklisted")
  101.                         #For opening new accounts
  102.                         if "!newacc" in message.body or "!openacc" in message.body or "!createacc" in message.body :
  103.                             accname = str(message.author)
  104.                             if not os.path.isfile(accname + ".txt") and "bot" not in message.body.lower() :
  105.                                 accowner = accname
  106.                                 with open (accname + ".txt", 'w') as newacc :
  107.                                     newacc.write ("0")
  108.                                 message.reply ('Account creation successful. '
  109.                                                + 'You will recieve a one-time "signing" bonus of 10 Willard Points.' + signature)
  110.                                 with open ('log.txt', 'a') as log :
  111.                                     log.write ("\n" + time + ' ' + accowner + " opened an account.")
  112.                                     print (time + ' ' + accowner + " opened an account.")
  113.                                 with open ('transactions.txt', 'a') as transa :
  114.                                    transa.write ('\n' + str(accname) + '+10')
  115.                             else :
  116.                                 if "bot" not in message.body.lower() :
  117.                                     message.reply ('Something went wrong. Account creation failed. You probably already have an account. If you continue to receive this error, contact NateNate60. You can always try again.'
  118.                                                    + signature)
  119.  
  120.  
  121.                         #For querying information
  122.                         elif "!inf" in message.body.lower() or "!help" in message.body.lower() :
  123.                             message.reply ("NateNate60's Willard Points Bot version " + version + "\n \n" +
  124.                                            "Willard Points Bot is a bot created by NateNate60 to conduct transactions in Willard Points. What are Willard Points, you say? WP is a completely useless" +
  125.                                            ' joke currency that is issued to people saying "shut up exe" and making dank memes in r/townofsalemgame.' +
  126.                                            " Commands may be issued to the bot using the NEUTRALEVIL protocol. \n \n" +
  127.                                            "`!createaccount` will open a new account for you. I'll even give you 10 WP just for doing that. \n \n" +
  128.                                            "`!bal [username]` to check [username]'s account balance. For example, `!bal Willard_Points_Bot` will query Willard_Points_Bot's account balance. \n \n" +
  129.                                            "`!transfer [amount] [recepient]` will transfer [amount] Willard Points to [recepient]. \n \n" +
  130.                                            "`[username]+[amount]` and `[username]~[amount]` will add and subtract [amount] WP from [username] respectively. \n \n" +
  131.                                            "`!blacklist` to unsubscribe yourself from the Willard Points programme. Your account will be deleted in due time and the bot will no longer reply to your posts awarding WP. \n \n" +
  132.                                            "As long as I see the command in my inbox I will process it. You can either reply to one of my messages, or compose a PM to me by clicking the little envelope button next" +
  133.                                            ' to your name and then going to "compose new message". I cannot use the chat function of New Reddit yet. Stay tuned for more updates! If you have any questions, contact NatenNate60.')
  134.  
  135.  
  136.                         #For moderators adding or removing money from people's accounts administratively.
  137.                         elif "+" in message.body or '~' in message.body :
  138.                             if message.author not in config.approved :
  139.                                 message.reply ('You are not authorised to make that command.' + signature)
  140.                             else :
  141.                                 trans = message.body
  142.                                 if "~" in trans :
  143.                                     trans = trans.split('~')
  144.                                     user = trans[0]
  145.                                     if os.path.isfile(user + ".txt") :
  146.                                         with open (user + ".txt", 'r') as u :
  147.                                             balance = u.read()
  148.                                         balance = int(balance) - int(trans[1])
  149.                                         if balance < 0 :
  150.                                             balance = 0
  151.                                             message.reply ("That user does not have enough WP, so their balance was set to zero." + signature)
  152.                                         else :
  153.                                             message.reply ("The command completed successfully. \n \n"+ " ^Willard ^Points ^Bot ^v" + version)
  154.                                         with open (user + ".txt", 'w') as s :
  155.                                             s.write(str(balance))
  156.                                         with open ('log.txt', 'a') as log :
  157.                                             log.write ("\n" + time + ' ' + user + " was docked " + trans[1] + " WP by "  + str(message.author))
  158.                                             print (time + ' ' + user + " was docked " + trans[1] + " WP by "  + str(message.author))
  159.                                         notify(r, user, balance, trans[1], '~~')
  160.                                     else :
  161.                                         message.reply ("That account does not exist. Please contact NateNate60 for help." + signature)
  162.                                 elif "+" in trans :
  163.                                     trans = trans.split('+')
  164.                                     user = trans[0]
  165.                                     if os.path.isfile(user + ".txt") :
  166.                                         with open (user + ".txt", 'r') as u :
  167.                                             balance = u.read()
  168.                                         balance = int(balance) + int(trans[1])
  169.                                         message.reply ("The command completed successfully. " + signature)
  170.                                         with open (user + ".txt", 'w') as s :
  171.                                             s.write(str(balance))
  172.                                         with open ('log.txt', 'a') as log :
  173.                                             log.write ("\n" + time + ' ' + user + " was awarded " + trans[1] + " WP by "  + str(message.author))
  174.                                         notify(r, user, balance, trans[1], '++')
  175.                                     else :
  176.                                         message.reply ("That account does not exist. Please contact NateNate60 for help." + signature)
  177.  
  178.                         #Balance checking
  179.                         elif "!bal" in message.body :
  180.                             payload = message.body.split(" ")
  181.                             if len(payload) != 2 :
  182.                                 message.reply ('Invalid syntax. Try !balance [username]')
  183.                             else :
  184.                                 if os.path.isfile(payload[1] + ".txt") :
  185.                                     with open (payload[1] + ".txt") as acc :
  186.                                         bal = acc.read()
  187.                                     message.reply("That account currently has " + bal + " Willard Points." + signature)
  188.                                 else :
  189.                                     message.reply ("That account does not exist. Use !newaccount" + signature)
  190.  
  191.                         # Transferring
  192.                         elif "!trans" in message.body :
  193.                             payload = message.body
  194.                             payload = payload.split(' ')
  195.                             to = payload [1]
  196.                             amt = payload [2]
  197.                             fromfile = str(message.author) + ".txt"
  198.                             if os.path.isfile(fromfile) :
  199.                                 if os.path.isfile(to + ".txt") :
  200.                                     with open (fromfile, 'r') as f :
  201.                                         balance = f.read()
  202.                                         balance = balance - amt
  203.                                         if balance < 0 :
  204.                                             balance = balance + amt
  205.                                             notify (r, message.author, balance, None, '0')
  206.                                         else :
  207.                                             with open ('transactions.txt', 'a') as trans :
  208.                                                 trans.write("\n" + str(message.author) + "~" + amt)
  209.                                                 trans.write('\n' + to + "+" + amt)
  210.                                 else :
  211.                                     message.reply ("Invalid recepient. Make sure you spelled the recepient's username correctly." + signature)
  212.                             else :
  213.                                 message.reply ("Invalid sender. You do not have an account. Use !newaccount to create a new account." + signature)
  214.                         elif "shut up" in message.body.lower() :
  215.                             message.reply ('no u (try `!blacklist`)' + signature)
  216.                         elif "bad bot" in message.body.lower() :
  217.                             message.reply ("shut up human (try `!blacklist`)" + signature)
  218.                         elif "!isup" in message.body.lower() or "!stat" in message.body.lower() :
  219.                             message.reply ("Online." + signature)
  220.                         #elif "!black" or "!ign
  221.                         # Mark the message as read.
  222.                         r.inbox.mark_read([message])
  223.  
  224.  
  225.  
  226.  
  227.                 #For awarding WP to good posts
  228.                 timen = int(timen) / 10
  229.                 timen = round (timen)
  230.                 timen = timen * 10
  231.                 if timen%21600 == 0 :
  232.                     for post in r.subreddit('townofsalemgame').hot(limit = 12) :
  233.                         if post.stickied or not os.path.isfile(str(post.author) + ".txt") :
  234.                             continue
  235.                         elif post.score > 50 and post.score < 100 :
  236.                             if post.id not in replied_to :
  237.                                 post.reply ("It looks like this is a good post. It's reached the Framer tier! \n \n" +
  238.                                             "Willard Points issued at the Framer tier are equal to 1 WP for every 15 upvotes for every 6 hours this stays on the front page. Pinned posts are not eligible. The longer it stays on the front page, the more you'll get.\n \n" +
  239.                                             signature)
  240.                             award = post.score // 15
  241.                             print (time, post.author, "gained", str(award), "for FRAMER.")
  242.                             with open ("transactions.txt", 'a') as trans :
  243.                                 trans.write (str(post.author) + "+" + str(award))
  244.                                 replied_to.append (post.id)
  245.                         elif post.score > 100 and post.score < 200 :
  246.                             if post.id in replied_to :
  247.                                 for comment in post.comments :
  248.                                     if comment.author != r.user.me() :
  249.                                         continue
  250.                                     else :
  251.                                         comment.edit ("It looks like this is a pretty good post. It's reached the Mafioso tier! \n \n" +
  252.                                                       "Willard Points issued at the Mafioso tier are equal to 1 WP for every 15 upvotes (plus 3 WP) for every 6 hours this stays on the front page. Pinned posts are not eligible. The longer it stays on the front page, the more you'll get.\n \n" +
  253.                                                       signature)
  254.                             else :
  255.                                 post.reply ("It looks like this is a pretty good post. It's reached the Mafioso tier! \n \n" +
  256.                                             "Willard Points issued at the Mafioso tier are equal to 1 WP for every 15 upvotes (plus 3 WP) for every 6 hours this stays on the front page. Pinned posts are not eligible. The longer it stays on the front page, the more you'll get.\n \n" +
  257.                                             signature)
  258.                             award = post.score // 20
  259.                             award = award + 3
  260.                             print (time, post.author, "gained", str(award), "for MAFIOSO.")
  261.                             with open ("transactions.txt", 'a') as trans :
  262.                                 trans.write ('\n' + str(post.author) + "+" + str(award))
  263.                         elif post.score > 200 and post.score < 500 :
  264.                             if post.id in replied_to :
  265.                                 for comment in post.comments :
  266.                                     if comment.author != r.user.me() :
  267.                                         continue
  268.                                     else :
  269.                                         comment.edit ("It looks like this is a really dank post. It's reached the Blackmailer tier! \n \n" +
  270.                                                       "Willard Points issued at the Blackmailer tier are equal to 1 WP for every 20 upvotes (plus 5 WP) for every 6 hours this stays on the front page. Pinned posts are not eligible. The longer it stays on the front page, the more you'll get.\n \n" +
  271.                                                       signature)
  272.                             else :
  273.                                 post.reply ("It looks like this is a really dank post. It's reached the Blackmailer tier! \n \n" +
  274.                                             "Willard Points issued at the Blackmailer tier are equal to 1 WP for every 20 upvotes. (plus 5 WP) for every 6 hours this stays on the front page. Pinned posts are not eligible. The longer it stays on the front page, the more you'll get.\n \n" +
  275.                                             signature)
  276.                                 replied_to.append (post.id)
  277.                             award = post.score // 20
  278.                             award = award + 5
  279.                             print (time, post.author, "gained", str(award), "for BLACKMAILER.")
  280.                             with open ("transactions.txt", 'a') as trans :
  281.                                 trans.write ('\n' + str(post.author) + "+" + str(award))
  282.                         elif post.score > 500 and post.score < 1000 :
  283.                             for comment in post.comments :
  284.                                 if comment.author != r.user.me() :
  285.                                     continue
  286.                                 else :
  287.                                     comment.edit ("It looks like this is an extremely good post. It's reached the Consigliere tier! \n \n" +
  288.                                                   "Willard Points issued at the Consigliere tier are equal to 1 WP for every 20 upvotes. (plus 10 WP) for every 6 hours this stays on the front page. Pinned posts are not eligible. The longer it stays on the front page, the more you'll get.\n \n" +
  289.                                                   signature)
  290.                                     award = post.score // 20
  291.                                     award = award + 10
  292.                                     print (time, post.author, "gained", str(award), "for CONSIGLIERE.")
  293.                                     with open ("transactions.txt", 'a') as trans :
  294.                                         trans.write ('\n' + str(post.author) + "+" + str(award))
  295.                         elif post.score > 1000 :
  296.                             for comment in post.comments :
  297.                                 if comment.author != r.user.me() :
  298.                                     continue
  299.                                 else :
  300.                                     comment.edit ("It looks like this is one of the best posts of all time! Congratulations! It's reached the Godfather tier! \n \n" +
  301.                                                   "Willard Points issued at the Godfather tier are equal to 1 WP for ever 20 upvotes (plus 20 WP) for every 6 hours this stays on the front page. Pinned posts are not eligible. The longer it stays on the front page, the more you'll get. \n \n" +
  302.                                                   signature)
  303.                                     award = post.score // 20
  304.                                     award = award + 20
  305.                                     print (time, post.author, "gained 50 for GODFATHER.")
  306.                                     with open ("transactions.txt", 'a') as trans :
  307.                                         trans.write ('\n' + str(post.author) + "+" + str(award))
  308.                         replied_to.append (post.id)
  309.                 write_comment_list(replied_to)
  310.  
  311.         def notify (r, user, balance, amt, sign) :
  312.             if sign == '~' :
  313.                 r.redditor(user).message('Willard Points were debited from your account', str(amt) + " Willard Points were deducted from your account. \n \n"
  314.                                          + 'You have ' + str(balance) + " Willard Points left.")
  315.             elif sign == '+' and int(amt) > 1 :
  316.                 r.redditor(user).message('Willard Points were credited to your account', str(amt) + " Willard Points were added to your account. \n \n"
  317.                                          + 'You have ' + str(balance) + " Willard Points now.")
  318.             elif sign == '~~' :
  319.                 r.redditor(user).message('Willard Points were debited to your account', str(amt) + " Willard Points were administratively removed from your account. \n \n"
  320.                                          + 'You have ' + str(balance) + " Willard Points left.")
  321.             elif sign == '++' :
  322.                 r.redditor(user).message('Willard Points were credited to your account', str(amt) + " Willard Points were administratively added to your account. \n \n"
  323.                                          + 'You have ' + str(balance) + " Willard Points now.")
  324.             elif sign == '0' :
  325.                 r.redditor(user).message('Attempted overdraw detected', "An attempt was made to overdraw your account. No points were deducted and the transaction has been cancelled. You have " + str(balance) + " WP.")
  326.  
  327.         def get_comment_list() :
  328.             with open ("comments.txt", "r") as f :
  329.                 comments_replied_to = f.read()
  330.                 comments_replied_to = comments_replied_to.split("\n")
  331.             return comments_replied_to
  332.         def write_comment_list(replied_to) :
  333.             with open ('comments.txt', 'w') as file :
  334.                 for i in replied_to :
  335.                     file.write (i + '\n')
  336.         print ('done')
  337.         #NOTES
  338.         # [OK] Test run_bot for a debiting statement in the queue file (which should be
  339.         # in the form of 1234-5 where 1234 is debited 5 WP)
  340.         #
  341.         # [OK] Make sure to add a statement for crediting, too.
  342.         #
  343.         # [OK] Account creation should be quick and easy. The bot should periodically
  344.         # check its inbox for messages with !createacc or !openacc or !newacc and make
  345.         # a new account
  346.         #
  347.         # [OK] The bot should honour !credit [amt], !add, !debit, !sub commands only from
  348.         # authorised users. Namely, NateNate60 and the mods of r/townofsalemgame
  349.         #
  350.         # [OK] The bot should be able to facilitate transactions between users with !transfer
  351.         # between the account holder (VERIFY THIS TO STOP FRAUD) to any other account.
  352.         # This may prove to be tricky to implement.
  353.         #
  354.         # [OK] The bot should honour !bal [acc #] commands from anyone, for any account.
  355.         #
  356.         # [OK] USERNAMES MUST NOT CONTAIN "+" OR "-"
  357.         #
  358.         # [OK] Mark read messages as read.
  359.  
  360.         replied_to = get_comment_list()
  361.         r = login()
  362.         blacklist = config.blacklist
  363.         time = datetime.datetime.fromtimestamp(t.time()).strftime('%Y-%m-%d %H:%M:%S')
  364.         print ("Right now, it's PST " + time)
  365.         while True :
  366.             replied_to = get_comment_list()
  367.             tick += 1
  368.             timen = int(t.time())
  369.             time = datetime.datetime.fromtimestamp(t.time()).strftime('%Y-%m-%d %H:%M:%S')
  370.             queue = retrieve()
  371.             run_bot(r, tick, timen, queue, replied_to, time, blacklist)
  372.             if tick == 1 :
  373.                 print (time + ": The bot has successfully completed one cycle.")
  374.             elif tick == 5 :
  375.                 print (time + ": The bot has successfully completed five cycles.")
  376.             elif tick%10 == 0 and tick < 99 :
  377.                 print (time + ": The bot has successfully completed " + str(tick) + " cycles.")
  378.             elif tick%100 == 0 and tick < 999 :
  379.                 print (time + ": The bot has successfully completed " + str(tick) + " cycles.")
  380.             elif tick%1000 == 0 and tick > 999:
  381.                 print (time + ": The bot has successfully completed " + str(tick) + " cycles.")
  382.  
  383.             t.sleep(15)
  384.     except e.RequestException :
  385.         print ('The bot crashed with RequestException. Restarting...')
  386.         continue
  387.     except ValueError :
  388.         print ('The bot crashed with ValueError. Restarting...')
  389.         continue
  390.     except PermissionError :
  391.         print ('The bot crashed with PermissionError. Restarting...')
  392.         continue
  393.     except e.Forbidden :
  394.         print ('The bot crashed because it recieved a 503 HTTP error. Restarting...')
  395.         continue
Add Comment
Please, Sign In to add comment