small refactor to use configs

This commit is contained in:
Ben Harris 2020-02-24 10:47:57 -05:00
parent c6c2d34b3c
commit c9aa98d225
6 changed files with 65 additions and 48 deletions

1
.gitignore vendored
View File

@ -58,3 +58,4 @@ docs/_build/
# PyBuilder
target/
venv/

View File

@ -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`

6
config.ini Normal file
View File

@ -0,0 +1,6 @@
[irc]
server = 127.0.0.1
channels = #bots, #meta, #team
nick = tracer
port = 6667

1
requirements.txt Normal file
View File

@ -0,0 +1 @@
tracery==0.1.1

84
tracer.py Executable file → Normal file
View File

@ -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()

View File

@ -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