Advertisement
Guest User

Untitled

a guest
May 11th, 2017
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 16.25 KB | None | 0 0
  1. #Word Assassins bot written by Crayboff and Dritz.
  2.  
  3. # system imports
  4. import time, sys, urllib, pickle, random, re, os, shelve, math, httplib
  5. #from datetime import *
  6.  
  7. from twisted.words.protocols import irc
  8. from twisted.internet import reactor, protocol, task, defer
  9.  
  10. global debug
  11. debug = True
  12.  
  13. class Komurin(irc.IRCClient):
  14.    
  15.     def __init__(self):
  16.         self.nickname = "Assassins"
  17.         self.password = ""
  18.         self.version = "0.6.0"
  19.         self.lineRate = 1
  20.         self.Owner = 'crayboff'
  21.         self.trigger = '-'
  22.         self.helpmessage = "Welcome to Word Assassins. The goal of the game is to 'kill' your targets by having/tricking/waiting for them to say a certain common word. After you kill a person, you will obtain their target and must 'kill' the new target as well, until you are the last man standing. Out of over 800 words, only one will kill you. The game ends every 24 hours, so good luck and good killing!"
  23.         self.helpcommands = "Possible commands are: %shelp  %sjoin  %smyscore  %sstats  %sstart  %stime  %stopscorer  %squit" % (self.trigger, self.trigger, self.trigger, self.trigger, self.trigger, self.trigger, self.trigger, self.trigger)
  24.         self.resetcycle = 86400
  25.         self.timeleftingame = self.resetcycle + 60
  26.         self.resetwarning = 3600
  27.         self.gamedata = {}
  28.         self.isgame = False
  29.         self.playerlist = []
  30.         self.joinedlist = []
  31.         self.userlists = {}
  32.         self.userlist = []
  33.         self.alreadyassigned = []
  34.         self.deadlist = []
  35.         self.quelist = []
  36.    
  37.     def resetstats(self):
  38.         self.gamedata = {}
  39.         self.playerlist = []
  40.         self.userlists = {}
  41.         self.userlist = []
  42.         self.alreadyassigned = []
  43.         self.deadlist = []
  44.         if self.isgame:
  45.             try:
  46.                 self.gameend.cancel()
  47.                 self.hourwarning.cancel()
  48.             except:
  49.                 pass
  50.         self.isgame = False
  51.         self.startgame(self.nickname)
  52.         if not self.isgame:
  53.             self.notifylist("There was a problem when automatically starting a new game.")
  54.    
  55.     def connectionMade(self):
  56.         irc.IRCClient.connectionMade(self)
  57.         #print self.wordlist
  58.        
  59.         if os.path.exists("assassins_wordlist.txt"):
  60.             wordfile = open("assassins_wordlist.txt", "r")
  61.             self.wordlist = wordfile.read()
  62.             wordfile.close()
  63.             self.wordlist = self.wordlist.lower().split(",")
  64.             print len(self.wordlist)
  65.             print 'number of words ^'
  66.         else:
  67.             print "ERROR: NO WORDLIST FOUND"
  68.        
  69.         if os.path.exists('assassins_joinedlist.txt'):
  70.             k = open('assassins_joinedlist.txt', 'r')
  71.             self.joinedlist = pickle.load(k)
  72.             k.close()
  73.         else:
  74.             self.joinedlist = []
  75.             k = open('assassins_joinedlist.txt', 'w')
  76.             pickle.dump(self.joinedlist, k)
  77.             k.close()
  78.         print "joinedlist loaded"
  79.            
  80.         if os.path.exists('assassins_scores.txt'):
  81.             m = open('assassins_scores.txt', 'r')
  82.             self.assassinsscores = pickle.load(m)
  83.             m.close()
  84.         else:
  85.             self.assassinsscores = {}
  86.             m = open('assassins_scores.txt', 'w')
  87.             pickle.dump(self.assassinsscores, m)
  88.             m.close()
  89.         print "scores loaded"
  90.        
  91.     def connectionLost(self, reason):
  92.         print("LOST CONNECTION! REASON:  %s" % reason)
  93.         self.timercounter.stop()
  94.         irc.IRCClient.connectionLost(self, reason)
  95.  
  96.     def signedOn(self):
  97.         self.join(self.factory.channel)
  98.         self.mode(self.nickname, True, '+B', limit=None, user=self.nickname)
  99.         print('Joined irc.foonetic.net as %s' %(self.nickname))
  100.         print "version %s" % self.version
  101.        
  102.     def joined(self, channel):
  103.         print('Joined %s' %(channel))
  104.         #self.me(channel, 'version '+self.version)        
  105.        
  106.     def noticed(self, user, channel, msg):
  107.         user = user.split('!', 1)[0]
  108.         if user == 'Nickserv':
  109.             self.msg('Nickserv', 'identify '+self.password)
  110.    
  111.     def action(self, user, channel, msg):
  112.         mask = user.split('!', 1)[1]
  113.         user = user.split('!', 1)[0].lower()
  114.         msg = msg.strip().lower()
  115.         if user in self.gamedata.keys() and self.isgame:
  116.             self.checkusermsg(user, mask, channel, msg)
  117.        
  118.     def privmsg(self, user, channel, msg):
  119.         mask = user.split('!', 1)[1]
  120.         user = user.split('!', 1)[0].lower()
  121.         msg = msg.strip().lower()
  122.         if msg.startswith(self.trigger) or msg.startswith(self.nickname.lower()+':') or msg.startswith(self.nickname.lower()+','):
  123.             self.gameparser(user, mask, channel, msg)
  124.         elif user in self.gamedata.keys() and self.isgame:
  125.             self.checkusermsg(user, mask, channel, msg)
  126.            
  127.     def writejoinlist(self):
  128.         joinedfile = open("assassins_joinedlist.txt", "w")
  129.         joinedfile.write(",".join(self.joinedlist))
  130.         joinedfile.close()
  131.            
  132.     def gameparser(self, user, mask, channel, msg):
  133.         if msg.startswith(self.nickname.lower()):
  134.             msg = msg.split(' ',1)[1]
  135.         else:
  136.             msg = msg.strip(self.trigger)
  137.        
  138.         if msg == ('join'):
  139.             self.playerjoin(user)
  140.         elif msg.startswith('start'):
  141.             self.startgame(user)
  142.         elif msg.startswith('stats') or msg.startswith('status'):
  143.             self.userstats(user)
  144.         elif msg.startswith('end'):
  145.             self.endgame(user)
  146.         elif msg.startswith('help'):
  147.             self.help(user)
  148.         elif msg.startswith('time'):
  149.             if self.isgame:
  150.                 self.istheretime(user)
  151.             else:
  152.                 self.notifyuser(user, 'There is no game playing!')
  153.         elif msg.startswith('quit'):
  154.             self.quitgame(user, channel, msg)
  155.         elif msg.startswith('version'):
  156.             self.notifyuser(user, self.version)
  157.         elif msg.startswith('myscore'):
  158.             self.myscore(user)
  159.         elif msg.startswith('topscorer'):
  160.             self.topscore(user)
  161.         elif msg.startswith('joinchan') and user == self.Owner:
  162.             self.channeljoiner(user, msg)
  163.         elif msg.startswith('partchan') and user == self.Owner:
  164.             self.channelparter(user, msg)
  165.        
  166.     def channeljoiner(self, user, msg):
  167.         chan = msg.split(' ', 1)[1]
  168.         self.notifyuser(user, "Attempting to join channel %s..." % (chan))
  169.         self.join(chan)
  170.    
  171.     def channelparter(self, user, msg):
  172.         chan = msg.split(' ', 1)[1]
  173.         self.notifyuser(user, "Attempting to part channel %s..." % (chan))
  174.         self.part(chan)
  175.            
  176.     def playerjoin(self, user):
  177.         if user in self.joinedlist:
  178.             self.notifyuser(user, 'You are already in the game.')
  179.         elif self.isgame:
  180.             self.notifyuser(user, "There is a game already in session. You will be notified when the next game begins.")
  181.             self.joinedlist.append(user)
  182.         else:
  183.             self.joinedlist.append(user)
  184.             self.notifyuser(user, "Welcome to the game of Word Assassins. When the game begins, you will recieve a target and a word you must have them say. If your target says the word (and it is detected by me, yes spelling counts) then he will be killed and you will recieve his target and so on. The last player standing wins! Good luck! Use %sstats whenever you want to check your current game status. The game will restart 24 hours after it has begun." % self.trigger)
  185.             self.writejoinlist()
  186.         k = open('assassins_joinedlist.txt', 'w')
  187.         pickle.dump(self.joinedlist, k)
  188.         k.close()
  189.  
  190.     def startgame(self, user):
  191.         self.alllist = self.gamedata.keys()
  192.         for player in self.joinedlist:
  193.             self.notifyuser(player, 'New game starting... handing out assignments...')
  194.         #try:
  195.         if self.isgame == False:
  196.             if len(self.joinedlist) <= 2:
  197.                 self.notifyuser(user, "There aren't enough players to begin! You need at least 3 players")
  198.                 return
  199.             else:
  200.                 self.playerlist = self.joinedlist
  201.                 random.shuffle(self.playerlist)
  202.                 for player in self.playerlist:
  203.                     playercount = self.playerlist.index(player)
  204.                     #print playercount
  205.                     #print self.playerlist[playercount]
  206.                     if playercount < len(self.playerlist)-1:
  207.                         target = self.playerlist[playercount+1]
  208.                     elif playercount == len(self.playerlist)-1:
  209.                         target = self.playerlist[0]
  210.                     deathword = random.choice(self.wordlist)
  211.                     self.gamedata[player] = {'target':target, 'wordtodie':deathword}
  212.                 for player in self.gamedata.keys():
  213.                     targ = self.gamedata[player]['target']
  214.                     wordtokill = self.gamedata[targ]['wordtodie']
  215.                     self.notifyuser(player, "Your mission is to kill: %s. You must get this person to say: %s." % (targ, wordtokill))
  216.                 self.isgame = True
  217.                 self.timeleftingame = self.resetcycle + 60
  218.                 self.gameend = reactor.callLater(self.resetcycle, self.hours24)
  219.                 self.hourwarning = reactor.callLater(self.resetcycle-self.resetwarning, self.hours23)
  220.                 self.timercounter = task.LoopingCall(self.timeleft)
  221.                 self.timercounter.start(60)
  222.         else:
  223.             self.notifyuser(user, "There is already a game in progress.")
  224.         #except IndexError:
  225.          #   self.gamedata = {}
  226.           #  self.alreadyassigned = []
  227.            # self.startgame(user)
  228.            
  229.     def quitgame(self, user, channel, msg):
  230.         if user in self.joinedlist:
  231.             self.joinedlist.remove(user)
  232.             self.notifyuser(user, "You will no longer join new games.")
  233.             self.writejoinlist()
  234.             if user in self.gamedata.keys() and self.isgame:
  235.                 self.playerdeath(user, channel, msg)
  236.             elif user in self.playerlist and self.isgame == False:
  237.                 self.notifylist("%s has quit!" % (user))
  238.                 self.playerlist.remove(user)
  239.         else:
  240.             self.notifyuser(user, "You can't quit a game you aren't in!")
  241.  
  242.     def checkusermsg(self, user, mask, channel, msg):
  243.         if self.gamedata[user]['wordtodie'] in msg:
  244.             self.playerdeath(user, channel, msg)
  245.            
  246.     def playerdeath(self, user, channel, msg):
  247.         newtarget = self.gamedata[user]['target']
  248.         newdeathword = self.gamedata[newtarget]['wordtodie']
  249.         for player in self.gamedata:
  250.             if self.gamedata[player]['target'] == user:
  251.                 if player in self.assassinsscores:
  252.                     self.assassinsscores[player] += 1
  253.                 else:
  254.                     self.assassinsscores[player] = 1
  255.                 m = open('assassins_scores.txt', 'w')
  256.                 pickle.dump(self.assassinsscores, m)
  257.                 m.close()
  258.                 self.notifyuser(player, "%s has said '%s'! You have taken on %s's target. \x02NEW TARGET:\x02 %s  \x02WORD TO KILL:\x02 %s. Your current kill count = %d" % (user, self.gamedata[user]['wordtodie'], user, newtarget, newdeathword, self.assassinsscores[player]))
  259.                 self.notifyuser(user, "You have said '%s'! That was the word your killer was trying to get you to say. Your killer has now taken your target to kill. Better luck next game." % self.gamedata[user]['wordtodie'])
  260.                 self.gamedata[player]['target'] = newtarget
  261.                
  262.         del self.gamedata[user]
  263.         self.deadlist.append(user)
  264.         self.notifylist("%s has just died, his/her mysterious killer roams free." % (user))
  265.         if len(self.gamedata.keys()) == 1:
  266.             winner = self.gamedata.keys()[0]
  267.             self.notifylist("The Assassin game is OVER. Congratulations to the new winner: %s" % winner)
  268.             self.timercounter.stop()
  269.             for player in self.gamedata.keys():
  270.                 self.topscore(player)
  271.             self.resetstats()
  272.  
  273.     def myscore(self, user):
  274.         if user not in self.assassinsscores:
  275.             self.assassinsscores[user] = 0
  276.         self.notifyuser(user, "Your current kill count: %d" % (self.assassinsscores[user]))
  277.         m = open('assassins_scores.txt', 'w')
  278.         pickle.dump(self.assassinsscores, m)
  279.         m.close()
  280.    
  281.     def topscore(self, user):
  282.         topsscore = {}
  283.         for player, score in self.assassinsscores.iteritems():
  284.             if score not in topsscore:
  285.                 topsscore[score] = []
  286.             topsscore[score].append(player)
  287.         sortedscore = sorted(topsscore.iteritems(), reverse=True, key=lambda n:n[0])
  288.         print 'top scorers:'
  289.         print sortedscore[0]
  290.         if sortedscore[0][0] == 0:
  291.             self.notifyuser(user, "Noone has a kill yet!")
  292.         else:
  293.             tops = ', '.join(sortedscore[0][1])
  294.             self.notifyuser(user, "\x02Top killer(s)\x02: \x02%s\x02 with a score of %d" % (tops, sortedscore[0][0]))
  295.        
  296.     def timeleft(self):
  297.         self.timeleftingame -= 60
  298.         print self.timeleftingame
  299.        
  300.     def istheretime(self, user):
  301.         if self.isgame:
  302.             minleft = (self.timeleftingame / 60) % 60
  303.             hoursleft = self.timeleftingame / 3600
  304.             self.notifyuser(user, "There are %d hours and %d minutes left in this round." % (hoursleft, minleft))
  305.            
  306.     def userstats(self, user):
  307.         if user in self.gamedata.keys() and self.isgame:
  308.             target = self.gamedata[user]['target']
  309.             wordtokill = self.gamedata[target]['wordtodie']
  310.             self.notifyuser(user, "Your mission is to kill: %s. You must get this person to say: %s." % (target, wordtokill))
  311.         elif self.isgame == False:
  312.             self.notifyuser(user, "There is no game currently in play to get your information from!")
  313.         elif user not in self.gamedata.keys() and user in self.deadlist:
  314.             self.notifyuser(user, "You are currently dead in this round!")
  315.         else:
  316.             self.notifyuser(user, "You are not currently playing!")
  317.         self.istheretime(user)
  318.  
  319.     def endgame(self, user):
  320.         if user == self.Owner:
  321.             self.notifylist("Game has been ended by owner.")
  322.             print 'Game ended by owner'
  323.             self.resetstats()
  324.         else:
  325.             self.notifyuser(user, "Only my owner may end games at this point.")
  326.  
  327.     def notifylist(self, message):
  328.         for player in self.playerlist:
  329.             self.notifyuser(player, message)
  330.            
  331.     def notifyuser(self, person, message):
  332.         self.notice(person, message)
  333.    
  334.     def hours23(self):
  335.         self.notifylist("There is one hour remaining before the game ends by default. Hurry up and get killing!")
  336.    
  337.     def hours24(self):
  338.         self.notifylist("24 hours have elapsed without a victor declared. Please rejoin now.")
  339.         for person in self.quelist:
  340.             self.notifyuser(person, "24 hours have elapsed without a victor declared. Please rejoin now.")
  341.         self.resetstats()
  342.        
  343.     def help(self, user):
  344.         self.notifyuser(user, self.helpmessage)
  345.         self.notifyuser(user, self.helpcommands)    
  346.            
  347. class KomurinFactory(protocol.ClientFactory):        #A 'factory' for the bot.
  348.     protocol = Komurin
  349.  
  350.     def __init__(self, channel):
  351.         self.channel = channel
  352.  
  353.     def clientConnectionLost(self, connector, reason):        #We got disconnected, reconnect.
  354.         connector.connect()
  355.        
  356.  
  357.     def clientConnectionFailed(self, connector, reason):
  358.         #print "connection failed:", reason
  359.         reactor.stop()
  360.  
  361.  
  362. if __name__ == '__main__':                                #Check if we ran it, not imported it.
  363.     dev = '#kiwi'
  364.     chan = '#kiwi,#pygbot,#mafia,#mafia-testing,#mafia-discuss,#xkcd-love,#xkcd-sex,#xkcd-cs,#bots,#boats,#uno,#TheJohnHenry,###,#,#assassins,#assassin,#xkcd-flu'
  365.    
  366.     if debug:
  367.         f = KomurinFactory(dev)                           #No spaces between channels
  368.     else:
  369.         f = KomurinFactory(chan)
  370.  
  371.     reactor.connectTCP("irc.foonetic.net", 6667, f)        #Connect the factory to the network.
  372.  
  373.     reactor.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement