Advertisement
BeamNG_IRC

Python script reader - Libraries needed

Mar 3rd, 2014
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 15.55 KB | None | 0 0
  1. """
  2. By Dan Jones - 2014
  3. Contents of 'critical.fag' (needed script, without it, it will refuse everything)
  4. _______________________________________
  5. # critical example script
  6. [green];
  7. //
  8. Multi line comment
  9. everything here is ignored
  10. \\
  11. print; Hello, World!
  12. _______________________________________
  13. """
  14. from Tkinter import *
  15. import tkFileDialog
  16. import autopy
  17. import re
  18. import winsound
  19. import win32com
  20. import win32com.client
  21. import ctypes
  22. import pyttsx
  23. import Tkinter
  24. import os
  25. import time
  26. import tkMessageBox
  27. import calendar
  28. import socket
  29. from random import *
  30. import sys
  31. class WTCW: # Huge thanks to Thomas Fischer (tdev) for this
  32.     WRAPPERS = ['{', '}']
  33.     STD_INPUT_HANDLE = -10 ; STD_OUTPUT_HANDLE= -11 ; STD_ERROR_HANDLE = -12
  34.     FG_BLUE = 0x01 ; FG_GREEN= 0x02 ; FG_RED  = 0x04 ; FG_INTENSITY = 0x08 ; BG_BLUE = 0x10 ; BG_GREEN= 0x20 ; BG_RED  = 0x40 ; BG_INTENSITY = 0x80
  35.     colors = {'r': FG_RED, 'g':FG_GREEN, 'b':FG_BLUE, 'R':BG_RED, 'G':BG_GREEN, 'B':BG_BLUE, 'i':FG_INTENSITY, 'I':BG_INTENSITY, 'w':FG_RED|FG_GREEN|FG_BLUE }
  36.     def _get_csbi_attributes(self):
  37.         import struct
  38.         csbi = ctypes.create_string_buffer(22) ; res = ctypes.windll.kernel32.GetConsoleScreenBufferInfo(self.handle, csbi) ; assert res
  39.         (bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
  40.         return wattr
  41.     def __init__(self, stream, defColor = ''):
  42.         self.stream = stream ; self.defColor = self._parseColor(defColor)
  43.         self.handle = ctypes.windll.kernel32.GetStdHandle(self.STD_OUTPUT_HANDLE)
  44.         self.reset  = self._get_csbi_attributes()
  45.     def __del__(self): self.resetColor()
  46.     def _parseColor(self, str):
  47.         colval = 0
  48.         for c in str:
  49.             if c.lower() == 'x':
  50.                 self.resetColor()
  51.                 break
  52.             colval |= self.colors[c]
  53.         return colval
  54.     def write(self, data):
  55.         if self.defColor != 0:
  56.             self.setColour(defColor)
  57.         parts = data.split(self.WRAPPERS[0])
  58.         for part in parts:
  59.             f = part.find(self.WRAPPERS[1])
  60.             if f != -1:
  61.                 self.setColour(self._parseColor(part[0:f]))
  62.                 self.stream.write(part[f+len(self.WRAPPERS[1]):])
  63.             else:
  64.                 self.stream.write(part)
  65.             self.stream.flush()
  66.         #self.resetColor() #uncomment this to reset the color after every invocation
  67.     def __getattr__(self, attr): return getattr(self.stream, attr)
  68.     def setColour(self, col): ctypes.windll.kernel32.SetConsoleTextAttribute(self.handle, col)
  69.     def resetColor(self): ctypes.windll.kernel32.SetConsoleTextAttribute(self.handle, self.reset)
  70. sys.stdout = WTCW(sys.stdout)
  71. def main():
  72.     global commands, color, substring, line, reason, noerror, mlcomment, arg, com, file, script, file_path # globalise for use outside of main()
  73.     debug = 0 # switch to 1 for debugging information
  74.     if os.path.isfile("critical.fag") == False: # before anything check for this script, if it doesn't exist, make it
  75.         file = open("critical.fag", "ab+") # lets make the file
  76.         file.write('# critical example script\n')
  77.         file.write('[green];\n')
  78.         file.write('//\n')
  79.         file.write('Multi line comment\n')
  80.         file.write('everything here is ignored\n')
  81.         file.write('\\\\\n') # needed due to escape characters
  82.         file.write('print; Hello, World!')
  83.         file.close()
  84.         print 'created default script'
  85.     mlcomment = 0
  86.     file_path = 'null'
  87.     color = ''
  88.     commands = ['msgbox','print','//','\\','[debug]','speak','beep','made','test','mouse','mouse_snap','wait','length','cal','getsubstring','[green]','binary','[red]','[blue]','list','send','randint','input','randstring','commands']
  89.     noerror = 0 # allows error script to be raised
  90.     args = 0
  91.     arg = str(sys.argv) # command line argument
  92.     try:
  93.         file = 'null' # set to null for the error script
  94.         arg = arg.split(" ")[1] # command line argument
  95.         arg = arg.replace("]","") # command line argument
  96.         arg = arg.replace("'","") # command line argument
  97.         args = 1
  98.         if arg[-4:] != '.fag':
  99.             print 'Unknown file format, attempting to open..'
  100.     except:
  101.         args = 0 # disables argument if none given
  102.     line = 0
  103.     run = 0 # run == 1 if no script found
  104.     if args == 0:
  105.         try:
  106.              # FAG = File Application Generator
  107.             file = open("critical.fag") # default script, if all else fails, open this
  108.             master = Tk() # start open file dialog
  109.             master.withdraw() # hiding tkinter window
  110.             file_path = tkFileDialog.askopenfilename(title="Open Script - (*.FAG)", filetypes=[("File App Generator",".FAG")]) # what kind of dialog?
  111.             if file_path != "":
  112.                 file = open((file_path)) # final file
  113.             else:
  114.                 window = Tkinter.Tk()
  115.                 window.wm_withdraw()
  116.                 tkMessageBox.showinfo(title='Error', message='No script selected, running default script')
  117.                 master.quit()
  118.         except:
  119.             reason = 'Internal script reading error\n\nDoes the default script exist?' # theoretically, this should never occur
  120.             com = 'null error'
  121.             arg = ' internal' # space at begining is critical!
  122.             print '\n' # for looks
  123.             error()
  124.  
  125.         split = ['(',')','"'] # never used, might be useful oneday
  126.         arg = '', str(file) # space at the start is critical!
  127.     else:
  128.         try:
  129.             file = open((arg)[1:])
  130.         except:
  131.             arg = arg.replace('-','')
  132.             reason = 'Unable to locate script: ' + arg # had to do it this way, otherwise it's a tulip!
  133.             noerror = 1 # avoids calling error on a script line
  134.             error()
  135.     while 1: # script loop starts here
  136.         line = int((line)) + 1 # set line to line + 1 = current line
  137.         com = file.readline() # set com to contain current lines content
  138.         if com.isspace():
  139.             ignore()
  140.         if not com: # the following code executes once parsing of the file is done
  141.             if run == 0:
  142.                 print '{ri}***********************************'
  143.                 print 'Error: No script found to execute!'
  144.                 print '***********************************'
  145.             break # ends the script, there has to be a better way!
  146.         if com.find('//') != -1:
  147.             mlcomment = 1
  148.         if com.find('\\') != -1:
  149.                 mlcomment = 0 # makes the script start reading script again!
  150.                 com = '# multi lined comment' # really a hack, it is horrible script lol
  151.         if mlcomment == 1:
  152.                 com = '# multil lined comment' # really a hack, it is horrible script lol
  153.         try:
  154.             comment = com[0]
  155.             prefix = com.split(';')[0]
  156.             reason = 'Unknown command: "' + prefix + '"' # again, had to do it this way
  157.             leng = len((prefix)) + 1
  158.             script = com.split(';')[1]
  159.             if prefix not in commands:
  160.                 error()                
  161.         except:
  162.             if comment.find('#') != -1 or com.isspace():
  163.                 ignore()
  164.             else:
  165.                 error()
  166.         if comment.find('#') != -1:
  167.             code = 3
  168.         else:
  169.             com = com[(leng):]
  170.             if prefix == 'list':
  171.                 run = 1 # tells the parser that a valid command was found
  172.                 count = 0
  173.                 for x in com:
  174.                     if script[0].isspace():
  175.                         script = script[1:]
  176.                     else:
  177.                         count = count + 1
  178.                         if script[-1:] == '=':
  179.                             script.replace('=', '')
  180.                             if x == '=':
  181.                                 count = count - 1
  182.                             print x, count  
  183.                         else:
  184.                             print x
  185.             parse = script
  186.             getsubstring(parse) # get substring
  187.             script = re.sub(r'\(.+?\)\s?','',script) # remove ()
  188.             if prefix == 'print':
  189.                 run = 1  
  190.                 if script[0].isspace():
  191.                     script = script[1:]
  192.                 print script                
  193.             if prefix == 'msgbox':
  194.                 run = 1  
  195.                 if script[0].isspace():
  196.                     script = script[1:]
  197.                 try:
  198.                     title = script.split(',')[0]
  199.                     msg = script.split(',')[1]
  200.                     window = Tkinter.Tk()
  201.                     window.wm_withdraw()
  202.                     tkMessageBox.showinfo(title=(title), message=(msg))
  203.                 except:
  204.                     reason = 'Syntax error, try: msgbox; title,message'  
  205.                     error()            
  206.             if prefix == 'send':
  207.                 run = 1  
  208.                 if script[0].isspace():
  209.                     script = script[1:]
  210.                     send = script
  211.                     s = socket.socket()
  212.                     host = socket.gethostname()
  213.                     port = 1234
  214.                     s.bind((host, port))
  215.                     print 'waiting to accept client...'
  216.                     s.listen(5)
  217.                     c, addr = s.accept()
  218.                     c.send(str((send)))
  219.                     s.close()
  220.                     print 'sent!'                
  221.             if prefix == 'input':
  222.                 run = 1
  223.                 if script[0].isspace():
  224.                     script = script[1:]
  225.                 com = script
  226.                 input = raw_input((com))
  227.                 print 'your input:', input            
  228.             if prefix == 'length':
  229.                 run = 1
  230.                 if script[0].isspace():
  231.                     script = script[1:]
  232.                 size = len((script)) - 1
  233.                 print 'string length:', size                
  234.             if prefix == 'randint':
  235.                 run = 1  
  236.                 if script[0].isspace():
  237.                     script = script[1:]
  238.                 try:
  239.                     low = script.split('-')[0]
  240.                     high = script.split('-')[1]
  241.                     num = randint(int((low)),int((high)))
  242.                     print num
  243.                 except:
  244.                     reason = 'Syntax error, try: randint; 0-100'
  245.                     error()
  246.             if prefix == 'commands':
  247.                 run = 1  
  248.                 print commands
  249.             if prefix == 'randstring':
  250.                 run = 1  
  251.                 if script[0].isspace():
  252.                     script = script[1:]
  253.                 try:
  254.                     print os.urandom(int(script)) # spices things up, not the same old try: except: crap
  255.                 except:
  256.                     reason = 'String found, you must use an integer (number)'
  257.                     error()
  258.             if prefix == '[red]':
  259.                 print '{ri}' # sets color to red
  260.                 color = '{ri}'
  261.             if prefix == '[green]':
  262.                 print '{gi}' # sets color to green         # RGB colors
  263.                 color = '{gi}'
  264.             if prefix == '[blue]':
  265.                 print '{bi}' # sets color to blue
  266.                 color = '{bi}'
  267.             if prefix == '[debug]':
  268.                 if debug == 0:
  269.                     debug = 1
  270.                 else:
  271.                     debug = 0
  272.             if prefix == 'cal':
  273.                 run = 1  
  274.                 if script[0].isspace(): # if script[0] == only space do the following
  275.                     script = script[1:]
  276.                 try:
  277.                     year = script.split(',')[0]
  278.                     day = script.split(',')[1]
  279.                     cal = calendar.month(int((year)),int((day)))
  280.                     print cal
  281.                 except:
  282.                     reason = 'Calendar error, try: cal; 2015,9'
  283.                     error()      
  284.             if debug == 1: # debug information
  285.                 if script == '' or script.isspace():
  286.                     script = '(no script found)'
  287.                 if prefix == '[debug]':
  288.                     ignore()
  289.                 else:
  290.                     print 'line:', str((line)) + ' prefix:', prefix + ' script:', script
  291.             if prefix == 'binary':
  292.                 run = 1  
  293.                 if script[0].isspace():
  294.                     script = script[1:]
  295.                 binary = bin(reduce(lambda x, y: 256*x+y, (ord(c) for c in (script)), 0))
  296.                 print binary
  297.             if prefix == 'getsubstring': # used in debugging
  298.                 run = 1  
  299.                 if script.find('(') != -1 and script.find (')') != -1:
  300.                     parse = script
  301.                     getsubstring(parse)
  302.                     print substring
  303.                 else:
  304.                     reason = 'no () found to get substring'
  305.                     error()
  306.             if prefix == 'wait':
  307.                 run = 1  
  308.                 if script[0].isspace(): # if script = only space do the following
  309.                     script = script[1:]
  310.                 try:
  311.                     time.sleep(int(script))
  312.                 except:
  313.                     reason = 'Wait error, try: wait; 5'
  314.                     error()
  315.             if prefix == 'mouse':
  316.                 run = 1
  317.                 try:
  318.                     x = script.split(',')[0]
  319.                     y = script.split(',')[1]
  320.                     autopy.mouse.smooth_move(int((x)),int((y)))
  321.                 except:
  322.                     reason = 'invalid X,Y'
  323.                     error()
  324.             if prefix == 'mouse_snap':
  325.                 run = 1
  326.                 try:
  327.                     x = script.split(',')[0]
  328.                     y = script.split(',')[1]
  329.                     autopy.mouse.move(int((x)),int((y)))
  330.                 except:
  331.                     reason = 'invalid X,Y'
  332.                     error()
  333.             if prefix == 'made':
  334.                 run = 1
  335.                 shell = win32com.client.Dispatch('WScript.Shell')
  336.                 shell.Run('notepad')
  337.                 time.sleep(0.1)
  338.                 shell.AppActivate('notepad')
  339.                 shell.SendKeys("Made by Dan Jones, for Windows", 0)
  340.                 shell.SendKeys("{Enter}", 0)
  341.                 shell.SendKeys("{F5}", 0)   # F5 prints the time/date
  342.             if prefix == 'beep':
  343.                 run = 1
  344.                 try:
  345.                     x = script.split(',')[0]
  346.                     y = script.split(',')[1]
  347.                     winsound.Beep(int((x)),int((y)))
  348.                 except:
  349.                     reason = 'beep error'
  350.                     error()
  351.             if prefix == 'speak':
  352.                 run = 1
  353.                 engine = pyttsx.init()
  354.                 engine.say((script))
  355.                 engine.runAndWait()
  356.             script = '' # fixes repeated prints of script - always at bottom
  357. def getsubstring(string):
  358.     substring = string[string.find('(')+1:string.find(')')] # parse () inside a command for example getsubstring((parse))
  359. def ignore():
  360.     pass # ignores everything, used mainly for comments
  361. def error():
  362.     print '{ri}'
  363.     if noerror == 0:
  364.         print 'File:{gi}', (arg)[1:], '{ri}Line:{gi}', str((line)) + '{ri}\n\n', com
  365.     reason.replace('\n', '') # i don't know why, but a \n occurs in (reason)
  366.     print '************************************\n'
  367.     print reason, '\n'
  368.     print '************************************'
  369.     sys.exit('Script Halted') # comment this line to continue the script when an error is found
  370. main() # starts the main script
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement