about summary refs log tree commit diff
diff options
context:
space:
mode:
authorBen Harris <ben@tilde.team>2020-03-11 14:35:46 -0400
committerBen Harris <ben@tilde.team>2020-03-11 14:35:46 -0400
commitb61f5c43219dd0616f71f5b85b0d5dc44b8ce420 (patch)
treea6d7f710b0828945cdf099fe482ddfa9cb5c0ef8
parentf7c8740729bca3b668db68297560bfc8236a502d (diff)
use irctokens library
-rw-r--r--requirements.txt1
-rw-r--r--tooter.py93
2 files changed, 59 insertions, 35 deletions
diff --git a/requirements.txt b/requirements.txt
index ae6c2bc..b8f0f66 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,2 +1,3 @@
 Mastodon.py==1.5.0
 emoji==0.5.4
+irctokens==0.5.1
diff --git a/tooter.py b/tooter.py
index c08c614..360a134 100644
--- a/tooter.py
+++ b/tooter.py
@@ -2,6 +2,7 @@
 
 from mastodon import Mastodon
 import emoji
+import irctokens
 import json
 import os
 import re
@@ -15,26 +16,31 @@ def masto_from_json(conf):
         client_id=conf["client_id"],
         client_secret=conf["client_secret"],
         access_token=conf["access_token"],
-        api_base_url=conf["base_url"]
+        api_base_url=conf["base_url"],
     )
 
 
-def rawsend(msg):
-    print(msg)
-    ircsock.send(f"{msg}\r\n".encode())
+def _send(line):
+    print(f"> {line.format()}")
+    e.push(line)
+    while e.pending():
+        e.pop(s.send(e.pending()))
 
 
 def send(chan, msg):
-    rawsend(f"PRIVMSG #{chan} :{msg}")
+    _send(irctokens.format("PRIVMSG", [chan, msg]))
 
 
-def eventloop(chan, nick, msg):
-    words = re.split("[ \t\s]+", msg)
+def think(line):
+    chan = line.params.pop(0)
+    words = line.params[0].split(" ")
+    nick = irctokens.Hostmask(line.source).nickname
+
     if len(words) > 0 and nick != botnick:
         if words[0] == "!toot":
             status = emoji.emojize(" ".join(words[1:]), use_aliases=True)
             print(f"{status} posted by {nick}")
-            if chan == "team":
+            if chan == "#team":
                 res = tildeteam.toot(status)
             else:
                 res = tildeverse.toot(status)
@@ -43,7 +49,10 @@ def eventloop(chan, nick, msg):
         elif words[0] == "!source":
             send(chan, "https://tildegit.org/ben/tooter")
         elif words[0] == "!botlist" or words[0] == "!toothelp":
-            send(chan, "helo i can send toots from irc: @tildeverse@tilde.zone - from @tildeteam from the #team channel)")
+            send(
+                chan,
+                "helo i can send toots from irc: @tildeverse@tilde.zone - from @tildeteam from the #team channel)",
+            )
 
 
 # do setup
@@ -70,31 +79,45 @@ with open(os.path.join(path, "tildeteam.json"), "r") as f:
     tildeteam = masto_from_json(f)
 
 if __name__ == "__main__":
-    ircsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-    ircsock.connect((config["address"], config["port"]))
-    rawsend(f"NICK {botnick}")
-    rawsend(f"USER {botnick} 0 * :mastodon tooter")
-
-    while 1:
-        for msg in ircsock.recv(2048).decode().split("\r\n"):
-            print(msg)
-
-            if "PING" in msg:
-                rawsend(msg.replace("I", "O", 1))
-
-            if "INVITE" in msg:
-                chan = msg.split(":")[-1]
-                rawsend(f"JOIN {chan}")
-
-            if "001" in msg:
-                for c in channels:
-                    rawsend(f"JOIN {c}")
-                rawsend(f"MODE {botnick} +B")
-                if account is not None:
-                    rawsend("SQUERY NickServ IDENTIFY %s %s" % (account["username"], account["password"]))
+    d = irctokens.StatefulDecoder()
+    e = irctokens.StatefulEncoder()
+    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+    s.connect((config["address"], config["port"]))
+
+    _send(irctokens.format("USER", [config["botnick"], "0", "*", "mastodon tooter"]))
+    _send(irctokens.format("NICK", [config["botnick"]]))
+
+    while True:
+        lines = d.push(s.recv(1024))
 
-            m = re.match(":(?P<nick>[^ ]+)!.*PRIVMSG #(?P<chan>\w+) :(?P<msg>.*)", msg)
-            if m and m.groupdict():
-                m = m.groupdict()
-                eventloop(m["chan"], m["nick"], m["msg"])
+        if lines == None:
+            print("! disconnected")
+            break
 
+        for line in lines:
+            print(f"< {line.format()}")
+
+            if line.command == "PING":
+                _send(irctokens.format("PONG", line.params))
+
+            elif line.command == "001":
+                _send(irctokens.format("MODE", [botnick, "+B"]))
+                if account is not None:
+                    _send(
+                        irctokens.format(
+                            "SQUERY",
+                            [
+                                "NickServ",
+                                "IDENTIFY",
+                                account["username"],
+                                account["password"],
+                            ],
+                        )
+                    )
+                _send(irctokens.format("JOIN", channels))
+
+            elif line.command == "INVITE":
+                _send(irctokens.format("JOIN", line.params))
+
+            elif line.command == "PRIVMSG":
+                think(line)