nxu/uxnbot.py

80 lines
1.9 KiB
Python
Raw Normal View History

2024-01-23 10:46:23 -05:00
#!/usr/bin/python
import re
import socket
import sys
import tempfile
import uxnrepl
server = "irc.libera.chat"
nick = b"uxnbot"
2024-01-23 10:47:12 -05:00
channel = b"#uxn"
2024-01-23 10:46:23 -05:00
sandbox = tempfile.mkdtemp(prefix='uxnrepl')
irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def send(msg):
print('>>> %r' % msg)
irc.send(msg + b'\r\n')
def recv():
msg = irc.recv(2040)
print('<<< %r' % msg)
return msg
print("connecting to: %s" % server)
irc.connect((server, 6667))
send(b"USER %s %s %s :bot for testing uxntal code" % (nick, nick, nick))
send(b"NICK %s" % nick)
#send("PRIVMSG nickserv :iNOOPE\r\n")
send(b"JOIN %s" % channel)
ping_re = re.compile(br'PING (.+)$')
chan_msg_re = re.compile(br':([^!]+)![^ ]+ PRIVMSG ([^ ]+) :' + nick + br': (.*)$')
priv_msg_re = re.compile(br':([^!]+)![^ ]+ PRIVMSG ' + nick + br' :(.*)$')
ignored = {b'rst', b'wst', b''}
def evaluate(msg):
2024-01-23 10:51:53 -05:00
output = uxnrepl.execute(msg.decode('utf-8'), sandbox=sandbox)
2024-01-23 10:46:23 -05:00
lines = [s.strip() for s in output.split(b'\n')]
interesting = [s for s in lines if s not in ignored]
result = b' | '.join(interesting)
print('*** executing %r gave %r -> %r -> %r' % (msg, output, interesting, result))
return result
while True:
text = recv()
m = ping_re.match(text)
if m:
2024-01-23 11:02:21 -05:00
send(b'PONG %s' % m.group(1).strip())
2024-01-23 10:46:23 -05:00
continue
m = chan_msg_re.match(text)
if m and m.group(2) == channel:
user = m.group(1)
msg = m.group(3).strip()
result = evaluate(msg)
send(b'PRIVMSG %s :%s: %s' % (channel, user, result))
continue
m = priv_msg_re.match(text)
if m:
user = m.group(1)
msg = m.group(2).strip()
result = evaluate(msg)
send(b'PRIVMSG %s :%s' % (user, result))
continue
# message from user in channel:
# b':d_m!~d_m@user/d-m/x-5109880 PRIVMSG #uxn :uxnbot: hello\r\n'
# keep alive:
# b'PING :mercury.libera.chat\r\n'
# private message
# b':d_m!~d_m@user/d-m/x-5109880 PRIVMSG uxnbot :hello\r\n'