NateNate60

Shut Up Exe Bot source code (ver. 9.6)

Sep 23rd, 2019
1,778
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 24.69 KB | None | 0 0
  1. import prawcore.exceptions as e
  2. while True :
  3.     try :
  4.         # NateNate60's Willard Points Bot
  5.         version = "3.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.         #signature = "\n \n ^NateNate60's ^Willard ^Points ^Bot ^v" + version + "\n\n" + "Don't be alarmed if the bot replied to you more than once. This is because the bot keeps corrupting its own memory and I can't figure out why."
  56.  
  57.         # The acutal code
  58.         def run_bot(r, tick, timen, queue, replied_to, time, blacklist) :
  59.             if on == True :
  60.                 for trans in queue :
  61.                     trans = str(trans)
  62.                     if "~" in trans and "+" not in trans :
  63.                         trans = trans.split('~')
  64.                         user = trans[0]
  65.                         if os.path.isfile (user + ".txt") :
  66.                             with open (user + ".txt", 'r') as u :
  67.                                 balance = u.read()
  68.                             balance = int(balance) - int(trans[1])
  69.                             if balance < 0 :
  70.                                 balance = balance + int(trans[1])
  71.                                 notify (r, user, balance, trans[1], 0)
  72.                             with open (user + ".txt", 'w') as s :
  73.                                 s.write(str(balance))
  74.                             with open ('log.txt', 'a') as log :
  75.                                 log.write ("\n" + time + ' ' + user + " paid " + trans[1] + " WP.")
  76.                                 print (time + ' ' + user + " paid " + trans[1] + " WP.")
  77.                             notify(r, user, balance, trans[1], '~')
  78.  
  79.                     elif "+" in trans and "~" not in trans :
  80.                         trans = trans.split('+')
  81.                         user = trans[0]
  82.                         if os.path.isfile (user + ".txt") :
  83.                             with open (user + ".txt", 'r') as u :
  84.                                 balance = u.read()
  85.                             balance = int(balance) + int(trans[1])
  86.                             with open (user + ".txt", 'w') as s :
  87.                                 s.write(str(balance))
  88.                             with open ('log.txt', 'a') as log :
  89.                                 log.write ("\n" + time + ' ' + user + " gained " + trans[1] + " WP.")
  90.                                 print (time + ' ' + user + " gained " + trans[1] + " WP.")
  91.                             notify(r, user, balance, trans[1], '+')
  92.                 if tick%2 == 0 :
  93.                     for message in r.inbox.unread(limit = 5) :
  94.                         #For blacklisting
  95.                         if "!black" in message.body.lower() or "unsub" in message.body.lower() or "ignore" in message.body.lower() :
  96.                             message.reply ("Sorry to see you go. You have been temporarily blacklisted. Due to a technical problem, the bot cannot permanently blacklist you automatically." +
  97.                                            " 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)
  98.                             blacklist.append(message.author)
  99.                             print (time, message.author, "requested to be blacklisted")
  100.                         #For opening new accounts
  101.                         if "!newacc" in message.body or "!openacc" in message.body or "!createacc" in message.body :
  102.                             accname = str(message.author)
  103.                             if not os.path.isfile(accname + ".txt") and "bot" not in message.body.lower() :
  104.                                 accowner = accname
  105.                                 with open (accname + ".txt", 'w') as newacc :
  106.                                     newacc.write ("0")
  107.                                 message.reply ('Account creation successful. '
  108.                                                + 'You will receive a one-time "signing" bonus of 10 Willard Points.' + signature)
  109.                                 with open ('log.txt', 'a') as log :
  110.                                     log.write ("\n" + time + ' ' + accowner + " opened an account.")
  111.                                     print (time + ' ' + accowner + " opened an account.")
  112.                                 with open ('transactions.txt', 'a') as transa :
  113.                                    transa.write ('\n' + str(accname) + '+10')
  114.                             else :
  115.                                 if "bot" not in message.body.lower() :
  116.                                     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.'
  117.                                                    + signature)
  118.  
  119.  
  120.                         #For querying information
  121.                         elif "!inf" in message.body.lower() or "!help" in message.body.lower() :
  122.                             message.reply ("NateNate60's Willard Points Bot version " + version + "\n \n" +
  123.                                            "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" +
  124.                                            ' joke currency that is issued to people saying "shut up exe" and making dank memes in r/townofsalemgame.' +
  125.                                            " Commands may be issued to the bot using the NEUTRALEVIL protocol. \n \n" +
  126.                                            "`!createaccount` will open a new account for you. I'll even give you 10 WP just for doing that. \n \n" +
  127.                                            "`!bal [username]` to check [username]'s account balance. For example, `!bal Willard_Points_Bot` will query Willard_Points_Bot's account balance. \n \n" +
  128.                                            "`!transfer [amount] [recepient]` will transfer [amount] Willard Points to [recepient]. \n \n" +
  129.                                            "`[username]+[amount]` and `[username]~[amount]` will add and subtract [amount] WP from [username] respectively. \n \n" +
  130.                                            "`!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" +
  131.                                            "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" +
  132.                                            ' 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.')
  133.  
  134.  
  135.                         #For moderators adding or removing money from people's accounts administratively.
  136.                         elif "+" in message.body or '~' in message.body :
  137.                             if message.author not in config.approved :
  138.                                 message.reply ('You are not authorised to make that command.' + signature)
  139.                             else :
  140.                                 trans = message.body
  141.                                 if "~" in trans :
  142.                                     trans = trans.split('~')
  143.                                     user = trans[0]
  144.                                     if os.path.isfile(user + ".txt") :
  145.                                         with open (user + ".txt", 'r') as u :
  146.                                             balance = u.read()
  147.                                         balance = int(balance) - int(trans[1])
  148.                                         if balance < 0 :
  149.                                             balance = 0
  150.                                             message.reply ("That user does not have enough WP, so their balance was set to zero." + signature)
  151.                                         else :
  152.                                             message.reply ("The command completed successfully. \n \n"+ " ^Willard ^Points ^Bot ^v" + version)
  153.                                         with open (user + ".txt", 'w') as s :
  154.                                             s.write(str(balance))
  155.                                         with open ('log.txt', 'a') as log :
  156.                                             log.write ("\n" + time + ' ' + user + " was docked " + trans[1] + " WP by "  + str(message.author))
  157.                                             print (time + ' ' + user + " was docked " + trans[1] + " WP by "  + str(message.author))
  158.                                         notify(r, user, balance, trans[1], '~~')
  159.                                     else :
  160.                                         message.reply ("That account does not exist. Please contact NateNate60 for help." + signature)
  161.                                 elif "+" in trans :
  162.                                     trans = trans.split('+')
  163.                                     user = trans[0]
  164.                                     if os.path.isfile(user + ".txt") :
  165.                                         with open (user + ".txt", 'r') as u :
  166.                                             balance = u.read()
  167.                                         balance = int(balance) + int(trans[1])
  168.                                         message.reply ("The command completed successfully. " + signature)
  169.                                         with open (user + ".txt", 'w') as s :
  170.                                             s.write(str(balance))
  171.                                         with open ('log.txt', 'a') as log :
  172.                                             log.write ("\n" + time + ' ' + user + " was awarded " + trans[1] + " WP by "  + str(message.author))
  173.                                         notify(r, user, balance, trans[1], '++')
  174.                                     else :
  175.                                         message.reply ("That account does not exist. Please contact NateNate60 for help." + signature)
  176.  
  177.                         #Balance checking
  178.                         elif "!bal" in message.body :
  179.                             payload = message.body.split(" ")
  180.                             if len(payload) != 2 :
  181.                                 message.reply ('Invalid syntax. Try !balance [username]')
  182.                             else :
  183.                                 if os.path.isfile(payload[1] + ".txt") :
  184.                                     with open (payload[1] + ".txt") as acc :
  185.                                         bal = acc.read()
  186.                                     message.reply("That account currently has " + bal + " Willard Points." + signature)
  187.                                 else :
  188.                                     message.reply ("That account does not exist. Use !newaccount" + signature)
  189.  
  190.                         # Transferring
  191.                         elif "!trans" in message.body :
  192.                             payload = message.body
  193.                             payload = payload.split(' ')
  194.                             to = payload [2]
  195.                             amt = payload [1]
  196.                             fromfile = str(message.author) + ".txt"
  197.                             if os.path.isfile(fromfile) :
  198.                                 if os.path.isfile(to + ".txt") :
  199.                                     with open (fromfile, 'r') as f :
  200.                                         balance = f.read()
  201.                                         balance = balance - amt
  202.                                         if balance < 0 :
  203.                                             balance = balance + amt
  204.                                             notify (r, message.author, balance, None, '0')
  205.                                         else :
  206.                                             with open ('transactions.txt', 'a') as trans :
  207.                                                 trans.write("\n" + str(message.author) + "~" + amt)
  208.                                                 trans.write('\n' + to + "+" + amt)
  209.                                 else :
  210.                                     message.reply ("Invalid recepient. Make sure you spelled the recepient's username correctly." + signature)
  211.                             else :
  212.                                 message.reply ("Invalid sender. You do not have an account. Use !newaccount to create a new account." + signature)
  213.                         elif "shut up" in message.body.lower() :
  214.                             message.reply ('no u (try `!blacklist`)' + signature)
  215.                         elif "bad bot" in message.body.lower() :
  216.                             message.reply ("shut up human (try `!blacklist`)" + signature)
  217.                         elif "!isup" in message.body.lower() or "!stat" in message.body.lower() :
  218.                             message.reply ("Online." + signature)
  219.                         r.inbox.mark_read([message])
  220.  
  221.  
  222.  
  223.  
  224.                 #For awarding WP to good posts
  225.                 if timen%21600 < 60 :
  226.                     print(time + ': Fetching submissions')
  227.                     crp = get_crp()
  228.                     for post in r.subreddit('townofsalemgame').hot(limit = 12) :
  229.                         if post.stickied or not os.path.isfile(str(post.author) + ".txt") or post.score < 80 :
  230.                             continue
  231.                         elif post.score >= 80 and post.score < 150 :
  232.                             tier = "FRAMER"
  233.                         elif post.score >= 150 and post.score < 300 :
  234.                             tier = "MAFIOSO"
  235.                         elif post.score >= 300 and post.score < 500 :
  236.                             tier = "BLACKMAILER"
  237.                         elif post.score >= 500 and post.score < 1000 :
  238.                             tier = "CONSIGLIERE"
  239.                         elif post.score >= 1000 :
  240.                             tier = "GODFATHER"
  241.                         if post.id not in crp and post.score > 79:
  242.                             award = 0
  243.                             if tier == "FRAMER" :
  244.                                 award = post.score // 15
  245.                             elif tier == "MAFIOSO" :
  246.                                 award = post.score // 20 + 3
  247.                             elif tier == "BLACKMAILER" :
  248.                                 award = post.score // 20 + 5
  249.                             elif tier == "BLACKMAILER" :
  250.                                 award = post.score // 20 + 10
  251.                             elif tier == "GODFATHER" :
  252.                                 award = 100
  253.                             with open(str(post.author) + ".txt", 'r') as auth :
  254.                                 bal = int(auth.read())
  255.                                 bal = bal + award
  256.                             with open(str(post.author) + ".txt", 'w') as auth :
  257.                                 auth.write(str(bal))
  258.                             print(time + ": " + str(post.author) + " gained " + str(award) + " WP.")
  259.                             with open('log.txt','a') as log :
  260.                                 log.write(time + " " + str(post.author) + " gained " + str(award) + " WP.")
  261.                             post.reply ("Hello. Thank you for you wonderful post to our subreddit. I am the bot (that you subscribed to) that awards Willard Points to good posts. I am pleased"+
  262.                                         " to inform you that your post has reached the " + tier + " tier. As such, I am awarding you " + str(award) + " Willard Points for this post. I will update" +
  263.                                         " you if you earn more Willard Points. I check the top 12 posts ever six hours. Pinned posts are unfortunately not eligible. You've got " + str(bal) + " WP now.")
  264.                             notify (r, post.author.name, bal, award, '+')
  265.                         elif post.score > 79 and post.id in crp :
  266.                             award = 0
  267.                             if tier == "FRAMER" :
  268.                                 award = post.score // 15
  269.                             elif tier == "MAFIOSO" :
  270.                                 award = post.score // 20 + 3
  271.                             elif tier == "BLACKMAILER" :
  272.                                 award = post.score // 20 + 5
  273.                             elif tier == "BLACKMAILER" :
  274.                                 award = post.score // 20 + 10
  275.                             elif tier == "GODFATHER" :
  276.                                 award = 100
  277.                             if award != 0 :
  278.                                 with open(str(post.author) + ".txt", 'r') as auth :
  279.                                     bal = int(auth.read())
  280.                                     bal = bal + award
  281.                                 with open(str(post.author) + ".txt", 'w') as auth :
  282.                                     auth.write(str(bal))
  283.                                 print(time + ": " + str(post.author) + " gained " + str(award) + " WP.")
  284.                                 with open('log.txt','a') as log :
  285.                                     log.write(time + " " + str(post.author) + " gained " + str(award) + " WP.")
  286.                                 for cmt in post.comments :
  287.                                     if cmt.author == r.user.me() and "that you subscribed to" in cmt.body :
  288.                                         oldbody = cmt.body
  289.                                         cmt.edit (oldbody + '\n\n' + "EDIT: It's me again! I found this post again on the front page, which means I can award more Willard Points to you! Here is " +
  290.                                                   str(award) + " more Willard Points. It's now in the " + tier + " tier. Keep it up! You've got " + str(bal) + " WP now.")
  291.                                 notify (r, post.author.name, bal, award, '+')
  292.                         crp.append(post.id)
  293.                     print (time + ': Done fetching.')
  294.                     write_crp(crp)
  295.                 write_comment_list(replied_to)
  296.  
  297.         def notify (r, user, balance, amt, sign) :
  298.             if sign == '~' :
  299.                 r.redditor(user).message('Willard Points were debited from your account', str(amt) + " Willard Points were deducted from your account. \n \n"
  300.                                          + 'You have ' + str(balance) + " Willard Points left.")
  301.             elif sign == '+' and int(amt) > 1 :
  302.                 r.redditor(user).message('Willard Points were credited to your account', str(amt) + " Willard Points were added to your account. \n \n"
  303.                                          + 'You have ' + str(balance) + " Willard Points now.")
  304.             elif sign == '~~' :
  305.                 r.redditor(user).message('Willard Points were debited to your account', str(amt) + " Willard Points were deducted from your account. \n \n"
  306.                                          + 'You have ' + str(balance) + " Willard Points left.")
  307.             elif sign == '++' :
  308.                 r.redditor(user).message('Willard Points were credited to your account', str(amt) + " Willard Points were added to your account. \n \n"
  309.                                          + 'You have ' + str(balance) + " Willard Points now.")
  310.             elif sign == '0' :
  311.                 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.")
  312.  
  313.         def get_comment_list() :
  314.             with open ("comments.txt", "r") as f :
  315.                 comments_replied_to = f.read()
  316.                 comments_replied_to = comments_replied_to.split("\n")
  317.             return comments_replied_to
  318.         def write_comment_list(replied_to) :
  319.             with open ('comments.txt', 'w') as file :
  320.                 for i in replied_to :
  321.                     file.write (i + '\n')
  322.         def write_crp(crp) :
  323.             with open ('crp.txt', 'w') as file :
  324.                 for i in crp :
  325.                     file.write (i + '\n')
  326.         def get_crp() :
  327.             with open ("crp.txt", "r") as f :
  328.                 crp = f.read()
  329.                 crp = crp.split("\n")
  330.             return crp
  331.         print ('done')
  332.         #NOTES
  333.         # [OK] Test run_bot for a debiting statement in the queue file (which should be
  334.         # in the form of 1234-5 where 1234 is debited 5 WP)
  335.         #
  336.         # [OK] Make sure to add a statement for crediting, too.
  337.         #
  338.         # [OK] Account creation should be quick and easy. The bot should periodically
  339.         # check its inbox for messages with !createacc or !openacc or !newacc and make
  340.         # a new account
  341.         #
  342.         # [OK] The bot should honour !credit [amt], !add, !debit, !sub commands only from
  343.         # authorised users. Namely, NateNate60 and the mods of r/townofsalemgame
  344.         #
  345.         # [OK] The bot should be able to facilitate transactions between users with !transfer
  346.         # between the account holder (VERIFY THIS TO STOP FRAUD) to any other account.
  347.         # This may prove to be tricky to implement.
  348.         #
  349.         # [OK] The bot should honour !bal [acc #] commands from anyone, for any account.
  350.         #
  351.         # [OK] USERNAMES MUST NOT CONTAIN "+" OR "-"
  352.         #
  353.         # [OK] Mark read messages as read.
  354.         #
  355.         # [OK] Make the write_crt and read_crt functions to write the list crt to the file crt.txt.
  356.         #
  357.         # Make a file called crt.txt
  358.         replied_to = get_comment_list()
  359.         r = login()
  360.         blacklist = config.blacklist
  361.         time = datetime.datetime.fromtimestamp(t.time()).strftime('%Y-%m-%d %H:%M:%S')
  362.         print ("Right now, it's " + time)
  363.         while True :
  364.             replied_to = get_comment_list()
  365.             tick += 1
  366.             timen = int(t.time())
  367.             time = datetime.datetime.fromtimestamp(t.time()).strftime('%Y-%m-%d %H:%M:%S')
  368.             queue = retrieve()
  369.             run_bot(r, tick, timen, queue, replied_to, time, blacklist)
  370.             if tick == 1 :
  371.                 print (time + ": The bot has successfully completed one cycle.")
  372.             elif tick == 5 :
  373.                 print (time + ": The bot has successfully completed five cycles.")
  374.             elif tick%10 == 0 and tick < 99 :
  375.                 print (time + ": The bot has successfully completed " + str(tick) + " cycles.")
  376.             elif tick%100 == 0 and tick < 999 :
  377.                 print (time + ": The bot has successfully completed " + str(tick) + " cycles.")
  378.             elif tick%1000 == 0 and tick > 999:
  379.                 print (time + ": The bot has successfully completed " + str(tick) + " cycles.")
  380.  
  381.             t.sleep(60)
  382.     except e.RequestException :
  383.         print ('The bot crashed with RequestException. Restarting...')
  384.         continue
  385.     except e.ResponseException :
  386.         print ('The bot crashed with Error 503: ResponseException. Restarting...')
  387.         continue
  388.     except ValueError :
  389.         print ('The bot crashed with ValueError. Restarting...')
  390.         continue
  391.     except PermissionError :
  392.         print ('The bot crashed with PermissionError. Restarting...')
  393.         continue
  394.     except e.Forbidden :
  395.         print ('The bot crashed because it recieved a 503 HTTP error. Restarting...')
  396.         continue
Advertisement
Add Comment
Please, Sign In to add comment