コード例 #1
0
class SBProg:

    timers = {}
    timersTime = {}
    startSessionTime = ""

    PATH_TO_SERVER = Settings.PATH_TO_SERVER
    RECEIVER = Settings.RECEIVER

    MAX_NUM_ERRORS = 5

    def __init__(self, sleepChar=None, sleepLine=None, isTest=False):
        self.isTest = isTest
        self.sleepChar = sleepChar
        self.sleepLine = sleepLine

    def runProgram(self):
        # try:
        self.output = Output(sleepChar=self.sleepChar,
                             sleepLine=self.sleepLine)
        self.write = self.output.write
        self.writeln = self.output.writeln
        self.canWrite = self.output.canWrite
        self.printHello()
        if not self.tryConnectToRemoteServer():
            print "Closing.. bye."
        self.dbManager = DbManager(self.output)
        self.tryConnectDB()
        self.mainBOT()
        self.newEntry()
        # except Exception, e:
        # 	self.write("Global Error.\n")
        # 	self.write(str(e) + "\n")

    def printHello(self):
        print """$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\n\
$$$$$$$$$$$$$$$$$$$$$$$$$$   WELCOME SOCIAL BOT   $$$$$$$$$$$$$$$$$$$$$$$$$$\n\
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\n"""

    def tryConnectToRemoteServer(self):
        "Look for the remote server"
        sys.stdout.write("Trying connecting to server online.. ")
        resp = self.post_request({"action": "server_alive"})
        if resp != None:
            print "ok"
            return True
        else:
            return False

    def tryConnectDB(self):
        "Look for database"
        sys.stdout.write("Look for database (" + self.dbManager.dbName +
                         ").. ")
        if (not os.path.exists(self.dbManager.dbName)):
            print "not in path"
            self.dbManager.initDB()
        else:
            print "already in path!"
            self.dbManager.initDB()

    def mainBOT(self):
        print "Initializing the BOT:"
        self.startSessionTime = datetime.datetime.fromtimestamp(
            float(int(time.time()))).strftime('%H:%M:%S %d/%m')
        print "Get data from online server:"
        self.accounts = Accounts(self)
        print "Get data from online server complete!"
        self.updateStatistics(firstTime=True)
        if self.isTest:
            self.testConnectedBlogs()
        print "Initialization finished! Run the blogs!"

    def newEntry(self):
        while True:
            entry = raw_input("\n" + self.output.startSimble)
            if entry in ["quit", "exit"]:
                self.closing_operations()
                break
            elif entry in ["help", "info"]:
                self.printHelpCmd()
            elif (entry != "") and (entry.split()[0] in ["clear", "Clear"]):
                self.accounts.clearDB4blog(entry)
            elif (entry != "") and (entry.split()[0] in ["log", "Log"]):
                self.accounts.log(entry)
            elif (entry != "") and (entry.split()[0]
                                    in ["changeSpeed", "speed", "cs"]):
                self.output.changeSpeed(entry)
            elif (entry != "") and (entry.split()[0] in ["run", "Run"]):
                # self.accounts.runBlogs(entry)
                print "Running Blogs!"
                t = threading.Thread(target=self.accounts.runBlogs,
                                     args=(entry, )).start()
            elif (entry != "") and (entry.split()[0] in ["stop", "Stop"]):
                self.accounts.stopBlogs(entry)
            elif (entry != "") and (entry.split()[0] == "copy"):
                self.copyBlog(entry)
            else:
                print "Unknown command '" + entry + "'"

    def logResults(self):
        self.canWrite = True
        print "\nLogging results.."
        while not raw_input() in ['q', 'Q']:
            pass
        self.canWrite = False

    def printHelpCmd(self):
        "Print list of available commands"
        prevCanWrite = self.canWrite
        self.canWrite = True
        print "List of commands:"
        print "   - 'help': for list of instructions"
        print "   - 'clean': clean directory"
        print "   - 'f': fast print"
        print "   - 'changeSpeed': for changing printing text speed"
        print "   - 'copy blog_to_copy my_blog': for copy an entire blog"
        print "   - 'run': for run a/all blog(s)"
        print "   - 'stop': for stop a/all blog(s)"
        print "   - 'quit': for quit"
        prevCanWrite = self.canWrite

    def closing_operations(self):
        self.canWrite = True
        print "Terminating program."
        self.accounts.closingOperations()
        try:
            self.timers["update"].cancel()
        except KeyError, msg:
            pass
        self.updateStatistics()
        resp = self.post_request({
            "action":
            "closing_operations",
            "stop_session_time":
            datetime.datetime.fromtimestamp(float(int(
                time.time()))).strftime('%H:%M:%S %d/%m')
        })
        print "   Bye!\n"