Skip to content

Instantly share code, notes, and snippets.

@assertivist
Created August 22, 2013 04:31
Show Gist options
  • Save assertivist/6303246 to your computer and use it in GitHub Desktop.
Save assertivist/6303246 to your computer and use it in GitHub Desktop.
the worst dicebot
#!/usr/pkg/bin/python2.7
import sys, socket, string, time, random, subprocess, random, datetime, code
import re
HOST="67.23.2.128"
PORT=6667
NICK="dicebot9K"
IDENT="v0.04"
REALNAME="dicebot9000"
CHANNEL="#dnd"
EIGHTBALL_PHRASES = [ "It is certain"
, "It is decidedly so"
, "Without a doubt"
, "Yes - definitely"
, "You may rely on it"
, "As I see it, yes"
, "Most likely"
, "Outlook good"
, "Yes"
, "Signs point to yes"
, "Reply hazy, try again"
, "Ask again later"
, "Better not tell you now"
, "Cannot predict now"
, "Concentrate and ask again"
, "Don't count on it"
, "My reply is no"
, "My sources say no"
, "Outlook not so good"
, "Very doubtful" ]
class Dicebot():
def __init__(self):
self.readbuffer=""
self.authed=False
self.joined=False
self.wait = 3
self.startuptime = datetime.datetime.now()
self.s=socket.socket()
self.s.connect((HOST,PORT))
self.s.send("NICK %s\r\n" % NICK)
time.sleep(1)
self.s.send("USER %s 8 * :%s\r\n" % (IDENT, REALNAME))
time.sleep(1)
self.heartbeat = datetime.datetime.now()
self.badusermsgs=[
"%s lives in the rank sweat of an enseamed bed, Stew'd in corruption, honeying and making love ove the nasty sty!",
"%s, idol of idiot-worshippers!",
"%s! Thou qualling rampallian clotpole!",
"%s! Thou errant tickle-brained knave!",
"%s! Thou currish unwash'd clack-dish!",
"%s! Thou surly beetle-headed canker-blossom!",
"%s art like the toad, ugly and venomous.",
"%s, Thou mangled rough-hewn pumpion!",
"You do unbend your noble strength, %s, to think so brainsickly of things.",
"%s! Thou froward dismal-dreaming joithead!",
"%s! Thou puking unwash'd popinjay!"
]
self.heh = [":)", ";)", ":D", ";D", "B^U"]
self.haveops = False
self.havehops = False
self.run()
#self.twclient = TWClient(self)
def say(self,something):
print "SAY >>> %s" % something
self.s.send("\r\nPRIVMSG %s %s\r\n" % (CHANNEL, something))
def action(self,something):
print "ACTION >>> %s" % something
self.s.send("\r\nPRIVMSG %s %sACTION %s%s\r\n" % (CHANNEL, chr(1), something, chr(1)))
def pm(self,user,something):
print "PRIVMSG %s >>> %s" % (user,something)
self.s.send("\r\nPRIVMSG %s %s\r\n" % (user, something))
def get_time_string_from_delta(self,tdelta):
elapsed = ""
if tdelta.days > 0:
elapsed += "%s days " % tdelta.days
if tdelta.seconds > 60:
if tdelta.seconds/60 > 60:
hours = (tdelta.seconds/60)/60
mins = (tdelta.seconds/60)%60
secs = tdelta.seconds%60
elapsed += "%s hours %s minutes %s seconds" % (hours, mins, secs)
else:
mins = tdelta.seconds/60
secs = tdelta.seconds%60
elapsed += "%s minutes %s seconds" % (mins, secs)
else:
elapsed += "%s seconds" % tdelta.seconds
return elapsed
def no_way(self,nick):
retort = random.choice(self.badusermsgs)
self.say(retort % nick)
def __del__(self):
pass
def process_command(self, innick, hostmask, command, input):
if command == "fortune":
wisdom = subprocess.Popen(['fortune', '-s'], stdout=subprocess.PIPE).communicate()[0]
self.say("%s: %s" % (innick, wisdom.strip().replace("\n"," ")))
elif command == "8":
prediction = random.choice(EIGHTBALL_PHRASES)
self.say("%s: %s" % (innick, prediction))
elif command in ["roll", "r"]:
try:
input = reduce(lambda x,y: x+y, input.split(' ')[1:])
total = 0
percent = False
diced = input.split(",")
for die in diced:
dd = die.strip().split('d')
count = int(dd[0])
if dd[1] is "%":
sides = 99
percent = True
else:
sides = int(dd[1])
subtotal = 0
out = "%s: " % innick
for i in range(count):
bottom = 0
if not percent:
bottom = 1
num = random.randint(bottom,sides)
if percent:
out += "%s " % (num)
else:
out += "d%s: %s " % (sides, num)
total += num
subtotal += num
if len(out) > 500:
out = out[:500]
if count < 2:
self.action("%s" % (out))
else:
self.action("%s (%s)" % (out,subtotal))
if not percent:
self.action("%s's total: %s" % (innick,total))
except:
raise
self.no_way(innick)
elif command == 'rmath':
try:
insts = reduce(lambda x,y: x+y, input.split(' ')[1:])
instd = insts.split(",")
for inst in instd:
dice_replace = re.findall('\d+d\d+', inst)
print dice_replace
for die in dice_replace:
dd = die.strip().split('d')
count = int(dd[0])
sides = int(dd[1])
result = self.roll_die(count,sides)
self.action("%s - %s: %s" % (innick, die, result))
inst = inst.replace(die, str(result))
self.action(inst)
final = self.do_math(inst)
self.action("%s's final result: %s" % (innick, final))
except:
self.no_way(innick)
elif command == "uptime":
delta = datetime.datetime.now() - self.startuptime
self.say("I've been online for %s" % self.get_time_string_from_delta(delta))
elif command == "hug":
self.action("hugs %s %s" % (innick,random.choice(self.heh)))
elif command == "math":
math_str = input.lstrip("!math ").strip()
try:
res = self.do_math(math_str)
if res == False:
raise
self.say(res)
except:
print sys.exc_info()[0]
self.say("that math is too strange")
def roll_die(self, count, sides):
total = 0
for i in range(count):
num = random.randint(1,sides)
total += num
return total
def do_math(self, math_str):
print math_str
r = re.match(r'^[\d\+\-\*()\/\%\s\.]+$', math_str)
r2 = re.search(r'\*{2}', math_str)
if r is not None and r2 is None and len(math_str) < 26:
answer = 0
try:
answer = eval(math_str)
except:
raise
return answer
else:
raise
def run(self):
while 1:
self.readbuffer=self.readbuffer+self.s.recv(1024)
self.heartbeat = datetime.datetime.now()
temp=string.split(self.readbuffer, "\n")
self.readbuffer=temp.pop()
for line in temp:
line=string.rstrip(line)
line=string.split(line)
print "<<< %s" % " ".join(line)
if(line[0] == "PING"):
self.s.send("\r\nPONG %s\r\n" % line[1])
self.authed = True
if not self.joined:
self.s.send("\r\nJOIN %s\r\n" % CHANNEL)
self.joined = True
if self.joined and self.authed:
delta = datetime.datetime.now() - self.startuptime
#delta
if "croc" in line[0].lower() and "sdf.org" in line[0].lower() and "dicebot" in line[2].lower(): #yes master...
#msg is in 3
commandarr = line[3].lstrip(":").split(" ")
if commandarr[0] == "join":
self.s.send("\r\nJOIN %s\r\n" % CHANNEL)
self.joined = True
if commandarr[0] == "quit":
self.say("Shutting down")
quit()
if ("privmsg" in line[1].lower()) and (NICK.lower() in line[2].lower()):
#private message
msg = " ".join(line[3:]).lstrip(":").split(" ")
innick = line[0].split("!")[0].lstrip(":")
self.pm(innick,'Hello %s!! I\'m dicebot!!!' % innick)
if len(line) > 4 and self.joined and CHANNEL in line[2] and "MODE" in line[4] and NICK.lower() in line[4].lower():
mode = line[3]
if mode is "+o":
self.haveops = True
elif mode is "-o":
self.haveops = False
elif mode is "+h":
self.havehops = True
elif mode is "-h":
self.havehops = False
if len(line) > 2 and self.joined and CHANNEL in line[2] and "PRIVMSG" in line[1]:
#chatroom
input = " ".join(line[3:])[1:]
innick = line[0].split("!")[0].lstrip(":")
hostmask = line[0].split("!")[1]
if NICK.lower() in input.lower() and input[0] is not "!":
input = input.replace(NICK, "")
if "o/" in input:
self.say("\\o")
continue
self.say('Hello %s!! I\'m dicebot!!!' % innick)
else:
if len(input) < 1:
continue
if input[0] == "!":
command = input.split(" ")[0][1:]
#print "command detected: %s" % command
self.process_command(innick, hostmask, command, input)
elif self.wait > 0:
self.wait = self.wait - 1
else:
self.wait = random.randint(15,70)
if(__name__== "__main__"):
dbot = Dicebot()
dbot.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment