Advertisement
Guest User

HvZGameMaster.py

a guest
Apr 16th, 2015
284
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.89 KB | None | 0 0
  1. import smtplib
  2. import imaplib
  3. import time
  4. import threading
  5. import Queue
  6. import sys
  7. import argparse
  8. import csv
  9. import random
  10. import string
  11. import subprocess as sp
  12. import os
  13. import email
  14. import re
  15.  
  16.  
  17. class mailMan(object):
  18.     """mailMan manages player interactions such as tags reported via text messages or emails"""
  19.     def __init__(self, playerManager):
  20.         super(mailMan, self).__init__()
  21.         self.mail = imaplib.IMAP4_SSL('imap.gmail.com')
  22.         self.mail.login(args.username,args.password)
  23.         self.mail.list()
  24.         # Out: list of "folders" aka labels in gmail.
  25.         self.mail.select("inbox") #connect to inbox.
  26.  
  27.     def getBody(self, emailMessage):
  28.         maintype = emailMessage.get_content_maintype()
  29.         if maintype == 'multipart':
  30.             for part in emailMessage.get_payload():
  31.                 if part.get_content_maintype() == 'text':
  32.                     return part.get_payload()
  33.         elif maintype == 'text':
  34.             return emailMessage.get_payload()
  35.  
  36.     def getUnread(self):
  37.         self.mail.select("inbox") # Select inbox or default namespace
  38.         (retcode, messages) = self.mail.search(None, '(UNSEEN)')
  39.         if retcode == 'OK':
  40.             retlist = []
  41.             for num in messages[0].split(' '):
  42.                 print 'Processing :', messages
  43.                 typ, data = self.mail.fetch(num,'(RFC822)')
  44.                 msg = email.message_from_string(data[0][1])
  45.                 typ, data = self.mail.store(num,'-FLAGS','\\Seen')
  46.                 if retcode == 'OK':
  47.                     for item in str(msg).split('\n'):
  48.                         #finds who sent the message
  49.                         if re.match("From: *",item):
  50.                             print (item[6:], self.getBody(msg))
  51.                             retlist.append((item[6:], self.getBody(msg).rstrip())
  52.                             #print (item, self.getBody(msg).rstrip())
  53. class players(object):
  54.     """manages the player"""
  55.     def __init__(self, pDict):
  56.         super(players, self).__init__()
  57.         self.pDict = pDict
  58.     #makes a partucular player a zombie
  59.     def makeZombie(self, pID):
  60.         self.pDict[pID].zombie = True
  61.     #makes a partucular player a zombie
  62.     def makeHuman(self, pID):
  63.         self.pDict[pID].zombie = False
  64.     def chosePZ(self):
  65.         #sp.call('clear', shell=True)
  66.         #os.system('clear')
  67.         picking = True
  68.         while picking:
  69.             selection = raw_input("\nEnter the player ID of the player who you would like to be PZ.\nIf you don't enter anything here a pz will be chosen at random.\n")
  70.             if selection == "":
  71.                 selection = random.choice(self.pDict.keys())
  72.                 self.pDict[selection].PZero = True
  73.  
  74.                 print "%s (%s) has been set as PZ, are you satisfied with this choice? (Y/N)" % (self.pDict[selection].getAttribs()[0], selection)
  75.                
  76.                 satisfied = raw_input()
  77.                 if satisfied.lower() == 'y':
  78.                     picking = False
  79.                 elif satisfied.lower() != 'n':
  80.                     print "Please enter a 'Y' or an 'N'.\n"
  81.                    
  82.             else:
  83.                 try:
  84.                     self.pDict[selection].PZero = True
  85.                     print "%s (%s) has been set as PZ, is this correct? (Y/N)" % (self.pDict[selection].getAttribs()[0], selection)
  86.                     satisfied = raw_input()
  87.  
  88.                     if satisfied.lower() == 'y':
  89.                         picking = False
  90.                     elif satisfied.lower() != 'n':
  91.                         print "Please enter a 'Y' or an 'N'.\n"
  92.                 except:
  93.                     print "That player ID does not exist please enter another one."
  94.  
  95.  
  96.  
  97.  
  98. #holds values for a single player
  99. class player(object):
  100.     """represents players and their values"""
  101.     def __init__(self, name, number, email):
  102.         super(player, self).__init__()
  103.         self.name = name
  104.         self.number = number
  105.         self.email = email
  106.         self.zombie = False
  107.         self.PZero = False
  108.         self.kills = 0
  109.     #returns a tupple of the name, phone number(formated as an email address) and email address of the playes.
  110.     def getAttribs(self):
  111.         return (self.name, self.number, self.email, self.zombie, self.PZero, self.kills)
  112.  
  113.  
  114.  
  115.  
  116. #Handles the login and sending of email messages via SMTP
  117. class messaging(object):
  118.     """Manages all funcitons of the program related to sending messages but not receving them"""
  119.     def __init__(self,fromaddr,playerManager):
  120.         super(messaging, self).__init__()
  121.         self.fromaddr = fromaddr
  122.         self.server = smtplib.SMTP('smtp.gmail.com:587')
  123.         self.server.starttls()
  124.  
  125.         print "Atempting to long in to %s (username: %s)" % (self.fromaddr, args.username)
  126.         try:
  127.             self.server.login(args.username,args.password)
  128.             print "login worked"
  129.         except Exception, e:
  130.             print "login failed, are your sure your username and password are correct?"
  131.             raise e
  132.  
  133.     #I should call all of the "send*" functions "text*" but im going to //todo that for now.
  134.     def sendAll(self, msg):
  135.         print "sending messages to players"
  136.  
  137.         # The actual mail send
  138.         print "sending mail..."
  139.         for key in playerManager.pDict.keys():
  140.             print addr
  141.             self.server.sendmail(self.fromaddr, playerManager.pDict[key].number, msg)
  142.         print "mail sent!"
  143.  
  144.     def sendZombies(self, msg):
  145.         for key in playerManager.pDict.keys():
  146.             if playerManager.pDict[key].zombie:
  147.                 self.server.sendmail(self.fromaddr, playerManager.pDict[key].number, msg)
  148.     def sendHumans(self, msg):
  149.         for key in playerManager.pDict.keys():
  150.             if playerManager.pDict[key].human:
  151.                 self.server.sendmail(self.fromaddr, playerManager.pDict[key].number, msg)
  152.     def sendPID(self, pIDList, msg):
  153.         for pIDs in pIDList:
  154.             server.sendmail(self.fromaddr, playerManager.pDict[pIDs].number, msg)
  155.     def sendPZero(self, msg):
  156.         for key in playerManager.pDict.keys():
  157.             if playerManager.pDict[key].PZero:
  158.                 self.server.sendmail(self.fromaddr,playerManager.pDict[key].number, msg)
  159.    
  160.     def emailAll(self, msg):
  161.         print "sending messages to players"
  162.  
  163.         # The actual mail send
  164.         print "sending mail..."
  165.         for key in playerManager.pDict.keys():
  166.             print addr
  167.             self.server.sendmail(self.fromaddr, playerManager.pDict[key].email, msg)
  168.         print "mail sent!"
  169.  
  170.     def emailZombies(self, msg):
  171.         for key in playerManager.pDict.keys():
  172.             if playerManager.pDict[key].zombie:
  173.                 self.server.sendmail(self.fromaddr, playerManager.pDict[key].email, msg)
  174.     def emailHumans(self, msg):
  175.         for key in playerManager.pDict.keys():
  176.             if playerManager.pDict[key].human:
  177.                 self.server.sendmail(self.fromaddr, playerManager.pDict[key].email, msg)
  178.     def emailPID(self, pIDList, msg):
  179.         for pIDs in pIDList:
  180.             server.sendmail(self.fromaddr, playerManager.pDict[pIDs].email, msg)
  181.     def emailPZero(self, msg):
  182.         for key in playerManager.pDict.keys():
  183.             if playerManager.pDict[key].PZero:
  184.                 self.server.sendmail(self.fromaddr,playerManager.pDict[key].email, msg)
  185.  
  186.  
  187.  
  188.  
  189.  
  190.  
  191. #############################################################################
  192. ##a couple of utility functions that are up here for cleanliness           ##
  193. ##and that realy only main (and truthfuly not even main) has to care about.##
  194. #############################################################################
  195.  
  196. #cleens up the numbers from the .csv only needed by the main.
  197. def cleenUpNumber(num):
  198.     all=string.maketrans('','')
  199.     nodigs=all.translate(all, string.digits)
  200.     num = num.translate(all, nodigs)
  201.     return num
  202.  
  203. #returns a dict of players
  204. def processFile(fileName):
  205.     carrerDict = {'Alltel Wireless':'@message.Alltel.com', 'Boost Mobile':'@myboostmobile.com', 'AT&T':'@txt.att.net','Sprint':'@messaging.sprintpcs.com','Straight Talk':'@VTEXT.COM', 'T-Mobile':'@tmomail.net','U.S. Cellular':'@email.uscc.net', 'Verizon':'@vtext.com', 'Virgin Mobile':'@vmobl.com'}
  206.  
  207.     playerTempList=[]
  208.  
  209.     with open(fileName, 'rb') as csvFile:
  210.         csvData = csv.reader(csvFile, dialect='excel')
  211.         for row in csvData:
  212.             if row[0] != "+9sdG":
  213.                 cleenNum = cleenUpNumber(row[2])
  214.  
  215.                 cleenNum = cleenNum+carrerDict[row[3]]
  216.  
  217.                 row.remove(row[2])
  218.                 row.insert(2, cleenNum)
  219.  
  220.                 playerTempList.append((row[0], player(row[1],row[2],row[3])))
  221.         playerDict = dict(playerTempList)
  222.     return playerDict
  223.  
  224.  
  225.  
  226. #main is mostly used to set some stuff up and for debug but honestly not much else.
  227. def main():
  228.  
  229.  
  230.     #create the object to handle sending messages.
  231.     """messenger = messaging(args.account, playerManager)
  232.    
  233.     playerManager.chosePZ()
  234.  
  235.     for key in playerManager.pDict.keys():
  236.         print "\n %s" % str(playerManager.pDict[key].getAttribs())
  237.         if playerManager.pDict[key].PZero:
  238.             print"PZero is %s (pID is %s)." % (playerManager.pDict[key].name, key)
  239.    
  240.     messenger.sendPZero("Hello World, if you get this text Mike Shlanta")"""
  241.  
  242.     mail = mailMan(playerManager)
  243.     #mail.getBody()
  244.     mail.getUnread()
  245.  
  246.     #game.run()
  247.  
  248.  
  249.  
  250. if __name__ == '__main__':
  251.     #because fuck you thats why aslo im lazy so ya...
  252.     parser = argparse.ArgumentParser(description="Helps with adminstration and management of Humans Vs. Zombies games.")
  253.     parser.add_argument('fileName', type=str, help="The name of the .csv file containing the list of players.")
  254.     parser.add_argument('account',  type=str, help="The address of the email account you are using i.e. example@gmail.com")
  255.     parser.add_argument('username', type=str, help="The username of the email account you want to login to.")
  256.     parser.add_argument('password', type=str, help="The password of the email account you want to login to.")
  257.  
  258.     args=parser.parse_args()
  259.  
  260.     #create the player manager object from the .csv
  261.     playerManager = players(processFile(args.fileName))
  262.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement