Ported banterbot to pinhook framework and some other changes

This commit is contained in:
Russell 2019-01-25 11:16:19 -05:00
parent 0627b4a9e3
commit bc102890b2
39 changed files with 1629 additions and 507 deletions

View File

@ -18,3 +18,4 @@ alias pp='python -mjson.tool'
alias ttbp='~endorphant/bin/ttbp'
alias vuln='find /home/ \! -type l -perm -o=w ! -iwholename '*.git*' 2> /dev/null'
alias vulnc='vuln | sed "s/\/home\/\([^/]*\)\/.*/\1/g" | sort | uniq -c | sort -nr'
alias chat='mesg n; /usr/local/bin/chat'

View File

@ -115,3 +115,5 @@ man() {
LESS_TERMCAP_us=$'\e[1;32m' \
man "$@"
}
PYTHONPATH=/home/krowbar/bin/python

View File

@ -4,7 +4,7 @@ After=banterbot.service
[Service]
Type=simple
ExecStart=/home/krowbar/Code/irc/banterbot.py -s 127.0.0.1:6667 -n banterbot -c #tildetown #bots
ExecStart=/home/krowbar/Code/irc/banterbot.py -s 127.0.0.1 -p 6667 -n banterbot -c #tildetown #bots
WorkingDirectory=/home/krowbar/Code/irc/
Restart=always
RestartSec=5

609
.tracery/aphorism Normal file
View File

@ -0,0 +1,609 @@
{
"origin": ["#aphorism.capitalize#."],
"aphorism": [
"#adjective.a# #money# #continuanc# #verb.s# #direction#",
"#verb.a#ing #animal# #continuance# #verb.s#",
"#animal.a# in the #bodypart# is #preposition# #number# in the #plant#",
"#noun.a# is only as #adjective# as its #comparative# #noun#",
"#animal.a# is #person.a#'s #comparative# #relation#",
"#person.ae# and #pronoun_possessive# #money# are #adverb# #verb#ed",
"#adjective.a# #noun#is the of #comparative# #noun.s#",
"#person.a# in #verb# is #person.a# #adverb#",
"#comparative.a# #noun# makes #comparative.a# #noun#",
"#person.a# of #adjective# #noun.s# is #person# of #adjective#",
"#noun.a# #preposition# #verb#ing is #preposition# #verb#ing #adverb#",
"#comparative.a# #noun# is a #adjective# thing",
"#person.a# is known by the #person# #pronoun# #verb.s#",
"#person.a# with #number# #noun# knows what #noun# it is. #person.a.capitalize# with #number# #noun.s# is #continuance# #adjective#",
"#person.a#'s #noun# is #pronoun_possessive# #noun#",
"#noun.a# is as #comparative# as #distance.a#",
"#adjective.a# #noun# #verb.s# #adjective#",
"#noun.a# is as #adjective# as #noun.a# to #adjective.a# #person#",
"#money.a# #verb#ed is #money.a# #verb#ed",
"#location.a# for everything and everything in its #location#",
"#verb.a#ing #noun# #verb.s# #adjective# #noun.s#",
"#noun.a# by any other #noun# would #verb# as #adjective#",
"#adjective.a# #noun# #verb#eth #direction# #noun#",
"#noun.a# in #noun# #verb.s# #number#",
"#noun.a# of #noun# is a #noun# #adverb#",
"#verb.a#ed #noun# #adverb# #verb.s#",
"#person.a#'s #noun# is in the #location#",
"#person.a#'s #noun# is #adverb# done.",
"#noun.a# to the #adjective# is #adjective#",
"#noun# #verb.s# the #noun# #verb# #adjective#",
"#noun.s# #verb# #adjective# than #noun.s#",
"#adjective# for #number# and #number# for #adjective#",
"#adjective# that #verb.s# is not #noun#",
"#adjective# the #location#'s a #noun#",
"#adjective# #noun.s# #verb# to #pronoun# who #verb.s#",
"#adjective# we #verb# from #noun# is that we #verb# #adverb# from #noun#",
"#adjective# #noun# and #adjective# #noun# #verb.s# #person.capitalize# #adjective.a# #noun#",
"#adjective#'s #adjective# in #noun# and #noun#",
"#adjective#'s #adverb# that #verb.s# #adverb#"
],
"adjective": [
"all",
"bad",
"blind",
"clean",
"dangerous",
"dull",
"fair",
"fonder",
"foolish",
"louder",
"new",
"no",
"none",
"soft",
"strong",
"sufficient",
"sure",
"sweet",
"wise"
],
"adverb": [
"forever",
"indeed",
"never",
"nothing",
"soon",
"well"
],
"animal": [
"bird",
"dog",
"man"
],
"bodypart": [
"hand"
],
"comparative": [
"best",
"good",
"little",
"weakest"
],
"continuance": [
"always",
"never"
],
"direction": [
"away",
"up",
"down"
],
"distance": [
"mile"
],
"location": [
"castle",
"home",
"place",
"world"
],
"money": [
"money",
"penny"
],
"noun": [
"action",
"absence",
"answer",
"beauty",
"beginning",
"boat",
"boy",
"broom",
"castle",
"chain",
"clock",
"consistency",
"ending",
"gold",
"heart",
"history",
"home",
"joy",
"learning",
"link",
"love",
"mind",
"miss",
"moss",
"name",
"nod",
"place",
"pot",
"rose",
"stitch",
"stage",
"stone",
"thing",
"tide",
"time",
"trade",
"war",
"wink",
"word",
"work",
"wrath"
],
"number": [
"one",
"two",
"nine"
],
"person": [
"company",
"fool",
"friend",
"hobgoblin",
"jack",
"man",
"master",
"woman"
],
"plant": [
"bush"
],
"preposition": [
"worth"
],
"pronoun": [
"he"
],
"pronoun_possessive": [
"his"
],
"relation": [
"friend"
],
"verb": [
"boil",
"come",
"do",
"earn",
"end",
"gather",
"glitter",
"grow",
"keep",
"learn",
"lift",
"make",
"need",
"part",
"rise",
"roll",
"save",
"smell",
"speak",
"sweep",
"turn",
"watch"
],
"todo": [
"Always cut the cards.",
"An apple a day keeps the doctor away.",
"An army marches on its stomach.",
"An ounce of prevention is worth a pound of cure.",
"Any port in a storm.",
"Anything that can go wrong, will go wrong.",
"Appearances can be deceiving.",
"April showers bring May flowers.",
"As you sow, so shall you reap.",
"Ask a silly question and you'll get a silly answer.",
"Ask and it shall be given.",
"Ask and you shall receive.",
"Ask no questions and hear no lies.",
"Bad news travels fast.",
"Barking dogs seldom bite.",
"Be careful you don't go from the frying pan into the fire.",
"Be it ever so humble, there's no place like home.",
"Be not penny wise and pound foolish.",
"Beauty is in the eye of the beholder.",
"Beauty is only skin deep.",
"Before you judge a man, you should walk a mile in his shoes.",
"Beggars can't be choosers.",
"Behind every successful man is a woman.",
"Better late than never.",
"Better safe than sorry.",
"Better the devil you know than the devil you don't.",
"Better to have loved and lost, than never to have loved at all.",
"Better to light a candle than to curse the darkness.",
"Beware of Greeks bearing gifts.",
"Birds of a feather flock together.",
"Blood is thicker than water.",
"Boys will be boys.",
"Brevity is the soul of wit.",
"Build a better mousetrap and the world will beat a path to your door.",
"Business before pleasure.",
"Candy is dandy but liquor is quicker.",
"Carpe diem ... seize the day.",
"Cast your bread upon the water, and it will be returned a hundred-fold.",
"Chickens will come home to roost.",
"Children should be seen and not heard.",
"Cleanliness is next to godliness.",
"Cold hands, warm heart.",
"Common sense is not so common.",
"Cream always rises to the top.",
"Crime does not pay.",
"Discretion is the better part of valor.",
"Do as I say, not as I do.",
"Do unto others as you would have them do unto you.",
"Don't bite off more than you can chew.",
"Don't bite the hand that feeds you.",
"Don't burn the candle at both ends.",
"Don't burn your bridges behind you.",
"Don't change horses in midstream.",
"Don't close the barn door after the horse runs away.",
"Don't count your chickens before they hatch.",
"Don't cry over spilt milk.",
"Don't cut off your nose to spite your face.",
"Don't fire until you see the whites of their eyes.",
"Don't foul your own nest.",
"Don't give up the ship.",
"Don't hide your light under a bushel.",
"Don't judge a book by its cover.",
"Don't kill the goose that lays the golden eggs.",
"Don't look a gift horse in the mouth.",
"Don't make mountains out of molehills.",
"Don't put all your eggs in one basket.",
"Don't put the cart before the horse.",
"Don't shoot the messenger.",
"Don't speak ill of the dead.",
"Don't spit into the wind.",
"Don't take any wooden nickels.",
"Don't throw out the baby with the bath water.",
"Don't throw pearls before swine.",
"Doubt is the beginning, not the end, of wisdom.",
"Early to bed, early to rise, makes a man healthy, wealthy and wise.",
"Easier said than done.",
"East is East, and West is West, and never the twain shall meet.",
"East or West, home is best.",
"Easy come, easy go.",
"Eat to live, don't live to eat.",
"Eat, drink and be merry, for tomorrow we die.",
"Even a broken clock is right twice a day.",
"Every cloud has a silver lining.",
"Every dog has his day.",
"Every man has a price.",
"Everybody talks about the weather, but nobody does anything about it.",
"Expect the unexpected.",
"Experience is the best teacher.",
"Faith will move mountains.",
"Familiarity breeds contempt.",
"Feed a cold, starve a fever.",
"Finders keepers, losers weepers.",
"First come, first served.",
"Flattery will get you nowhere.",
"Fools rush in where angels fear to tread.",
"For want of a nail, a kingdom was lost.",
"Forewarned is forearmed.",
"Forgive and forget.",
"Forgive them, for they know not what they do.",
"Frailty, thy name is woman!",
"From the sublime to the ridiculous is but a step.",
"Gather ye rosebuds while ye may.",
"Genius is one percent inspiration and 99 percent perspiration.",
"Give a man a fish and he eats for one night. Teach him how and he eats for life.",
"Give him an inch and he'll take a mile.",
"Give him enough rope and he'll hang himself.",
"Give me liberty, or give me death.",
"Give the devil his due.",
"God helps those who help themselves.",
"Good fences make good neighbors.",
"Good gifts come in small packages.",
"Great minds think alike.",
"Great oaks from little acorns grow.",
"Grin and bear it.",
"Half a loaf is better than none.",
"Handsome is as handsome does.",
"Haste makes waste.",
"He that is not with me is against me.",
"He who fights and runs away, lives to fight another day.",
"He who hesitates is lost.",
"He who laughs last, laughs best.",
"He who lives by the sword shall die by the sword.",
"He who pays the piper calls the tune.",
"Hell hath no fury like a woman scorned.",
"Here today, gone tomorrow.",
"History repeats itself.",
"Hitch your wagon to a star.",
"Home is where the heart is.",
"Honesty is the best policy.",
"Hope springs eternal in the human breast.",
"Hunger is the best sauce.",
"I think, therefore I am.",
"Idle hands are the devil's workshop.",
"If at first you don't succeed, try, try again.",
"If it's not broke, don't fix it.",
"If it's not one thing, it's another.",
"If the mountain won't come to Mohammed, then Mohammed will go to the mountain.",
"If the shoe fits, wear it.",
"If wishes were fishes then no man would starve.",
"If wishes were horses, then beggars would ride.",
"If you can't beat them, join them.",
"If you can't stand the heat, get out of the kitchen.",
"If you do what you've always done you'll get what you've always got.",
"If you lie down with dogs, you wake up with fleas.",
"If you snooze, you lose.",
"Ignorance is bliss.",
"Ignoriance of the law is no excuse for breaking it.",
"Imitation is the sincerest form of flattery.",
"In for a penny, in for a pound.",
"In the country of the blind, the one-eyed man is king.",
"In the spring a young man's fancy lightly turns to thoughts of love.",
"It never rains but it pours.",
"It takes a thief to catch a thief.",
"It takes two to tango.",
"It'll all come out in the wash.",
"It's an ill wind that blows no good.",
"It's every man for himself.",
"It's never too late to mend.",
"It's no use beating a dead horse.",
"It's not over till it's over.",
"It's not over until the fat lady sings.",
"It's not the heat, it's the humidity.",
"It's not the knowing that is difficult, but the doing.",
"It's not whether you win or lose, but how you play the game.",
"It's the empty can that makes the most noise.",
"It's the squeaky wheel that gets the grease.",
"It's time to fish or cut bait.",
"Keep a stiff upper lip.",
"Keep your eyes peeled.",
"Keep your fingers crossed.",
"Keep your head above water.",
"Keep your nose to the grindstone.",
"Keep your powder dry.",
"Know thyself.",
"Know which side your bread is buttered on.",
"Knowledge is power.",
"Laugh, and the world laughs with you; weep, and you weep alone.",
"Laughter is the best medicine.",
"Leave no stone unturned.",
"Leave well enough alone.",
"Let bygones be bygones.",
"Let he who is without sin cast the first stone.",
"Let nature takes its course.",
"Let sleeping dogs lie.",
"Let's cross the bridge when we come to it.",
"Life is short, art is long.",
"Lightning never strikes twice in the same place.",
"Little pitchers have big ears.",
"Little strokes fell great oaks.",
"Live and learn.",
"Live and let live.",
"Live every day as if it were your last.",
"Look before you leap.",
"Love conquers all.",
"Love is blind.",
"Love makes the world go 'round.",
"Make a virtue of necessity.",
"Make haste slowly.",
"Make hay while the sun shines.",
"Man cannot live by bread alone.",
"Man proposes, God disposes.",
"Many are called but few are chosen.",
"Many hands make light work.",
"Marry in haste, repent at leisure.",
"Might makes right.",
"Mind your P's and Q's.",
"Misery loves company.",
"Money isn't everything.",
"Murder will out.",
"Music hath charms to soothe the savage breast.",
"Nature abhors a vacuum.",
"Necessity is the mother of invention.",
"Never give a sucker an even break.",
"Never judge a book by its cover.",
"Never put off until tomorrow what you can do today.",
"Never say die.",
"No good deed goes unrewarded.",
"No man can serve two masters.",
"No man is an island.",
"No news is good news.",
"No pain, no gain.",
"Nothing is certain but death and taxes.",
"Nothing succeeds like success.",
"Nothing ventured, nothing gained.",
"Oil and water don't mix.",
"Old habits die hard.",
"Once bitten, twice shy.",
"One good turn deserves another.",
"One man's loss is another man's gain.",
"One man's meat is another man's poison.",
"One picture is worth a thousand words.",
"One rotten apple spoils the barrel.",
"Only the wearer knows where the shoe pinches.",
"Opportunity never knocks twice.",
"Opposites attract.",
"Out of sight, out of mind.",
"People who live in glass houses shouldn't throw stones.",
"Politics makes strange bedfellows.",
"Possession is nine-tenths of the law.",
"Power corrupts; absolute power corrupts absolutely.",
"Practice makes perfect.",
"Practice what you preach.",
"Pride goeth before a fall.",
"Procrastination is the thief of time.",
"Rats desert a sinking ship.",
"Revenge is a dish best eaten cold.",
"Revenge is sweet.",
"Rome wasn't built in a day.",
"Seeing is believing.",
"Seek and ye shall find.",
"Share and share alike.",
"Silence is golden.",
"Sink or swim.",
"Slow but steady wins the race.",
"Spare the rod and spoil the child.",
"Still waters run deep.",
"Stone walls do not a prison make.",
"Strike while the iron is hot.",
"Take the bitter with the sweet.",
"Take the bull by the horns.",
"That's life.",
"That's the way the ball bounces.",
"The apple doesn't fall far from the tree.",
"The bad workman always blames his tools.",
"The best things in life are free.",
"The best-laid plans of mice and men often go awry.",
"The bigger they come, the harder they fall.",
"The burnt child shuns the fire.",
"The child is the father of the man.",
"The course of true love never did run smooth.",
"The devil can cite Scripture for his purpose.",
"The early bird gets the worm.",
"The end justifies the means.",
"The eyes are the windows to the soul.",
"The grass is always greener on the other side.",
"The hotter the battle, the sweeter the victory.",
"The leopard cannot change its spots.",
"The longest journey begins with but a single footstep.",
"The love of money is the root of all evil.",
"The meek shall inherit the earth.",
"The more the merrier.",
"The more things change, the more they stay the same.",
"The pen is mightier than sword.",
"The quality of mercy is not strained.",
"The proof of the pudding is in the eating.",
"The race isn't always to the swift, nor the fight to the strong, but that's the way to bet.",
"The road to Hell is paved with good intentions.",
"The sea refuses no river.",
"The show must go on.",
"The truth will out.",
"The teacher appears when the student is ready.",
"The turtle only makes progress when it sticks its neck out.",
"The walls have ears.",
"The way to a man's heart is through his stomach.",
"The wish is father of the deed.",
"There ain't no such thing as a free lunch.",
"There are plenty of fish in the sea.",
"There are old soldiers, and bold soldiers, but there are no old, bold soldiers.",
"There are two sides to every question.",
"There is nothing good or bad but thinking makes it so.",
"There's a first time for everything.",
"There's many a slip 'twixt the cup and the lip.",
"There's method in his madness.",
"There's more than one way to skin a cat.",
"There's no accounting for taste.",
"There's no defense like a good offense.",
"There's no disputing about taste.",
"There's no fool like an old fool.",
"There's no place like home.",
"There's no rest for the wicked.",
"There's no such thing as a free lunch.",
"There's nothing new under the sun.",
"There's something rotten in Denmark.",
"There, but for the grace of God, go I.",
"Things aren't always what they seem.",
"This too shall pass.",
"Those who cannot remember the past are condemned to repeat it.",
"Time and tide wait for no man.",
"Time heals all wounds.",
"Time is money.",
"Time is of the essence.",
"To err is human, to forgive divine.",
"Too many cooks spoil the broth.",
"Truth is stranger than fiction.",
"Turn the other cheek.",
"Turnabout is fair play.",
"Two heads are better than one.",
"Two wrongs don't make a right.",
"Two's company, three's a crowd.",
"Uneasy lies the head that wears a crown.",
"Variety is the spice of life.",
"Waste not, want not.",
"Water seeks its own level.",
"Well begun is half done.",
"We're too soon old and too late smart.",
"What can't be cured must be endured.",
"What goes around, comes around.",
"What goes up, must come down.",
"What will be, will be.",
"What's good for the goose is good for the gander.",
"When all you have are lemons, make lemonade.",
"When in Rome, do as the Romans do.",
"When it rains, it pours.",
"When the cat's away, the mice will play.",
"When the going gets tough, the tough get going.",
"When your only tool is a hammer, every problem looks like a nail.",
"Where there's a will, there's a way.",
"Where there's smoke, there's fire.",
"While there's life, there's hope.",
"Who pays the piper calls the tune.",
"Winners never quit and quitters never win.",
"You can catch more flies with honey than with vinegar.",
"You can fool some of the people all of the time, and all of the people some of the time, but you can't fool all of the people all of the time.",
"You can kill a man but you can't kill an idea.",
"You can lead a horse to water, but you can't make it drink.",
"You can take the boy out of the country, but you can't take the country out of the boy.",
"You can't fight city hall.",
"You can't fit a round peg in a square hole.",
"You can't get the toothpaste back in the tube.",
"You can't go home again.",
"You can't have your cake and eat it too.",
"You can't make a silk purse out of a sow's ear.",
"You can't make an omelet without breaking eggs.",
"You can't squeeze blood from a turnip.",
"You can't take it with you.",
"You can't teach an old dog new tricks.",
"You can't tell a book by its cover.",
"You can't unring a bell.",
"You can't unscramble an egg.",
"You don't get something for nothing.",
"You get what you pay for.",
"You have to take the bitter with the sweet.",
"You have to take the good with the bad.",
"You made your bed, now lie in it.",
"You need to stop to smell the roses.",
"You need to take a bull by the horns, and a man by his word.",
"You pays your money and you takes your choice.",
"You're never too old to learn."
]
}

8
.tracery/guid Normal file
View File

@ -0,0 +1,8 @@
{
"origin": ["#guid#"],
"guid": ["#eightchar#-#fourchar#-#fourchar#-#twelvechar#"],
"fourchar": ["#char##char##char##char#"],
"eightchar": ["#fourchar##fourchar#"],
"twelvechar": ["#eightchar##fourchar#"],
"char": ["1","2","3","4","5","6","7","8","9","0","a","b","c","d","e","f"]
}

29
.tracery/mission Normal file
View File

@ -0,0 +1,29 @@
{
"origin": ["#prefix##mission.capitalize#"],
"adj": ["Ancient","Bold","Breaking","Brightest","Brilliant","Crescent","Dark|Darkness","Darkest|Darkness","Desert|Desert","Eternal","Evening|Darkness","Final","First","Forever","Giant|Giant","Glorious|Glory","Joyful|Joy","July","Last","Liberty|Liberty","Magic|Magic","Morning|Morning","Power|Power","Phantom","Present","Righteous","Roaring|Roar|Scream","Rolling","Sand","Screaming|Roar|Scream","Silent","Sleeping","Soaring","Standing|Stand","Star|Star","Stunning","Super","Thunderous|Thunder","Twisted","Urgent","Utopian","Valiant"],
"noun": ["Action","Alert","Bane","Beauty","Claw","Darkness","Dawn","Day","Defense","Desert","Envy","Fall","Fist","Flight","Fury","Guard","Glory","Hammer","Hand","Honor","Hope","Hunt","Hurricane","Joy","Liberty","Light","Lightning","Magic","Morning","October","Power","Rain","Response","Repose","Roar","Scream","Skull","Sky","Skies","Shield","Shout","Stand","Star","Storm","Streak","Strike","Sun","Thunder","Victory","Whisper","Wind","Wrath"],
"color": ["Black","Blue","Brown","Golden","Gray","Green","Indego","Orange","Purple","Rainbow","Red","Scarlet","Silver","Violet","White","Yellow"],
"actor": ["Cobra","Condor","Dragon","Eagle","Giant","Guardian","Hawk","Hydra","Jackal","King","Knight","Lady","Lion","Scorpion","Spartan","Stranger","Titan","Victor","Viking","Warrior"],
"prefix": [
"",
"Operation ",
"Project ",
"Code: "
],
"mission": [
"#adj# #noun#",
"#adj# #actor#",
"#color# #noun#",
"#color# #actor#",
"#actor#'s #noun#",
"#noun# of the #actor#",
"#actor# of the #noun#",
"#noun# of #noun#",
"#noun# of #color# #noun#",
"#adj# #noun# and #adj# #noun#",
"Attack of the #actor.s#",
"Return of the #actor.s#",
"The #actor# Awakens"
]
}

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
Code/irc/banterbot_legacy.py Executable file
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 !!")

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))

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))

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())

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?")

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

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)

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!")

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)

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)))

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)

