def run_class_configuration(request):
    if request.method == 'POST':
        db = Base('backendDB.pdl')
        if db.exists():
            db.open()
        else: 
            db.create('Type','Log', 'Run', 'Prefix','Rule','Threshold', 'TimeStamp', 'Status')

        configuration_json = json.loads(request.body)
        print configuration_json
        log = configuration_json["log"]
        prefix = configuration_json['prefix']
        rule = configuration_json['rule']
        threshold = configuration_json['threshold']

        # Encode the file.
        encoding.encode(log, prefix)
        for encodingMethod in configuration_json['encoding']:
            for clustering in configuration_json['clustering']:
                for classification in configuration_json['classification']:
                    django_rq.enqueue(tasks.classifierTask, log,
                                      prefix, encodingMethod, clustering, classification, rule, threshold)
                    run = classification + '_' + encodingMethod + '_' + clustering
                    records = [r for r in db if r['Run'] == run and r['Prefix'] == str(prefix) and r['Log'] == log and r['Rule'] == rule and r['Threshold'] == str(threshold)]
                    print records
                    if not records:
                        db.insert("Classification", log, run, str(prefix), rule, str(threshold), time.strftime("%b %d %Y %H:%M:%S", time.localtime()), 'queued')
                    else:
                        db.update(records[0], TimeStamp=time.strftime("%b %d %Y %H:%M:%S", time.localtime()), Status= 'queued')
        db.commit()        
    return HttpResponse("YOLO")
Exemplo n.º 2
0
class Dao_in_memory():
    
    def __init__(self, region_name):
        self.db = Base(region_name, save_to_file=False)
        self.db.create('address', 'band', 'latency', 'resources', mode="override")
    
    def add_blocks(self, blocks):
        
        for block in blocks:
            self.db.insert(address=block.get('address'), band=block.get('band'),
                       latency=block.get('latency'), resources=block.get('resources'))
    
    def update_blocks(self, blocks):
        for block in blocks:
            try:
                old_record = self.db(address=block.get('address'))[0]
                self.db.update(old_record, band=block.get('band'),
                       latency=block.get('latency'), resources=block.get('resources'))
            except IndexError:
                print ('Not present')
            
    def get_block(self, address):
        
        try:
            block = self.db(address=address)[0]
            return block
        except IndexError:
            return None
        
    def get_all_blocks(self):
        
        return self.db
        
    
        
def winner(bot, currentMessage, chat_id): # Decide who wins here. Only the judge is able to use this
    gameRecords = Base("chatStorage/records.pdl")
    gameRecords.open()
    rec = gameRecords._gameID[currentMessage.text[5:10]]
    if not rec:
        botSendFunctions.sendText(bot, chat_id, "Invalid command format")
        return
    rec = rec[-1]
    if currentMessage.from_user.id == rec['creator']:
        revD = {value: key for key, value in globalVars.resp[rec['gameID']].items()}
        winningResp = currentMessage.text[11:]
        if winningResp in revD.keys():
            winningPerson = revD[winningResp]
            pointsList = rec['memberPoints'].split() # List stuff for the database
            memberList = rec['memberUserIDs'].split()
            nameList = rec['memberUsernames'].split()
            pointsList[memberList.index(winningPerson)] = int(pointsList[memberList.index(winningPerson)]) + 1
            gameRecords.update(rec, memberPoints=" ".join([str(i) for i in pointsList])) # Points backend for Assign 3
            gameRecords.commit()
            botSendFunctions.sendText(bot, rec['groupChatID'], "The winner was " + nameList[memberList.index(winningPerson)] + " with " + winningResp + " They now have " + str(pointsList[memberList.index(winningPerson)]) + " point(s).") # Send who won to the group chat
            try:
                globalVars.currBlackCard[currentMessage.text[5:10]] = str(globalVars.blackCards[rec['gameID']].pop()['Value']) # Get the next black card
            except IndexError: # If there are no more cards end the game
                botSendFunctions.sendText(bot, rec['groupChatID'], "Sorry, out of cards. Thanks for playing")
                endGame(bot, currentMessage, chat_id)
                return
            botSendFunctions.sendText(bot, rec['groupChatID'], globalVars.currBlackCard[currentMessage.text[5:10]]) # Send the next black card
            for player in rec['memberChatIDs'].split(): # Send all the players a new card to replace the one they used
                del globalVars.resp[rec['gameID']][player]
                botSendFunctions.sendText(bot, player, "Here are your new cards", 0, globalVars.playerCards[player])
        else:
            botSendFunctions.sendText(bot, chat_id, "Invalid answer")
    else:
        botSendFunctions.sendText(bot, chat_id, "You are not the judge")
def run_configuration(request):
    if request.method == 'POST':
        db = Base('backendDB.pdl')
        # db.create('Type','Log', 'Run', 'Prefix','Rule','Threshold', 'TimeStamp', 'Status', mode="override")
        if db.exists():
            db.open()
        else: 
            db.create('Type','Log', 'Run', 'Prefix','Rule','Threshold', 'TimeStamp', 'Status')


        configuration_json = json.loads(request.body)
        print configuration_json
        log = configuration_json["log"]
        prefix = configuration_json['prefix']
        # Encode the file.
        encoding.encode(log, prefix)
        
        for encodingMethod in configuration_json['encoding']:
            for clustering in configuration_json['clustering']:
                for regression in configuration_json['regression']:
                    django_rq.enqueue(tasks.regressionTask, log,
                                      prefix, encodingMethod, clustering, regression)
                    run = regression + '_' + encodingMethod + '_' + clustering
                    records = [r for r in db if r['Run'] == run and r['Prefix'] == str(prefix) and r['Log'] == log]
                    # for r in db:
                    #     if (r['Run'] == run) and (r['Prefix'] == str(prefix)) and (r['Log'] == log):
                    #         records.append(r)
                    print records
                    if not records:
                        db.insert("Regression", log, run, str(prefix),"NaN","NaN", time.strftime("%b %d %Y %H:%M:%S", time.localtime()), 'queued')
                    else:
                        db.update(records[0], TimeStamp=time.strftime("%b %d %Y %H:%M:%S", time.localtime()), Status= 'queued')
                    # if run in df['Run'].unique():
                    #     df.loc[df.Run == run, 'TimeStamp'] = time.strftime("%b %d %Y %H:%M:%S", time.localtime())
                    #     df.loc[df.Run == run, 'Status'] = "queued"
                    # else: 
                    #     df.loc[df.shape[0]] = [run, time.strftime("%b %d %Y %H:%M:%S", time.localtime()), 'queued']
        # print df
        # print df['Run'] 
        # df.to_csv('core_results_queue/' + log + '/' + str(prefix) + '/reg_queueStatus.csv', sep=',',header=writeHeader, mode='w+', index=False)
        db.commit()
    return HttpResponse("YOLO")
Exemplo n.º 5
0
class Rates:
    """ Persistence layer for exchange rates. """
    def __init__(self, filename, erase_db):
        self.__db = Base(filename)
        self.__db.create('currency',
                         'rate',
                         mode="override" if erase_db else "open")
        self.__db.create_index('currency')

    def setRate(self, currency, rate):
        """ Persist a currency's exchange rate. """
        assert rate > 0.0

        records = self.__db._currency[currency]

        if len(records) > 0:
            assert len(
                records
            ) == 1  # We never expect several exchange rates for the same currency
            self.__db.update(records[0], rate=rate)
        else:
            self.__db.insert(currency=currency, rate=rate)

        self.__db.commit()

    def getRate(self, currency):
        """ Get the exchange rate with EUR for the provided currency or None if it is not found.
            An exchange rate for currency CUR is Value(EUR) / Value(CUR): 1 EUR = rate(CUR) CUR <=> 1/rate(CUR) EUR = 1 CUR.
        """
        records = self.__db._currency[currency]
        return records[0]['rate'] if len(records) > 0 else None

    def getAllRates(self):
        """ Get all known exchange rates as a dict. """
        return [(r['currency'], r['rate']) for r in self.__db]

    def getRatesCount(self):
        """ Get total number of exchange rates in db. """
        return len(self.__db)
Exemplo n.º 6
0
class Rates:
    """ Persistence layer for exchange rates. """

    def __init__(self, filename, erase_db):
        self.__db = Base(filename)
        self.__db.create('currency', 'rate', mode="override" if erase_db else "open")
        self.__db.create_index('currency')

    def setRate(self, currency, rate):
        """ Persist a currency's exchange rate. """
        assert rate > 0.0

        records = self.__db._currency[currency]

        if len(records) > 0:
            assert len(records) == 1 # We never expect several exchange rates for the same currency
            self.__db.update(records[0], rate = rate)
        else:
            self.__db.insert(currency = currency, rate = rate)

        self.__db.commit()

    def getRate(self, currency):
        """ Get the exchange rate with EUR for the provided currency or None if it is not found.
            An exchange rate for currency CUR is Value(EUR) / Value(CUR): 1 EUR = rate(CUR) CUR <=> 1/rate(CUR) EUR = 1 CUR.
        """
        records = self.__db._currency[currency]
        return records[0]['rate'] if len(records) > 0 else None

    def getAllRates(self):
        """ Get all known exchange rates as a dict. """
        return [(r['currency'], r['rate']) for r in self.__db]

    def getRatesCount(self):
        """ Get total number of exchange rates in db. """
        return len(self.__db)
Exemplo n.º 7
0
def likeconvert(likesRoot):
    histPath = likesRoot + '/history'
    convertcsv2db(likesRoot + '/totals.csv', likesRoot + '/likes.pdl')
    db = Base(likesRoot + '/likes.pdl')
    db.open()
    db.add_field('history', "")
    db.add_field('liked', "")
    dirContents = os.listdir(histPath)
    histFiles = []

    for File in dirContents:
        if ".csv" in File:
            histFiles.append(File)
    for histFile in histFiles:
        try:
            csvfile = open(histPath + '/' + histFile, 'rb')
            reader = csv.DictReader(csvfile)
            for row in reader:
                if histFile.endswith('history.csv'):
                    recName = histFile[:-11]
                    print(recName)
                if db(userID=recName):
                    rec = db(userID=recName).pop()
                    if not rec['liked']:
                        db.update(rec, liked=row['liked'])
                    else:
                        tmpLiked = rec['liked']
                        tmpLiked += " " + row['liked']
                        db.update(rec, liked=tmpLiked)
                    if not rec['history']:
                        db.update(rec, history=row['messageID'])
                    else:
                        tmpHist = rec['history']
                        tmpHist += " " + row['messageID']
                        db.update(rec, history=tmpHist)
                db.commit()
        except csv.Error:
                print("Could not open CSV file")
Exemplo n.º 8
0
def likeconvert(likesRoot):
    histPath = likesRoot + "/history"
    convertcsv2db(likesRoot + "/totals.csv", likesRoot + "/likes.pdl")
    db = Base(likesRoot + "/likes.pdl")
    db.open()
    db.add_field("history", "")
    db.add_field("liked", "")
    dirContents = os.listdir(histPath)
    histFiles = []

    for File in dirContents:
        if ".csv" in File:
            histFiles.append(File)
    for histFile in histFiles:
        try:
            csvfile = open(histPath + "/" + histFile, "rb")
            reader = csv.DictReader(csvfile)
            for row in reader:
                if histFile.endswith("history.csv"):
                    recName = histFile[:-11]
                    print(recName)
                if db(userID=recName):
                    rec = db(userID=recName).pop()
                    if not rec["liked"]:
                        db.update(rec, liked=row["liked"])
                    else:
                        tmpLiked = rec["liked"]
                        tmpLiked += " " + row["liked"]
                        db.update(rec, liked=tmpLiked)
                    if not rec["history"]:
                        db.update(rec, history=row["messageID"])
                    else:
                        tmpHist = rec["history"]
                        tmpHist += " " + row["messageID"]
                        db.update(rec, history=tmpHist)
                db.commit()
        except csv.Error:
            print("Could not open CSV file")
def classifierTask(fileName, prefix, encoding, cluster, method, label,
                   threshold):
    db = Base('backendDB.pdl')
    db.open()
    run = method + '_' + encoding + '_' + cluster
    records = [
        r for r in db
        if r['Run'] == run and r['Prefix'] == str(prefix) and r['Log'] ==
        fileName and r['Rule'] == label and r['Threshold'] == str(threshold)
    ]
    db.update(records[0],
              TimeStamp=time.strftime("%b %d %Y %H:%M:%S", time.localtime()),
              Status='Running')
    db.commit()
    try:
        prediction.classifier(fileName, prefix, encoding, cluster, method,
                              label, threshold)
        records = [
            r for r in db if r['Run'] == run and r['Prefix'] == str(prefix)
            and r['Log'] == fileName
        ]
        db.update(records[0],
                  TimeStamp=time.strftime("%b %d %Y %H:%M:%S",
                                          time.localtime()),
                  Status='Completed')
        db.commit()

    except Exception, e:  # Guard against race condition
        records = [
            r for r in db if r['Run'] == run and r['Prefix'] == str(prefix)
            and r['Log'] == fileName and r['Rule'] == label
            and r['Threshold'] == str(threshold)
        ]
        db.update(records[0],
                  TimeStamp=time.strftime("%b %d %Y %H:%M:%S",
                                          time.localtime()),
                  Status='Failed: ' + str(e))
        db.commit()
        raise
def regressionTask(fileName, prefix, encoding, cluster, regressionType):
    db = Base('backendDB.pdl')
    db.open()
    run = regressionType + '_' + encoding + '_' + cluster

    records = [
        r for r in db if r['Run'] == run and r['Prefix'] == str(prefix)
        and r['Log'] == fileName
    ]
    db.update(records[0],
              TimeStamp=time.strftime("%b %d %Y %H:%M:%S", time.localtime()),
              Status='Running')
    db.commit()
    try:
        prediction.regressior(fileName, prefix, encoding, cluster,
                              regressionType)
        records = [
            r for r in db if r['Run'] == run and r['Prefix'] == str(prefix)
            and r['Log'] == fileName
        ]
        db.update(records[0],
                  TimeStamp=time.strftime("%b %d %Y %H:%M:%S",
                                          time.localtime()),
                  Status='Completed')
        db.commit()

    except Exception, e:  # Guard against race condition
        records = [
            r for r in db if r['Run'] == run and r['Prefix'] == str(prefix)
            and r['Log'] == fileName
        ]
        db.update(records[0],
                  TimeStamp=time.strftime("%b %d %Y %H:%M:%S",
                                          time.localtime()),
                  Status='Failed: ' + str(e))
        db.commit()

        raise
Exemplo n.º 11
0
db = Base("test.db", save_to_file=False)

if db.exists():
    db.open()
else:
    db.create("name", "age")

db.insert("bob", 10)
index = db.insert(name="alice", age=20)

print db[index] # 按照主键访问record

record = db[1]

db.update(record, name="dellian")

#db.delete(record)

# db.records (所有记录)

# query
for r in db("age") > 10:
    print r


for r in (db("age") > 5 ) & (db("name") == "bob"):
    print r

print db.records
#db.commit() # flush to disk
Exemplo n.º 12
0
#index field
db.create_index('age')

#db search supports built-in comparison functions and return lists
for r in db('age') >= 20:
    print(r)
print('#######')
print('shortguy')
for r in db('name').ilike('jeremy'):
    print(r)
print('#######')
#db support list comprehension
really_really_really_short = next(r for r in db('size') < 1.0)

#update supports record(s) value(s) and updates the indicie
db.update(really_really_really_short, size=0.1)
fp()  #even shorter
db.update(db, age='23')
fp()

#delete supports single and multiple records
db.delete(r for r in db('size') >= 0.2)
fp()
del db[next(r for r in db('size') < 0.2)['__id__']]
fp()

#useful utility functions
db.add_field('mood',
             default='catcucumber')  # adds field, with optional default value
