|
#!/usr/bin/env python |
|
import signal |
|
import sys |
|
import ssl |
|
import argparse |
|
import re |
|
import threading |
|
import irc.client |
|
import jaraco.logging |
|
import pytesseract |
|
from PIL import Image |
|
from PIL import ImageGrab |
|
|
|
# Nuclear button because the thread logic is a bit naff |
|
def signal_handler(sig, frame): |
|
print('Bye!') |
|
sys.exit(0) |
|
|
|
signal.signal(signal.SIGINT, signal_handler) |
|
|
|
current_level_code = None |
|
kill = False |
|
|
|
# Periodically |
|
def scanForLevelCode(): |
|
global current_level_code |
|
# Capture the screen and run it through the OCR |
|
image_string = pytesseract.image_to_string(ImageGrab.grab()) |
|
# Try and extract a level code from it |
|
m = re.search('(\w\w\w-\w\w\w-\w\w\w)', image_string) |
|
if m: |
|
current_level_code = m.group(0) |
|
print("New level code found") |
|
print(m.group(0)) |
|
if not kill: |
|
threading.Timer(1, scanForLevelCode).start() |
|
|
|
scanForLevelCode() |
|
|
|
def on_connect(connection, event): |
|
if irc.client.is_channel(channel): |
|
connection.join(channel) |
|
return |
|
main_loop(connection) |
|
|
|
def on_join(connection, event): |
|
main_loop(connection) |
|
|
|
def main_loop(connection): |
|
connection.privmsg(channel, "Mario Helper, ready and waiting!") |
|
|
|
def on_pubmsg(connection, event): |
|
sender = event.source.split('!')[0] |
|
text = event.arguments[0].strip() |
|
|
|
# Returns latest seen level |
|
if (text == "!level"): |
|
if (current_level_code is None): |
|
connection.privmsg(channel, "No level available.") |
|
else: |
|
connection.privmsg(channel, "Mario Helper: " + current_level_code) |
|
|
|
# Disconnects the bot, which will in turn end the program |
|
# Only accepted if user requesting it is the bot user itself. |
|
if (text == "!disconnect" and sender == nickname): |
|
connection.privmsg(channel, "Mario Helper disconnecting, see you later!") |
|
connection.quit() |
|
|
|
def on_disconnect(connection, event): |
|
# Stop the image processing thread from running. |
|
global kill |
|
kill = True |
|
# Seeya! |
|
raise SystemExit() |
|
|
|
server = "irc.chat.twitch.tv" |
|
port = 6697 |
|
nickname = "your_twitch_name" |
|
channel = "#your_twitch_name" |
|
oauth = "your_oauth_key" |
|
|
|
def main(): |
|
parser = argparse.ArgumentParser() |
|
jaraco.logging.add_arguments(parser) |
|
jaraco.logging.setup(parser.parse_args()) |
|
ssl_factory = irc.connection.Factory(wrapper=ssl.wrap_socket) |
|
reactor = irc.client.Reactor() |
|
try: |
|
c = reactor.server().connect(server, port, nickname, "oauth:"+oauth, connect_factory=ssl_factory) |
|
except irc.client.ServerConnectionError: |
|
print(sys.exc_info()[1]) |
|
raise SystemExit(1) |
|
|
|
c.add_global_handler("welcome", on_connect) |
|
c.add_global_handler("join", on_join) |
|
c.add_global_handler("disconnect", on_disconnect) |
|
c.add_global_handler("pubmsg", on_pubmsg) |
|
|
|
reactor.process_forever() |
|
|
|
if __name__ == "__main__": |
|
main() |