playbot/actors.py

59 lines
2.3 KiB
Python

import irc.bot
import time
import re
class PlayBot(irc.bot.SingleServerIRCBot):
def __init__(self, channel, nickname, server, port, play_file):
irc.bot.SingleServerIRCBot.__init__(self, [(server, port)], nickname, nickname)
self.channel = channel
self.play_file = play_file
self.lines = []
self.read_play_file()
def read_play_file(self):
with open(self.play_file, 'r') as f:
for line in f:
self.lines.append(line.strip())
def on_welcome(self, connection, event):
connection.join(self.channel)
def on_join(self, connection, event):
for line in self.lines:
# If the line contains a colon, extract the character name and use it as the nickname
if ":" in line:
# Replace any non-alphanumeric characters with an empty string
character = line.split(": ")[0].replace(" ", "_")
character = re.sub(r"[^a-zA-Z0-9]", "", character)
# Otherwise, set the nickname to "NARRATOR"
else:
character = "NARRATOR"
# Set the bot's nickname to the character name
connection.nick(character)
# Send the text of the line without the character name prefix to the channel
text = line.split(": ")[1] if ":" in line else line
# Split the message into multiple messages if it's too long
limit = 400
if len(text) > limit:
messages = [text[i:i+limit] for i in range(0, len(text), limit)]
else:
messages = [text]
# Send each message with the appropriate pause
for message in messages:
connection.privmsg(self.channel, message)
words = len(message.split())
pause = max((words / 200)*60, 4) # divide by reading speed of middle schooler, with a minimum
time.sleep(pause) # pause for calculated time
# Set the bot's nickname back to its original nickname
connection.nick(self._nickname)
if __name__ == "__main__":
channel = "#playhouse"
nickname = "PlayBot"
server = "localhost"
port = 6667
play_file = "play.txt"
bot = PlayBot(channel, nickname, server, port, play_file)
bot.start()