db.drop_field('mood')  # drops field
db.path  # path of db, can be changed
Exemplo n.º 13
0
def process(bot, chat_id, parsedCommand, messageText, currentMessage, update, instanceAge):
    def sendText(givenText, replyingMessageID=0, keyboardLayout=[]):
        if not chatInstanceArray[chat_id]['adminDisable']:
            atbSendFunctions.sendText(bot, chat_id, givenText, replyingMessageID, keyboardLayout)

    def sendPhoto(imageName):
        atbSendFunctions.sendPhoto(bot, chat_id, "images/"+ imageName)

    def sendSticker(stickerName):
        atbSendFunctions.sendSticker(bot, chat_id, "stickers/"+ stickerName)

    def passSpamCheck():
        return atbMiscFunctions.spamCheck(chat_id, currentMessage.date)


    try:
        chatInstanceArray[chat_id]['checking'] = True
    except Exception:
        chatInstanceArray[chat_id] = {'checking': True, 'adminDisable': False, 'spamTimestamp': 0, 'shottyTimestamp': 0, 'shottyWinner': "", 'checkingVehicles': False, 'whoArray': []}


    try:
        #commands go here, in this if-elif block. Python doesn't have switch statements.
        if parsedCommand == "/mom": #sends "MOM GET THE CAMERA"
            sendText("MOM GET THE CAMERA")

        elif atbMiscFunctions.isMoom(parsedCommand): #sends M {random number of Os} M
            if passSpamCheck(): #use this to prevent spamming of a command
                response = "M"
                for i in range(0, random.randint(3, 75)):
                    response += "O"
                sendText(response + "M")

        elif parsedCommand == "/swag":
            sendText("swiggity swag, what\'s in the bag?")

        elif parsedCommand == "/worms":
            if passSpamCheck():
                response = "hey man can I borrow your "
                if len(messageText) > len("/worms "):
                    response += messageText[len("/worms "):]
                else:
                    response += "worms"
                sendText(response)

        elif parsedCommand == "/shh" or parsedCommand == "/shhh":
            if passSpamCheck():
                sendPhoto("shhh.jpg")

        elif parsedCommand == "/father":
            if (random.randint(0, 1)):
                sendText("You ARE the father!")
            else:
                sendText("You are NOT the father!")

        elif parsedCommand == "/rip":   #sends "I can't believe that [name (defaults to sender's name)] is f*****g dead."
            if passSpamCheck():
                response = "I can't believe that "
                if len(messageText) > len("/rip "):
                    if (messageText[len("/rip "):] == "me"):
                        response += currentMessage.from_user.first_name
                    else:
                        response += messageText[len("/rip "):]
                else:
                    response += currentMessage.from_user.first_name
                response += " is f*****g dead."
                sendText(response)

        elif parsedCommand == "/scrub":
            checkingStats = False
            try:
                if currentMessage.text.lower().split()[1] == "stats":
                    db = Base('chatStorage/scrub.pdl') #The path to the DB
                    db.create('username', 'name', 'counter', mode="open")
                    K = list()
                    for user in db:
                        K.append(user)
                    sortedK = sorted(K, key=lambda x: int(x['counter']), reverse=True)
                    outputString = "SCRUBBIEST LEADERBOARD:\n"
                    for user in sortedK:
                        pluralString = " SCRUB POINT"
                        if not(int(user['counter']) == 1):
                            pluralString += "S"
                        pluralString += "\n"
                        outputString += user['name'].upper() + ": " + str(user['counter']) + pluralString
                    sendText(outputString)
                    checkingStats = True
            except IndexError:
                pass

            if not checkingStats and (currentMessage.from_user.id == 169883788 or currentMessage.from_user.id == 44961843):
                db = Base('chatStorage/scrub.pdl')
                db.create('username', 'name', 'counter', mode="open")

                userWasFound = False
                valueSuccessfullyChanged = False

                for user in db:
                    if int(user['username']) == currentMessage.reply_to_message.from_user.id:
                        db.update(user, counter=int(user['counter']) + 1)
                        valueSuccessfullyChanged = True
                        userWasFound = True
                db.commit()

                if not userWasFound:
                    db.insert(currentMessage.reply_to_message.from_user.id, currentMessage.reply_to_message.from_user.first_name, 1)
                    db.commit()

                if valueSuccessfullyChanged or not userWasFound:
                    sendText("Matt Gomez awarded a scrub point to " + currentMessage.reply_to_message.from_user.first_name + ".")

            elif not checkingStats:
                sendText("AdamTestBot, powered by ScrubSoft (C)")

        elif parsedCommand == "/hiss":
            checkingStats = False
            try:
                if currentMessage.text.lower().split()[1] == "stats":
                    db = Base('chatStorage/hiss.pdl')
                    db.create('username', 'name', 'counter', mode="open")
                    K = list()
                    for user in db:
                        K.append(user)
                    sortedK = sorted(K, key=lambda x: int(x['counter']), reverse=True)
                    outputString = "Hiss Leaderboard:\n"
                    for user in sortedK:
                        pluralString = " hiss"
                        if not(int(user['counter']) == 1):
                            pluralString += "es"
                        pluralString += "\n"
                        outputString += user['name'] + ": " + str(user['counter']) + pluralString
                    sendText(outputString)
                checkingStats = True
            except IndexError:
                pass

            if not checkingStats and (currentMessage.from_user.id == 122526873 or currentMessage.from_user.id == 44961843):
                db = Base('chatStorage/hiss.pdl')
                db.create('username', 'name', 'counter', mode="open")

                userWasFound = False
                valueSuccessfullyChanged = False

                for user in db:
                    if int(user['username']) == currentMessage.reply_to_message.from_user.id:
                        db.update(user, counter=int(user['counter']) + 1)
                        valueSuccessfullyChanged = True
                        userWasFound = True
                db.commit()
                
                if not userWasFound:
                    db.insert(currentMessage.reply_to_message.from_user.id, currentMessage.reply_to_message.from_user.first_name, 1)
                    db.commit()

                if valueSuccessfullyChanged or not userWasFound:
                    sendText("Robyn hissed at " + currentMessage.reply_to_message.from_user.first_name + ".")

        elif parsedCommand == "/water":
            if (random.randint(0, 1) == 0):
                sendSticker("water.webp")
            else:
                sendSticker("hoboken_water.webp")

        #this command should go last:
        elif parsedCommand == "/community": #add your command to this list
            response = "/mom - get the camera\n"
            response += "/mooom (any number of \'o\'s) - call for help\n"
            response += "/swag - more memes\n"
            response += "/worms - can I borrow them?\n"
            response += "/shh(h) - here, be relaxed\n"
            response += "/father - are you the father?\n"
            response += "/rip (something) - I can't believe they're dead!\n"
            response += "/hiss stats - see how many time Robyn has hissed at people\n"
            response += "/scrub or /scrub stats - see who sponsors me or how many times Matt Gomez has called you a scrub\n"
            response += "/water - does this water look brown to you?"
            sendText(response)

        else:
            return False

        return True
    except Exception:
        print traceback.format_exc()
        return False
def process(bot, chat_id, parsedCommand, messageText, currentMessage, update,
            instanceAge):
    def sendText(givenText,
                 replyingMessageID=0,
                 keyboardLayout=[]
                 ):  # A simple wrapper for botSendFunctions.sendText()
        botSendFunctions.sendText(bot, chat_id, givenText, replyingMessageID,
                                  keyboardLayout)

    gameRecords = Base(
        "chatStorage/records.pdl"
    )  # The following two lines create a DB to map gameID's to group chat ID's and player ID's
    gameRecords.create("gameID",
                       "groupChatID",
                       "memberUsernames",
                       "memberUserIDs",
                       "memberChatIDs",
                       "memberPoints",
                       "creator",
                       "creatorChatID",
                       "started",
                       mode="open")
    gameRecords.create_index(
        "gameID")  # Create a index to make selections by gameID
    gameRecords.create_index(
        "groupChatID")  # Create a index to make selections by groupChatID
    gameRecords.commit()  # Save changes to disk

    try:
        try:
            chatInstances[chat_id]['checking'] = True
        except Exception:
            chatInstances[chat_id] = {'checking': True}
        print("Processing command " + messageText)
        if parsedCommand == "/help" or parsedCommand == "/start":  # The default command Telegram sends to a bot is /start
            s = "This is the Cards Against Huge Manatees Bot\n"
            s += "To create a game type /newgame in a group chat\n"
            s += "To join a game type /join [gameID] in a private chat with the bot\n"
            s += "To start the game after everyone has joined type /startgame in the group chat.\n"
            s += "A new black card will appear in the group chat and your white cards will appear\n"
            s += "in your private chat. The judge will choose the winner of each round.\n"
            s += "To end the game type /quit in the group chat\n"
            s += "To add a custom black card type /addblackcard the card text here To insert a blank use 5 underscores\n"
            s += "To add a custom white card type /addwhitecard the card text here"

            sendText(s)
        elif parsedCommand == "/newgame":
            ident = game.generate()  # Generate a game ID
            gameRecords.insert(ident, str(chat_id), "", "", "", "",
                               currentMessage.from_user.id, "",
                               0)  # Make a new database record skeleton
            gameRecords.commit()
            sendText("The game ID is " + ident + " Please type /join " +
                     ident + " in a private chat with the bot."
                     )  # Send the ID to the group chat
        elif parsedCommand == "/join":
            rec = gameRecords._gameID[currentMessage.text.upper().split()
                                      [1]]  # Get the DB record by GameID
            if not rec:
                sendText("Game ID not found.")
                return
            rec = rec[-1]
            if rec['started']:  # If the game has already started they can't join.
                sendText("The game has already started. Sorry.")
                return
            if rec['groupChatID'] != str(chat_id):
                memberChats = rec['memberChatIDs']
                memberIDs = rec['memberUserIDs']
                memberNames = rec['memberUsernames']
                points = rec['memberPoints']
                if str(chat_id) not in memberChats:
                    if str(currentMessage.from_user.id) == str(rec['creator']):
                        gameRecords.update(rec, creatorChatID=chat_id)
                        gameRecords.commit()
                        sendText("You are the judge of game " +
                                 str(rec['gameID']))
                        return
                    memberChats += str(
                        chat_id
                    ) + " "  # String to list and back for the database.
                    memberIDs += str(currentMessage.from_user.id) + " "
                    memberNames += str(
                        currentMessage.from_user.first_name) + " "
                    points += "0 "
                    gameRecords.update(
                        rec,
                        memberUsernames=memberNames,
                        memberUserIDs=memberIDs,
                        memberChatIDs=memberChats,
                        memberPoints=points
                    )  # On every join update the database record
                    gameRecords.commit()
                    sendText("You have successfully joined the game " +
                             str(rec['gameID']))
                else:
                    sendText("You have already joined the game.")
            else:
                sendText(
                    "Please type this command in a private chat with the bot.")
        elif parsedCommand == "/startgame":
            try:
                rec = gameRecords._groupChatID[str(chat_id)]
                rec = rec[-1]
                if not rec['started']:
                    game.initGameEnv(rec['gameID'])
                    game.playGame(bot, rec['gameID'])
                    gameRecords.update(rec, started=1)
                    gameRecords.commit()
                else:
                    sendText("Game already started.")
            except Exception:
                traceback.format_exc()
                sendText("Error. No game record for this chat found.")
        elif parsedCommand == "/ans":
            game.getAnswers(bot, currentMessage, chat_id)
        elif parsedCommand == "/win":
            game.winner(bot, currentMessage, chat_id)
        elif parsedCommand == "/quit":
            game.endGame(bot, currentMessage, chat_id)
        elif parsedCommand == "/addblackcard":
            admin.customBlackCard(bot, currentMessage, chat_id)
        elif parsedCommand == "/addwhitecard":
            admin.customWhiteCard(bot, currentMessage, chat_id)
        elif parsedCommand[0] == "/":  # Error handling
            sendText("Not a valid command")

    except Exception:
        print(traceback.format_exc())
class SignalDB:
    def __init__(self, name, path='./', mode="open"):
        '''mode can be 'override' '''

        name_sig = name + '_sig.pdl'
        name_sig = join(path, name_sig)
        self.db_sig = Base(name_sig)
        self.db_sig.create('signal_bundle',
                           'signals',
                           'timestamps',
                           'name',
                           'labels',
                           'md5',
                           'sublabel',
                           mode=mode)
        self.db_sig.open()

    def commit(self):
        self.db_sig.commit()

    def tohash(self, data):
        md5 = hashlib.md5(pickle.dumps(data)).hexdigest()
        return md5

    def findld(self, ld):
        md5 = self.tohash(ld.signal_bundle.signals[0])
        recarr = [r for r in (self.db_sig('md5') == md5)]
        if len(recarr) > 1:
            print 'duplicate signal bundles'
        elif len(recarr) == 1:
            r = recarr[0]
            sb = r['signal_bundle']
            labels = r['labels']
            name = r['name']
            ld_out = LabeledData(sb)
            ld_out.labels = labels
            return ld_out
        else:
            print "signal doesn't currently exist"
            return None

    def add_labeleddata(self, ld, overwrite=False):
        md5 = self.tohash(ld.signal_bundle.signals[0])
        recarr = [r for r in (self.db_sig('md5') == md5)]
        if len(recarr) > 1:
            print 'duplicate signal bundles'
        if not recarr:
            self.db_sig.insert(signal_bundle = ld.signal_bundle,\
                               signals = ld.signal_bundle.signals,\
                               timestamps = ld.signal_bundle.timestamps,\
                               name = ld.signal_bundle.name, \
                               labels = ld.labels,\
                               md5 = md5)

        else:
            rec = recarr[0]
            print rec['__id__']
            if overwrite == False:
                for idx, (reclabel,
                          ldlabel) in enumerate(zip(rec['labels'], ld.labels)):
                    if reclabel == '':
                        rec['labels'][idx] = ldlabel
            else:
                for idx, (reclabel,
                          ldlabel) in enumerate(zip(rec['labels'], ld.labels)):
                    if ldlabel != '':
                        rec['labels'][idx] = ldlabel

            # print rec['__id__'],rec['labels']
            self.db_sig.update(rec, labels=rec['labels'])

    def get_labeleddata(self):
        ld_arr = []
        # signal_bundle, timestamps = None, label = "")
        for r in self.db_sig:
            sb = r['signal_bundle']
            labels = r['labels']
            name = r['name']
            ld = LabeledData(sb)
            ld.labels = labels
            ld_arr.append(ld)
        return ld_arr
Exemplo n.º 16
0
def handleLikes(isLiking, currentMessage):
    try:
        db = Base('chatStorage/likes/likes.pdl') #The path to the database
        db.create('userID', 'likes', 'dislikes', 'history', 'liked', mode="open")  # Create a new DB if one doesn't exist. If it does, open it
        #get disliked comment ID
        likedID = currentMessage.reply_to_message.message_id
        likeReceivedID = currentMessage.reply_to_message.from_user.id
        #check if likedID is in user's liked history
        passedCheck = True
        isLikingSelf = int(likeReceivedID) == int(currentMessage.from_user.id)
        if isLikingSelf:
            passedCheck = False
        if passedCheck:
            if db(userID=currentMessage.from_user.id):
                liker = db(userID=currentMessage.from_user.id).pop()
            else:
                liker = ""
            if db(userID=likeReceivedID):
                liked = db(userID=likeReceivedID).pop()
            else:
                liked = ""
            if liker and likedID not in liker['history'] and liked:
                hist = liker['history']
                hist += " " + likedID
                db.update(liker, history=hist)
                lik = liker['liked']
                tmpLikes = liked['likes']
                tmpDis = liked['dislikes']
                if isLiking:
                    tmpLikes = int(tmpLikes) + 1
                    db.update(liked, likes=tmpLikes)
                    lik += " " + "t"
                else:
                    tmpDis = int(tmpDis) + 1
                    db.update(liked, dislikes=tmpDis)
                    lik += " " + "f"
                db.update(liker, liked=lik)
            elif liker and not liked:
                hist = liker['history']
                hist += " " + likedID
                db.update(liker, history=hist)
                lik = liker['liked']
                if isLiking:
                    db.insert(likeReceivedID, 1, 0, "", "")
                    lik += " " + "t"
                else:
                    db.insert(likeReceivedID, 0, 1, "", "")
                    lik += " " + "f"
                db.update(liker, liked=lik)
            elif not liker and liked:
                if isLiking:
                    tmpLikes = liked['likes']
                    db.insert(currentMessage.from_user.id, 0, 0, likedID, 't')
                    tmpLikes = int(tmpLikes) + 1
                    db.update(liked, likes=tmpLikes)
                else:
                    tmpDis = liked['dislikes']
                    db.insert(currentMessage.from_user.id, 0, 0, likedID, 'f')
                    tmpDis = int(tmpDis) + 1
                    db.update(liked, dislikes=tmpDis)
            elif not liker and not liked:
                if isLiking:
                    db.insert(currentMessage.from_user.id, 0, 0, likedID, 't')
                    db.insert(likeReceivedID, 1, 0, "", "")
                else:
                    db.insert(currentMessage.from_user.id, 0, 0, likedID, 'f')
                    db.insert(likeReceivedID, 0, 1, "", "")
            db.commit()
    except Exception:
        print traceback.format_exc()
