From 649a56f6c2f2ea8d44e5567f3a6f4a18867bc937 Mon Sep 17 00:00:00 2001 From: Ben Harris Date: Tue, 9 Oct 2018 02:43:19 -0400 Subject: [PATCH] another big diff. tested some things --- Code/.gitignore | 2 + Code/irc/banterbot.py | 35 ++++------ Code/irc/defineWord.py | 7 +- Code/irc/dict_puzzle.py | 27 ++++--- Code/irc/duckduckgo.py | 9 +-- Code/irc/int2word.py | 115 ------------------------------ Code/irc/int2word.pyc | Bin 1979 -> 0 bytes Code/irc/puzzle.py | 110 ++++++++++++----------------- Code/irc/quote_bot.py | 25 +++---- Code/irc/tilde_bot.py | 124 --------------------------------- Code/irc/tildebot.py | 59 +++++----------- Code/irc/tildejackpot.txt | 1 + Code/irc/tildescores.txt | 12 +--- Code/irc/topicbot.py | 143 +++++++++++--------------------------- Code/irc/topicscores.txt | 1 + Code/irc/util.py | 44 ++++++++---- Code/irc/wangbot.py | 19 ++--- 17 files changed, 180 insertions(+), 553 deletions(-) create mode 100644 Code/.gitignore delete mode 100644 Code/irc/int2word.py delete mode 100644 Code/irc/int2word.pyc delete mode 100755 Code/irc/tilde_bot.py create mode 100644 Code/irc/tildejackpot.txt diff --git a/Code/.gitignore b/Code/.gitignore new file mode 100644 index 0000000..d646835 --- /dev/null +++ b/Code/.gitignore @@ -0,0 +1,2 @@ +*.pyc +__pycache__/ diff --git a/Code/irc/banterbot.py b/Code/irc/banterbot.py index 9c48ed0..1f73dbf 100755 --- a/Code/irc/banterbot.py +++ b/Code/irc/banterbot.py @@ -10,6 +10,7 @@ import fileinput import random import re import subprocess +import textwrap import time import datetime @@ -17,7 +18,6 @@ import inflect from rhymesWith import getRhymes from rhymesWith import rhymeZone from defineWord import defWord -from rainbow import makeRainbow import welch import evil import tumblr @@ -49,7 +49,7 @@ parser.add_option( "-n", "--nick", dest="nick", - default="tildebot", + default="banterbot", help="the nick to use", metavar="NICK", ) @@ -200,7 +200,7 @@ def define_word(channel, user, text): def make_rainbow(channel, user, text): - rbword = makeRainbow(text[9:]) + rbword = util.makeRainbow(text[9:]) util.sendmsg(ircsock, channel, rbword) @@ -320,37 +320,28 @@ def mug_off(channel): def rollcall(channel): - util.sendmsg( - ircsock, - channel, - """ + text = """ 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 get_user_from_message(msg): - try: - i1 = msg.index(":") + 1 - i2 = msg.index("!") - return msg[i1:i2] - except ValueError: - return "" + """ + for line in textwrap.dedent(text).split("\n"): + if line == "": + continue + util.sendmsg(ircsock, channel, line) def listen(botnick): while 1: - ircmsg = ircsock.recv(2048) + ircmsg = ircsock.recv(2048).decode() ircmsg = ircmsg.strip("\n\r") if ircmsg[:4] == "PING": - ping(ircmsg.split(" ")[1]) + util.ping(ircsock, ircmsg) formatted = util.format_message(ircmsg) @@ -359,7 +350,7 @@ def listen(botnick): # print formatted - time, user, command, channel, messageText = formatted.split("\t") + _time, user, _command, channel, messageText = formatted.split("\t") if ircmsg.find("#banter") != -1 or ircmsg.find("#bantz") != -1: score_banter(channel, user, messageText) @@ -418,7 +409,7 @@ def listen(botnick): mug_off(channel) if ircmsg[:4] == "PING": - util.ping(ircsock, msg) + util.ping(ircsock, ircmsg) sys.stdout.flush() time.sleep(1) diff --git a/Code/irc/defineWord.py b/Code/irc/defineWord.py index 104e5cc..e290ac0 100644 --- a/Code/irc/defineWord.py +++ b/Code/irc/defineWord.py @@ -5,7 +5,7 @@ import random def define(word): defs = [] - url = "http://www.merriam-webster.com/dictionary/%s" % word + url = "http://www.merriam-webster.com/dictionary/{}".format(word) soup = BeautifulSoup(urllib.urlopen(url).read(), "html.parser") head = soup.find("div", id="headword") if head: @@ -19,9 +19,8 @@ key = open("/home/krowbar/.secret/key").readline().rstrip() def defWord(word, short=True): defs = [] - url = "http://www.dictionaryapi.com/api/v1/references/collegiate/xml/%s?key=%s" % ( - word, - key, + url = "http://www.dictionaryapi.com/api/v1/references/collegiate/xml/{}?key={}".format( + word, key ) soup = BeautifulSoup(urllib.urlopen(url).read(), "html5lib") entry = soup.find("entry") diff --git a/Code/irc/dict_puzzle.py b/Code/irc/dict_puzzle.py index 40233dd..85459eb 100644 --- a/Code/irc/dict_puzzle.py +++ b/Code/irc/dict_puzzle.py @@ -7,8 +7,9 @@ dictionary = "/usr/share/dict/american-english-small" BAD_WORDS_FILE = "badwords.txt" -def get_wordlist(): +def gen_wordlist(): # I feel weird calling this "get_wordlist" when it's a generator without calling out that I do in fact realise it's weird - ~deltawitch + # how about gen_wordlist with open(BAD_WORDS_FILE, "r") as fp: bad_words = set(fp) @@ -18,14 +19,11 @@ def get_wordlist(): def get_puzzle(): - dict_words = list(get_wordlist()) + dict_words = list(gen_wordlist()) words = random.sample(dict_words, 3) key = random.randrange(0, 3) # get values 1-3 - puzzle = ( - "When alphebetized, what is the " - + p.ordinal(p.number_to_words(key + 1)) - + " in " - + ", ".join(words) + puzzle = "When alphebetized, what is the {} in {}?".format( + p.ordinal(p.number_to_words(key + 1)), ", ".join(words) ) words.sort() answer = words[key] @@ -34,14 +32,12 @@ def get_puzzle(): def get_anagram(maxlen=6): dict_words = [ - word for word in get_wordlist() if len(word) > 2 and len(word) <= maxlen + 1 + word for word in gen_wordlist() if len(word) > 2 and len(word) < maxlen + 1 ] word = random.choice(dict_words) - while True: - anagram = "".join(random.sample(word, len(word))) - if anagram != word: - break - puzzle = "Unscramble the following word: '" + anagram + "'" + anagram = list(word) + random.shuffle(anagram) + anagram = "".join(anagram) # Anagrams can have multiple answers, so we provide a check function that accepts all possibilities def answer_checker(guess): @@ -52,6 +48,7 @@ def get_anagram(maxlen=6): if sorted(guess) != sorted(word): return False # Ok, gotta actually check if it's a word now - return any(guess == item for item in get_wordlist()) + return any(guess == item for item in gen_wordlist()) - return [answer_checker, puzzle] + challenge_text = "Unscramble the following word: '{}'".format(anagram) + return [answer_checker, challenge_text] diff --git a/Code/irc/duckduckgo.py b/Code/irc/duckduckgo.py index 25ecd03..b00dda4 100755 --- a/Code/irc/duckduckgo.py +++ b/Code/irc/duckduckgo.py @@ -1,5 +1,5 @@ +import requests import urllib -import urllib2 import json as j import sys @@ -50,12 +50,9 @@ def query( encparams = urllib.urlencode(params) url = "http://api.duckduckgo.com/?" + encparams - request = urllib2.Request(url, headers={"User-Agent": useragent}) - response = urllib2.urlopen(request) - json = j.loads(response.read()) - response.close() + request = requests.get(url, headers={"User-Agent": useragent}) - return Results(json) + return Results(request.json()) class Results(object): diff --git a/Code/irc/int2word.py b/Code/irc/int2word.py deleted file mode 100644 index 8c2e532..0000000 --- a/Code/irc/int2word.py +++ /dev/null @@ -1,115 +0,0 @@ -# integer number to english word conversion -# can be used for numbers as large as 999 vigintillion -# (vigintillion --> 10 to the power 60) -# tested with Python24 vegaseat 07dec2006 -def int2word(n): - """ - convert an integer number n into a string of english words - """ - # break the number into groups of 3 digits using slicing - # each group representing hundred, thousand, million, billion, ... - n3 = [] - r1 = "" - # create numeric string - ns = str(n) - for k in range(3, 33, 3): - r = ns[-k:] - q = len(ns) - k - # break if end of ns has been reached - if q < -2: - break - else: - if q >= 0: - n3.append(int(r[:3])) - elif q >= -1: - n3.append(int(r[:2])) - elif q >= -2: - n3.append(int(r[:1])) - r1 = r - - # print n3 # test - - # break each group of 3 digits into - # ones, tens/twenties, hundreds - # and form a string - nw = "" - for i, x in enumerate(n3): - b1 = x % 10 - b2 = (x % 100) // 10 - b3 = (x % 1000) // 100 - # print b1, b2, b3 # test - if x == 0: - continue # skip - else: - t = thousands[i] - if b2 == 0: - nw = ones[b1] + t + nw - elif b2 == 1: - nw = tens[b1] + t + nw - elif b2 > 1: - nw = twenties[b2] + ones[b1] + t + nw - if b3 > 0: - nw = ones[b3] + "hundred " + nw - return nw - - -############# globals ################ -ones = [ - "", - "one ", - "two ", - "three ", - "four ", - "five ", - "six ", - "seven ", - "eight ", - "nine ", -] -tens = [ - "ten ", - "eleven ", - "twelve ", - "thirteen ", - "fourteen ", - "fifteen ", - "sixteen ", - "seventeen ", - "eighteen ", - "nineteen ", -] -twenties = [ - "", - "", - "twenty ", - "thirty ", - "forty ", - "fifty ", - "sixty ", - "seventy ", - "eighty ", - "ninety ", -] -thousands = [ - "", - "thousand ", - "million ", - "billion ", - "trillion ", - "quadrillion ", - "quintillion ", - "sextillion ", - "septillion ", - "octillion ", - "nonillion ", - "decillion ", - "undecillion ", - "duodecillion ", - "tredecillion ", - "quattuordecillion ", - "sexdecillion ", - "septendecillion ", - "octodecillion ", - "novemdecillion ", - "vigintillion ", -] diff --git a/Code/irc/int2word.pyc b/Code/irc/int2word.pyc deleted file mode 100644 index 2b29b7370f4834068f6f573d6b013e7279942156..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1979 zcmb7E-EJF26#mx#Svx-jlGKILZGqxasA+nOP^IPyA%s$-N>O{^_)P32&TO(fPF!K% zP@V*F0S^Ih01v zkWI)Iq1Oe9|??bLbBFGKMO~?n34>-3pFr+FK81V+ zxeIASK1Xi@dra~k9<{bvLN_2;;VN@IIt zvGepdOiCCRF)pEgeNu)is6;#!S0)vV*^Cknf%FN!wW*iOI4mRm5#s>g7vX5nrWFv; zieF&A_Na?Zqd9f7wdjdeahMp2z?V=&15M7?EEE&t z_n3hnwU+f-cSypBziwhrP3oeKjbiIe&!mwZ9_{OUeB89l`&Yw2`z zY5~j9B)#vq^j~2Pd29O8uw1Rr*8=0jgN z(dhZvG?;bI@+5pP@>=0RlB(LXj5B353R#Vw$DrWT*W#wU_fI}gKOd>w var1: var1, var2 = var2, var1 answer = var1 - var2 - puzzle += ( - p.number_to_words(var1) - + " " - + random.choice(["minus", "subtract", "take away", "less"]) - + " " - + p.number_to_words(var2) + puzzle += "{} {} {}".format( + p.number_to_words(var1), + random.choice(["minus", "subtract", "take away", "less"]), + p.number_to_words(var2), ) + elif roll == 3: if var2 > var1: var1, var2 = var2, var1 answer = var1 * 2 / var2 - puzzle += ( - p.number_to_words(var1 * 2) - + " " - + random.choice(["divided by", "over"]) - + " " - + p.number_to_words(var2) - + " (no remainder)" + puzzle += "{} {} {} (no remainder)".format( + p.number_to_words(var1 * 2), + random.choice(["divided by", "over"]), + p.number_to_words(var2), ) + elif roll == 4: answer = var1 ** var2 - puzzle += ( - p.number_to_words(var1) - + " to the " - + p.ordinal(p.number_to_words(var2)) - + " power" + puzzle += "{} to the {} power".format( + p.number_to_words(var1), p.ordinal(p.number_to_words(var2)) ) + elif roll == 5: p1 = random.choice(primes) p2 = random.choice(primes) @@ -103,10 +95,10 @@ def make_puzzle(obfuscate=True): return attempt == correct bonus = 1 - puzzle += ( + puzzle += "{} when factored into its two primes (answer in the form of the two primes with a comma between)".format( p.number_to_words(p1 * p2) - + " when factored into its two primes (answer in the form of the two primes with a comma between)" ) + elif roll == 6: prime = random.choice(primes) answer = prime % var1 @@ -115,57 +107,43 @@ def make_puzzle(obfuscate=True): if let1_ord + var1 > ord("z"): let1_ord -= var1 answer = chr(let1_ord + var1) - puzzle = ( - "What letter comes " - + p.number_to_words(var1) - + " letters after '" - + chr(let1_ord) - + "'" + puzzle += "What letter comes {} letters after '{}'".format( + p.number_to_words(var1), chr(let1_ord) ) + obfuscate = False elif roll == 8: if let1_ord - var1 < ord("a"): let1_ord += var1 answer = chr(let1_ord - var1) - puzzle = ( - "What letter comes " - + p.number_to_words(var1) - + " letters before '" - + chr(let1_ord) - + "'" + puzzle += "What letter comes {} letters before '{}'".format( + p.number_to_words(var1), chr(let1_ord) ) + obfuscate = False elif roll == 9: answer, puzzle = quote_puzzle.get_quote() obfuscate = False elif roll == 10: answer = str(min(var1, var2, var3, var4)) - puzzle = ( - "What is the " - + random.choice(["smallest", "lowest"]) - + " of " - + p.number_to_words(var1) - + ", " - + p.number_to_words(var2) - + ", " - + p.number_to_words(var3) - + ", and " - + p.number_to_words(var4) + puzzle += "What is the {} of {}, {}, {}, and {}".format( + random.choice(["smallest", "lowest"]), + p.number_to_words(var1), + p.number_to_words(var2), + p.number_to_words(var3), + p.number_to_words(var4), ) + elif roll == 11: answer = str(max(var1, var2, var3, var4)) - puzzle = ( - "What is the " - + random.choice(["biggest", "largest"]) - + " of " - + p.number_to_words(var1) - + ", " - + p.number_to_words(var2) - + ", " - + p.number_to_words(var3) - + ", and " - + p.number_to_words(var4) + puzzle += "What is the {} of {}, {}, {}, and {}".format( + random.choice(["biggest", "largest"]), + p.number_to_words(var1), + p.number_to_words(var2), + p.number_to_words(var3), + p.number_to_words(var4), ) + elif roll <= 14: # 12-14 answer, puzzle = dict_puzzle.get_puzzle() obfuscate = False diff --git a/Code/irc/quote_bot.py b/Code/irc/quote_bot.py index af36fad..600b1e2 100755 --- a/Code/irc/quote_bot.py +++ b/Code/irc/quote_bot.py @@ -31,7 +31,7 @@ parser.add_option( "-n", "--nick", dest="nick", - default="quote_bot", + default="quotebot", help="the nick to use", metavar="NICK", ) @@ -51,19 +51,10 @@ def haiku(channel): util.sendmsg(ircsock, channel, h) -def get_user_from_message(msg): - try: - i1 = msg.index(":") + 1 - i2 = msg.index("!") - return msg[i1:i2] - except ValueError: - return "" - - def say_mentions(user, message): - nick = get_user_from_message(message) + nick = util.get_user_from_message(message) menschns = ( - os.popen("/home/karlen/bin/mensch -u %s -t 24 -z +0" % (user)) + os.popen("/home/karlen/bin/mensch -u {} -t 24 -z +0".format(user)) .read() .replace("\t", ": ") .split("\n") @@ -86,8 +77,8 @@ def say_chatty(channel): def listen(): while 1: - ircmsg = ircsock.recv(2048) - ircmsg = ircmsg.strip("\n\r") + ircmsg = ircsock.recv(2048).decode() + ircmsg = ircmsg.strip("\r\n") formatted = util.format_message(ircmsg) @@ -96,7 +87,7 @@ def listen(): print(formatted) - time, user, messageText = formatted.split("\t") + user = formatted.split("\t")[1] if ircmsg.find(":!quote") != -1: random_quote(options.channel) @@ -111,10 +102,10 @@ def listen(): haiku(options.channel) if ircmsg[:4] == "PING": - ping(ircmsg.split(" ")[1]) + util.ping(ircsock, ircmsg) sys.stdout.flush() - time.sleep(1) + # time.sleep(1) ircsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) diff --git a/Code/irc/tilde_bot.py b/Code/irc/tilde_bot.py deleted file mode 100755 index ec6cba4..0000000 --- a/Code/irc/tilde_bot.py +++ /dev/null @@ -1,124 +0,0 @@ -#!/usr/bin/python -# http://wiki.shellium.org/w/Writing_an_IRC_bot_in_Python - -# Import some necessary libraries. -import socket -import os -import sys -from optparse import OptionParser - -import get_users -import mentions -import formatter - -parser = OptionParser() - -parser.add_option( - "-s", - "--server", - dest="server", - default="127.0.0.1", - help="the server to connect to", - metavar="SERVER", -) -parser.add_option( - "-c", - "--channel", - dest="channel", - default="#bot_test", - help="the channel to join", - metavar="CHANNEL", -) -parser.add_option( - "-n", - "--nick", - dest="nick", - default="tilde_bot", - help="the nick to use", - metavar="NICK", -) - -(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 tilde(channel, user, time): - # h = os.popen("haiku").read().replace("\n", " // ") - msg = time + ":" + user - print(msg) - ircsock.send("PRIVMSG " + channel + " :" + msg + "\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) - - -def get_user_from_message(msg): - try: - i1 = msg.index(":") + 1 - i2 = msg.index("!") - return msg[i1:i2] - except ValueError: - return "" - - -def listen(): - while 1: - - ircmsg = ircsock.recv(2048) - ircmsg = ircmsg.strip("\n\r") - - if ircmsg[:4] == "PING": - ping(ircmsg.split(" ")[1]) - - formatted = formatter.format_message(ircmsg) - - if "" == formatted: - continue - - print(formatted) - - split = formatted.split("\t") - time = split[0] - user = split[1] - messageText = split[2] - - if ircmsg.find(":!tilde") != -1: - tilde(options.channel, user, time) - - if ircmsg[:4] == "PING": - ping(ircmsg.split(" ")[1]) - - sys.stdout.flush() - - -ircsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) -connect(options.server, options.channel, options.nick) -listen() diff --git a/Code/irc/tildebot.py b/Code/irc/tildebot.py index 7ce279b..43e0e54 100755 --- a/Code/irc/tildebot.py +++ b/Code/irc/tildebot.py @@ -48,7 +48,7 @@ challenges = {} SCORE_FILE = "tildescores.txt" JACKPOT_FILE = "tildejackpot.txt" JACKPOT_MIN = 3 -DEBUG = False +DEBUG = True def too_recent(time1, time2): @@ -190,7 +190,7 @@ def get_prize(name, isHuman, bonus=0): prize, "{}: {}! You are {} and get {} tildes!".format( name, - (get_positive() if isHuman else get_negative), + (get_positive() if isHuman else get_negative()), get_superlative(prize), p.number_to_words(prize), ), @@ -240,10 +240,10 @@ def give_tilde(channel, user, name, time, human, bonus=0): scorefile.seek(0) scorefile.truncate() for score in scores: - person = score.strip("\n").split("&^%") - if person[0] == user: + name, score_on_file, timestamp = score.strip("\n").split("&^%") + if name == user: found = True - if too_recent(time, person[2]) and not DEBUG: + if too_recent(time, timestamp) and not DEBUG: util.sendmsg( ircsock, channel, @@ -252,22 +252,22 @@ def give_tilde(channel, user, name, time, human, bonus=0): ), ) else: - prize = get_prize(name, human, bonus) + prizevalue, prizetext = get_prize(name, human, bonus) score = "{}&^%{}&^%{}\n".format( - person[0], int(person[1] + prize[0]), time + name, str(int(score_on_file) + prizevalue), time ) - util.sendmsg(ircsock, channel, prize[1]) + util.sendmsg(ircsock, channel, prizetext) scorefile.write(score) if not found: - prize = get_prize(name, True, bonus) + prizevalue, prizetext = get_prize(name, True, bonus) util.sendmsg( ircsock, channel, - "Welcome to the tilde game! Here's {} free tilde(s) to start you off.".format( - p.number_to_words(prize[0] + 1) + "Welcome to the tilde game! Here's {} free tildes to start you off.".format( + p.number_to_words(prizevalue + 1) ), ) - scorefile.write("{}&^%{}&^%{}\n".format(user, str(prize[0] + 1), time)) + scorefile.write("{}&^%{}&^%{}\n".format(user, str(prizevalue + 1), time)) def show_tildescore(channel, user, name): @@ -298,14 +298,13 @@ def challenge(channel, user, name, time): global challenges challenge = puzzle.make_puzzle() challenges[user] = challenge[1:] - # challenges[USER] = [ANSWER, BONUS] - util.sendmsg(ircsock, channel, "{}: {}".format(name, challenge[1])) + util.sendmsg(ircsock, channel, "{}: {}".format(name, challenge[0])) def challenge_response(channel, user, name, time, msg): global challenges print(msg) - if challenges.has_key(user): + if user in challenges: answer, bonus = challenges[user] if (callable(answer) and answer(msg.lower())) or ( msg.lower() == str(answer).lower() or msg == p.number_to_words(answer) @@ -323,31 +322,10 @@ def rollcall(channel): ) -def connect(server, channel, botnick): - 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)) - - joinchan(channel) - if not DEBUG: - joinchan("#bots") - - -def get_user_from_message(msg): - try: - i1 = msg.index(":") + 1 - i2 = msg.index("!") - return msg[i1:i2] - except ValueError: - return "" - - def listen(): while 1: - ircmsg = ircsock.recv(2048) + ircmsg = ircsock.recv(2048).decode() for msg in ircmsg.split("\n"): msg = msg.strip("\n\r") @@ -356,20 +334,19 @@ def listen(): continue formatted = util.format_message(msg) + print(formatted) if "" == formatted: continue - # print formatted - iTime, user, command, channel, messageText = formatted.split("\t") name = util.get_name(user) if msg.find(":!tildescore") != -1: show_tildescore(channel, user, name) - elif msg.find(":!tilde") != -1 and not challenges.has_key(user): + elif msg.find(":!tilde") != -1 and user not in challenges: challenge(channel, user, name, iTime) - elif challenges.has_key(user) and (channel == "#bots" or DEBUG): + elif user in challenges and (channel == "#bots" or DEBUG): challenge_response(channel, user, name, iTime, messageText) if msg.find(":!jackpot") != -1: diff --git a/Code/irc/tildejackpot.txt b/Code/irc/tildejackpot.txt new file mode 100644 index 0000000..9d07aa0 --- /dev/null +++ b/Code/irc/tildejackpot.txt @@ -0,0 +1 @@ +111 \ No newline at end of file diff --git a/Code/irc/tildescores.txt b/Code/irc/tildescores.txt index 618cac1..8393826 100644 --- a/Code/irc/tildescores.txt +++ b/Code/irc/tildescores.txt @@ -122,14 +122,4 @@ x4464&^%1&^%1532028546 pounce&^%19&^%1532133325 von_&^%5&^%1532502104 livix&^%7&^%1533603142 -ben&^%3&^%1533767627 -npa&^%78&^%1536235183 -ezo&^%6&^%1533883842 -aliasless&^%30&^%1537198276 -kirch&^%41&^%1535571833 -root&^%2&^%1535558514 -byte&^%5&^%1536416308 -qbe&^%6&^%1537112151 -informati&^%3&^%1536733938 -h00fi&^%1&^%1537050053 -fantoro&^%4&^%1537106482 +ben&^%28&^%1539065026 diff --git a/Code/irc/topicbot.py b/Code/irc/topicbot.py index 19e4739..b7cdf98 100755 --- a/Code/irc/topicbot.py +++ b/Code/irc/topicbot.py @@ -10,12 +10,8 @@ import fileinput import random import time -import formatter -import get_users -import mentions -import pretty_date import inflect -import names +import util parser = OptionParser() @@ -23,7 +19,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", ) @@ -49,22 +45,6 @@ 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") - - -def hello(): - ircsock.send("PRIVMSG " + channel + " :Hello!\n") - - def get_topic(channel, user, time): # topic scores are saved as &^%&^% with open("topicscores.txt", "r") as scorefile: @@ -84,19 +64,16 @@ def get_topic(channel, user, time): with open("topics_" + channel + ".txt", "r") as topics: topic = topics.readlines()[-1].strip("\n").split("&^%", 3) - byuser = names.get_name(topic[1]) - ircsock.send( - "PRIVMSG " - + channel - + " :I've told you " - + p.number_to_words(userscore) - + " times! It's \"" - + topic[2] - + '" (Set by ' - + byuser - + " " - + pretty_date.pretty_date(int(topic[0])) - + ")\n" + byuser = util.get_name(topic[1]) + util.sendmsg( + ircsock, + channel, + "I've told you {} times! It's \"{}\" (set by {} {})".format( + p.number_to_words(userscore), + topic[2], + byuser, + util.pretty_date(int(topic[0])), + ), ) @@ -117,14 +94,10 @@ def count_topic(channel, user, time, msg): scorefile.writelines(scores) if not found: scorefile.write(user + "&^%0&^%1") - ircsock.send( - "PRIVMSG " - + channel - + " :" - + user - + " has changed the topic " - + p.number_to_words(userscore) - + " times!\n" + util.sendmsg( + ircsock, + channel, + "{} has changed the topic {} times!".format(user, p.number_to_words(userscore)), ) @@ -139,29 +112,29 @@ def random_topic(channel, user, time, setTopic=False): if setTopic: set_topic(channel, user, time, msg) else: - ircsock.send("PRIVMSG " + channel + " :Suggested Topic: " + msg + "\n") + util.sendmsg(ircsock, channel, "Suggested Topic: {}".format(msg)) def rollcall(channel): - ircsock.send( - "PRIVMSG " - + channel - + " :topicbot reporting! I respond to !topic !settopic !suggesttopic !thistory\n" + util.sendmsg( + ircsock, + channel, + "topicbot reporting! I respond to !topic !settopic !suggesttopic !thistory", ) def topic_score(channel): - ircsock.send("PRIVMSG " + channel + " :Not implemented yet") + util.sendmsg(ircsock, channel, "Not implemented yet") def topic_scores(channel): - ircsock.send("PRIVMSG " + channel + " :Not implemented yet") + util.sendmsg(ircsock, channel, "Not implemented yet") def topic_history(channel, user, count): try: iCount = int(count.split()[1]) - except (ValueError, IndexError) as e: + except (ValueError, IndexError): iCount = 3 if iCount > 10: iCount = 10 @@ -169,73 +142,40 @@ def topic_history(channel, user, count): iCount = 3 with open("topics_" + channel + ".txt", "r") as topicsfile: # topics = topicsfile.readlines()[-iCount:].reverse() - ircsock.send( - "PRIVMSG " - + channel - + " :Ok, here were the last " - + p.number_to_words(iCount) - + " topics\n" + util.sendmsg( + ircsock, + channel, + "Ok, here are the last {} topics".format(p.number_to_words(iCount)), ) for idx, topic in enumerate(reversed(topicsfile.readlines()[-iCount:])): topic = topic.strip("\n").split("&^%", 3) - byuser = names.get_name(topic[1]) - ircsock.send( - "PRIVMSG " - + channel - + " :" - + str(idx + 1) - + ': "' - + topic[2] - + '" (Set by ' - + byuser - + " " - + pretty_date.pretty_date(int(topic[0])) - + ")\n" + byuser = util.get_name(topic[1]) + util.sendmsg( + ircsock, + channel, + "{}: {} (set by {} {})".format( + str(idx + 1), topic[2], byuser, util.pretty_date(int(topic[0])) + ), ) -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 - i2 = msg.index("!") - return msg[i1:i2] - except ValueError: - return "" - - def listen(): while 1: - ircmsg = ircsock.recv(2048) + ircmsg = ircsock.recv(2048).decode() ircmsg = ircmsg.strip("\n\r") if ircmsg[:4] == "PING": - ping(ircmsg.split(" ")[1]) + util.ping(ircsock, ircmsg) - formatted = formatter.format_message(ircmsg) + formatted = util.format_message(ircmsg) if "" == formatted: continue # print formatted - split = formatted.split("\t") - msgtime = split[0] - user = split[1] - command = split[2] - channel = split[3] - messageText = split[4] + msgtime, user, command, channel, messageText = formatted.split("\t") if command == "TOPIC" and user != options.nick: count_topic(channel, user, msgtime, messageText) @@ -262,13 +202,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/topicscores.txt b/Code/irc/topicscores.txt index c1304b2..7781292 100644 --- a/Code/irc/topicscores.txt +++ b/Code/irc/topicscores.txt @@ -1 +1,2 @@ vilmibm&^%0&^%2 +ben&^%3&^%0 diff --git a/Code/irc/util.py b/Code/irc/util.py index 96dceee..e3da9ed 100644 --- a/Code/irc/util.py +++ b/Code/irc/util.py @@ -4,30 +4,44 @@ import random import re -def hello(ircsock, chan): - sendmsg(ircsock, chan, "Hello!") - - -def ping(pong): - ircsock.send("PONG {}\n".format(pong.split(" ")[1])) +def ping(ircsock, msg): + ircsock.send("PONG {}\n".format(msg.split(" ")[1]).encode()) def sendmsg(ircsock, chan, msg): - ircsock.send("PRIVMSG {} :{}\r\n".format(chan, msg)) + print("sending {} to {}".format(msg, chan)) + ircsock.send("PRIVMSG {} :{}\r\n".format(chan, msg).encode()) def joinchan(ircsock, chan): - ircsock.send("JOIN {}\r\n".format(chan)) + print("joining {}".format(chan)) + ircsock.send("JOIN {}\r\n".format(chan).encode()) + + +def get_user_from_message(msg): + try: + i1 = msg.index(":") + 1 + i2 = msg.index("!") + return msg[i1:i2] + except ValueError: + return "" 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) + print(options) + server, port = options.server.split(":") + ircsock.connect((server, int(port))) + print(ircsock) + nick = "NICK {}\r\n".format(options.nick).encode() + print(nick) + ircsock.send(nick) + login = "USER {0} {0} {0} {0}".format(options.nick).encode() + print(login) + ircsock.send(login) + mode = "MODE +B {}\r\n".format(options.nick).encode() + print(mode) + ircsock.send(mode) + joinchan(ircsock, options.channel) # integer number to english word conversion diff --git a/Code/irc/wangbot.py b/Code/irc/wangbot.py index 8249cd2..5e08bee 100755 --- a/Code/irc/wangbot.py +++ b/Code/irc/wangbot.py @@ -37,7 +37,7 @@ parser.add_option( "-n", "--nick", dest="nick", - default="numberwang_bot", + default="wangbot", help="the nick to use", metavar="NICK", ) @@ -274,27 +274,18 @@ def rollcall(channel): 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", + "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 get_user_from_message(msg): - try: - i1 = msg.index(":") + 1 - i2 = msg.index("!") - return msg[i1:i2] - except ValueError: - return "" - - def listen(): while 1: - ircmsg = ircsock.recv(2048) + ircmsg = ircsock.recv(2048).decode() ircmsg = ircmsg.strip("\n\r") if ircmsg[:4] == "PING": - ping(ircmsg.split(" ")[1]) + util.ping(ircsock, ircmsg) formatted = util.format_message(ircmsg) @@ -303,7 +294,7 @@ def listen(): # print formatted - time, user, command, channel, messageText = formatted.split("\t") + _time, user, _command, channel, messageText = formatted.split("\t") if ircmsg.find(":!numberwang") != -1 and roundsLeft == 0: start_numberwang(channel, user)