playbot/playbot.py

70 lines
2.9 KiB
Python

import argparse
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__":
parser = argparse.ArgumentParser(description='PlayBot - an IRC bot for performing plays')
parser.add_argument('-c', '--channel', default='#playhouse', help='the IRC channel to join')
parser.add_argument('-n', '--nickname', default='PlayBot', help='the nickname for the bot')
parser.add_argument('-s', '--server', default='localhost', help='the IRC server to connect to')
parser.add_argument('-p', '--port', default='6667', help='the port to connect to on the IRC server')
parser.add_argument('-f', '--file', default="play.txt", dest='play_file', help='the file containing the play script')
args = parser.parse_args()
channel = args.channel
nickname = args.nickname
server = args.server
port = int(args.port)
play_file = args.play_file
bot = PlayBot(channel, nickname, server, port, play_file)
bot.start()