Exemplo n.º 17
0
def process(bot, chat_id, parsedCommand, messageText, currentMessage, update, instanceAge):
    def sendText(givenText, replyingMessageID=0, keyboardLayout=[]):
        if not chatInstanceArray[chat_id]['adminDisable']:
            atbSendFunctions.sendText(bot, chat_id, givenText, replyingMessageID, keyboardLayout)

    def sendPhoto(imageName):
        atbSendFunctions.sendPhoto(bot, chat_id, "images/" + imageName)

    def sendSticker(stickerName):
        atbSendFunctions.sendSticker(bot, chat_id, "stickers/" + stickerName)

    def sendAudio(audioName):
        atbSendFunctions.sendAudio(bot, chat_id, "audio/" + audioName)

    def sendVideo(videoName):
        atbSendFunctions.sendVideo(bot, chat_id, "videos/" + videoName)

    def passSpamCheck(timeDelay=15):
        return atbMiscFunctions.spamCheck(chat_id, currentMessage.date, timeDelay)

    try:
        chatInstanceArray[chat_id]['checking'] = True
    except Exception:
        chatInstanceArray[chat_id] = {'checking': True, 'adminDisable': False, 'spamTimestamp': 0, 'shottyTimestamp': 0, 'shottyWinner': "", 'checkingVehicles': False, 'whoArray': []}

    try:
        #commands go here, in this if-elif block. Python doesn't have switch statements.
        if parsedCommand == "/mom": #sends "MOM GET THE CAMERA"
            sendText("MOM GET THE CAMERA")

        elif atbMiscFunctions.isMoom(parsedCommand): #sends M {random number of Os} M
            if passSpamCheck(): #use this to prevent spamming of a command
                response = "M"
                for i in range(0, random.randint(3, 75)):
                    response += "O"
                sendText(response + "M")

        elif parsedCommand == "/swag":
            sendText("swiggity swag, what\'s in the bag?")

        elif parsedCommand == "/worms":
            if passSpamCheck():
                response = "hey man can I borrow your "
                if len(messageText) > len("/worms "):
                    response += messageText[len("/worms "):]
                else:
                    response += "worms"
                sendText(response)

        elif parsedCommand == "/shh" or parsedCommand == "/shhh":
            if passSpamCheck():
                sendPhoto("shhh.jpg")

        elif parsedCommand == "/father":
            if (random.randint(0, 1)):
                sendText("You ARE the father!")
            else:
                sendText("You are NOT the father!")

        elif parsedCommand == "/rip":   #sends "I can't believe that [name (defaults to sender's name)] is f*****g dead."
            if passSpamCheck():
                response = "I can't believe that "

                while "my " in messageText:
                    messageText = messageText.replace("my ", currentMessage.from_user.first_name + "\'s ", 1)

                if len(messageText) > len("/rip "):
                    if messageText[len("/rip "):] == "me":
                        response += currentMessage.from_user.first_name
                    else:
                        response += messageText[len("/rip "):]
                else:
                    response += currentMessage.from_user.first_name
                response += " is f*****g dead."
                sendText(response)

        elif parsedCommand == "/rips":   #sends "I can't believe that [name (defaults to sender's name)] is f*****g dead."
            if passSpamCheck():
                response = "I can't believe that "

                while "my " in messageText:
                    messageText = messageText.replace("my ", currentMessage.from_user.first_name + "\'s ", 1)

                if len(messageText) > len("/rip "):
                    if messageText[len("/rip "):] == "me":
                        response += currentMessage.from_user.first_name
                    else:
                        response += messageText[len("/rip "):]
                else:
                    response += currentMessage.from_user.first_name
                response += " are f*****g dead."
                sendText(response)

        elif parsedCommand == "/scrub":
            checkingStats = False
            try:
                if currentMessage.text.lower().split()[1] == "stats":
                    db = Base('chatStorage/scrub.pdl') #The path to the DB
                    db.create('username', 'name', 'counter', mode="open")
                    K = list()
                    for user in db:
                        K.append(user)
                    sortedK = sorted(K, key=lambda x: int(x['counter']), reverse=True)
                    outputString = "SCRUBBIEST LEADERBOARD:\n"
                    for user in sortedK:
                        pluralString = " SCRUB POINT"
                        if not(int(user['counter']) == 1):
                            pluralString += "S"
                        pluralString += "\n"
                        outputString += user['name'].upper() + ": " + str(user['counter']) + pluralString
                    sendText(outputString)
                    checkingStats = True
            except IndexError:
                pass

            if not checkingStats and (currentMessage.from_user.id == 169883788 or currentMessage.from_user.id == 44961843):
                db = Base('chatStorage/scrub.pdl')
                db.create('username', 'name', 'counter', mode="open")

                userWasFound = False
                valueSuccessfullyChanged = False

                try:
                    pointsAdded = float(currentMessage.text.lower().split()[1])
                except (IndexError, ValueError):
                    pointsAdded = 1

                for user in db:
                    if int(user['username']) == currentMessage.reply_to_message.from_user.id:
                        db.update(user, counter=int(user['counter']) + pointsAdded)
                        valueSuccessfullyChanged = True
                        userWasFound = True
                db.commit()

                if not userWasFound:
                    db.insert(currentMessage.reply_to_message.from_user.id, currentMessage.reply_to_message.from_user.first_name, pointsAdded)
                    db.commit()

                if valueSuccessfullyChanged or not userWasFound:
                    sendText("Matt Gomez awarded " + str(pointsAdded) + " scrub point(s) to " + currentMessage.reply_to_message.from_user.first_name + ".")

            elif not checkingStats:
                sendText("AdamTestBot, powered by ScrubSoft (C)")

        elif parsedCommand == "/hiss":
            checkingStats = False
            try:
                if currentMessage.text.lower().split()[1] == "stats":
                    db = Base('chatStorage/hiss.pdl')
                    db.create('username', 'name', 'counter', mode="open")
                    K = list()
                    for user in db:
                        K.append(user)
                    sortedK = sorted(K, key=lambda x: int(x['counter']), reverse=True)
                    outputString = "Hiss Leaderboard:\n"
                    for user in sortedK:
                        pluralString = " hiss"
                        if not(int(user['counter']) == 1):
                            pluralString += "es"
                        pluralString += "\n"
                        outputString += user['name'] + ": " + str(user['counter']) + pluralString
                    sendText(outputString)
                checkingStats = True
            except IndexError:
                pass

            if not checkingStats and (currentMessage.from_user.id == 122526873 or currentMessage.from_user.id == 44961843):
                db = Base('chatStorage/hiss.pdl')
                db.create('username', 'name', 'counter', mode="open")

                userWasFound = False
                valueSuccessfullyChanged = False

                for user in db:
                    if int(user['username']) == currentMessage.reply_to_message.from_user.id:
                        db.update(user, counter=int(user['counter']) + 1)
                        valueSuccessfullyChanged = True
                        userWasFound = True
                db.commit()

                if not userWasFound:
                    db.insert(currentMessage.reply_to_message.from_user.id, currentMessage.reply_to_message.from_user.first_name, 1)
                    db.commit()

                if valueSuccessfullyChanged or not userWasFound:
                    sendText("Robyn hissed at " + currentMessage.reply_to_message.from_user.first_name + ".")

        elif parsedCommand == "/water":
            if passSpamCheck():
                if (random.randint(0, 1) == 0):
                    sendSticker("water.webp")
                else:
                    sendSticker("hoboken_water.webp")

        elif parsedCommand == "/sysinfo":
            if passSpamCheck():
                cpu = []
                for x in range(3):
                    cpu.append(psutil.cpu_percent(interval=1))
                cpuavg = round(sum(cpu) / float(len(cpu)), 1)
                memuse = psutil.virtual_memory()[2]
                diskuse = psutil.disk_usage('/')[3]
                sendText("The CPU uasge is " + str(cpuavg) + "%, the memory usage is " + str(memuse) + "%, and " + str(diskuse) + "% of the disk has been used.")

        elif parsedCommand == "/grill":
            if passSpamCheck():
                sendPhoto("grill.jpg")

        elif parsedCommand == "/pants":
            if passSpamCheck():
                sendText("Shit! I can't find my pants.")

        elif parsedCommand == "/broken":
            if passSpamCheck():
                if len(messageText) > len("/broken "):
                    message = str(currentMessage.from_user.username) + " says: @magomez96 my " + messageText[len("/broken "):] + " is broken!"
                else:
                    message = str(currentMessage.from_user.username) + " says: @magomez96 my shit is broken!"
                sendText(message)

        elif parsedCommand == "/quote":
            if passSpamCheck(5):
                try:
                    sendText(atbQuote.getQuoteAt(chat_id, int(messageText.split()[1])))
                except:
                    sendText(atbQuote.getQuote(chat_id))

        elif parsedCommand == "/quotefrom":
            print("\n" + messageText[len("/quotefrom "):])
            if passSpamCheck(5):
                sendText(atbQuote.getQuoteFrom(chat_id, messageText[len("/quotefrom "):]))

        elif parsedCommand == "/quoteremove":
            if currentMessage.from_user.username == "AdamZG" or currentMessage.from_user.username == "magomez96" or currentMessage.from_user.username == "Peribot":
                if atbQuote.quoteRemove(chat_id, int(messageText.split()[1])):
                    sendText("Quote " + messageText.split()[1] + " removed")
                else:
                    sendText("That quote doesn't exist or you never added any quotes")

        elif parsedCommand == "/quoteadd":
            if currentMessage.reply_to_message == None and messageText == "/quoteadd":
                sendText("Try replying to a message with this command to add it to the quote list")
            else:
                userLastName = ""
                try:
                    userLastName = " " + currentMessage.from_user.last_name
                except:
                    pass
                try:
                    replyUserLastName = ""
                    try:
                        replyUserLastName = " " + currentMessage.reply_to_message.from_user.last_name
                    except:
                        replyUserLastName = ""
                    quote_resp = atbQuote.quoteAdd(chat_id, '"' + currentMessage.reply_to_message.text + '"', (currentMessage.reply_to_message.from_user.first_name + replyUserLastName).strip())
                    sendText(quote_resp)
                except(Exception):
                    quoteParse = currentMessage.text.split("-")
                    quote = "-".join(quoteParse[:-1])
                    quote = quote[len("/quoteadd "):].strip()
                    quote_resp = atbQuote.quoteAdd(chat_id, quote, quoteParse[-1].strip(), (currentMessage.from_user.first_name + userLastName).strip())
                    sendText(quote_resp)

        elif parsedCommand == "/quotelegacy":
            if passSpamCheck(5):
                sendText(atbQuote.getQuoteLegacy(chat_id))

        elif parsedCommand == "/pogo":
            def getPokeInfo():
                start = time.time()
                try:
                    nf = urlopen("https://pgorelease.nianticlabs.com/plfe/", timeout = 3)
                    page = nf.read()
                    end = time.time()
                    nf.close()
                except TimeoutError:
                    end=time.time()
                    rTime = round((end - start) * 1000)
                    if (rTime < 800):
                        sendText("Pokémon GO is UP\n{}ms Response Time".format(rTime))
                    elif (rTime >= 800 and rTime < 3000):
                        sendText("Pokémon GO's servers are struggling\n{}ms Response Time".format(rTime))
                    elif (rTime >= 3000):
                        sendText("Pokémon GO is DOWN\n{}ms Response Time".format(rTime))
                except Exception as e:
                    sendText("Pokémon GO's servers are really not doing well\nHere's what I got back\n" + e.__str__())
            
            myThread = Thread(target=getPokeInfo)
            myThread.start()

        elif parsedCommand == "/discourse":
            if passSpamCheck():
                if (random.randint(0, 1) == 0):
                    sendPhoto("discourse.jpg")
                else:
                    sendText("http://thediscour.se")

        #this command should go last:
        elif parsedCommand == "/community": #add your command to this list
            response = "/mom - get the camera\n"
            response += "/mooom (any number of \'o\'s) - call for help\n"
            response += "/swag - more memes\n"
            response += "/worms - can I borrow them?\n"
            response += "/shh(h) - here, be relaxed\n"
            response += "/father - are you the father?\n"
            response += "/rip(s) (something) - I can't believe they're dead! (The s is for plural dead things)\n"
            response += "/hiss stats - see how many time Robyn has hissed at people\n"
            response += "/scrub or /scrub stats - see who sponsors me or how many times Matt Gomez has called you a scrub\n"
            response += "/water - does this water look brown to you?\n"
            response += "/sysinfo - Gets server performance info.\n"
            response += "/grill - I'm a George Foreman grill!\n"
            response += "/pants - Pants?\n"
            response += "/broken - Tell Matt Gomez your stuff is broken.\n"
            response += "/quote - Pulls a random quote from a list. Reply to a message with /quoteadd to add one!\n"
            response += "/pogo - Want to know if Pokémon GO's servers are up?\n"
            response += "/discourse - Break in case of spicy discourse"
            sendText(response)

        else:
            return False

        return True
    except Exception:
        print(traceback.format_exc())
        return False
Exemplo n.º 18
0
            'class': True,
            'ranks': 1,
            'check': 'int'
        }
    },
    'feats': {
        'spell penetration': 1,
    }
}

if not db._owner['bhamlin#6283']:
    db.insert(owner='bhamlin#6283', name='Covfefe', game=None, char=c)
    db.commit()

for rec in db._owner['bhamlin#6283']:
    q = rec['char']
    q['level'][0] += 1
    db.update(rec, char=q)
    db.commit()

for rec in (db('owner') == 'bhamlin#6283'):
    #print(rec)
    #print(json.dumps(rec['char']))
    print(rec['char']['name'], rec['char']['level'])

print()

# for rec in [rec for rec in db if rec['owner'] == 'bhamlin#6283']:
#     print(rec)
#     print(rec['char'].__dict__)