about summary refs log tree commit diff
diff options
context:
space:
mode:
-rw-r--r--.gitignore1
-rw-r--r--README.md19
-rw-r--r--config.ini6
-rw-r--r--requirements.txt1
-rw-r--r--[-rwxr-xr-x]tracer.py84
-rw-r--r--tracer.service2
6 files changed, 65 insertions, 48 deletions
diff --git a/.gitignore b/.gitignore
index 7f7cccc..6969ff3 100644
--- a/.gitignore
+++ b/.gitignore
@@ -58,3 +58,4 @@ docs/_build/
 # PyBuilder
 target/
 
+venv/
diff --git a/README.md b/README.md
index 86b891f..7ccf485 100644
--- a/README.md
+++ b/README.md
@@ -7,5 +7,22 @@ irc tracery bot
 deps:
 * https://github.com/aparrish/pytracery
 
-edit channels and botnick to test somewhere in irc
+### setup
+
+1. install deps
+    virtualenv -p python3 venv
+    . venv/bin/activate
+    pip install -r requirements.txt
+
+1. adjust config.ini
+1. start the bot
+    venv/bin/python3 tracer.py
+
+### daemonization
+
+1. adjust tracer.service
+1. `mkdir -p ~/.config/systemd/user`
+1. `cp tracer.service ~/.config/systemd/user/`
+1. `systemctl --user daemon-reload`
+1. `systemctl --user enable --now tracer`
 
diff --git a/config.ini b/config.ini
new file mode 100644
index 0000000..e17bb24
--- /dev/null
+++ b/config.ini
@@ -0,0 +1,6 @@
+[irc]
+server = 127.0.0.1
+channels = #bots, #meta, #team
+nick = tracer
+port = 6667
+
diff --git a/requirements.txt b/requirements.txt
new file mode 100644
index 0000000..0c151f0
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1 @@
+tracery==0.1.1
diff --git a/tracer.py b/tracer.py
index 66d183b..bef3ee0 100755..100644
--- a/tracer.py
+++ b/tracer.py
@@ -1,18 +1,26 @@
 #!/usr/bin/env python3
 
-import socket
-import re
 from random import randint, choice
-import sys, os
-import time
-import subprocess
-import tracery
-import traceback
 from tracery.modifiers import base_english
+import configparser
+import glob
 import json
+import os
 import random
+import re
+import socket
+import subprocess
+import sys
+import time
+import traceback
+import tracery
 
 DB = {}
+config = configparser.ConfigParser(
+    converters={"list": lambda x: [i.strip() for i in x.split(",")]}
+)
+config.read("config.ini")
+bot = config["irc"]
 
 
 def grammar(rules):
@@ -35,23 +43,17 @@ def load_rules(path):
 def populate():
     global DB
     DB = {}
-    for subdir in os.listdir("/home"):
-        d = f"/home/{subdir}/.tracery"
-        if os.path.isdir(d):
-            for p in os.listdir(d):
-                rule = d + "/" + p
-                name, ext = os.path.splitext(p)
-                if p.startswith(".") or ext not in (".json", ""): # dot file or not .json or extensionless
-                    continue # skip file
-                # print(p, rule, name)
-                if p in DB:
-                    DB[name].append(grammar(load_rules(rule)))
-                else:
-                    DB[name] = [grammar(load_rules(rule))]
+    for p in glob.glob("/home/*/.tracery/*"):
+        name, ext = os.path.splitext(p)
+        if name.startswith(".") or ext not in (".json", ""):
+            continue
+        if p in DB:
+            DB[name].append(grammar(load_rules(p)))
+        else:
+            DB[name] = [grammar(load_rules(p))]
 
 
 populate()
-print(DB)
 
 
 def generate(rule):
@@ -72,7 +74,6 @@ def shuffle(col):
     a = random.choice(list(col))
     b = random.choice(list(col))
     if "origin" in [a, b]:
-        print("origin discard")
         return col
     col[a], col[b] = col[b], col[a]
     return col
@@ -94,27 +95,18 @@ def fuse(argv):
     return grammar(raw).flatten("#origin#")
 
 
-server = "127.0.0.1"
-channels = ["#bots", "#meta", "#team"]
-if len(sys.argv) > 1:
-    for c in sys.argv[1:]:
-        channels.append("#" + c)
-botnick = "tracer"
-
-
 def rawsend(msg):
     print(msg)
     ircsock.send(f"{msg}\r\n".encode())
 
 
 def send(chan, msg):
-    # This is the send message function, it simply sends messages to the channel.
     rawsend(f"PRIVMSG #{chan} :{msg}")
 
 
 def think(chan, nick, msg):
     words = re.split("[ \t\s]+", msg)
-    if len(words) > 0 and nick != "tracer":
+    if len(words) > 0 and nick != bot["nick"]:
         if words[0] == "!!list":
             res = ""
             for k in DB:
@@ -151,29 +143,28 @@ def think(chan, nick, msg):
 
 if __name__ == "__main__":
     ircsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-    ircsock.connect((server, 6667))  # Here we connect to the server using port 6667
-    rawsend(f"NICK {botnick}")  # here we actually assign the nick to the bot
-    rawsend(f"USER {botnick} 0 * :tracery bot")  # user authentication
+    ircsock.connect((bot["server"], int(bot["port"])))
+    rawsend("NICK %s" % bot["nick"])
+    rawsend("USER %s 0 * :tracery bot" % bot["nick"])
 
     while 1:
-        msg = ircsock.recv(2048).decode().split("\r\n")
-        for ircmsg in msg:
-            print(ircmsg)
+        for msg in ircsock.recv(2048).decode().split("\r\n"):
+            print(msg)
 
-            if "PING" in ircmsg:
-                rawsend(ircmsg.replace("I", "O", 1))
+            if "PING" in msg:
+                rawsend(msg.replace("I", "O", 1))
 
-            if "INVITE" in ircmsg:
-                chan = ircmsg.split(":")[-1]
+            if "INVITE" in msg:
+                chan = msg.split(":")[-1]
                 rawsend(f"JOIN {chan}")
 
-            if "001" in ircmsg:
-                for c in channels:
+            if "001" in msg:
+                for c in bot.getlist("channels"):
                     rawsend(f"JOIN {c}")
-                rawsend(f"MODE {botnick} +B")
+                rawsend("MODE %s +B" % bot["nick"])
 
             m = re.match(
-                ":(?P<nick>[^ ]+)!.*PRIVMSG #(?P<chan>\w+) :(?P<msg>.*)", ircmsg
+                ":(?P<nick>[^ ]+)!.*PRIVMSG #(?P<chan>\w+) :(?P<msg>.*)", msg
             )
             if m and m.groupdict():
                 m = m.groupdict()
@@ -183,3 +174,4 @@ if __name__ == "__main__":
                     print("ERROR" + str(m))
                     print(e)
                     traceback.print_exc()
+
diff --git a/tracer.service b/tracer.service
index e65f3c7..1924bd1 100644
--- a/tracer.service
+++ b/tracer.service
@@ -5,7 +5,7 @@ After=tracer.service
 [Service]
 Type=simple
 WorkingDirectory=/home/ben/workspace/tracer
-ExecStart=/home/ben/workspace/tracer/tracer.py
+ExecStart=/home/ben/workspace/tracer/venv/bin/python3 /home/ben/workspace/tracer/tracer.py
 Restart=always
 RestartSec=5
 StartLimitInterval=60s