Ported banterbot to pinhook framework and some other changes

This commit is contained in:
RussellChamp committed 2019-01-25 11:16:19 -05:00
1 parent 0627b4a9e3
commit bc102890b2
39 files changed
+1629 -507

No files matched your search

+21 -391
View File
@@ -1,32 +1,7 @@
#!/usr/bin/python3
# using python3 because of unicode and crap
# http://wiki.shellium.org/w/Writing_an_IRC_bot_in_Python
# Import some necessary libraries.
import argparse
import socket
import os
import sys
import fileinput
import random
import re
import subprocess
import textwrap
import time
import datetime
import inflect
from rhymesWith import getRhymes
from rhymesWith import rhymeZone
from defineWord import defWord
import welch
import evil
import tumblr
import xkcdApropos
import wikiphilosophy
import acronymFinder
import util
from whosaid import whoSaid
from pinhook.bot import Bot
parser = argparse.ArgumentParser()
@@ -34,10 +9,19 @@ parser.add_argument(
"-s",
"--server",
dest="server",
default="127.0.0.1:6667",
default="127.0.0.1",
help="the server to connect to",
metavar="SERVER",
)
parser.add_argument(
"-p",
"--port",
dest="port",
type=int,
default=6667,
help="the port to connect to",
metavar="PORT",
)
parser.add_argument(
"-c",
"--channels",
@@ -65,370 +49,16 @@ parser.add_argument(
)
args = parser.parse_args()
print(args)
p = inflect.engine()
def hello():
util.sendmsg(ircsoc, channel, "Hello!")
def score_banter(channel, user, messageText):
score = 5
with open("banterscores.txt", "r") as banterfile:
bantz = banterfile.readlines()
words = messageText.strip("\n").split(" ")
for word in words:
for bant in bantz:
bword = bant.strip("\n").split("|")
if re.sub("[^a-z0-9]+", "", word.lower()) == bword[0]:
score += int(bword[1])
score += messageText.count("!") * 2 # hype is banter
score -= messageText.count("!!!") * 6 # too much hype is not banter
score += messageText.count("#") * 3 # hashs are mad bantz
score -= messageText.count("##") * 6 # but too many is garbage
names = ["mate", "lad", "my best boy"]
compliment = [
"top-drawer",
"top-shelf",
"bangin'",
"legendary",
"smashing",
"incredible",
"impeccable",
"stunning",
]
msg = ""
if score > 100:
msg = "Truely {}, {}! That was some #banter! You earned a {} for that!".format(
random.choice(compliment).capitalize(), random.choice(names), score
)
elif score > 50:
msg = "{} #banter! You get a {} from me!".format(
random.choice(compliment).capitalize(), score
)
elif score > 10:
msg = "{} #banter. You get a {}".format(
random.choice(["acceptible", "reasonable", "passable"]).capitalize(), score
)
else:
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"]
),
random.choice(["lad", "lah", "boy", ""]),
score,
bot = Bot(
channels = args.channels,
nickname = args.nick,
ops = [ args.owner ],
plugin_dir = "{}_plugins".format(args.nick),
server = args.server,
port = args.port
)
util.sendmsg(ircsock, channel, msg)
def get_new_banter(channel, user):
with open("/usr/share/dict/words", "r") as dict:
words = list(filter(lambda word: re.search(r"^[^']*$", word), dict.readlines()))
if random.randint(0, 1): # look for *ant words
words = list(filter(lambda word: re.search(r"ant", word), words))
random.shuffle(words)
word = words[0].strip("\n")
start = word.find("ant")
if start == 0:
word = "b" + word
else:
if "aeiou".find(word[start]) > -1: # just append a 'b'
word = word[:start] + "b" + word[start:]
else: # replace the letter with 'b'
word = word[: start - 1] + "b" + word[start:]
else: # look for ban* words
words = list(filter(lambda word: re.search(r"ban", word), words))
random.shuffle(words)
word = words[0].strip("\n")
end = word.find("ban") + 3
if end == len(word):
word = word + "t"
else:
if "aeiou".find(word[end]) > -1: # just append 't'
word = word[:end] + "t" + word[end:]
else: # replace the letter with 'b'
word = word[:end] + "t" + word[end + 1 :]
util.sendmsg(
ircsock, channel, "{} : Here, why don't you try '{}'?".format(user, word)
)
def get_rhymes(channel, user, text):
word = ""
if len(text.split(" ")) > 1:
word = text.split(" ")[1]
else:
with open("/home/nossidge/poems/words_poetic.txt", "r") as words:
word = random.choice(words.readlines()).strip("\n")
rhymes = rhymeZone(word)
if len(rhymes) == 0:
util.sendmsg(
ircsock,
channel,
"{}: Couldn't find anything that rhymes with '{}' :(".format(user, word),
)
else:
util.sendmsg(
ircsock,
channel,
"{}: Here, these words rhyme with '{}': {}".format(
user, word, ", ".join(rhymes)
),
)
def define_word(channel, user, text):
word = ""
defs = []
if len(text.split(" ")) > 1:
word = text.split(" ")[1]
defs = defWord(word)
if len(defs) == 0:
util.sendmsg(
ircsock,
channel,
"{}: Couldn't find the definition of '{}' :(".format(user, word),
)
elif isinstance(defs, list):
for entry in defs:
util.sendmsg(
ircsock, channel, "{} : Define '{}' {}".format(user, word, entry[0:400])
)
else:
util.sendmsg(
ircsock, channel, "{} : Define '{}' {}".format(user, word, defs[0:400])
)
def make_rainbow(channel, user, text):
rbword = util.makeRainbow(text[9:])
util.sendmsg(ircsock, channel, rbword)
def get_welch(channel):
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)]:
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)]:
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)]:
util.sendmsg(ircsock, channel, line)
def get_wphilosophy(channel, text):
util.sendmsg(ircsock, channel, "Ok, give me a minute while I look up '{}'".format(text))
steps = wikiphilosophy.get_philosophy_lower(text)
if not steps:
util.sendmsg(
ircsock, channel, "Couldn't find a wikipedia entry for {}".format(text)
)
else:
joined_steps = " > ".join(steps)
if steps[-1] == "Philosophy":
joined_steps += "!!!"
for line in [
joined_steps[i : i + 400] for i in range(0, len(joined_steps), 400)
]:
util.sendmsg(ircsock, channel, line)
def figlet(channel, text):
if not text:
util.sendmsg(ircsock, channel, "No text given. :(")
else:
lines = subprocess.Popen(
["figlet", "-w140"] + text.split(" "), shell=False, stdout=subprocess.PIPE
).stdout.read().decode("utf-8")
for line in lines.split("\n"):
util.sendmsg(ircsock, channel, line)
time.sleep(0.4) # to avoid channel throttle due to spamming
def toilet(channel, text):
if not text:
util.sendmsg(ircsock, channel, "No text given. :(")
else:
lines = subprocess.Popen(
["toilet", "-w140", "--irc"] + text.split(" "),
shell=False,
stdout=subprocess.PIPE,
).stdout.read().decode("utf-8")
for line in lines.split("\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:
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'
util.sendmsg(ircsock, channel, d)
if len(defs) > 5:
util.sendmsg(ircsock, channel, defs[-1])
def get_whosaid(channel, text):
if not text:
util.sendmsg(ircsock, channel, " :No text given :(")
else:
result = whoSaid(text)
date = datetime.date.fromtimestamp(result["timecutoff"])
dateStr = date.strftime("%B %d")
if not result["data"]:
msg = "Nobody said '%s' since %s" % (text, dateStr)
else:
msg = "Since %s, %s said '%s' %d times" % (
dateStr,
result["data"][0][0],
text,
result["data"][0][1],
)
if len(result["data"]) > 1:
msg += " and %s said it %d times" % (
result["data"][1][0],
result["data"][1][1],
)
util.sendmsg(ircsock, channel, msg)
def get_notice(user, channel):
util.notice(ircsock, user, channel, "Notice me senpai!")
def get_water(user, channel, msg, botnick):
if msg.find(botnick) == 0:
util.sendmsg(ircsock, channel, "Fight me, {}!".format(user))
def mug_off(channel):
util.sendmsg(ircsock, channel, "u want some of this, m8?")
def rollcall(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 !evil !kjp and !help
"""
for line in textwrap.dedent(text).split("\n"):
if line == "":
continue
util.sendmsg(ircsock, channel, line)
def listen(botnick):
while 1: # loop forever
ircmsg = ircsock.recv(2048).decode('utf-8')
for msg in ircmsg.split("\n"):
msg = msg.strip("\n\r")
if msg[:4] == "PING":
util.ping(ircsock, msg)
continue
formatted = util.format_message(msg)
if "" == formatted:
continue
print(formatted)
_time, user, _command, channel, messageText = formatted.split("\t")
if messageText.find("#banter") != -1 or messageText.find("#bantz") != -1:
score_banter(channel, user, messageText)
if messageText.startswith("!newbanter"):
get_new_banter(channel, user)
if messageText.startswith("!rhymes"):
get_rhymes(channel, user, messageText)
if messageText.startswith("!define"):
define_word(channel, user, messageText)
if messageText.startswith("!rainbow"):
make_rainbow(channel, user, messageText)
if messageText.startswith("!welch"):
get_welch(channel)
if messageText.startswith("!evil"):
get_evil(channel)
if messageText.startswith("!kjp"):
get_tumble("http://kingjamesprogramming.tumblr.com", channel)
if messageText.startswith("!help"):
get_tumble("http://thedoomthatcametopuppet.tumblr.com", channel)
if messageText.startswith("!xkcd"):
get_xkcd(channel, messageText)
if messageText.startswith("!wiki-philosophy"):
get_wphilosophy(channel, messageText[17:])
if messageText.startswith("!figlet"):
figlet(channel, messageText[8:])
if messageText.startswith("!toilet"):
toilet(channel, messageText[8:])
if messageText.startswith("!acronym"):
get_acronym(channel, messageText[9:])
if messageText.startswith("!whosaid"):
get_whosaid(channel, messageText[9:])
if messageText.startswith("!notice"):
get_notice(user, channel)
if messageText.startswith("!water"):
get_water(user, channel, messageText[7:], botnick)
if messageText.startswith("!rollcall"):
rollcall(channel)
if messageText.startswith(botnick + ":"):
mug_off(channel)
if messageText.startswith("!join") and user == args.owner:
util.joinchan(ircsock, messageText[6:])
if messageText.startswith("!part") and user == args.owner:
util.part(ircsock, messageText[6:])
if messageText.startswith("!quit") and user == args.owner:
util.quit(ircsock, "Later chumps!")
return
sys.stdout.flush()
time.sleep(1)
# ROOT: i commented this out until it stops pegging the CPU.
# ~krowbar: this has the same logic loop as tildebot but for whatever reason
# it is banterbot that gets booted from IRC then rage-thrashes the machine
ircsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
util.connect(ircsock, args)
listen(args.nick)
if __name__ == "__main__":
bot.start()
+440
View File
@@ -0,0 +1,440 @@
#!/usr/bin/python3
# using python3 because of unicode and crap
# http://wiki.shellium.org/w/Writing_an_IRC_bot_in_Python
# Import some necessary libraries.
import argparse
import socket
import os
import sys
import fileinput
import random
import re
import subprocess
import textwrap
import time
import datetime
import inflect
from rhymesWith import getRhymes
from rhymesWith import rhymeZone
from defineWord import defWord
import welch
import evil
import tumblr
import xkcdApropos
import wikiphilosophy
import acronymFinder
import util
from whosaid import whoSaid
parser = argparse.ArgumentParser()
parser.add_argument(
"-s",
"--server",
dest="server",
default="127.0.0.1:6667",
help="the server to connect to",
metavar="SERVER",
)
parser.add_argument(
"-c",
"--channels",
dest="channels",
nargs="+",
default=["#bot_test"],
help="the channels to join",
metavar="CHANNELS",
)
parser.add_argument(
"-n",
"--nick",
dest="nick",
default="banterbot_legacy",
help="the nick to use",
metavar="NICK",
)
parser.add_argument(
"-o",
"--owner",
dest="owner",
default="krowbar",
help="the owner of this bot",
metavar="OWNER",
)
args = parser.parse_args()
p = inflect.engine()
def hello():
util.sendmsg(ircsoc, channel, "Hello!")
def score_banter(channel, user, messageText):
score = 5
with open("banterscores.txt", "r") as banterfile:
bantz = banterfile.readlines()
words = messageText.strip("\n").split(" ")
for word in words:
for bant in bantz:
bword = bant.strip("\n").split("|")
if re.sub("[^a-z0-9]+", "", word.lower()) == bword[0]:
score += int(bword[1])
score += messageText.count("!") * 2 # hype is banter
score -= messageText.count("!!!") * 6 # too much hype is not banter
score += messageText.count("#") * 3 # hashs are mad bantz
score -= messageText.count("##") * 6 # but too many is garbage
names = ["mate", "lad", "my best boy"]
compliment = [
"top-drawer",
"top-shelf",
"bangin'",
"legendary",
"smashing",
"incredible",
"impeccable",
"stunning",
]
msg = ""
if score > 100:
msg = "Truely {}, {}! That was some #banter! You earned a {} for that!".format(
random.choice(compliment).capitalize(), random.choice(names), score
)
elif score > 50:
msg = "{} #banter! You get a {} from me!".format(
random.choice(compliment).capitalize(), score
)
elif score > 10:
msg = "{} #banter. You get a {}".format(
random.choice(["acceptible", "reasonable", "passable"]).capitalize(), score
)
else:
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"]
),
random.choice(["lad", "lah", "boy", ""]),
score,
)
util.sendmsg(ircsock, channel, msg)
def get_new_banter(channel, user):
with open("/usr/share/dict/words", "r") as dict:
words = list(filter(lambda word: re.search(r"^[^']*$", word), dict.readlines()))
if random.randint(0, 1): # look for *ant words
words = list(filter(lambda word: re.search(r"ant", word), words))
random.shuffle(words)
word = words[0].strip("\n")
start = word.find("ant")
if start == 0:
word = "b" + word
else:
if "aeiou".find(word[start]) > -1: # just append a 'b'
word = word[:start] + "b" + word[start:]
else: # replace the letter with 'b'
word = word[: start - 1] + "b" + word[start:]
else: # look for ban* words
words = list(filter(lambda word: re.search(r"ban", word), words))
random.shuffle(words)
word = words[0].strip("\n")
end = word.find("ban") + 3
if end == len(word):
word = word + "t"
else:
if "aeiou".find(word[end]) > -1: # just append 't'
word = word[:end] + "t" + word[end:]
else: # replace the letter with 'b'
word = word[:end] + "t" + word[end + 1 :]
util.sendmsg(
ircsock, channel, "{} : Here, why don't you try '{}'?".format(user, word)
)
def get_rhymes(channel, user, text):
word = ""
if len(text.split(" ")) > 1:
word = text.split(" ")[1]
else:
with open("/home/nossidge/poems/words_poetic.txt", "r") as words:
word = random.choice(words.readlines()).strip("\n")
rhymes = rhymeZone(word)
if len(rhymes) == 0:
util.sendmsg(
ircsock,
channel,
"{}: Couldn't find anything that rhymes with '{}' :(".format(user, word),
)
else:
util.sendmsg(
ircsock,
channel,
"{}: Here, these words rhyme with '{}': {}".format(
user, word, ", ".join(rhymes)
),
)
def define_word(channel, user, text):
word = ""
defs = []
if len(text.split(" ")) > 1:
word = text.split(" ")[1]
defs = defWord(word)
if len(defs) == 0:
util.sendmsg(
ircsock,
channel,
"{}: Couldn't find the definition of '{}' :(".format(user, word),
)
elif isinstance(defs, list):
for entry in defs:
util.sendmsg(
ircsock, channel, "{} : Define '{}' {}".format(user, word, entry[0:400])
)
else:
util.sendmsg(
ircsock, channel, "{} : Define '{}' {}".format(user, word, defs[0:400])
)
def make_rainbow(channel, user, text):
rbword = util.makeRainbow(text[9:])
util.sendmsg(ircsock, channel, rbword)
def get_welch(channel):
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)]:
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)]:
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)]:
util.sendmsg(ircsock, channel, line)
def get_wphilosophy(channel, text):
util.sendmsg(ircsock, channel, "Ok, give me a minute while I look up '{}'".format(text))
steps = wikiphilosophy.get_philosophy_lower(text)
if not steps:
util.sendmsg(
ircsock, channel, "Couldn't find a wikipedia entry for {}".format(text)
)
else:
joined_steps = " > ".join(steps)
if steps[-1] == "Philosophy":
joined_steps += "!!!"
for line in [
joined_steps[i : i + 400] for i in range(0, len(joined_steps), 400)
]:
util.sendmsg(ircsock, channel, line)
def figlet(channel, text):
if not text:
util.sendmsg(ircsock, channel, "No text given. :(")
else:
lines = subprocess.Popen(
["figlet", "-w140"] + text.split(" "), shell=False, stdout=subprocess.PIPE
).stdout.read().decode("utf-8")
for line in lines.split("\n"):
util.sendmsg(ircsock, channel, line)
time.sleep(0.4) # to avoid channel throttle due to spamming
def toilet(channel, text):
if not text:
util.sendmsg(ircsock, channel, "No text given. :(")
else:
lines = subprocess.Popen(
["toilet", "-w140", "-F", "crop", "--irc"] + text.split(" "),
shell=False,
stdout=subprocess.PIPE,
).stdout.read().decode("utf-8")
for line in lines.split("\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:
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'
util.sendmsg(ircsock, channel, d)
if len(defs) > 5:
util.sendmsg(ircsock, channel, defs[-1])
def get_whosaid(channel, text):
if not text:
util.sendmsg(ircsock, channel, " :No text given :(")
else:
result = whoSaid(text)
date = datetime.date.fromtimestamp(result["timecutoff"])
dateStr = date.strftime("%B %d")
if not result["data"]:
msg = "Nobody said '%s' since %s" % (text, dateStr)
else:
msg = "Since %s, %s said '%s' %d times" % (
dateStr,
result["data"][0][0],
text,
result["data"][0][1],
)
if len(result["data"]) > 1:
msg += " and %s said it %d times" % (
result["data"][1][0],
result["data"][1][1],
)
util.sendmsg(ircsock, channel, msg)
def get_notice(user, channel):
util.notice(ircsock, user, channel, "Notice me senpai!")
def get_water(user, channel, msg, botnick):
if msg.find(botnick) == 0:
util.sendmsg(ircsock, channel, "Fight me, {}!".format(user))
def mug_off(channel):
util.sendmsg(ircsock, channel, "u want some of this, m8?")
def rollcall(channel):
text = """
U wot m8? I score all the top drawer #banter and #bantz on this channel! / Find new top-shelf banter with !newbanter [mungeWord [dictionary]], !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 !evil !kjp and !help
"""
for line in textwrap.dedent(text).split("\n"):
if line == "":
continue
util.sendmsg(ircsock, channel, line)
def listen(botnick):
while 1: # loop forever
ircmsg = ircsock.recv(2048).decode('utf-8')
for msg in ircmsg.split("\n"):
msg = msg.strip("\n\r")
if msg[:4] == "PING":
util.ping(ircsock, msg)
continue
formatted = util.format_message(msg)
if "" == formatted:
time.sleep(1)
continue
# print(formatted)
_time, user, _command, channel, messageText = formatted.split("\t")
if messageText.find("#banter") != -1 or messageText.find("#bantz") != -1:
score_banter(channel, user, messageText)
if messageText.startswith("!newbanter"):
get_new_banter(channel, user, messageText)
if messageText.startswith("!rhymes"):
get_rhymes(channel, user, messageText)
if messageText.startswith("!define"):
define_word(channel, user, messageText)
if messageText.startswith("!rainbow"):
make_rainbow(channel, user, messageText)
if messageText.startswith("!welch"):
get_welch(channel)
if messageText.startswith("!evil"):
get_evil(channel)
if messageText.startswith("!kjp"):
get_tumble("http://kingjamesprogramming.tumblr.com", channel)
if messageText.startswith("!help"):
get_tumble("http://thedoomthatcametopuppet.tumblr.com", channel)
if messageText.startswith("!xkcd"):
get_xkcd(channel, messageText)
if messageText.startswith("!wiki-philosophy"):
get_wphilosophy(channel, messageText[17:])
if messageText.startswith("!figlet"):
figlet(channel, messageText[8:])
if messageText.startswith("!toilet"):
toilet(channel, messageText[8:])
if messageText.startswith("!acronym"):
get_acronym(channel, messageText[9:])
if messageText.startswith("!whosaid"):
get_whosaid(channel, messageText[9:])
if messageText.startswith("!notice"):
get_notice(user, channel)
if messageText.startswith("!water"):
get_water(user, channel, messageText[7:], botnick)
if messageText.startswith("!rollcall"):
rollcall(channel)
if messageText.startswith(botnick + ":"):
mug_off(channel)
if messageText.startswith("!join") and user == args.owner:
util.joinchan(ircsock, messageText[6:])
if messageText.startswith("!part") and user == args.owner:
util.part(ircsock, messageText[6:])
if messageText.startswith("!quit") and user == args.owner:
util.quit(ircsock, "Later chumps!")
return
sys.stdout.flush()
time.sleep(1)
if __name__ == "__main__":
# ROOT: i commented this out until it stops pegging the CPU.
# ~krowbar: this has the same logic loop as tildebot but for whatever reason
# it is banterbot that gets booted from IRC then rage-thrashes the machine
ircsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
util.connect(ircsock, args)
listen(args.nick)
else:
# create a fake socket that we'll use to just write to the screen
import mock
ircsock = mock.Mock()
# print("!! ircsock was not initialized! most methods will not work !!")
+8
View File
@@ -0,0 +1,8 @@
#!/usr/bin/python3
import pinhook.plugin
from util import acronymFinder
@pinhook.plugin.register('!acronym')
def acronym_plugin(msg):
return pinhook.plugin.message(acronymFinder.get_acros(msg.arg, True, True))
+19
View File
@@ -0,0 +1,19 @@
#!/usr/bin/python3
import pinhook.plugin
from util import defineWord
@pinhook.plugin.register('!define')
def define_plugin(msg):
if not msg.arg:
return pinhook.plugin.message("{}: No word given".format(msg.nick))
word = msg.arg.split()[0]
defs = defineWord.defWord(word)
if not defs:
return pinhook.plugin.message("{}: Couldn't find the definition of '{}' :(".format(msg.nick, word))
elif isinstance(defs, list):
return pinhook.plugin.message("\n".join(["{} : Define '{}' {}".format(msg.nick, word, entry) for entry in defs]))
else:
return pinhook.plugin.message("{} : Define '{}' {}".format(msg.nick, word, defs))
+8
View File
@@ -0,0 +1,8 @@
#!/usr/bin/python3
import pinhook.plugin
from util import evil
@pinhook.plugin.register('!evil')
def evil_plugin(msg):
return pinhook.plugin.message(evil.get_thing())
+8
View File
@@ -0,0 +1,8 @@
#!/usr/bin/python3
import pinhook.plugin
@pinhook.plugin.listener('fight')
def fight_plugin(msg):
if msg.botnick + ": " in msg.text:
return pinhook.plugin.message("u want some of this, m8?")
+18
View File
@@ -0,0 +1,18 @@
#!/usr/bin/python3
import pinhook.plugin
import subprocess
import time
@pinhook.plugin.register('!figlet')
def figlet_plugin(msg):
if not msg.arg:
return pinhook.plugin.message("No text given. :(")
else:
lines = subprocess.Popen(
["figlet", "-w140"] + msg.arg.split(" "), shell=False, stdout=subprocess.PIPE
).stdout.read().decode("utf-8")
for line in lines.split("\n"):
msg.privmsg(msg.channel, line)
time.sleep(0.4) # to avoid channel throttle due to spamming
+23
View File
@@ -0,0 +1,23 @@
#!/usr/bin/python3
import pinhook.plugin
from util import newBanter
@pinhook.plugin.register('!newbanter')
def newbanter_plugin(msg):
try:
args = msg.arg.split()
banter = newBanter.getBanter(*args)
if banter == "":
text = "{}: Could not find any new banter".format(msg.nick)
if len(args) >= 1:
text += " using munge word '{}'. Try something else?".format(args[0])
return pinhook.plugin.message(text)
else:
return pinhook.plugin.message("{}: Here, why don't you try '{}'?".format(msg.nick, banter))
except FileNotFoundError as e: # this happens if you attempt to search a word dict that doesn't exist
text = "{}: Could not find word dictionary".format(msg.nick)
if len(args) >= 2:
text += " '{}'. Maybe try another one?".format(args[1])
return pinhook.plugin.message(text)
+7
View File
@@ -0,0 +1,7 @@
#!/usr/bin/python3
import pinhook.plugin
@pinhook.plugin.register('!notice')
def notice_plugin(msg):
msg.notice(msg.nick, "Notice me senpai!")
+21
View File
@@ -0,0 +1,21 @@
#!/usr/bin/python3
import pinhook.plugin
import random
@pinhook.plugin.register('!rainbow')
def rainbow_plugin(msg):
word = msg.arg 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 pinhook.plugin.message(output)
+21
View File
@@ -0,0 +1,21 @@
#!/usr/bin/python3
import pinhook.plugin
from util import rhymesWith
poetic_file = "/home/nossidge/poems/words_poetic.txt"
@pinhook.plugin.register('!rhymes')
def rhymes_plugin(msg):
word = ""
if msg.arg == "":
with open(poetic_file, "r") as words:
word = random.choice(words.readlines()).strip("\n")
else:
word = msg.arg.split()[0]
rhymes = rhymesWith.rhymeZone(word)
if len(rhymes) == 0:
return pinhook.plugin.message("{}: Couldn't find anything that rhymes with '{}' :(".format(msg.nick, word))
else:
return pinhook.plugin.message("{}: Here, these words rhyme with '{}': {}".format(msg.nick, word, ", ".join(rhymes)))
+10
View File
@@ -0,0 +1,10 @@
#!/usr/bin/python3
import pinhook.plugin
@pinhook.plugin.register('!rollcall')
def rollcall_plugin(msg):
text = "U wot m8? I score all the top drawer #banter and #bantz on this channel! / Find new top-shelf banter with !newbanter [mungeWord [dictionary]], !rhymes, and !define."
text += "\nLook up things with !acronym and !whosaid / Make your chatter #legend with !rainbow, !toilet, and !figlet."
text += "\nFind interesting things with !xkcd and !wiki-philosophy / Get jokes with !welch !evil !kjp and !help"
return pinhook.plugin.message(text)
@@ -0,0 +1,10 @@
#!/usr/bin/python3
import pinhook.plugin
from util import banter
@pinhook.plugin.listener('banter')
def banter_plugin(msg):
if "#banter" in msg.text.lower() or "#bantz" in msg.text.lower():
message = banter.score_banter(msg.nick, msg.text)
return pinhook.plugin.message(message)
+7
View File
@@ -0,0 +1,7 @@
#!/usr/bin/python3
import pinhook.plugin
@pinhook.plugin.register('!')
def _plugin(msg):
return pinhook.plugin.message()
+19
View File
@@ -0,0 +1,19 @@
#!/usr/bin/python3
import pinhook.plugin
import subprocess
import time
@pinhook.plugin.register('!toilet')
def toilet_plugin(msg):
if not msg.arg:
return pinhook.plugin.message("No text given. :(")
else:
lines = subprocess.Popen(
["toilet", "-w140", "-F", "crop", "--irc"] + msg.arg.split(" "),
shell=False,
stdout=subprocess.PIPE,
).stdout.read().decode("utf-8")
for line in lines.split("\n"):
msg.privmsg(msg.channel, line)
time.sleep(0.4) # to avoid channel throttle due to spamming
+12
View File
@@ -0,0 +1,12 @@
#!/usr/bin/python3
import pinhook.plugin
from util import tumblr
@pinhook.plugin.register('!kjp')
def kjp_plugin(msg):
return pinhook.plugin.message(tumblr.tumble("http://kingjamesprogramming.tumblr.com"))
@pinhook.plugin.register('!help')
def help_plugin(msg):
return pinhook.plugin.message(tumblr.tumble("http://thedoomthatcametopuppet.tumblr.com"))
+8
View File
@@ -0,0 +1,8 @@
#!/usr/bin/python3
import pinhook.plugin
@pinhook.plugin.register('!water')
def water_plugin(msg):
if msg.botnick in msg.arg:
return pinhook.plugin.message("Fight me, {}!".format(msg.nick))
+8
View File
@@ -0,0 +1,8 @@
#!/usr/bin/python3
import pinhook.plugin
from util import welch
@pinhook.plugin.register('!welch')
def welch_plugin(msg):
return pinhook.plugin.message(welch.get_thing())
+8
View File
@@ -0,0 +1,8 @@
#!/usr/bin/python3
import pinhook.plugin
from util import whoSaid
@pinhook.plugin.register('!whosaid')
def whosaid_plugin(msg):
return pinhook.plugin.message(whoSaid.whoSaid(msg.arg))
+18
View File
@@ -0,0 +1,18 @@
#!/usr/bin/python3
import pinhook.plugin
from util import wikiphilosophy
@pinhook.plugin.register('!wphilosophy')
def wiki_philosophy_plugin(msg):
msg.privmsg(msg.channel, "Ok, give me a minute while I look up '{}'".format(msg.arg))
steps = wikiphilosophy.get_philosophy_lower(msg.arg)
if not steps:
return pinhook.plugin.message("Couldn't find a wikipedia entry for {}".format(msg.arg))
else:
joined_steps = " > ".join(steps)
if steps[-1] == "Philosophy":
joined_steps += "!!!"
for line in [ joined_steps[i : i + 400] for i in range(0, len(joined_steps), 400) ]:
msg.privmsg(msg.channel, line)
+8
View File
@@ -0,0 +1,8 @@
#!/usr/bin/python3
import pinhook.plugin
from util import xkcdApropos
@pinhook.plugin.register('!xkcd')
def xkcd_plugin(msg):
return pinhook.plugin.message(xkcdApropos.xkcd(msg.arg))
+55
View File
@@ -0,0 +1,55 @@
#!/usr/bin/python3
import random
import re
dictDir = "/usr/share/dict/"
def getBanter(morphWord="bant", dictName="words"):
with open(dictDir + dictName, "r") as dict:
# get rid of all the words with apostrophes
words = list(filter(lambda word: re.search(r"^[^']*$", word), dict.readlines()))
head = getBanterHead(words, morphWord)
tail = getBanterTail(words, morphWord)
if head == "" and tail == "":
return "" # dang, we just failed
else:
# pick randomly between non-empty strings
return random.choice([w for w in [head, tail] if w != ""])
def getBanterHead(words, morphWord):
morphHead = morphWord[0:-1]
morphLast = morphWord[-1]
filtered = list(filter(lambda word: re.search(morphHead, word), words))
if len(filtered) == 0:
return "" # nothing applicable found
word = random.choice(filtered).strip("\n")
end = word.find(morphHead) + len(morphHead)
if end == len(word):
return word + morphLast
else:
if "aeiou".find(word[end]) > -1: # just append 't'
return word[:end] + morphLast + word[end:]
else: # replace the letter with 'b'
return word[:end] + morphLast + word[end + 1 :]
def getBanterTail(words, morphWord):
morphTail = morphWord[1:]
morphFirst = morphWord[0]
filtered = list(filter(lambda word: re.search(morphTail, word), words))
if len(filtered) == 0:
return "" # nothing applicable found
word = random.choice(filtered).strip("\n")
start = word.find(morphTail)
if start == 0:
return morphFirst + word
else:
if "aeiou".find(word[start]) > -1: # just append a 'b'
return word[:start] + morphFirst + word[start:]
else: # replace the letter with 'b'
return word[: start - 1] + morphFirst + word[start:]
+14 -2
View File
@@ -1,15 +1,17 @@
#!/usr/bin/python
import random
import hashlib
import inflect
import quote_puzzle
import dict_puzzle
import textcaptcha
p = inflect.engine()
primes = [11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]
fuzz_amount = 3
def make_puzzle(obfuscate=True):
def make_puzzle(obfuscate=True, roll=None):
answer = 0
bonus = 0
puzzle = random.choice(
@@ -43,7 +45,7 @@ def make_puzzle(obfuscate=True):
]
)
puzzle += " "
roll = random.randrange(0, 18)
roll = roll or random.randrange(0, 21)
var1 = random.randrange(1, 10)
var2 = random.randrange(1, 10)
var3 = random.randrange(1, 20)
@@ -159,6 +161,16 @@ def make_puzzle(obfuscate=True):
elif roll <= 17: # 15-17
answer, puzzle = dict_puzzle.get_anagram()
obfuscate = False
elif roll == 18:
answer, puzzle = quote_puzzle.get_chuck()
obfuscate = False
elif roll <= 20: #19-20
captcha = textcaptcha.get_captcha()
puzzle = captcha['q'] # the question part of the captcha
print(captcha)
answer = lambda a : hashlib.md5(a.encode()).hexdigest() in captcha['a'] # check if the answer is correct
obfuscate = False
bonus = 1
# Add a question mark on the end of the question
if puzzle[-1] != "?":
+15 -1
View File
@@ -1,8 +1,13 @@
#!/usr/bin/python
import json
import urllib
import random
import re
quotefile = "/home/karlen/irc/quotes.txt"
chuckfile = "chuck.txt"
chuckApi = "https://api.icndb.com/jokes/random"
def get_quote():
quotes = open(quotefile, "r").read().split("---")
@@ -11,3 +16,12 @@ def get_quote():
word = random.choice([q for q in quote.split(" ") if len(q) > 1])
quote = quote.replace(word, re.sub(r"[a-zA-Z]", "_", word))
return [word, 'Fill in the blank: "' + quote + '" ' + attr]
def get_chuck():
#chucks = open(chuckfile, "r").readlines()
#chuck = random.choice(chucks).rstrip()[:200] # get only the first 200 chars
# ha ha! let's see if we can confus login
chuck = json.loads(urllib.urlopen(chuckApi).read().decode())['value']['joke'][:200]
word = random.choice([w for w in chuck.split(" ") if len(w) > 1 and w.lower() != "chuck" and w.lower() != "norris"])
chuck = chuck.replace(word, re.sub(r"[a-zA-Z]", "_", word)).replace("&quot;", "\"")
return [word, 'Fill in the blank: "{}"'.format(chuck)]
+30 -1
View File
@@ -71,6 +71,9 @@ def get_positive():
"Totally right",
"Close enough",
"That's it",
"Winner, winner",
"Bingo",
"Affirmative",
]
)
@@ -88,10 +91,13 @@ def get_negative():
"Not today",
"Try again",
"Maybe later",
"Maybe next time",
"Probably not",
"Answer hazy",
"Not quite",
"Not even close",
"Not for you",
"I think not"
]
)
@@ -152,6 +158,7 @@ def get_superlative(score):
"my friend",
"probably not a robot",
"valuable to the team",
"now trending",
]
)
@@ -161,15 +168,17 @@ def get_bad_thing():
[
"is a meanie",
"mugs me right off",
"miffed me off",
"is worse than a horse",
"smells like a ghost",
"probably didn't bathe today",
"probably shakes babies",
"didn't guess hard enough",
"isn't lucky",
"smells of elderberries",
"should reconsider their life choices",
"did't believe in the heart of the tilde",
"came to the wrong chat channel",
"came to the wrong side of town",
"should have stopped while they were ahead",
"requires annotations from an authoratative source",
"could have been a contender",
@@ -177,6 +186,26 @@ def get_bad_thing():
"drank my milkshake",
"is probably cheating",
"is trying too hard",
"didn't really try",
"should try harder",
"caught me in a bad mood",
"should have gone with their first choice",
"did not receive IFR clearance from tower",
"was tardy for class",
"is on double secret probation",
"forgot their keys",
"forgot to bribe me",
"forgot to close the door",
"waited too long",
"doesn't call me on my cellphone",
"isn't wearing a seatbelt",
"didn't courtesy flush",
"asked a bot for answers",
"was right but I didn't feel like it",
"is right on opposite day",
"actually answered the last question",
"has their pants on backwards",
"forgot their own name",
]
)
+49 -49
View File
@@ -1,10 +1,10 @@
krowbar&^%2640&^%1544031477
krowbar&^%2740&^%1548423098
karlen&^%498&^%1527613440
endorphant&^%803&^%1543250496
endorphant&^%809&^%1444775660
jumblesale&^%25&^%1426171214
marcus&^%2578&^%1538071912
papa&^%181&^%1474509971
epicmorphism&^%11&^%1543094151
epicmorphism&^%15&^%1546280322
audy&^%83&^%1504564254
kc&^%28&^%1480730333
vilmibm&^%24&^%1540452691
@@ -23,7 +23,7 @@ cel&^%11&^%1430162676
quote_bots&^%3&^%1424737471
bave&^%1&^%1427591141
scellef&^%13&^%1428707074
cndorphbot&^%20&^%1441299746
cndorphbot&^%60&^%1441299746
reppard&^%11&^%1437512059
jesse&^%6&^%1437569027
khoi&^%3&^%1438044039
@@ -34,30 +34,27 @@ tahnok&^%4&^%1464913072
nilsding&^%12&^%1454100197
vypr&^%3&^%1452470872
synergian&^%22&^%1458152889
dheeraj&^%5&^%1456489270
demobot&^%6&^%1454439605
premysl&^%65&^%1461768606
minerobber&^%280&^%1543039424
xkeeper&^%201&^%1539193279
cosnok&^%807&^%1508878859
escobar&^%1&^%1475431401
amicabot&^%30&^%1481225205
caff&^%1030&^%1540040705
kadin&^%19&^%1542733284
desvox&^%42&^%1543941924
kadin&^%19&^%1541514839
desvox&^%59&^%1548198585
mankins&^%3&^%1480211581
cinch&^%2&^%1480454755
caffbot&^%969&^%1532662872
evilbot&^%4&^%1480693919
tybaltcat&^%7&^%1481076625
minerbot&^%146&^%1520382015
Minerbot&^%316&^%1548341661
mio&^%347&^%1529720473
archangelic&^%484&^%1542913092
tehfraga&^%671&^%1542490496
tehfraga&^%673&^%1547260565
sushi&^%10&^%1493253212
troido&^%302&^%1538991819
gamebot&^%203&^%1542958081
nilaky&^%1552&^%1544038067
troido&^%303&^%1548409580
gamebot&^%336&^%1548409599
nilaky&^%1757&^%1548386011
bucket&^%103&^%1507931139
lolbot&^%1&^%1502568407
m455&^%12&^%1512076715
@@ -69,12 +66,10 @@ feoh&^%48&^%1513959989
pinhook&^%8&^%1509744722
emfor&^%3&^%1509671353
k2l8m11n2&^%11&^%1510932395
sacredpix&^%3&^%1522082931
deltawitch&^%3351&^%1544023739
login&^%2766&^%1544040853
sacredpixel&^%3&^%1522082931
login&^%3249&^%1548423081
kelpiebot&^%3&^%1513101957
unreal&^%2&^%1534387108
tildethief&^%7421&^%1542467787
kinsey&^%26&^%1520446672
testgameb&^%2&^%1537604954
erin&^%2&^%1517681999
@@ -85,57 +80,62 @@ silver&^%9&^%1519333029
equa&^%53&^%1534373756
audiodude&^%2&^%1519453927
whimsy&^%47&^%1529678733
wangofett&^%242&^%1544037429
saturn597&^%3&^%1521429369
cwmccabe&^%2&^%1521598124
wangofett&^%285&^%1547499873
saturn&^%3&^%1521429369
lucidiot&^%28&^%1526201925
tracer&^%1&^%1521744878
jan6&^%1143&^%1543703382
jan&^%10&^%1522319160
etathetae&^%3&^%1522937843
eeeeeta&^%52&^%1540361066
cmccabe&^%79&^%1529698164
jan6_test&^%7&^%1523252589
jan6_&^%8&^%1523641589
jan6&^%1346&^%1548353997
eeeeeta&^%55&^%1540361066
cmccabe&^%81&^%1529698164
carbon&^%9&^%1524135505
ne1&^%7&^%1524024485
Halian&^%32&^%1528360263
lunasspec&^%4&^%1524164784
littlebigly&^%49&^%1535927253
severak&^%17&^%1540822455
lunasspecto&^%4&^%1524164784
severak&^%17&^%1546438400
ralph&^%4&^%1526980620
von&^%449&^%1543590188
ensis&^%1750&^%1539356542
von&^%490&^%1548233084
ensis&^%1750&^%1546853217
simon&^%26&^%1527937489
benharri&^%2533&^%1544038200
benharri&^%3241&^%1548427827
cpb&^%3&^%1528930564
calmbit&^%160&^%1542220635
wisebot&^%5652&^%1542183214
calmbit&^%160&^%1541625694
wisebot&^%5652&^%1539612163
paannd_a&^%2&^%1529617165
nincollin&^%6&^%1531186900
ninlenna&^%6&^%1531186900
x4464&^%1&^%1532028546
pounce&^%19&^%1532133325
von_&^%5&^%1532502104
livix&^%7&^%1533603142
ben&^%3&^%1533767627
npa&^%261&^%1543988008
npa&^%319&^%1548385964
ezo&^%6&^%1533883842
aliasless&^%36&^%1541001821
kirch&^%246&^%1544033582
kirch&^%487&^%1548427938
root&^%2&^%1535558514
byte&^%5&^%1536416308
qbe&^%7&^%1537850181
informati&^%3&^%1536733938
informativeheck&^%3&^%1536733938
h00fi&^%1&^%1537050053
fantoro&^%50&^%1543968518
benjaminwil&^%558&^%1543607099
fantoro&^%57&^%1542125611
tildethief&^%7421&^%1542132794
benjaminwil&^%581&^%1548377274
deltawitch&^%3451&^%1548192292
archangelic&^%484&^%1541101297
diodelass&^%3&^%1539382302
minerobber&^%420&^%1548341654
brendantcc&^%3&^%1539908223
dozens&^%21&^%1542222479
dozens&^%21&^%1541090333
bowlercaptain&^%6&^%1540926135
nicole&^%6&^%1541276844
midnightpupil&^%12&^%1542216854
ahriman&^%332&^%1544037605
tunas&^%101&^%1543361911
khuxkm&^%19&^%1543867110
ckipp01&^%3&^%1543438777
littlebigly&^%49&^%1541283119
ahriman&^%624&^%1548397580
tunas&^%114&^%1545848648
netscape_navigator&^%5&^%1545846867
roan&^%5&^%1545846612
ckipp01&^%3&^%1545813774
ben&^%3&^%1545800958
l0010o0001l&^%3&^%154529473
rgdrake&^%1&^%1546086404
handyc&^%5&^%1546456002
fosslinux&^%8&^%1548296029
banterbot&^%3&^%1547588758
testgamebot&^%4&^%1547722176
+31 -28
View File
@@ -164,47 +164,50 @@ def listen():
while 1:
ircmsg = ircsock.recv(2048).decode("utf-8")
ircmsg = ircmsg.strip("\n\r")
for msg in ircmsg.split("\n"):
msg = msg.strip("\n\r")
if ircmsg[:4] == "PING":
util.ping(ircsock, ircmsg)
if msg[:4] == "PING":
util.ping(ircsock, msg)
continue
formatted = util.format_message(ircmsg)
formatted = util.format_message(msg)
if "" == formatted:
continue
if "" == formatted:
time.sleep(1)
continue
# print formatted
# print formatted
msgtime, user, command, channel, messageText = formatted.split("\t")
msgtime, user, command, channel, messageText = formatted.split("\t")
if command == "TOPIC" and user != args.nick:
count_topic(channel, user, msgtime, messageText)
if command == "TOPIC" and user != args.nick:
count_topic(channel, user, msgtime, messageText)
if ircmsg.find(":!topic") != -1:
get_topic(channel, user, msgtime)
if msg.find(":!topic") != -1:
get_topic(channel, user, msgtime)
if ircmsg.find(":!settopic") != -1:
set_topic(channel, user, msgtime, messageText[10:])
if msg.find(":!settopic") != -1:
set_topic(channel, user, msgtime, messageText[10:])
if ircmsg.find(":!tscores") != -1:
topic_scores(channel)
elif ircmsg.find(":!tscores") != -1:
topic_score(channel)
if msg.find(":!tscores") != -1:
topic_scores(channel)
elif msg.find(":!tscores") != -1:
topic_score(channel)
if ircmsg.find(":!randomtopic") != -1:
random_topic(channel, user, msgtime, True)
if ircmsg.find(":!suggesttopic") != -1:
random_topic(channel, user, msgtime, False)
if msg.find(":!randomtopic") != -1:
random_topic(channel, user, msgtime, True)
if msg.find(":!suggesttopic") != -1:
random_topic(channel, user, msgtime, False)
if ircmsg.find(":!thistory") != -1:
topic_history(channel, user, messageText)
if msg.find(":!thistory") != -1:
topic_history(channel, user, messageText)
if ircmsg.find(":!rollcall") != -1:
rollcall(channel)
if msg.find(":!rollcall") != -1:
rollcall(channel)
sys.stdout.flush()
time.sleep(1)
sys.stdout.flush()
time.sleep(1)
ircsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+2 -1
View File
@@ -1,2 +1,3 @@
vilmibm&^%0&^%4
krowbar&^%2&^%1vantablack
krowbar&^%3&^%1vantablack
login&^%1&^%0
+1 -1
View File
@@ -7,7 +7,7 @@ MAX_LINE = 400
def ping(ircsock, msg):
print("{} => PONG {}".format(msg, msg.split(" ")[1]))
# print("{} => PONG {}".format(msg, msg.split(" ")[1]))
ircsock.send("PONG {}\n".format(msg.split(" ")[1]).encode())
+12 -5
View File
@@ -1,7 +1,7 @@
#!/usr/bin/python3
import urllib
from bs4 import BeautifulSoup
import random
import requests
def get_philosophy(word, max_steps=20):
@@ -10,7 +10,8 @@ def get_philosophy(word, max_steps=20):
url = "https://en.wikipedia.org/wiki/%s" % word
while steps < max_steps:
soup = BeautifulSoup(urllib.request.urlopen(url).read(), "html.parser")
print("url: {}".format(url))
soup = BeautifulSoup(requests.get(url).content, "html.parser")
title = soup.find("h1", id="firstHeading")
content = soup.find("div", id="mw-content-text")
if not content:
@@ -35,7 +36,7 @@ def get_philosophy(word, max_steps=20):
][0]
step_words.append(item.get("title"))
# print item.get('title') + "\n"
url = "https://en.wikipedia.org%s" % item.get("href")
url = "https://en.wikipedia.org{}".format(item.get("href"))
steps += 1
return step_words
@@ -48,9 +49,15 @@ def get_philosophy_lower(word, max_steps=20):
step_words = [word]
steps = 0
url = "https://en.wikipedia.org/wiki/%s" % word
url = "https://en.wikipedia.org/wiki/{}".format(word.replace(" ", "%20"))
while steps < max_steps:
soup = BeautifulSoup(urllib.request.urlopen(url).read(), "html.parser")
print("url: {}".format(url))
soup = BeautifulSoup(requests.get(url).content, "html.parser")
if soup.find(id="noarticletext"):
step_words.append("(not found)")
break
title = soup.find("h1", id="firstHeading")
content = soup.find("div", id="mw-content-text")
if not content: