Advertisement
oldecrow

DiceRoll.py

Aug 8th, 2013
267
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 12.14 KB | None | 0 0
  1. #!/usr/bin/python
  2. import praw
  3. import time
  4. import re
  5. import random
  6. import traceback
  7. import datetime
  8. import sys
  9. import logging
  10.  
  11. def characterRoll(dicetoroll, results, sumlist):
  12.     for i in range(6):
  13.         for r in range(int(dicetoroll)):
  14.             results.append(random.randint(1,6))
  15.         if len(results) == 3:
  16.             sumlist.append(results[0]+results[1]+results[2])
  17.         else:
  18.             sortresults = results
  19.             sortresults = sorted(sortresults)
  20.             sumlist.append(sortresults[1]+sortresults[2]+sortresults[3])
  21.         values.append(results)
  22.         results = []
  23.     for p in range(len(values)):
  24.         try:
  25.         #print rolls[p][0]
  26.             if p == 0 and int(dicetoroll) == 3:
  27.                 #string = "for %sd%s:  \n%s" % (rolls[p][0],rolls[p][1],str(values[p]).strip('\[\]'))
  28.                 string = "for %sd6:  \n%s = %s" % (dicetoroll,str(values[p]).strip('\[\]'),sumlist[p])
  29.             elif int(dicetoroll) == 3:
  30.                 #string = string+"  \n"+"for %sd%s:  \n%s" % (rolls[p][0],rolls[p][1],str(values[p]).strip('\[\]'))
  31.                 string = string+"  \n"+"for %sd6:  \n%s = %s" % (dicetoroll,str(values[p]).strip('\[\]'),sumlist[p])
  32.             elif p == 0 and int(dicetoroll) == 4:
  33.                 string = "for %sd6:  \n%s sum with lowest roll dropped %s" % (dicetoroll,str(values[p]).strip('\[\]'),sumlist[p])
  34.             elif int(dicetoroll) == 4:
  35.                 string = string+"  \n"+"for %sd6:  \n%s sum with lowest roll dropped %s" % (dicetoroll,str(values[p]).strip('\[\]'),sumlist[p])
  36.         except:
  37.             traceback.print_exc(file=sys.stdout)
  38.             logging.warning('%s\nFailed to print rolls',traceback.print_exc())
  39.             break
  40.     return string
  41.            
  42. COMMENT_TEMPLATE = "Here are your dice rolls!"
  43. BOT_DISCLAIMER = "^I'm ^a ^bot! ^PM ^me ^if ^something ^seems ^off."
  44. logging.basicConfig(filename='/var/log/DiceRollBot.log', format='%(asctime)s %(levelname)s:%(message)s', datefmt='%I:%M:%S%p %Y-%m-%d', level=logging.INFO)
  45. results = []
  46. values = []
  47. user_agent = ("Random Dice Roll for r/rpg by /u/oldecrow")
  48. r = praw.Reddit(user_agent=user_agent)
  49. phrase = re.compile('\[r(\d*)d(\d*)([+*-/]?)(\d*?)(t?)(\d*?)\]')
  50. character = re.compile('\[char([34])d6\]')
  51. #phrase = re.compile(r"""
  52. #(?P<command>        # start command group
  53. #\[                  # '[' - opening bracket syntax
  54. #r                   # 'r' - rolling dice syntax
  55. #(?P<count>\d{1,2})  # 0-99 - number of dice
  56. #d                   # 'd' - rolling dice syntax
  57. #(?P<sides>\d{1,5})  # 0-99999 - number of sides
  58. #(                   # start optional modifier group
  59. #   (?P<operator>[\-+/*])   # '-', '+', '/', '*' - operator
  60. #   (?P<modifier>\d{1,5})   # 0-99999 - number to apply with operator
  61. #)?                  # end optional modifier group
  62. #\]                  # ']' - closing bracket syntax
  63. #)                   # end command group
  64. #""", re.VERBOSE) # this amazingly awesome regex brought to you by /u/Durinthal
  65. #suggestion = re.compile('[sS]uggestion')
  66. #roll = re.compile('[rR]oll')
  67. #link = re.compile('[lL]ink')
  68. #urladdress = re.compile('https?:\/\/www\.reddit\.com\/r\/rpg\/comments\/.*\/[^/]*\/.*')
  69. sumlist = []
  70. rollingsum=0
  71. results = []
  72. values = []
  73. success = ''
  74. successlist = []
  75. dicetoroll, faces, mod, modnumber, threshtest, threshhold = ('','','','', False,'a')
  76. limit = 500
  77. print "logging in..."
  78. ########################################################################
  79. r.login('DiceRollBot','REDACTED') ####REMOVE WHEN POSTING CODE#######
  80. ########################################################################
  81. while True:
  82.     timeStamp = str(datetime.datetime.now()).split('.')[0]
  83.     print timeStamp
  84.     logging.info('Starting New Process')
  85.     try:
  86.         f = open('LatestDone.conf','r')
  87.         try:
  88.             comment_id = f.read()
  89.             comment_id = comment_id.rstrip()
  90.             logging.info('Old ID: %s', comment_id)
  91.             controlNumber = 1
  92.         except:
  93.             traceback.print_exc(file=sys.stdout)
  94.             f.close()
  95.             logging.critical('Couldn\'t read file! Terminating!')
  96.             sys.exit("Couldn't read file")
  97.         finally:
  98.             f.close()
  99.  
  100. #       for letter in r.get_unread(limit=None):
  101. #           letter.body
  102. #       subreddit = r.get_subreddit('bottest')
  103.         subreddit = r.get_subreddit('rpg')
  104.         for comment in subreddit.get_comments(limit=limit):
  105.             if controlNumber == 1:
  106.                 latestID = comment.id
  107.                 controlNumber+=1763432
  108.             print "...fetching..."
  109.             logging.debug('latest:  %s',latestID)
  110.             logging.debug('current: %s',comment.id)
  111.             values = []
  112.             if character.search(comment.body) and comment.id != comment_id:
  113.                 dicetoroll = character.search(comment.body).group(1)
  114.                 iterations = 6*int(dicetoroll)
  115.                 print "replying..."
  116.                 logging.info('replying')
  117.                 string = characterRoll(dicetoroll, results, sumlist)
  118.                 comment.reply(COMMENT_TEMPLATE+"  \n"+string+"  \n"+BOT_DISCLAIMER)
  119.                 sumlist = []
  120.                 #print COMMENT_TEMPLATE+"  \n"+string+"  \n"+BOT_DISCLAIMER
  121.             elif phrase.search(comment.body) and comment.id != comment_id:
  122.                 try:
  123.                     print "rolling..."
  124.                     rolls = phrase.findall(comment.body)
  125.                     #print rolls
  126.                     for q in range(len(rolls)):
  127.                         dicetoroll, faces, mod, modnumber, threshtest,threshhold = rolls[q]
  128.                         if threshtest == 't':
  129.                             threshtest = True
  130.                         elif threshtest != 't' and threshhold != '' and 'b':
  131.                             modnumber = threshhold
  132.                             threshhold = 'a'
  133.                             threshtest = False
  134.                         else:
  135.                             threshtest = False
  136.                         if int(rolls[q][0])<=20:
  137.                             for i in range(int(rolls[q][0])):
  138.                                 print rolls[q]
  139.                                 number = random.randint(1,int(rolls[q][1]))
  140.                                 if mod == '+':
  141.                                     number += int(modnumber)
  142.                                 elif mod == '*':
  143.                                     number *= int(modnumber)
  144.                                 elif mod == '%':
  145.                                     number = number/float(rolls[q][1])
  146.                                     number = number * 100
  147.                                     number = str(number)+'%'
  148.                                 elif mod == '-':
  149.                                     number -= int(modnumber)
  150.                                 elif mod == '/':
  151.                                     try:
  152.                                         number /= int(modnumber)
  153.                                     except ZeroDivisionError:
  154.                                         results.append('it makes me sad when you divide by zero :(')
  155.                                         logging.warning('Divide by zero')
  156.                                         break
  157.                                 #if threshhold != 'a' and threshhold != 'b':
  158.                                 if threshtest == True:
  159.                                     if number >= int(threshhold):
  160.                                         success = "roll succeeded!"
  161.                                         threshhold = 'b'
  162.                                         threshtest = False
  163.                                     elif number < int(threshhold):
  164.                                         success = "roll failed!"
  165.                                 elif threshhold == 'a':
  166.                                     success = ''
  167.                                 elif threshhold == 'b':
  168.                                     pass
  169.                                 results.append(number)
  170.                             for n in range(len(results)):
  171.                                 rollingsum += int(results[n])
  172.                             sumlist.append(rollingsum)
  173.                             successlist.append(success)
  174.                             values.append(results)
  175.                             results = []
  176.                             success = ''
  177.                             threshhold = 'a'
  178.                             rollingsum = 0
  179.                             mod == None
  180.                         else:
  181.                             values.append('I can\'t do more than 20 dice at a time :\ ')
  182.                             mod == None
  183.                     if len(values) <= 15:
  184.                         for p in range(len(values)):
  185.                             try:
  186.                                 #print rolls[p][0]
  187.                                 if int(rolls[p][0]) > 1:
  188.                                     if p == 0:
  189.                                         #string = "for %sd%s:  \n%s" % (rolls[p][0],rolls[p][1],str(values[p]).strip('\[\]'))
  190.                                         string = "for %sd%s:  \n%s = %s  \n%s" % (rolls[p][0],rolls[p][1],str(values[p]).strip('\[\]'),sumlist[p], str(successlist[p]))
  191.                                     else:
  192.                                         #string = string+"  \n"+"for %sd%s:  \n%s" % (rolls[p][0],rolls[p][1],str(values[p]).strip('\[\]'))
  193.                                         string = string+"  \n"+"for %sd%s:  \n%s = %s  \n%s" % (rolls[p][0],rolls[p][1],str(values[p]).strip('\[\]'),sumlist[p], str(successlist[p]))
  194.                                 elif int(rolls[p][0]) == 1:
  195.                                     if p == 0:
  196.                                         #string = "for %sd%s:  \n%s" % (rolls[p][0],rolls[p][1],str(values[p]).strip('\[\]'))
  197.                                         string = "for %sd%s:  \n%s  \n%s" % (rolls[p][0],rolls[p][1],str(values[p]).strip('\[\]'), str(successlist[p]))
  198.                                     else:
  199.                                         #string = string+"  \n"+"for %sd%s:  \n%s" % (rolls[p][0],rolls[p][1],str(values[p]).strip('\[\]'))
  200.                                         string = string+"  \n"+"for %sd%s:  \n%s  \n%s" % (rolls[p][0],rolls[p][1],str(values[p]).strip('\[\]'), str(successlist[p]))
  201.                             except:
  202.                                 break
  203.                     else:
  204.                         p = 0
  205.                         while p <= 15:
  206.                             try:
  207.                                 if int(rolls[p][0]) > 1:
  208.                                     if p == 0:
  209.                                         #string = "for %sd%s:  \n%s" % (rolls[p][0],rolls[p][1],str(values[p]).strip('\[\]'))
  210.                                         string = "for %sd%s:  \n%s = %s  \n%s" % (rolls[p][0],rolls[p][1],str(values[p]).strip('\[\]'),sumlist[p], str(successlist[p]))
  211.                                     else:
  212.                                         #string = string+"  \n"+"for %sd%s:  \n%s" % (rolls[p][0],rolls[p][1],str(values[p]).strip('\[\]'))
  213.                                         string = string+"  \n"+"for %sd%s:  \n%s = %s  \n%s" % (rolls[p][0],rolls[p][1],str(values[p]).strip('\[\]'),sumlist[p], str(successlist[p]))
  214.                                 elif int(rolls[p][0]) == 1:
  215.                                     if p == 0:
  216.                                         #string = "for %sd%s:  \n%s" % (rolls[p][0],rolls[p][1],str(values[p]).strip('\[\]'))
  217.                                         string = "for %sd%s:  \n%s  \n%s" % (rolls[p][0],rolls[p][1],str(values[p]).strip('\[\]'), str(successlist[p]))
  218.                                     else:
  219.                                         #string = string+"  \n"+"for %sd%s:  \n%s" % (rolls[p][0],rolls[p][1],str(values[p]).strip('\[\]'))
  220.                                         string = string+"  \n"+"for %sd%s:  \n%s  \n%s" % (rolls[p][0],rolls[p][1],str(values[p]).strip('\[\]'), str(successlist[p]))
  221.                                 if p==15:
  222.                                     string = string+"  \n"+"maximum of 15 roll commands per comment reached."
  223.                                 p+=1
  224.                             except:
  225.                                 break
  226.                     print "replying..."
  227.                     logging.info('replying')
  228.                     comment.reply(COMMENT_TEMPLATE+"  \n"+string+"  \n"+BOT_DISCLAIMER)
  229.                     sumlist = []
  230.                     #print COMMENT_TEMPLATE+"  \n"+string+"  \n"+BOT_DISCLAIMER
  231.                 except:
  232.                     print "ERROR!:\n"+comment.body
  233.                     logging.warning("Comment:\n%s\n\nError:\n%s",comment.body,traceback.print_exc())
  234.                     traceback.print_exc(file=sys.stdout)
  235.             #else:
  236.                 #print "nothing"
  237.             elif comment.id == comment_id:
  238.                 f = open('LatestDone.conf', 'w')
  239.                 try:
  240.                     f.write(latestID)
  241.                     print "configuring..."
  242.                     controlNumber += 42
  243.                 except:
  244.                     traceback.print_exc(file=sys.stdout)
  245.                     f.close()
  246.                     logging.critical('Couldn\t write LatestDone.conf! Terminating!')
  247.                     sys.exit("Couldn't write file")
  248.                 finally:
  249.                     f.close()
  250.                     print'done!'
  251.                     results = []
  252.                     success = ''
  253.                     threshhold = 'a'
  254.                     rollingsum = 0
  255.                     mod == None
  256.                     print "sleeping..."
  257.                     limit = 20
  258.                     logging.info('sleeping 10 minutes')
  259.                     time.sleep(600)
  260.                     break
  261.             time.sleep(1)
  262.             mod = None
  263.             limit = 20
  264.             rollingsum = 0
  265.     except KeyboardInterrupt:
  266.         f = open('LatestDone.conf', 'w')
  267.         logging.warning('caught KeyboardInterrupt')
  268.         try:
  269.             f.write(latestID)
  270.             print "configuring..."
  271.             controlNumber += 42
  272.         except:
  273.             traceback.print_exc(file=sys.stdout)
  274.             f.close()
  275.             logging.critical('Couldn\t write LatestDone.conf! Terminating!')
  276.             sys.exit("Couldn't write file")
  277.         finally:
  278.             f.close()
  279.             logging.info('Shutdown')
  280.             sys.exit('done!')
  281.    
  282. LICENSE = """
  283. Copyright (c) 2013, /u/oldecrow
  284. All rights reserved.
  285.  
  286. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
  287.  
  288. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  289. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  290. Neither the name of the program nor /u/DiceRollBot nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
  291. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."""
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement