diff --git a/Code/irc/banterbot.py b/Code/irc/banterbot.py index ce16a9f..9c48ed0 100755 --- a/Code/irc/banterbot.py +++ b/Code/irc/banterbot.py @@ -13,10 +13,6 @@ import subprocess import time import datetime -import formatter -import get_users -import mentions -import pretty_date import inflect from rhymesWith import getRhymes from rhymesWith import rhymeZone @@ -37,7 +33,7 @@ parser.add_option( "-s", "--server", dest="server", - default="127.0.0.1", + default="127.0.0.1:6667", help="the server to connect to", metavar="SERVER", ) @@ -63,20 +59,12 @@ parser.add_option( p = inflect.engine() -def ping(pong): - ircsock.send("PONG {}\n".format(pong)) - - -def sendmsg(chan, msg): - ircsock.send("PRIVMSG " + chan + " :" + msg + "\n") - - def joinchan(chan): - ircsock.send("JOIN " + chan + "\n") + ircsock.send("JOIN " + chan + "\r\n") def hello(): - ircsock.send("PRIVMSG " + channel + " :Hello!\n") + util.sendmsg(ircsoc, channel, "Hello!") def score_banter(channel, user, messageText): @@ -109,42 +97,27 @@ def score_banter(channel, user, messageText): msg = "" if score > 100: - msg = ( - "Truely " - + random.choice(compliment).capitalize() - + ", " - + random.choice(names) - + "! That was some #banter! You earned a " - + str(score) - + " for that!" + msg = "Truely {}, {}! That was some #banter! You earned a {} for that!".format( + random.choice(compliment).capitalize(), random.choice(names), score ) elif score > 50: - msg = ( - random.choice(compliment).capitalize() - + " #banter! You get a " - + str(score) - + " from me!" + msg = "{} #banter! You get a {} from me!".format( + random.choice(compliment).capitalize(), score ) elif score > 10: - msg = ( - random.choice(["acceptible", "reasonable", "passable"]).capitalize() - + " #banter. You get a " - + str(score) + msg = "{} #banter. You get a {}".format( + random.choice(["acceptible", "reasonable", "passable"]).capitalize(), score ) else: - msg = ( - "That " - + random.choice( + msg = "That {} #banter, {}. I'll give you a {}. Maybe try again?".format( + random.choice( ["was hardly", "was barely", "wasn't", "won't pass for", "was awful"] - ) - + " #banter" - + random.choice([", lad", ", lah", ", boy", "", ""]) - + ". I'll give you a " - + str(score) - + ". Maybe try again?" + ), + random.choice(["lad", "lah", "boy", ""]), + score, ) - ircsock.send("PRIVMSG " + channel + " :" + msg + "\n") + util.sendmsg(ircsock, channel, msg) def get_new_banter(channel, user): @@ -174,14 +147,8 @@ def get_new_banter(channel, user): word = word[:end] + "t" + word[end:] else: # replace the letter with 'b' word = word[:end] + "t" + word[end + 1 :] - ircsock.send( - "PRIVMSG " - + channel - + " :" - + user - + ": Here, why don't you try '" - + word - + "'?\n" + util.sendmsg( + ircsock, channel, "{} : Here, why don't you try '{}'?".format(user, word) ) @@ -194,26 +161,18 @@ def get_rhymes(channel, user, text): word = random.choice(words.readlines()).strip("\n") rhymes = rhymeZone(word) if len(rhymes) == 0: - ircsock.send( - "PRIVMSG " - + channel - + " :" - + user - + ": Couldn't find anything that rhymes with '" - + word - + "' :(\n" + util.sendmsg( + ircsock, + channel, + "{}: Couldn't find anything that rhymes with '{}' :(".format(user, word), ) else: - ircsock.send( - "PRIVMSG " - + channel - + " :" - + user - + ": Here, these words rhyme with '" - + word - + "': " - + ", ".join(rhymes) - + "\n" + util.sendmsg( + ircsock, + channel, + "{}: Here, these words rhyme with '{}': {}".format( + user, word, ", ".join(rhymes) + ), ) @@ -224,68 +183,48 @@ def define_word(channel, user, text): word = text.split(" ")[1] defs = defWord(word) if len(defs) == 0: - ircsock.send( - "PRIVMSG " - + channel - + " :" - + user - + ": Couldn't find the definition of '" - + word - + "' :(\n" + util.sendmsg( + ircsock, + channel, + "{}: Couldn't find the definition of '{}' :(".format(user, word), ) elif isinstance(defs, list): for entry in defs: - ircsock.send( - "PRIVMSG " - + channel - + " :" - + user - + ": Define '" - + word - + "'" - + entry[0:400] - + "\n" + util.sendmsg( + ircsock, channel, "{} : Define '{}' {}".format(user, word, entry[0:400]) ) else: - ircsock.send( - "PRIVMSG " - + channel - + " :" - + user - + ": Define '" - + word - + "'" - + defs[0:400] - + "\n" + util.sendmsg( + ircsock, channel, "{} : Define '{}' {}".format(user, word, defs[0:400]) ) def make_rainbow(channel, user, text): rbword = makeRainbow(text[9:]) - ircsock.send("PRIVMSG " + channel + " :" + rbword + "\n") + util.sendmsg(ircsock, channel, rbword) def get_welch(channel): - ircsock.send("PRIVMSG " + channel + " :" + welch.get_thing()[0:400] + "\n") + util.sendmsg(ircsock, channel, welch.get_thing()[0:400]) def get_evil(channel): evilThing = evil.get_thing() for line in [evilThing[i : i + 400] for i in range(0, len(evilThing), 400)]: - ircsock.send("PRIVMSG " + channel + " :" + line + "\n") + util.sendmsg(ircsock, channel, line) def get_tumble(url, channel): tumble = tumblr.tumble(url) for line in [tumble[i : i + 400] for i in range(0, len(tumble), 400)]: - ircsock.send("PRIVMSG " + channel + " :" + line + "\n") + util.sendmsg(ircsock, channel, line) def get_xkcd(channel, text): links = xkcdApropos.xkcd(text[6:]) joined_links = ", ".join(links) for line in [joined_links[i : i + 400] for i in range(0, len(joined_links), 400)]: - ircsock.send("PRIVMSG " + channel + " :" + line + "\n") + util.sendmsg(ircsock, channel, line) # res = xkcdApropos.xkcd(text[6:]) # ircsock.send("PRIVMSG " + channel + " :" + res + "\n") @@ -293,12 +232,8 @@ def get_xkcd(channel, text): def get_wphilosophy(channel, text): steps = wikiphilosophy.get_philosophy_lower(text[17:]) if not steps: - ircsock.send( - "PRIVMSG " - + channel - + " :Couldn't find a wikipedia entry for " - + text - + "\n" + util.sendmsg( + ircsock, channel, "Couldn't find a wikipedia entry for {}".format(text) ) else: joined_steps = " > ".join(steps) @@ -307,24 +242,24 @@ def get_wphilosophy(channel, text): for line in [ joined_steps[i : i + 400] for i in range(0, len(joined_steps), 400) ]: - ircsock.send("PRIVMSG " + channel + " :" + line + "\n") + util.sendmsg(ircsock, channel, line) def figlet(channel, text): if not text: - ircsock.send("PRIVMSG " + channel + " :No text given. :(\n") + util.sendmsg(ircsock, channel, "No text given. :(") else: lines = subprocess.Popen( ["figlet", "-w140"] + text.split(" "), shell=False, stdout=subprocess.PIPE ).stdout.read() for line in lines.split("\n"): - ircsock.send("PRIVMSG " + channel + " :" + line + "\n") + util.sendmsg(ircsock, channel, line) time.sleep(0.4) # to avoid channel throttle due to spamming def toilet(channel, text): if not text: - ircsock.send("PRIVMSG " + channel + " :No text given. :(\n") + util.sendmsg(ircsock, channel, "No text given. :(") else: lines = subprocess.Popen( ["toilet", "-w140", "--irc"] + text.split(" "), @@ -332,24 +267,24 @@ def toilet(channel, text): stdout=subprocess.PIPE, ).stdout.read() for line in lines.split("\n"): - ircsock.send("PRIVMSG " + channel + " :" + line + "\n") + util.sendmsg(ircsock, channel, line) time.sleep(0.4) # to avoid channel throttle due to spamming def get_acronym(channel, text): if not text: - ircsock.send("PRIVMSG " + channel + " :No text given :(\n") + util.sendmsg(ircsock, channel, "No text given :(") else: defs = acronymFinder.get_acros(text, True, True) for d in defs[0:5]: # only the first five. they are already sorted by 'score' - ircsock.send("PRIVMSG " + channel + " :" + d.encode("utf-8") + "\n") + util.sendmsg(ircsock, channel, d.encode("utf-8")) if len(defs) > 5: - ircsock.send("PRIVMSG " + channel + " :" + defs[-1] + "\n") + util.sendmsg(ircsock, channel, defs[-1]) def get_whosaid(channel, text): if not text: - ircsock.send("PRIVMSG " + channel + " :No text given :(\n") + util.sendmsg(ircsock, channel, " :No text given :(") else: result = whoSaid(text) date = datetime.date.fromtimestamp(result["timecutoff"]) @@ -368,46 +303,37 @@ def get_whosaid(channel, text): result["data"][1][0], result["data"][1][1], ) - ircsock.send("PRIVMSG " + channel + " :" + msg + ".\n") + util.sendmsg(ircsock, channel, msg) def get_notice(user, channel): - ircsock.send("CNOTICE " + user + " " + channel + " :Notice me sempai!\n") + ircsock.send("CNOTICE " + user + " " + channel + " :Notice me senpai!\r\n") def get_water(user, channel, msg, botnick): if msg.find(botnick) == 0: - ircsock.send("PRIVMSG " + channel + " :Fight me, " + user + "!\n") + util.sendmsg(ircsock, channel, "Fight me, {}!".format(user)) def mug_off(channel): - ircsock.send("PRIVMSG " + channel + " :u want some of this, m8?\n") + util.sendmsg(ircsock, channel, "u want some of this, m8?") def rollcall(channel): - ircsock.send( - "PRIVMSG " - + channel - + " :U wot m8? I score all the top drawer #banter and #bantz on this channel! \ - Find new top-shelf banter with !newbanter, !rhymes, and !define. \ - Look up things with !acronym and !whosaid. \ - Make your chatter #legend with !rainbow, !toilet, and !figlet. \ - Find interesting things with !xkcd and !wiki-philosophy. \ - Get jokes with !welch and !evil\n" + util.sendmsg( + ircsock, + channel, + """ + U wot m8? I score all the top drawer #banter and #bantz on this channel! + Find new top-shelf banter with !newbanter, !rhymes, and !define. + Look up things with !acronym and !whosaid. + Make your chatter #legend with !rainbow, !toilet, and !figlet. + Find interesting things with !xkcd and !wiki-philosophy. + Get jokes with !welch and !evil + """, ) -def connect(server, channel, botnick): - ircsock.connect((server, 6667)) - ircsock.send( - "USER " + botnick + " " + botnick + " " + botnick + " :krowbar\n" - ) # user authentication - ircsock.send("NICK " + botnick + "\n") - - joinchan(channel) - joinchan("#bots") - - def get_user_from_message(msg): try: i1 = msg.index(":") + 1 @@ -433,12 +359,7 @@ def listen(botnick): # print formatted - split = formatted.split("\t") - # time = split[0] - user = split[1] - command = split[2] - channel = split[3] - messageText = split[4] + time, user, command, channel, messageText = formatted.split("\t") if ircmsg.find("#banter") != -1 or ircmsg.find("#bantz") != -1: score_banter(channel, user, messageText) @@ -497,12 +418,12 @@ def listen(botnick): mug_off(channel) if ircmsg[:4] == "PING": - ping(ircmsg.split(" ")[1]) + util.ping(ircsock, msg) sys.stdout.flush() time.sleep(1) ircsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) -connect(options.server, options.channel, options.nick) +util.connect(ircsock, options) listen(options.nick) diff --git a/Code/irc/get_users.py b/Code/irc/get_users.py deleted file mode 100644 index 32a7381..0000000 --- a/Code/irc/get_users.py +++ /dev/null @@ -1,13 +0,0 @@ -# Return a list of users on this system - - -def get_users(): - # thanks, ~dan! - users = [] - with open("/etc/passwd", "r") as f: - for line in f: - if "/bin/bash" in line: - u = line.split(":")[0] # Grab all text before first ':' - users.append(u) - - return users diff --git a/Code/irc/madlibbot/madlibbot.py b/Code/irc/madlibbot/madlibbot.py index 5f6934e..bfc685a 100755 --- a/Code/irc/madlibbot/madlibbot.py +++ b/Code/irc/madlibbot/madlibbot.py @@ -41,7 +41,7 @@ parser.add_option( "-s", "--server", dest="server", - default="127.0.0.1", + default="127.0.0.1:6667", help="the server to connect to", metavar="SERVER", ) @@ -223,14 +223,6 @@ def finish_story(channel): # System things -def ping(pong): - ircsock.send("PONG {}\n".format(pong)) - - -def sendmsg(chan, msg): - ircsock.send("PRIVMSG {} :{}\n".format(chan, msg)) - - def joinchan(chan): global state state[chan] = State.idle @@ -258,15 +250,6 @@ def rollcall(channel, botnick): ) -def connect(server, channel, botnick): - ircsock.connect((server, 6667)) - ircsock.send( - "USER {} {} {} :krowbar\n".format(botnick, botnick, botnick) - ) # user authentication - ircsock.send("NICK {}\n".format(botnick)) - joinchan(channel) - - def listen(botnick): botmsgre = re.compile( "^{}\:?\s*(.*)$".format(botnick) @@ -304,5 +287,5 @@ def listen(botnick): ircsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) -connect(options.server, options.channel, options.nick) +util.connect(ircsock, options) listen(options.nick) diff --git a/Code/irc/names.py b/Code/irc/names.py deleted file mode 100644 index 89be86a..0000000 --- a/Code/irc/names.py +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/python -import json - -names_file = "/home/jumblesale/Code/canonical_names/canonical_names.json" - - -def get_name(name): - try: - with open(names_file) as names_data: - names = json.load(names_data) - try: - return names[name]["userName"] - except KeyError: - return name - except IOError: - return name # if we didn't already diff --git a/Code/irc/pretty_date.py b/Code/irc/pretty_date.py deleted file mode 100644 index 80a8966..0000000 --- a/Code/irc/pretty_date.py +++ /dev/null @@ -1,43 +0,0 @@ -def pretty_date(time=False): - """ - Get a datetime object or a int() Epoch timestamp and return a - pretty string like 'an hour ago', 'Yesterday', '3 months ago', - 'just now', etc - """ - from datetime import datetime - - now = datetime.now() - if type(time) is int: - diff = now - datetime.fromtimestamp(time) - elif isinstance(time, datetime): - diff = now - time - elif not time: - diff = now - now - second_diff = diff.seconds - day_diff = diff.days - - if day_diff < 0: - return "" - - if day_diff == 0: - if second_diff < 10: - return "just now" - if second_diff < 60: - return str(second_diff) + " seconds ago" - if second_diff < 120: - return "a minute ago" - if second_diff < 3600: - return str(second_diff / 60) + " minutes ago" - if second_diff < 7200: - return "an hour ago" - if second_diff < 86400: - return str(second_diff / 3600) + " hours ago" - if day_diff == 1: - return "Yesterday" - if day_diff < 7: - return str(day_diff) + " days ago" - if day_diff < 31: - return str(day_diff / 7) + " weeks ago" - if day_diff < 365: - return str(day_diff / 30) + " months ago" - return str(day_diff / 365) + " years ago" diff --git a/Code/irc/quote_bot.py b/Code/irc/quote_bot.py index f17f8f5..af36fad 100755 --- a/Code/irc/quote_bot.py +++ b/Code/irc/quote_bot.py @@ -7,9 +7,7 @@ import os import sys from optparse import OptionParser -import get_users -import mentions -import formatter +import util parser = OptionParser() @@ -17,7 +15,7 @@ parser.add_option( "-s", "--server", dest="server", - default="127.0.0.1", + default="127.0.0.1:6667", help="the server to connect to", metavar="SERVER", ) @@ -41,48 +39,16 @@ parser.add_option( (options, args) = parser.parse_args() -def ping(pong): - ircsock.send("PONG {}\n".format(pong)) - - -def sendmsg(chan, msg): - ircsock.send("PRIVMSG " + chan + " :" + msg + "\n") - - -def joinchan(chan): - ircsock.send("JOIN " + chan + "\n") - - -def hello(): - ircsock.send("PRIVMSG " + channel + " :Hello!\n") - - def random_quote(channel): quote = os.popen("/home/frs/quotes/randquote.py").read() if len(quote) >= 256: quote = quote[:253] + "..." - ircsock.send("PRIVMSG " + channel + " :" + quote + "\n") + util.sendmsg(ircsock, channel, quote) def haiku(channel): h = os.popen("haiku").read().replace("\n", " // ") - ircsock.send("PRIVMSG " + channel + " :" + h + "\n") - - -def connect(server, channel, botnick): - ircsock.connect((server, 6667)) - ircsock.send( - "USER " - + botnick - + " " - + botnick - + " " - + botnick - + " :This bot is a result of a tutoral covered on http://shellium.org/wiki.\n" - ) # user authentication - ircsock.send("NICK " + botnick + "\n") - - joinchan(channel) + util.sendmsg(ircsock, channel, h) def get_user_from_message(msg): @@ -114,7 +80,7 @@ def say_chatty(channel): chattyOut = os.popen("/home/karlen/bin/chatty").read().split("\n") for line in chattyOut: if line: - ircsock.send("PRIVMSG " + channel + " :" + line + "\n") + util.sendmsg(ircsock, channel, line) def listen(): @@ -123,20 +89,14 @@ def listen(): ircmsg = ircsock.recv(2048) ircmsg = ircmsg.strip("\n\r") - if ircmsg[:4] == "PING": - ping(ircmsg.split(" ")[1]) - - formatted = formatter.format_message(ircmsg) + formatted = util.format_message(ircmsg) if "" == formatted: continue print(formatted) - split = formatted.split("\t") - time = split[0] - user = split[1] - messageText = split[2] + time, user, messageText = formatted.split("\t") if ircmsg.find(":!quote") != -1: random_quote(options.channel) @@ -158,5 +118,5 @@ def listen(): ircsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) -connect(options.server, options.channel, options.nick) +util.connect(ircsock, options) listen() diff --git a/Code/irc/rainbow.py b/Code/irc/rainbow.py deleted file mode 100644 index f439bb6..0000000 --- a/Code/irc/rainbow.py +++ /dev/null @@ -1,19 +0,0 @@ -import random - - -def makeRainbow(word): - - word = word or "RAINBOW" - output = "" - rb = ["5", "7", "8", "3", "12", "13", "6"] - bg = "01" - idx = random.randrange(0, len(rb)) - - for l in word: - if l == " ": - output += " " - else: - output += "\x03" + rb[idx % len(rb)] + "," + bg + l - idx += 1 - - return output diff --git a/Code/irc/run_wang.sh b/Code/irc/run_wang.sh index ccc8658..6dd82ac 100755 --- a/Code/irc/run_wang.sh +++ b/Code/irc/run_wang.sh @@ -1,4 +1,4 @@ #!/bin/bash -nohup ./wangbot.py -s 127.0.0.1 -n numberwang_bot -c \#bots >> wanglog 2>> wanglog & +nohup ./wangbot.py -n numberwang_bot -c \#bots >> wanglog 2>> wanglog & #nohup ./wangbot.py -s 127.0.0.1 -n numberwang_bot -c \#bot_test >> wanglog 2>> wanglog & diff --git a/Code/irc/systemd/tildebot.service b/Code/irc/systemd/tildebot.service index 75b1cf0..d44a791 100644 --- a/Code/irc/systemd/tildebot.service +++ b/Code/irc/systemd/tildebot.service @@ -4,7 +4,7 @@ After=tildebot.service [Service] Type=simple -ExecStart=/home/krowbar/Code/irc/tildebot.py -s 127.0.0.1 -n tildebot -c \#tildetown +ExecStart=/home/krowbar/Code/irc/tildebot.py -n tildebot -c \#tildetown WorkingDirectory=/home/krowbar/Code/irc/ Restart=always RestartSec=5 diff --git a/Code/irc/tildebot.py b/Code/irc/tildebot.py index 1b61938..7ce279b 100755 --- a/Code/irc/tildebot.py +++ b/Code/irc/tildebot.py @@ -10,11 +10,6 @@ from optparse import OptionParser import fileinput import random -import formatter -import get_users -import names -import mentions -import pretty_date import inflect import puzzle import util @@ -25,7 +20,7 @@ parser.add_option( "-s", "--server", dest="server", - default="127.0.0.1", + default="127.0.0.1:6667", help="the server to connect to", metavar="SERVER", ) @@ -56,10 +51,6 @@ JACKPOT_MIN = 3 DEBUG = False -def hello(): - util.sendmsg(ircsock, channel, "Hello!") - - def too_recent(time1, time2): return int(time1) - int(time2) < 60 * 60 @@ -197,14 +188,12 @@ def get_prize(name, isHuman, bonus=0): ): # 80% of the time it's a normal prize (40% for not humans) return [ prize, - name - + ": " - + (get_positive() if isHuman else get_negative()) - + "! You are " - + get_superlative(prize) - + " and get " - + p.number_to_words(prize) - + " tildes!", + "{}: {}! You are {} and get {} tildes!".format( + name, + (get_positive() if isHuman else get_negative), + get_superlative(prize), + p.number_to_words(prize), + ), ] else: # 20% of the time its a jackpot situation with open(JACKPOT_FILE, "r+") as jackpotfile: @@ -220,21 +209,17 @@ def get_prize(name, isHuman, bonus=0): ) # increase the jackpot by the prize size return [ 0, - name - + " " - + get_bad_thing() - + " and gets no tildes! (Jackpot is now " - + str(new_jackpot) - + " tildes)", + "{} {} and gets no tildes! (Jackpot is now {} tildes)".format( + name, get_bad_thing(), new_jackpot + ), ] else: # hit jackpot! jackpotfile.write(str(JACKPOT_MIN)) return [ jackpot, - name - + " hit the jackpot and won **" - + p.number_to_words(jackpot) - + " tildes!**", + "{} hit the jackpot and won **{}**".format( + name, p.number_to_words(jackpot) + ), ] @@ -268,13 +253,8 @@ def give_tilde(channel, user, name, time, human, bonus=0): ) else: prize = get_prize(name, human, bonus) - score = ( - person[0] - + "&^%" - + str(int(person[1]) + prize[0]) - + "&^%" - + time - + "\n" + score = "{}&^%{}&^%{}\n".format( + person[0], int(person[1] + prize[0]), time ) util.sendmsg(ircsock, channel, prize[1]) scorefile.write(score) @@ -287,7 +267,7 @@ def give_tilde(channel, user, name, time, human, bonus=0): p.number_to_words(prize[0] + 1) ), ) - scorefile.write(user + "&^%" + str(prize[0] + 1) + "&^%" + time + "\n") + scorefile.write("{}&^%{}&^%{}\n".format(user, str(prize[0] + 1), time)) def show_tildescore(channel, user, name): @@ -344,7 +324,8 @@ def rollcall(channel): def connect(server, channel, botnick): - ircsock.connect((server, 6667)) + server, port = server.split(":") + ircsock.connect((server, port)) ircsock.send("USER {0} {0} {0} :krowbar\r\n".format(botnick)) # user authentication ircsock.send("NICK {}\r\n".format(botnick)) ircsock.send("MODE +B {}\r\n".format(botnick)) @@ -372,21 +353,17 @@ def listen(): if msg[:4] == "PING": util.ping(ircsock, msg) + continue - formatted = formatter.format_message(msg) + formatted = util.format_message(msg) if "" == formatted: continue # print formatted - split = formatted.split("\t") - iTime = split[0] - user = split[1] - name = names.get_name(user) - command = split[2] - channel = split[3] - messageText = split[4] + iTime, user, command, channel, messageText = formatted.split("\t") + name = util.get_name(user) if msg.find(":!tildescore") != -1: show_tildescore(channel, user, name) @@ -394,7 +371,6 @@ def listen(): challenge(channel, user, name, iTime) elif challenges.has_key(user) and (channel == "#bots" or DEBUG): challenge_response(channel, user, name, iTime, messageText) - # give_tilde(channel, user, name, iTime) if msg.find(":!jackpot") != -1: show_jackpot(channel) @@ -402,13 +378,10 @@ def listen(): if msg.find(":!rollcall") != -1: rollcall(channel) - if msg[:4] == "PING": - util.ping(ircsock, msg) - sys.stdout.flush() time.sleep(1) ircsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) -connect(options.server, options.channel, options.nick) +util.connect(ircsock, options) listen() diff --git a/Code/irc/util.py b/Code/irc/util.py index f8e4ad3..96dceee 100644 --- a/Code/irc/util.py +++ b/Code/irc/util.py @@ -1,7 +1,13 @@ +import json import time +import random import re +def hello(ircsock, chan): + sendmsg(ircsock, chan, "Hello!") + + def ping(pong): ircsock.send("PONG {}\n".format(pong.split(" ")[1])) @@ -11,7 +17,17 @@ def sendmsg(ircsock, chan, msg): def joinchan(ircsock, chan): - ircsock.send("JOIN {}\n".format(chan)) + ircsock.send("JOIN {}\r\n".format(chan)) + + +def connect(ircsock, options): + server, channel, botnick = options + server, port = server.split(":") + ircsock.connect((server, port)) + ircsock.send("USER {0} {0} {0} :krowbar".format(botnick)) + ircsock.send("NICK {}\r\n".format(botnick)) + ircsock.send("MODE +B {}\r\n".format(botnick)) + joinchan(channel) # integer number to english word conversion @@ -158,6 +174,19 @@ def get_users(): return users +def get_name(name): + names_file = "/home/jumblesale/Code/canonical_names/canonical_names.json" + try: + with open(names_file) as names_data: + names = json.load(names_data) + try: + return names[name]["userName"] + except KeyError: + return name + except IOError: + return name # if we didn't already + + def pretty_date(time=False): """ Get a datetime object or a int() Epoch timestamp and return a @@ -201,3 +230,21 @@ def pretty_date(time=False): if day_diff < 365: return str(day_diff / 30) + " months ago" return str(day_diff / 365) + " years ago" + + +def makeRainbow(word): + + word = word or "RAINBOW" + output = "" + rb = ["5", "7", "8", "3", "12", "13", "6"] + bg = "01" + idx = random.randrange(0, len(rb)) + + for l in word: + if l == " ": + output += " " + else: + output += "\x03" + rb[idx % len(rb)] + "," + bg + l + idx += 1 + + return output diff --git a/Code/irc/wangbot.py b/Code/irc/wangbot.py index ad32d31..8249cd2 100755 --- a/Code/irc/wangbot.py +++ b/Code/irc/wangbot.py @@ -12,11 +12,8 @@ import time import re import operator -import formatter -import get_users -import mentions -import pretty_date import inflect +import util parser = OptionParser() @@ -24,7 +21,7 @@ parser.add_option( "-s", "--server", dest="server", - default="127.0.0.1", + default="127.0.0.1:6667", help="the server to connect to", metavar="SERVER", ) @@ -75,64 +72,41 @@ def resetGlobals(): currentScores.clear() -def ping(pong): - ircsock.send("PONG {}\n".format(pong)) - - -def sendmsg(chan, msg): - ircsock.send("PRIVMSG " + chan + " :" + msg + "\n") - - -def joinchan(chan): - ircsock.send("JOIN " + chan + "\n") - - -def hello(): - ircsock.send("PRIVMSG " + channel + " :Hello!\n") - - def start_numberwang(channel, user): if channel != "#bots": - ircsock.send( - "PRIVMSG " - + channel - + " :Numberwang has been disabled for " - + channel - + " due to spamminess. Please join " - + GOOD_CHAN - + " to start a game.\n" + util.sendmsg( + ircsock, + channel, + "Numberwang has been disabled in {} due to spamminess. Please join {} to start a game.".format( + channel, GOOD_CHAN + ), ) return print(user + " started a game") resetGlobals() - ircsock.send("PRIVMSG " + channel + " :It's time for Numberwang!\n") + util.sendmsg(ircsock, channel, "It's time for Numberwang!") time.sleep(1) - ircsock.send("PRIVMSG " + channel + " :Here's how to play:\n") + util.sendmsg(ircsock, channel, "Here's how to play:") - ircsock.send("PRIVMSG " + channel + " :1. There are 10 rounds\n") - ircsock.send( - "PRIVMSG " - + channel - + " :2. Each round lasts 10 seconds. You're up against the clock!\n" + util.sendmsg(ircsock, channel, "1. There are 10 rounds") + util.sendmsg( + ircsock, channel, "2. Each round lasts 10 seconds. You're up against the clock!" ) - ircsock.send( - "PRIVMSG " - + channel - + " :3. Play your numbers, as long as they're between 0 and 99.\n" + util.sendmsg( + ircsock, channel, "3. Play your numbers, as long as they're between 0 and 99." ) - ircsock.send("PRIVMSG " + channel + " :4. That's Numberwang!\n") + util.sendmsg(ircsock, channel, "4. That's Numberwang!") time.sleep(2) - ircsock.send("PRIVMSG " + channel + " :Let's get started!\n") + util.sendmsg(ircsock, channel, "Let's get started!") global roundsLeft global bonusRound roundsLeft = random.randint(MIN_ROUNDS, MAX_ROUNDS) bonusRound = random.randint(2, roundsLeft - 1) print( - "There will be " - + str(roundsLeft) - + " rounds with the bonus on round " - + str(roundsLeft - bonusRound + 1) + "There will be {} rounds with the bonus on round {}".format( + str(roundsLeft), str(roundsLeft - bonusRound + 1) + ) ) @@ -141,14 +115,14 @@ def print_scores(channel): first = True for name in currentScores: scoreStrs.append( - name - + " is " - + ("also " if not first and random.randint(1, 3) == 3 else "") - + "on " - + str(currentScores[name]) + "{} is {} on {}".format( + name, + ("also " if not first and random.randint(1, 3) == 3 else ""), + currentScores[name], + ) ) first = False - ircsock.send("PRIVMSG " + channel + " :" + p.join(scoreStrs) + "!\n") + util.sendmsg(ircsock, channel, p.join(scoreStrs)) def guess_numberwang(channel, user, messageText): @@ -162,12 +136,10 @@ def guess_numberwang(channel, user, messageText): ) # must have a number in the first 'word' if guess: if LIMIT_GUESSING and user == lastGuesser: - ircsock.send( - "PRIVMSG " - + channel - + " :" - + user - + ", you just guessed! Give another player a try!\n" + util.sendmsg( + ircsock, + channel, + "{}, you just guessed! Give another player a try!".format(user), ) else: guesses += 1 @@ -178,9 +150,7 @@ def guess_numberwang(channel, user, messageText): ): # the more guesses, the higher the probability guesses = 0 lastGuesser = "" - ircsock.send( - "PRIVMSG " + channel + " :" + user + ": THAT'S NUMBERWANG!\n" - ) + util.sendmsg(ircsock, channel, "{}: THAT'S NUMBERWANG!".format(user)) points = random.randint(2, 10) * ( random.randint(2, 4) if roundsLeft == bonusRound else 1 ) @@ -191,12 +161,12 @@ def guess_numberwang(channel, user, messageText): roundsLeft -= 1 time.sleep(2) if roundsLeft == 0: - ircsock.send( - "PRIVMSG " - + channel - + " :Numberwang is now over. Thank you for playing!\n" + util.sendmsg( + ircsock, + channel, + "Numberwang is now over. Thank you for playing!", ) - ircsock.send("PRIVMSG " + channel + " :Final scores:\n") + util.sendmsg(ircsock, channel, "Final scores:") print_scores(channel) save_scores() else: @@ -210,43 +180,41 @@ def guess_numberwang(channel, user, messageText): newRoundStr += "New Round!" if random.randint(1, 10) > 8: newRoundStr += " Let's rotate the board!" - ircsock.send( - "PRIVMSG " + channel + " :" + newRoundStr + " Start guessing!\n" + util.sendmsg( + ircsock, channel, "{} Start guessing!".format(newRoundStr) ) ###INCORRECT GUESS### else: - ircsock.send( - "PRIVMSG " - + channel - + " :" - + random.choice(["Sorry", "I'm sorry", "No", "Nope"]) - + ", " - + user - + ", " - + random.choice( - [ - "that's not", - "that is not", - "that isn't", - "that is not", - "that won't make", - "that will not make", - ] - ) - + " Numberwang!\n" + util.sendmsg( + ircsock, + channel, + "{}, {}, {} Numberwang!".format( + random.choice(["Sorry", "I'm sorry", "No", "Nope"]), + user, + random.choice( + [ + "that's not", + "that is not", + "that isn't", + "that is not", + "that won't make", + "that will not make", + ] + ), + ), ) def stop_numberwang(channel, user): print(user + " stopped a game") resetGlobals() - ircsock.send( - "PRIVMSG " - + channel - + " :Numberwang has been stopped. No points have been awarded. " - + user - + " is such a party pooper!\n" + util.sendmsg( + ircsock, + channel, + "Numberwang has been stopped. No points have been awarded. {} is such a party pooper!".format( + user + ), ) @@ -259,19 +227,15 @@ def save_scores(): for name in currentScores: score = line.strip("\n").split("&^%") if score[0] == name: - line = ( - score[0] - + "&^%" - + str(int(score[1]) + currentScores[name]) - + "\n" + line = "{}&^%{}\n".format( + score[0], int(score[1]) + currentScores[name] ) del currentScores[name] break scorefile.write(line) for name in currentScores: # new wangers - line = name + "&^%" + str(currentScores[name]) + "\n" - scorefile.write(line) + scorefile.write("{}&^%{}\n".format(name, currentScores[name])) def show_highscores(channel): @@ -282,16 +246,10 @@ def show_highscores(channel): scores.append((int(sline[1]), sline[0])) scores = sorted(scores, reverse=True)[:SHOW_TOP_NUM] - ircsock.send("PRIVMSG " + channel + " : ====TOP WANGERS====\n") + util.sendmsg(ircsock, channel, "====TOP WANGERS====") for score in scores: - ircsock.send( - "PRIVMSG " - + channel - + " :== ~" - + score[1] - + " (" - + str(score[0]) - + " points!) ==\n" + util.sendmsg( + ircsock, channel, " :== ~{} ({} points!) ==".format(score[1], score[0]) ) @@ -300,45 +258,26 @@ def show_user_score(channel, user): for line in scorefile.readlines(): score = line.strip("\n").split("&^%") if user == score[0]: - ircsock.send( - "PRIVMSG " - + channel - + " :" - + user - + ": Your global numberwang score is " - + str(score[1]) - + "!\n" + util.sendmsg( + ircsock, + channel, + "{}: Your global numberwang score is {}!".format(user, score[1]), ) return # if we don't find a score line - ircsock.send( - "PRIVMSG " - + channel - + " :" - + user - + ": You haven't scored any points yet!\n" + util.sendmsg( + ircsock, channel, "{} You haven't scored any points yet!".format(user) ) def rollcall(channel): - ircsock.send( - "PRIVMSG " - + channel - + " :Is it time for Numberwang? It might be! Start a new game with !numberwang or stop a current game with !wangernumb Get your score with !myscore and the list of top wangers with !topwangers\n" + util.sendmsg( + ircsock, + channel, + " :Is it time for Numberwang? It might be! Start a new game with !numberwang or stop a current game with !wangernumb Get your score with !myscore and the list of top wangers with !topwangers", ) -def connect(server, channel, botnick): - ircsock.connect((server, 6667)) - ircsock.send( - "USER " + botnick + " " + botnick + " " + botnick + " :krowbar\n" - ) # user authentication - ircsock.send("NICK " + botnick + "\n") - - joinchan(channel) - joinchan(GOOD_CHAN) - - def get_user_from_message(msg): try: i1 = msg.index(":") + 1 @@ -357,19 +296,14 @@ def listen(): if ircmsg[:4] == "PING": ping(ircmsg.split(" ")[1]) - formatted = formatter.format_message(ircmsg) + formatted = util.format_message(ircmsg) if "" == formatted: continue # print formatted - split = formatted.split("\t") - time = split[0] - user = split[1] - command = split[2] - channel = split[3] - messageText = split[4] + time, user, command, channel, messageText = formatted.split("\t") if ircmsg.find(":!numberwang") != -1 and roundsLeft == 0: start_numberwang(channel, user) @@ -388,13 +322,10 @@ def listen(): if ircmsg.find(":!rollcall") != -1: rollcall(channel) - if ircmsg[:4] == "PING": - ping(ircmsg.split(" ")[1]) - sys.stdout.flush() time.sleep(1) ircsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) -connect(options.server, options.channel, options.nick) +util.connect(ircsock, options) listen() diff --git a/Code/irc/whosaid.py b/Code/irc/whosaid.py index 468aae8..e16f19b 100755 --- a/Code/irc/whosaid.py +++ b/Code/irc/whosaid.py @@ -22,7 +22,9 @@ nameFix = { def whoSaid(word): word = word.lower() - userData = {} # hash keyed by "user" that contains a hash of mentioned other users with count + userData = ( + {} + ) # hash keyed by "user" that contains a hash of mentioned other users with count # Get a list of all user names by checking the logs for people who have said things with open(logfile, "r") as log: for line in log: diff --git a/Code/python/chatbesties.py b/Code/python/chatbesties.py index bdbfca0..8a6b0d9 100755 --- a/Code/python/chatbesties.py +++ b/Code/python/chatbesties.py @@ -16,7 +16,9 @@ outfile = "/home/krowbar/logs/chatBesties.json" outCircle = "/home/krowbar/logs/chatcircle.json" timePeriod = calendar.timegm(time.gmtime()) - (2 * 7 * 24 * 60 * 60) # 2 weeks -userData = {} # hash keyed by "user" that contains a hash of mentioned other users with count +userData = ( + {} +) # hash keyed by "user" that contains a hash of mentioned other users with count nameFix = { "jumblesal": "jumblesale", "hardmath1": "kc", diff --git a/Code/python/chatstats.py b/Code/python/chatstats.py index 88d5b63..bf20212 100755 --- a/Code/python/chatstats.py +++ b/Code/python/chatstats.py @@ -9,7 +9,9 @@ import re logfile = "/home/archangelic/irc/log" # logfile = "/home/jumblesale/Code/irc/log" outfile = "/home/krowbar/logs/chatStats.json" -userData = {} # hash keyed by "user" that contains a start timestamp, last timestamp, last said string, chat count, letter count, and word count +userData = ( + {} +) # hash keyed by "user" that contains a start timestamp, last timestamp, last said string, chat count, letter count, and word count # also now happy emotes and sad emotes rejectRegexp = "http[s]?://|[0-9]{2}[;:][0-9]{2}" happyRegexp = ":[-]?[])}]"