View File

@ -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)

View File

@ -0,0 +1,7 @@
#!/usr/bin/python3
import pinhook.plugin
@pinhook.plugin.register('!')
def _plugin(msg):
return pinhook.plugin.message()

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

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"))

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))

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())

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))

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)

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
Code/irc/newBanter.py Normal file
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:]

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] != "?":

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)]

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",
]
)

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

View File

@ -164,14 +164,17 @@ 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:
time.sleep(1)
continue
# print formatted
@ -181,26 +184,26 @@ def listen():
if command == "TOPIC" and user != args.nick:
count_topic(channel, user, msgtime, messageText)
if ircmsg.find(":!topic") != -1:
if msg.find(":!topic") != -1:
get_topic(channel, user, msgtime)
if ircmsg.find(":!settopic") != -1:
if msg.find(":!settopic") != -1:
set_topic(channel, user, msgtime, messageText[10:])
if ircmsg.find(":!tscores") != -1:
if msg.find(":!tscores") != -1:
topic_scores(channel)
elif ircmsg.find(":!tscores") != -1:
elif msg.find(":!tscores") != -1:
topic_score(channel)
if ircmsg.find(":!randomtopic") != -1:
if msg.find(":!randomtopic") != -1:
random_topic(channel, user, msgtime, True)
if ircmsg.find(":!suggesttopic") != -1:
if msg.find(":!suggesttopic") != -1:
random_topic(channel, user, msgtime, False)
if ircmsg.find(":!thistory") != -1:
if msg.find(":!thistory") != -1:
topic_history(channel, user, messageText)
if ircmsg.find(":!rollcall") != -1:
if msg.find(":!rollcall") != -1:
rollcall(channel)
sys.stdout.flush()

