changeset 2777:1b37a020ba4b

<ThatOtherPerson> cp -r d/DCPUToolBot-master t
author HackBot
date Mon, 22 Apr 2013 16:08:04 +0000
parents d9d90d9001c6
children 677bbaa9d86c
files t/DCPUToolBot-master/.gitattributes t/DCPUToolBot-master/.gitignore t/DCPUToolBot-master/.gitmodules t/DCPUToolBot-master/README.md t/DCPUToolBot-master/dcpu.py t/DCPUToolBot-master/dcpubot.py t/DCPUToolBot-master/irc.py t/DCPUToolBot-master/sample_config.py
diffstat 8 files changed, 624 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/t/DCPUToolBot-master/.gitattributes	Mon Apr 22 16:08:04 2013 +0000
@@ -0,0 +1,22 @@
+# Auto detect text files and perform LF normalization
+* text=auto
+
+# Custom for Visual Studio
+*.cs     diff=csharp
+*.sln    merge=union
+*.csproj merge=union
+*.vbproj merge=union
+*.fsproj merge=union
+*.dbproj merge=union
+
+# Standard to msysgit
+*.doc	 diff=astextplain
+*.DOC	 diff=astextplain
+*.docx diff=astextplain
+*.DOCX diff=astextplain
+*.dot  diff=astextplain
+*.DOT  diff=astextplain
+*.pdf  diff=astextplain
+*.PDF	 diff=astextplain
+*.rtf	 diff=astextplain
+*.RTF	 diff=astextplain
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/t/DCPUToolBot-master/.gitignore	Mon Apr 22 16:08:04 2013 +0000
@@ -0,0 +1,165 @@
+#################
+## Eclipse
+#################
+
+*.pydevproject
+.project
+.metadata
+bin/
+tmp/
+*.tmp
+*.bak
+*.swp
+*~.nib
+local.properties
+.classpath
+.settings/
+.loadpath
+
+# External tool builders
+.externalToolBuilders/
+
+# Locally stored "Eclipse launch configurations"
+*.launch
+
+# CDT-specific
+.cproject
+
+# PDT-specific
+.buildpath
+
+
+#################
+## Visual Studio
+#################
+
+## Ignore Visual Studio temporary files, build results, and
+## files generated by popular Visual Studio add-ons.
+
+# User-specific files
+*.suo
+*.user
+*.sln.docstates
+
+# Build results
+[Dd]ebug/
+[Rr]elease/
+*_i.c
+*_p.c
+*.ilk
+*.meta
+*.obj
+*.pch
+*.pdb
+*.pgc
+*.pgd
+*.rsp
+*.sbr
+*.tlb
+*.tli
+*.tlh
+*.tmp
+*.vspscc
+.builds
+*.dotCover
+
+## TODO: If you have NuGet Package Restore enabled, uncomment this
+#packages/
+
+# Visual C++ cache files
+ipch/
+*.aps
+*.ncb
+*.opensdf
+*.sdf
+
+# Visual Studio profiler
+*.psess
+*.vsp
+
+# ReSharper is a .NET coding add-in
+_ReSharper*
+
+# Installshield output folder
+[Ee]xpress
+
+# DocProject is a documentation generator add-in
+DocProject/buildhelp/
+DocProject/Help/*.HxT
+DocProject/Help/*.HxC
+DocProject/Help/*.hhc
+DocProject/Help/*.hhk
+DocProject/Help/*.hhp
+DocProject/Help/Html2
+DocProject/Help/html
+
+# Click-Once directory
+publish
+
+# Others
+[Bb]in
+[Oo]bj
+sql
+TestResults
+*.Cache
+ClientBin
+stylecop.*
+~$*
+*.dbmdl
+Generated_Code #added for RIA/Silverlight projects
+
+# Backup & report files from converting an old project file to a newer
+# Visual Studio version. Backup files are not needed, because we have git ;-)
+_UpgradeReport_Files/
+Backup*/
+UpgradeLog*.XML
+
+
+
+############
+## Windows
+############
+
+# Windows image file caches
+Thumbs.db
+
+# Folder config file
+Desktop.ini
+
+
+#############
+## Python
+#############
+
+*.py[co]
+
+# Packages
+*.egg
+*.egg-info
+dist
+build
+eggs
+parts
+bin
+var
+sdist
+develop-eggs
+.installed.cfg
+
+# Installer logs
+pip-log.txt
+
+# Unit test / coverage reports
+.coverage
+.tox
+
+#Translations
+*.mo
+
+#Mr Developer
+.mr.developer.cfg
+
+# Mac crap
+.DS_Store
+
+config.py
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/t/DCPUToolBot-master/.gitmodules	Mon Apr 22 16:08:04 2013 +0000
@@ -0,0 +1,3 @@
+[submodule "cryptolib"]
+	path = cryptolib
+	url = https://github.com/HyperVerseSystems/cryptolib.git
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/t/DCPUToolBot-master/README.md	Mon Apr 22 16:08:04 2013 +0000
@@ -0,0 +1,7 @@
+# DCPUToolBot
+To use, copy sample_config.js to config.js and set the settings.
+
+Make sure the DCPU Toolchain is installed and then run `python dcputoolbot.py`
+
+## Dependencies
+You need the [DCPU Toolchain](http://dcputoolcha.in/) installed and in your PATH to run.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/t/DCPUToolBot-master/dcpu.py	Mon Apr 22 16:08:04 2013 +0000
@@ -0,0 +1,175 @@
+import subprocess
+import tempfile
+import os
+import re
+import time
+import threading
+
+def link(files):
+    out_fd, out_fname = tempfile.mkstemp()
+    os.fdopen(out_fd).close()
+
+    process_flags = ["dtld", "-o", out_fname, "-k", "none"]
+    filenames = []
+    for file in files:
+        fd, fname = tempfile.mkstemp()
+	f = os.fdopen(fd, 'wb')
+	f.write(file)
+	f.close()
+        filenames.append(fname)
+        process_flags.append(fname)
+
+    proc = subprocess.Popen(process_flags, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+    res, err = proc.communicate()
+
+    for file in filenames:
+        os.remove(file)
+
+    final = open(out_fname)
+    res = final.read()
+    final.close()
+
+    return (res, err)
+
+def assemble_file(code, binary=False):
+    code = '\n'.join(code.split('/'))
+    code = '\n'.join(code.split('\\'))
+
+    process_flags = ["dtasm", "-o", "-", "-"]
+    if binary:
+        process_flags.append("--binary")
+    process = subprocess.Popen(process_flags, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+    results = process.communicate(code)
+    res = results[0]
+    err = results[1]
+    return (res, err)
+
+def assemble_binary(code):
+
+    code = '///'.join(code.split('\\\\\\'))
+    files = code.split('///')
+
+    if len(files) > 1:
+        file_binaries = []
+	err = ""
+        for file in files:
+            assembled = assemble_file(file)
+            if assembled[0]:
+                file_binaries.append(assembled[0])
+            if assembled[1]:
+                err += assembled[1]
+        res, link_err = link(file_binaries)
+        err += link_err
+	return (res, err)
+    else:
+        return assemble_file(code, True)
+
+def assemble(code):
+    res, err = assemble_binary(code)
+    words = []
+    i = 0
+    while i < len(res) /  2:
+        byte_one = ord(res[2*i])
+        byte_two = ord(res[2*i+1])
+        print "Bytes:", byte_one, byte_two
+        word = "0x%04x" % ((byte_one << 8) + byte_two)
+        words.append(word)
+        i += 1
+    print "Assembly attempted"
+    return (words, err)
+
+def timeout(p):
+    if p.poll() == None:
+        p.kill()
+
+hex_re = re.compile("^0x[0-9a-fA-F]+")
+disasm_re = re.compile("0x[0-9a-fA-F]{4} \(0x[0-9a-fA-F]{4}\): *(>>>)? *(.+)\r?\n?")
+null_re = re.compile("<null>")
+
+def disassemble(binary_str):
+    byte_strings = binary_str.split(",")
+
+    print byte_strings
+
+    fd, filename = tempfile.mkstemp()
+    file = os.fdopen(fd, 'wb')
+    
+    for byte in byte_strings:
+        byte = byte.strip()
+        if hex_re.match(byte):
+            byte = int(byte, 16)
+        else:
+            byte = int(byte)
+        file.write(chr(byte >> 8))
+        file.write(chr(byte & 0xff))
+
+    file.close()
+
+    length = hex(len(byte_strings))
+    print length
+
+    args = 'dtdb -c "disasm 0x0 ' + length + '" ' + filename
+    print args
+
+    proc = subprocess.Popen(args, stderr=subprocess.PIPE, shell=True)
+    proc.wait()
+
+    res = proc.stderr.read()
+
+    matches = disasm_re.findall(res)
+
+    res = []
+
+    for match in matches:
+        if not null_re.match(match[1]):
+            res.append(match[1].replace('\r', ''))
+
+    response = ' / '.join(res)
+
+    os.remove(filename)
+    return response
+
+register_re = re.compile(r"([A-Z]{1,2}):\s*0x([\dA-F]+)")
+
+def execute(code):
+    binary, err = assemble_binary(code)
+    if err and not ("warning" in err):
+        return ("", err)
+
+    num_words = len(binary) / 2
+
+    fd, filename = tempfile.mkstemp()
+    file = os.fdopen(fd, 'wb')
+    file.write(binary)
+    file.close()
+
+    start = time.time()
+    proc = subprocess.Popen(['dtemu', '-t', '-h', filename], stderr=subprocess.PIPE)
+    t = threading.Timer(5, timeout, [proc])
+    while proc.poll() == None:
+        if time.time() - start > 5:
+	    proc.kill()
+    final = time.time() - start
+
+    err = proc.stderr.read()
+
+    err_lines = err.split("\n")
+
+    for i in range(11):
+        err_lines.pop()
+
+    errors = "\n".join(err_lines)
+
+    os.remove(filename)
+
+    register_matches = register_re.findall(err)
+
+    changed_registers = []
+
+    for match in register_matches:
+        if match[1] != "0000":
+            changed_registers.append(match[0] + ":0x" + match[1])
+    registers = ', '.join(changed_registers)
+    ms = final * 1000
+    response = "[" + str(num_words) + " words][" + registers + "][%dms]" % round(ms)
+    return (response, errors)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/t/DCPUToolBot-master/dcpubot.py	Mon Apr 22 16:08:04 2013 +0000
@@ -0,0 +1,119 @@
+#!/usr/bin/env python
+import irc
+import config
+import subprocess
+import dcpu
+import random
+
+irc.connect(config.host, config.port, config.nick, config.password)
+irc.join(config.chan)
+
+def onAssemble(nick, user, host, chan, matches):
+    print "Assembling"
+    print matches.group()
+    print matches.group(1)
+    binary, errors = dcpu.assemble(matches.group(1))
+
+    if binary:
+        irc.privmsg(nick, chan, ', '.join(binary))
+    if errors:
+        irc.privmsg(nick, chan, errors)
+
+irc.onPrivmsg(">>>(.+)", onAssemble)
+
+def onDisassemble(nick, user, host, chan, matches):
+    print "Disassembling"
+    print matches.group()
+    print matches.group(1)
+    code = dcpu.disassemble(matches.group(1))
+
+    if code:
+        irc.privmsg(nick, chan, code)
+
+irc.onPrivmsg("<<<(.+)", onDisassemble)
+
+def onExecute(nick, user, host, chan, matches):
+    executed, errors = dcpu.execute(matches.group(1))
+
+    if executed:
+        irc.privmsg(nick, chan, executed)
+    if errors:
+        irc.privmsg(nick, chan, errors)
+
+irc.onPrivmsg(">>([^>].+)", onExecute)
+
+def onHex(nick, user, host, chan, matches):
+    converted = 0
+    
+    if matches.group(1) == "0b":
+        converted = hex(int(matches.group(2), 2))
+    else:
+        converted = hex(int(matches.group(2)))
+
+    irc.privmsg(nick, chan, converted)
+
+irc.onPrivmsg(r"^hex\((0b)?(\d+)\)", onHex)
+
+def onDec(nick, user, host, chan, matches):
+    converted = 0
+    
+    if matches.group(1) == "0b":
+        converted = str(int(matches.group(2), 2))
+    elif matches.group(1) == "0x":
+        converted = str(int(matches.group(2), 16))
+    else:
+        converted = str(int(matches.group(2)))
+
+    irc.privmsg(nick, chan, converted)
+
+irc.onPrivmsg(r"^dec\((0b|0x)?([0-9a-fA-F]+)\)", onDec)
+
+def onBin(nick, user, host, chan, matches):
+    converted = 0
+
+    if matches.group(1) == "0x":
+        converted = bin(int(matches.group(2), 16))
+    else:
+        converted = bin(int(matches.group(2), 16))
+
+    irc.privmsg(nick, chan, converted)
+
+irc.onPrivmsg(r"^bin\((0x)?([0-9a-fA-F]+)\)", onBin)
+
+def onStinks(nick, user, host, chan, matches):
+    messages = ["So do you!!!", "Shut up.", "You smell even worse.", "You really shouldn't be talking."]
+    irc.privmsg(nick, chan, choice(messages))
+
+irc.onPrivmsg(".*" + config.nick + r":?( ?is| you)? stink(ing|s)?.*", onStinks)
+
+def onReload(nick, user, host, chan, matches):
+    if(host == "unaffiliated/thatotherpersony"):
+        subprocess.call(["git", "pull", "origin", "master"]);
+        irc.privmsg(nick, chan, "Pulled latest changes from GitHub. Restarting.")
+        exit()
+    elif(host == "unaffiliated/quu"):
+        irc.privmsg(nick, chan, "wat. Quu. derp.\nReally?\nInitializing spambot mode. >:D")
+    else:
+        irc.privmsg(nick, chan, "No. I don't wanna!")
+
+irc.onMsgToMe(".*reload.*", onReload)
+
+def onTest(nick, user, host, chan, matches):
+    irc.privmsg(nick, chan, "lolololol wat derp. ping Quu! ping mrout! Why not!")
+
+irc.onMsgToMe(".*test.*", onTest)
+
+def onRudeness(nick, user, host, chan, matches):
+    irc.privmsg(nick, chan, "Why don't you?")
+
+irc.onMsgToMe(".*stfu.*", onRudeness)
+
+def onHello(nick, user, host, chan, matches):
+    irc.privmsg(nick, chan, "Howdy!")
+
+irc.onMsgToMe(".*hello.*", onHello)
+
+def onSup(nick, user, host, chan, matches):
+    irc.privmsg(nick, chan, "I'm fine. How about you?")
+
+irc.onMsgToMe(".*(how.*you|sup|what.*up).*", onSup)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/t/DCPUToolBot-master/irc.py	Mon Apr 22 16:08:04 2013 +0000
@@ -0,0 +1,128 @@
+import socket
+import re
+import threading
+import sys
+
+command_handlers = []
+privmsg_handlers = []
+msgtome_handlers = []
+
+def command(command, params):
+    print "Command: (\"" + command + "\", \"" + params + ")"
+    msg = command + " " + params
+    print msg
+    server.sendall(msg + "\r\n")
+
+def privmsg(nickIn, chan, msg):
+
+    lines = msg.split("\n")
+    if len(lines) > 1:
+        for line in lines:
+            privmsg(nickIn, chan, line)
+    elif msg != "":
+        response = ""
+
+        if chan == nick:
+            response += nickIn + " :" + msg
+        else:
+            response += chan + " :" + nickIn + ": " + msg
+
+        command("PRIVMSG", response)
+
+def handlePing(nick, user, host, chan, params):
+    print params
+    command('PONG', params)
+
+def handleMsgToMe(nick, user, host, chan, params):
+    for regex, callback in msgtome_handlers:
+        matches = regex.match(params)
+        if matches:
+            callback(nick, user, host, chan, params)
+
+def handlePrivmsg(nickIn, user, host, chan, params):
+    for regex, callback in privmsg_handlers:
+        matches = regex.match(params)
+        if matches:
+            callback(nickIn, user, host, chan, matches)
+            
+    global nick
+    matches = re.match("^" + nick + "[:, ]?(.*)", params)
+    if matches:
+        handleMsgToMe(nickIn, user, host, chan, matches.group(1))
+
+    if chan == nick:
+        handleMsgToMe(nickIn, user, host, chan, params)
+
+class EventHandler(threading.Thread):
+    def run(self):
+        while True:
+            try:
+                message = server.recv(4096)
+                if message == '':
+                    server.close()
+
+                handleCommand(message)
+            except Exception as e:
+               print e.message
+
+def connect(host, port, nickIn="TestBot", password="", name="dcpubot", realname="DCPU Bot"):
+    global nick
+    nick = nickIn
+    
+    global server
+    server = socket.create_connection((host, port))
+
+    server.sendall("PASS " + password + "\r\n")
+    server.sendall("NICK " + nick + "\r\n")
+    server.sendall("USER " + name + " 0 * :" + realname + "\r\n")
+
+    onCommand('PING', handlePing)
+    onCommand('PRIVMSG', handlePrivmsg)
+
+    eventHandler = EventHandler()
+    eventHandler.start()
+
+def join(channels):
+    print channels
+    if type(channels) is str:
+        print "JOIN " + channels
+        server.sendall("JOIN " + channels + "\r\n")
+    else:
+        for channel in channels:
+            print "JOIN " + channel
+            server.sendall("JOIN " + channel + "\r\n")
+
+message_re = re.compile("^((:([^!@ ]+)(!([^@ ]+))?(@([^ ]+))? ?)?([^ ]+)?)? ?((?!:)[^ ]*)[^:]*(:(.*))?")
+
+def handleCommand(message):
+    print "Message: " + message
+    message_data = message_re.match(message)
+
+    if message_data:
+    
+        nick = message_data.group(3)
+        user = message_data.group(5)
+        host = message_data.group(7)
+        command = message_data.group(8)
+        chan = message_data.group(9)
+        params = message_data.group(11)
+    
+        for com, callback in command_handlers:
+            if com == command:
+                callback(nick, user, host, chan, params)
+    else:
+        print "Message could not be parsed: " + message
+
+def onCommand(command, callback):
+    global command_handlers
+    command_handlers.append((command, callback))
+
+def onPrivmsg(reg, callback):
+    global privmsg_handlers
+    regex = re.compile(reg)
+    privmsg_handlers.append((regex, callback))
+
+def onMsgToMe(reg, callback):
+    global msgtome_handlers
+    regex = re.compile(reg)
+    msgtome_handlers.append((regex, callback))
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/t/DCPUToolBot-master/sample_config.py	Mon Apr 22 16:08:04 2013 +0000
@@ -0,0 +1,5 @@
+host = "irc.freenode.net"
+port = 6667
+chan = ["#pieislikemyfavoritefood"]
+nick = "DCPUPieBot"
+password = "hahahahayouactuallythoughtyouwouldfindmyrealpassword"