Add unix domain socket to echo messages

This commit is contained in:
Matt Arnold 2022-03-08 18:10:11 -05:00
parent 6ffac6077c
commit a0b1f7f4c5
1 changed files with 53 additions and 3 deletions

View File

@ -11,8 +11,18 @@ import json
import sqlite3
import logging
from daemonize import Daemonize
import threading
from queue import Queue, Empty
NODEAMON = True
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logger.propagate = True
fh = logging.FileHandler("bot.log", "w")
fh.setLevel(logging.DEBUG)
logger.addHandler(fh)
keep_fds = [fh.stream.fileno()]
logging.basicConfig(filename='bot.log', encoding='utf-8', level=logging.DEBUG)
class NullDevice:
def write(self,s):
@ -26,8 +36,34 @@ with open('config.json') as f:
config = json.loads(jld)
uds_addr = config['uds']
try:
os.unlink(uds_addr)
except OSError:
if os.path.exists(uds_addr):
raise
def uds_thread(in_q):
uds = socket.socket(socket.AF_UNIX,socket.SOCK_STREAM)
uds.bind(uds_addr)
uds.listen(1)
while True:
connection, client_address = uds.accept()
try:
data = connection.recv(255)
print(str(type(data)))
if data:
#pds = data.strip()
#pds = bytes(pds.strip(LINEEND))
connection.sendall(bytes("ACK" + LINEEND, 'UTF-8'))
in_q.put_nowait(data)
else:
connection.sendall(bytes("NACK" + LINEEND))
continue
except Exception as e:
logging.exception(str(e))
# Need to pass the IRCBot class a socket the reason it doesn't do this itself is
# so you can set up TLS or not as you need it
# These provide good defaults. But your milage may vary
@ -76,6 +112,9 @@ def generate_response(person, message):
def do_main_loop():
irc = do_connect()
q = Queue()
x = threading.Thread(target=uds_thread, args=(q,))
x.start()
while True:
try:
@ -88,10 +127,21 @@ def do_main_loop():
r = generate_response(text[0],text[2][1])
if r is not None:
irc.send_privmsg(config['channel'],r)
try:
d = q.get_nowait()
irc.send_privmsg(config['channel'], d.decode("UTF-8"))
except Empty:
printred("Empty")
except IRCError as e:
logging.error(e)
sys.exit(1)
pid = "bot.pid"
daemon = Daemonize(app="theodebot", pid=pid, action=do_main_loop)
daemon.start()
if not NODEAMON:
daemon = Daemonize(app="theodebot", pid=pid,keep_fds=keep_fds, action=do_main_loop)
daemon.start()
else:
do_main_loop()