View File

@ -1,2 +1,3 @@
vilmibm&^%0&^%4
krowbar&^%2&^%1vantablack
krowbar&^%3&^%1vantablack
login&^%1&^%0

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())

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:

View File

@ -7,6 +7,7 @@ import re
import shutil
import argparse
import logging, sys
import math
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
@ -54,6 +55,12 @@ parser.add_argument(
help="the minimum occurence of a word to include it in the cloud",
default=3,
)
parser.add_argument(
"-timestamp",
help="what kind of time stamp should be inserted into the chat cloud. valid values are none, start, end, month, and full",
default="none"
)
args = parser.parse_args()
@ -75,16 +82,22 @@ bannedWords = open(args.bannedWordsFile).read().splitlines()
bannedUsers = open(args.bannedUsersFile).read().splitlines()
with open(args.logfile, "r") as log:
firstTime = None # track these for the timestamp we may do later
lastTime = None
for line in log:
try:
time, user, message = line.split("\t", 3)
time = int(time)
mtime, user, message = line.split("\t", 3)
mtime = int(mtime)
except ValueError:
continue # There are some bad lines in the log file that we'll ignore if we can't parse
if user in bannedUsers:
continue # We don't care what they say
if time >= args.timestart and time <= args.timeend:
# print "Processing line from " + user + " at " + str(time)
if mtime >= args.timestart and mtime <= args.timeend:
# print "Processing line from " + user + " at " + str(mtime)
if firstTime is None:
firstTime = mtime
lastTime = mtime
for word in (
re.sub("['\"\`\/\\;:,.?!*&^\-()<>\{\}|_\[\]0-9]", " ", message)
.lower()
@ -103,9 +116,26 @@ with open(args.logfile, "r") as log:
wordData = {i: wordData[i] for i in wordData if wordData[i] >= args.minOccurrence}
if len(wordData) == 0:
wordData = {"NOTHING": 1, "INTERESTING": 1, "TODAY": 1}
elif args.timestamp is not "none":
stamp = "DATE";
if args.timestamp == "start":
stamp = time.strftime("%B %d, %Y", time.gmtime(firstTime))
elif args.timestamp == "end":
stamp = time.strftime("%B %d, %Y", time.gmtime(lastTime))
elif args.timestamp == "full":
stamp = "{} to {}".format(time.strftime("%b %d, %Y", time.gmtime(firstTime)), time.strftime("%b %d, %Y", time.gmtime(lastTime)))
elif args.timestamp == "month":
# use the month of one day before the last day
stamp = time.strftime("%B %Y", time.gmtime(lastTime - 86400))
# make the timestamp a bit bigger than everything else
size = int(math.ceil(wordData[max(wordData, key=wordData.get)] * 1.3)) + 1
wordData[stamp] = size
print("Added timestamp \"{}\" of size {}".format(stamp, size))
if args.outfile == "":
print(json.dumps(wordData))
else:
with open(args.outfile + ".tmp", "w") as tmpFile:
tmpFile.write(json.dumps(wordData))
shutil.move(args.outfile + ".tmp", args.outfile)
print("Dumped {} words to {}".format(len(wordData), args.outfile))

View File

@ -1,15 +1,23 @@
#!/bin/bash
START=$((`date +%s` - 2678400))
START=$((`date +%s` - 2678400)) # 31 days
END=`date +%s`
MONTH=`date -d yesterday +_%Y_%m`
DATE=`date -d yesterday +%b\ %Y`
OUT=/home/krowbar/logs/chatcloud${MONTH}.json
DIR=/home/krowbar/public_html/data
PAGE=/home/krowbar/public_html/chatcloud/index.html
LINE=16
LINE=16 # This is the magic line number where we want to insert the new option in the dropdown
/usr/bin/python /home/krowbar/Code/python/chatcloud2.py -timeend $END -timestart $START -outfile $OUT
ln -s $OUT $DIR
/usr/bin/python /home/krowbar/Code/python/chatcloud2.py -timeend $END -timestart $START -outfile $OUT -timestamp "month"
if [ ! -e ${DIR}/chatcloud${MONTH}.json ]
then
ln -s $OUT $DIR
echo Creating link to $OUT in $DIR
else
echo Skipping linking... already exists in $DIR
fi
sed "${LINE}i <option value=\"${MONTH}\">${DATE}</option>" < $PAGE > $PAGE.tmp
echo Added option for ${DATE} in $PAGE
mv $PAGE.tmp $PAGE

View File

@ -13,24 +13,26 @@
<div>
<select id="series">
<option value="">Today</option>
<option value="_2018_11">Nov 2018</option>
<option value="_2018_10">Oct 2018</option>
<option value="_2018_09">Sep 2018</option>
<option value="_2018_08">Aug 2018</option>
<option value="_2018_07">Jul 2018</option>
<option value="_2018_06">Jun 2018</option>
<option value="_2018_05">May 2018</option>
<option value="_2018_04">Apr 2018</option>
<option value="_2018_03">Mar 2018</option>
<option value="_2018_02">Feb 2018</option>
<option value="_2018_01">Jan 2018</option>
<option value="_2017_12">Dec 2017</option>
<option value="_2017_11">Nov 2017</option>
<option value="_2017_10">Oct 2017</option>
<option value="_2017_09">Sep 2017</option>
<option value="_2017_08">Aug 2017</option>
<option value="_2017_07">Jul 2017</option>
<option value="_2017_06">Jun 2017</option>
<option value="_2019_01">Jan 2019</option>
<option value="_2018_12">Dec 2018</option>
<option value="_2018_11">Nov 2018</option>
<option value="_2018_10">Oct 2018</option>
<option value="_2018_09">Sep 2018</option>
<option value="_2018_08">Aug 2018</option>
<option value="_2018_07">Jul 2018</option>
<option value="_2018_06">Jun 2018</option>
<option value="_2018_05">May 2018</option>
<option value="_2018_04">Apr 2018</option>
<option value="_2018_03">Mar 2018</option>
<option value="_2018_02">Feb 2018</option>
<option value="_2018_01">Jan 2018</option>
<option value="_2017_12">Dec 2017</option>
<option value="_2017_11">Nov 2017</option>
<option value="_2017_10">Oct 2017</option>
<option value="_2017_09">Sep 2017</option>
<option value="_2017_08">Aug 2017</option>
<option value="_2017_07">Jul 2017</option>
<option value="_2017_06">Jun 2017</option>
<option value="_2017_06">Jun 2017</option>
<option value="_2017_05">May 2017</option>
<option value="_2017_04">Apr 2017</option>
@ -121,7 +123,8 @@ jQuery.getJSON(source, function(json) {
.size([1200, 800])
.words(jsonWords)
.padding(3)
.rotate(function() { return ~~(Math.random() * 2) * 90 * !document.getElementById('flat').checked; })
// Never rotate the largest item. It is most likely the date
.rotate(function(d) { return ~~(Math.random() * 2) * 90 * (!document.getElementById('flat').checked && d.size != maxCount); })
.font("Impact")
.fontSize(function(d) { return Math.sqrt(d.size) * 50 / maxSize + 6; })
.on("end", draw);