def loadTable(table_name, turn_n = None, load_turn = None, cb = None, external_path = None): print 'loading table %s at %s %s from %s'%(table_name, turn_n, load_turn, external_path) if cb: util.appendLog(cb, 'loading "%s" from turn %s'%(table_name, turn_n)) try: if turn_n: load_turn = turn_n if external_path: path = external_path else: path = config.options['data']['path'] if load_turn: path = os.path.join(path, str(load_turn)) path = os.path.join(path, '%s.csv'%(table_name,)) for p in csv.DictReader(open(path, 'rt')): for s in unicode_strings: if s in p and p[s]: p[s] = p[s].decode('utf-8') todel = [] for k,v in p.iteritems(): if v == '' or v==unicode(''): todel.append(k) for td in todel: del p[td] #print 'setting data for table %s %s %s'%(table_name, p, turn_n) db.setData(table_name, p, turn_n) except IOError, e: log.error('failed to load table %s: %s'%(table_name, e)) if cb: util.appendLog(cb, 'Error loading "%s" from turn %s'%(table_name, turn_n)) return
def load_all_visible_geo(path ): for f in os.listdir(path): print 'loading %s'%(f,) try: for p in csv.DictReader(open(os.path.join(path,f), 'rt')): for s in unicode_strings: if s in p and p[s]: p[s] = p[s].decode('utf-8') db.setData('planet_size', p, None) yield p except IOError, e: log.error('failed to load csv %s: %s'%(path, e))
def addToInventory(discordID, item, quantity): inv = getInventory(discordID) if (getItemExistsPosition(discordID, item) != -1): pos = getItemExistsPosition(discordID, item) inv[pos][1] = str(int(inv[pos][1]) + int(quantity)) else: if (getFreeInventorySlot(discordID) == -1): return "No Space" else: inv[getFreeInventorySlot(discordID)][0] = item inv[getFreeInventorySlot(discordID)][1] = str(quantity) db.setData("users", "inventory='" + convertToDBInventory(inv) + "'", 'discordid=\'' + str(discordID) + '\'') return "success"
def removeFromInventory(discordID, item, quantity="all"): inv = getInventory(discordID) try: pos = getItemExistsPosition(discordID, getSingular(item)) except: raise Exception("No item found.") return "No item found." if (quantity == "all") or (quantity >= int(inv[pos][1])): inv[pos][0] = "empty" inv[pos][1] = str(0) else: inv[pos][1] = str(int(inv[pos][1]) - int(quantity)) db.setData("users", "inventory='" + convertToDBInventory(inv) + "'", 'discordid=\'' + str(discordID) + "'") return "success"
def gamble(discordID:int, amount:int): playerMoney = int(db.getData("dollars", "users", f"WHERE discordid='{discordID}'")[0]) if playerMoney >= amount: victory = True if random.randint(0, 100) >= 51 else False if victory: if inventory.payDollars(-1, discordID, amount): return f">>> The odds were in your favor. You won {amount * 2} dollars." else: return f">>> There was an error with payout you out." else: db.setData("users", f"dollars={playerMoney - amount}", f"discordid='{discordID}'") return f">>> You lost the gamble, losing {amount} dollars in the process." else: return ">>> You don't have enough to gamble." return ">>> Is your account set up? Try !xp"
def scheduledjob(): """ Send new notifications that come on KTU site. \n Checks subscription status of each user from Firebase Realtime Database and sends notifs to subscribers """ contents = get_contents() if contents and contents != []: for key, value in users().items(): chat_id = key """ checking if unsubscribed and send the notification """ if value != "F": send_notifs(chat_id, contents, value) setData(notifs)
def pollAllPosts(self): """ get the highest post id and compare it to our last known post id save it and alert if higher """ query = "select post_id from posts order by post_id desc limit 1" rows = putQuery(self, query) if rows is False: return False self.newAllPostId = rows['rows'][0][0] self.savedAllPostId = db.getData(self, 'all_post_id', 0) if self.newAllPostId > self.savedAllPostId: db.setData(self, 'all_post_id', self.newAllPostId) return True else: return False
def chatPoll(self): """ poll the server for new chat messages """ #first get the chat_post_id from local db chatPostId = db.getData(self, 'chat_post_id', 0) query = "select post_id, address, data from posts where post_id > " + str(chatPostId) + " and data like 'chat:%' order by ts asc" rows = putQuery(self, query) if rows is not False: for post in rows['rows']: if post[1] == self.agentAddress: continue self.writeConsole(getNick(self, post[1]) + ' (' + post[0] + ') >> ' + post[2].split(':',1)[1]) chatPostId = post[0] db.setData(self, 'chat_post_id', chatPostId) return
def genPubKey(self): """ Using PyCrypto, generate a new public/private key pair save to the database """ #generate a random number key = RSA.generate(2048) pubKey = key.publickey() pubKey = pubKey.exportKey(passphrase=self.password) privKey = key.exportKey(passphrase=self.password) try: self.agent.post('whisperpubkey:' + pubKey) except netvend.NetvendResponseError as e: return False db.setData(self, pubKey, privKey) return pubKey
def whisperPoll(self): """ Poll netvend for new tip information send our way """ whisperId = db.getData(self,'whisper_id',0) query = "select t.tip_id, p.data, t.from_address from posts as p inner join tips as t on t.post_id = p.post_id where t.to_address = '" + str(self.agentAddress) + "' and t.tip_id > " + str(whisperId) + " and p.data like 'whisper:%' order by t.ts asc" rows = putQuery(self, query) if rows is not False: self.writeConsole('') self.writeConsole('===== New Whispers =====') self.writeConsole('') for whisper in rows['rows']: self.writeConsole(str(getNick(self,whisper[2])) + ' [whisper] >> ' + str(decryptWhisper(self, whisper[1]))) whisperId = whisper[0] self.writeConsole('') db.setData(self, 'whisper_id', whisperId) return
def loadExternalTable(path, turn_n ): table = os.path.basename(path) print 'table name %s from path %s'%(table, path) try: for p in csv.DictReader(open(path, 'rt')): for s in unicode_strings: if s in p and p[s]: p[s] = p[s].decode('utf-8') todel = [] for k,v in p.iteritems(): if v == '' or v==unicode(''): todel.append(k) for td in todel: del p[td] db.setData(table, p, turn_n) except IOError, e: log.error('failed to load table %s: %s'%(table_name, e))
def applyToJob(discordID, job): discordID = '\'' + str(discordID) + '\'' jobID = getJobID(job) currentJobID = int(db.getData('jobid', 'users', 'WHERE discordid=' + discordID)[0]) currentXP = db.getData('experience', 'users', 'WHERE discordid=' + discordID)[0] try: neededXP = jobs[jobID]['minXP'] except: return "What are you even applying to, dumbass? Check !jobs, if you're such a smartass." if (jobID == currentJobID): return f"You are already employed as {job}." else: if (currentXP < neededXP): return f"You don't have enough experience to apply to a position of {job}. Get lost, loser." else: #Succeed at job application db.setData("users", f"jobid={jobID}", f"discordid={discordID}") return f"You have been accepted to the position of {job}. Congratulations!"
def startRaftServer(self): time.sleep(4) print( "------------------------------Starting Raft Server-------------------------------------" ) otherNodes = self.getListOfOtherNodes( self.activeNodesChecker.getAllAvailableIPAddresses()) for node in otherNodes: print(node) otherNodes.remove(self.serverAddress) raftInstance = Raft(self.serverAddress, otherNodes) print("Raft utility has been started") n = 0 old_value = -1 isLeaderUpdated = False while True: time.sleep(0.5) if raftInstance.getCounter() != old_value: old_value = raftInstance.getCounter() if raftInstance._getLeader() is None: #print(len(self.activeNodesChecker.getActiveChannels())) if (not isLeaderUpdated and len( self.activeNodesChecker.getActiveChannels()) == 1): print( "Since the leader is None, hence declaring myself the leader:", self.serverAddress) db.setData("primaryStatus", 1) self.sendLeaderInfoToSuperNode() isLeaderUpdated = True continue n += 1 if n % 20 == 0: if True: print("===================================") print("Am I the leader?", raftInstance._isLeader()) print("Current Leader running at address:", raftInstance._getLeader()) self.updatePrimaryStatus(raftInstance._isLeader(), raftInstance)
def chatPoll(self): """ poll the server for new chat messages """ #first get the chat_post_id from local db chatPostId = db.getData(self, 'chat_post_id', 0) query = "select post_id, address, data from posts where post_id > " + str( chatPostId) + " and data like 'chat:%' order by ts asc" rows = putQuery(self, query) if rows is not False: for post in rows['rows']: if post[1] == self.agentAddress: continue self.writeConsole( getNick(self, post[1]) + ' (' + post[0] + ') >> ' + post[2].split(':', 1)[1]) chatPostId = post[0] db.setData(self, 'chat_post_id', chatPostId) return
def genPubKey(self): """ Using PyCrypto, generate a new public/private key pair save to the database """ #generate a random number key = RSA.generate(2048) pubKey = key.publickey() pubKey = pubKey.exportKey(passphrase=self.password) privKey = key.exportKey(passphrase=self.password) try: self.agent.post('whisperpubkey:' + pubKey) except netvend.NetvendResponseError as e: return False #we should only need to retain the previous one public/private key in the database. #any whispers sent to us while logged out will have been encrypted using our last generated public key #any encrypted using public keys generated prior to that would have been viewed the last time we logged in. #on the other hand it may be useful to retain all keys as then past whispers can still be decrypted. db.setData(self, pubKey, privKey) return pubKey
def whisperPoll(self): """ Poll netvend for new tip information send our way """ whisperId = db.getData(self, 'whisper_id', 0) query = "select t.tip_id, p.data, t.from_address from posts as p inner join tips as t on t.post_id = p.post_id where t.to_address = '" + str( self.agentAddress) + "' and t.tip_id > " + str( whisperId) + " and p.data like 'whisper:%' order by t.ts asc" rows = putQuery(self, query) if rows is not False: self.writeConsole('') self.writeConsole('===== New Whispers =====') self.writeConsole('') for whisper in rows['rows']: self.writeConsole( str(getNick(self, whisper[2])) + ' [whisper] >> ' + str(decryptWhisper(self, whisper[1]))) whisperId = whisper[0] self.writeConsole('') db.setData(self, 'whisper_id', whisperId) return
def readAvailableIPAddresses(self): print("Inside readAvailableIPAddresses") # Read all the available IP addresses from iptable.txt ip_addresses = self.getAllAvailableIPAddresses() # Create channels with all the IP addresses self.createChannelListForAvailableIPs(ip_addresses) db.setData("ip_addresses", self.getStringFromIPAddressesList(ip_addresses)) while True: time.sleep(0.5) ip_addresses = [] try: ip_addresses_old = self.getIPAddressListFromString( db.getData("ip_addresses")) except: db.setData("ip_addresses", "") ip_addresses = self.getAllAvailableIPAddresses() db.setData("ip_addresses", self.getStringFromIPAddressesList(ip_addresses)) # If there is any addition or deletion of node then create a new channel for that and update {channel, ip} map. if (ip_addresses != ip_addresses_old): self.createChannelListForAvailableIPs(ip_addresses) # Update the active {IP, channel} map self.heartBeatChecker()
def sellItem(discordID, item, quantity): dID = discordID discordID = "'" + str(discordID) + "'" currentMoney = db.getData("dollars", "users", f"WHERE discordid={discordID}")[0] itemPrice = getItemPrice(getSingular(item)) if getItemExistsPosition(dID, getSingular(item)) == -1: return False if (itemPrice > 0): try: removeFromInventory(dID, getSingular(item), int(quantity)) except: return False finally: profit = getItemPrice(item) * int(quantity) newMoney = currentMoney + profit db.setData("users", f"dollars={str(newMoney)}", f"discordid={discordID}") return True else: return False
def pollFollowsPosts(self): """ get the highest post id of posts made by our follows compare to our stored id and report """ follows = getFollows(self) if not follows: return False followList = '' for follow in follows: followList += '\'' + str(follow[1]) + '\',' query = "select post_id from posts where address in (" + followList[:-1] + ") order by post_id desc limit 1" rows = putQuery(self, query) if rows is False: return False self.newFollowPostId = rows['rows'][0][0] self.savedFollowPostId = db.getData(self, 'follow_post_id', 0) if self.newFollowPostId > self.savedFollowPostId: db.setData(self, 'follow_post_id', self.newFollowPostId) return True else: return False
def goToWork(discordID): discordID = '\'' + str(discordID) + '\'' jobID = int(db.getData('jobid', 'users', 'WHERE discordid=' + discordID)[0]) timesWorked = db.getData('timesWorked', 'users', 'WHERE discordid=' + discordID)[0] currentXP = db.getData('experience', 'users', 'WHERE discordid=' + discordID)[0] jobTitle = jobs[jobID]['name'] jobSalary = jobs[jobID]['salary'] customEvent = random.choice(jobs[jobID]["customEvents"]) currentDollars = db.getData('dollars', 'users', 'WHERE discordid=' + discordID)[0] newDollars = currentDollars + jobSalary db.setData('users', 'dollars=' + str(newDollars), "discordid=" + discordID) db.setData('users', 'lastWorked=\'' + datetime.datetime.now().strftime("%Y-%m-%d") + "'", "discordid=" + discordID) db.setData('users', 'timesWorked=' + str(timesWorked + 1), "discordid=" + discordID) db.setData('users', 'experience=' + str(currentXP + jobs[jobID]['xpPerWork']), "discordid=" + discordID) return f"You have worked as a {jobTitle}. {customEvent} You earned {str(jobSalary)} dollars and {str(jobs[jobID]['xpPerWork'])} XP."
def main_feed(): LINK = "https://www.annauniv.edu/more.php" page = urllib2.urlopen(LINK) page1 = urllib2.urlopen(LINK) soup = BeautifulSoup(page, "html.parser") remote_data = page1.read() remote_hash = hashlib.md5(remote_data).hexdigest() data = {"md5": remote_hash, "date": datetime.datetime.now().isoformat(), "feed": []} html = soup.findAll('td', height="25") for i in html: # print(i.parent) x = i.find('a') if x: print(x) # redis_db.set('main_feed', main_feed()) data["feed"].append({"link": x.get('href'), "text": x.getText()}) # print("Link", x.get('href')) # print(x.getText()) print(data) setData('main_feed', data)
def sendDataToDestination(self, currDataBytes, node, nodeReplica, username, filename, seqNo, channel): if (node == self.serverAddress): key = username + "_" + filename + "_" + str(seqNo) db.setData(key, currDataBytes) if (nodeReplica != ""): print("Sending replication to ", nodeReplica) active_ip_channel_dict = self.activeNodesChecker.getActiveChannels( ) replica_channel = active_ip_channel_dict[nodeReplica] stub = fileService_pb2_grpc.FileserviceStub(replica_channel) response = stub.UploadFile( self.sendDataInStream(currDataBytes, username, filename, seqNo, "")) return response else: print("Sending the UPLOAD_SHARD_SIZE to node :", node) stub = fileService_pb2_grpc.FileserviceStub(channel) response = stub.UploadFile( self.sendDataInStream(currDataBytes, username, filename, seqNo, nodeReplica)) print("Response from uploadFile: ", response.message) return response
def payDollars(fromDiscordID: int, toDiscordID, quantity): giverDollars = 0 if (toDiscordID == fromDiscordID): return ">>> You're trying to pay to yourself. That's not even how Patreon works." if fromDiscordID != -1: giverDollars = int( db.getData("dollars", "users", f"WHERE discordid='{str(fromDiscordID)}'")[0]) else: giverDollars = 9999999 recipientDollars = int( db.getData("dollars", "users", f"WHERE discordid='{str(toDiscordID)}'")[0]) if (giverDollars >= int(quantity)): if fromDiscordID != -1: db.setData("users", f"dollars={str(giverDollars - int(quantity))}", f"discordid='{str(fromDiscordID)}'") db.setData("users", f"dollars={str(recipientDollars + int(quantity))}", f"discordid='{str(toDiscordID)}'") return True else: return ">>> You don't have enough dollars to pay. Have you tried contacting Babibank?" return "Error. Get help."
def post(self): year = request.args.get('year') month = request.args.get('month') code = request.args.get('code') YM = str(year) + str(month) receipt_prizenum = getPrizeNum(int(year), int(month)) receipt_prizenum_json = json.loads(receipt_prizenum) if(receipt_prizenum_json['msg'] != '無此期別資料'): win, money = show_prize(str(code), receipt_prizenum_json) else: win = -1 money = 0 if(checkData('Mtranditional_code', code) == -1): addsql = 'Mtranditional_code(period, bar_code, win, money)' addsqlparams = "VALUES ('%s', '%s', '%s', '%s');" % (YM, code, win, money) setData(addsql, addsqlparams) print('insert data into database') else: print('bar_code exist!') return code
def updatePrimaryStatus(self, isLeader, raftInstance): isPrimary = int(db.get("primaryStatus")) if (isPrimary == 1): self.sendLeaderInfoToSuperNode() if (raftInstance._getLeader() is None): db.setData("primaryStatus", 1) self.sendLeaderInfoToSuperNode() elif (isLeader and isPrimary == 0): db.setData("primaryStatus", 1) self.sendLeaderInfoToSuperNode() elif (not isLeader and isPrimary == 1): db.setData("primaryStatus", 0)
t2.start() t1.start() print("Both threads have been started") # Keep the server running for '_ONE_DAY_IN_SECONDS' seconds. try: while True: time.sleep(_ONE_DAY_IN_SECONDS) except KeyboardInterrupt: server.stop(0) # ----------------------Main Method-------------------- # if __name__ == '__main__': # Read the configuration from 'config.yaml' config_dict_orig = yaml.load(open('config.yaml')) if(len(sys.argv)<2): print("Usage python3 server.py <<server No>>") print("Enter one, two or three for server No.") exit() config_dict = config_dict_orig[str(sys.argv[1]).lower()] server_host = config_dict['hostname'] server_port = str(config_dict['server_port']) raft_port = str(config_dict['raft_port']) super_node_address = config_dict_orig['super_node_address'] #Initially set the primaryStatus to 0 db.setData("primaryStatus", 0) # Start the server run_server(server_host, server_port, raft_port, super_node_address)
def UploadFile(self, request_iterator, context): print("Inside Server method ---------- UploadFile") data = bytes("", 'utf-8') username, filename = "", "" totalDataSize = 0 active_ip_channel_dict = self.activeNodesChecker.getActiveChannels() # list to store the info related to file location. metaData = [] # If the node is the leader of the cluster. if (int(db.get("primaryStatus")) == 1): print("Inside primary upload") currDataSize = 0 currDataBytes = bytes("", 'utf-8') seqNo = 1 # Step 1: # Get 2 least loaded nodes based on the CPU stats. # 'Node' is where the actual data goes and 'node_replica' is where replica will go. node, node_replica = self.getLeastLoadedNode() if (node == -1): return fileService_pb2.ack( success=False, message="Error Saving File. No active nodes.") # Step 2: # Check whether file already exists, if yes then return with message 'File already exists'. for request in request_iterator: username, filename = request.username, request.filename print("Key is-----------------", username + "_" + filename) if (self.fileExists(username, filename) == 1): print("sending neg ack") return fileService_pb2.ack( success=False, message= "File already exists for this user. Please rename or delete file first." ) break # Step 3: # Make chunks of size 'UPLOAD_SHARD_SIZE' and start sending the data to the least utilized node trough gRPC streaming. currDataSize += sys.getsizeof(request.data) currDataBytes += request.data for request in request_iterator: if ((currDataSize + sys.getsizeof(request.data)) > UPLOAD_SHARD_SIZE): response = self.sendDataToDestination( currDataBytes, node, node_replica, username, filename, seqNo, active_ip_channel_dict[node]) metaData.append([node, seqNo, node_replica]) currDataBytes = request.data currDataSize = sys.getsizeof(request.data) seqNo += 1 node, node_replica = self.getLeastLoadedNode() else: currDataSize += sys.getsizeof(request.data) currDataBytes += request.data if (currDataSize > 0): response = self.sendDataToDestination( currDataBytes, node, node_replica, username, filename, seqNo, active_ip_channel_dict[node]) metaData.append([node, seqNo, node_replica]) # Step 4: # Save the metadata on the primary node after the completion of sharding. if (response.success): db.saveMetaData(username, filename, metaData) db.saveUserFile(username, filename) # Step 5: # Make a gRPC call to replicate the matadata on all the other nodes. self.saveMetadataOnAllNodes(username, filename, metaData) return fileService_pb2.ack(success=True, message="Saved") # If the node is not the leader. else: print("Saving the data on my local db") sequenceNumberOfChunk = 0 dataToBeSaved = bytes("", 'utf-8') # Gather all the data from gRPC stream for request in request_iterator: username, filename, sequenceNumberOfChunk = request.username, request.filename, request.seqNo dataToBeSaved += request.data key = username + "_" + filename + "_" + str(sequenceNumberOfChunk) # Save the data in local DB. db.setData(key, dataToBeSaved) # After saving the chunk in the local DB, make a gRPC call to save the replica of the chunk on different # node only if the replicaNode is present. if (request.replicaNode != ""): print("Sending replication to ", request.replicaNode) replica_channel = active_ip_channel_dict[request.replicaNode] t1 = Thread(target=self.replicateChunkData, args=( replica_channel, dataToBeSaved, username, filename, sequenceNumberOfChunk, )) t1.start() # stub = fileService_pb2_grpc.FileserviceStub(replica_channel) # response = stub.UploadFile(self.sendDataInStream(dataToBeSaved, username, filename, sequenceNumberOfChunk, "")) return fileService_pb2.ack(success=True, message="Saved")
def post(self): file = request.files['image'] if file.filename == '': print('no image') return { 'msg' : 'no data' } else: filename = 'image.jpg' file.save(filename) data = decode_qrcode(filename) if os.path.exists(filename): os.remove(filename) print('remove img already') if(data == -1): print('decode fail') return { 'msg' : 'no data' }, 200 # insert into database # print(data['invDate']) # print(data['invPeriod']) year = int(data['invPeriod'][0:3]) month = int(data['invPeriod'][3:]) receipt_prizenum = getPrizeNum(year, month) receipt_prizenum_json = json.loads(receipt_prizenum) if(receipt_prizenum_json['msg'] != '無此期別資料'): win, money = show_prize(str(data['invNum'][2:]), receipt_prizenum_json) else: win = -1 money = 0 # if it is already in database # print(data['invNum'][2:]) # print(len(data['details'])) if(checkData('bar_code', data['invNum'][2:]) == -1): addsql = 'bar_code(date, period, prefix_barcode, bar_code, win, money)' addsqlparams = "VALUES ('%s', '%s', '%s', '%s', '%s', '%s');" % (data['invDate'], data['invPeriod'], data['invNum'][0:2], data['invNum'][2:] , win, money) setData(addsql, addsqlparams) id = getDataBar(data['invNum'][2:]) # print(id[0][0]) for it in data['details']: addsql = 'receipt_group(group_name, item, price, number, barID)' addsqlparams = "VALUES ('%s', '%s', '%s', '%s', '%s');" % ('食物', it['description'], it['unitPrice'], it['quantity'], id[0][0]) # addsqlparams = 'VALUES ("食物", "8888888888", "1", 2000)' setData(addsql, addsqlparams) print('insert data into database') else: print('bar_code exist!') # print(data) return data
def startElement(self, name, attrs): if XmlHandler.NodeDC == name: self.user.update( getAttrs(attrs, {'user':'******', 'id':'id', 'turn-n':'turn'}) ) print 'loaded user %s'%(self.user,) if 'id' in self.user and 'turn' in self.user: self.storeArchive() if 'turn' in self.user: self.turn = int(self.user['turn']) db.db.set_turn(self.turn) print 'prepare turn %s'%(self.turn,) elif XmlHandler.Errors == name: log.error('Found errors node') self.errors = True elif XmlHandler.Error == name and self.errors: log.error('Found error node!') errid = int(attrs['id']) if errid == 10000: self.status = self.StatusAuthError log.error('Error id %s'%(attrs['id'],)) elif errid != 10025: self.status = self.StatusError log.error('Error id %s'%(attrs['id'],)) #elif XmlHandler.NotLoggedInError == name: # log.error('Not logged in - turn in progress') # self.status = self.StatusTurnInProgress elif XmlHandler.UserInfo == name: d = getAttrs(attrs, {'homeworldx':'hw_x', 'homeworldy':'hw_y', 'race-id':'race_id', 'login':"******"}) self.user.update( d ) print 'update user %s'%(self.user,) db.db.set_object('hw', {'hw_x':d['hw_x'], 'hw_y':d['hw_y'], 'player_id':self.user['id']}) user_obj = db.db.get_object(db.Db.USER, {'=':{'id':self.user['id']}}) if user_obj and int(user_obj['turn']) > self.turn: #should not normally happen ( unless you loading old xml files) pass db.db.set_object('user', {'id':self.user['id'], 'turn':self.turn, 'login':d['login'], 'race_id':d['race_id'], 'name':self.user['name']}) config.set_user_id(d['login'], self.user['id']) config.saveUsers() elif XmlHandler.UserRace == name: d = getAttrs(attrs, { 'race-id':'id', 't-delta':'temperature_delta', 't-optimal':'temperature_optimal', 'race-nature':'resource_nature', 'bonus-multiply':'population_growth', 'industry-nature': 'resource_main', 'unused-resource': 'resource_secondary', 'bonus-speed': 'modifier_fly', 'bonus-build-war': 'modifier_build_war', 'bonus-build-peace': 'modifier_build_peace', 'bonus-iq': 'modifier_science', #'bonus-surface': 'modifier_surface', 'bonus-stealth': 'modifier_stealth', 'bonus-detectors': 'modifier_detection', 'bonus-mining': 'modifier_mining', 'bonus-price': 'modifier_price', #'bonus-ground-units': 'modifier_build_ground', #'bonus-space-units': 'modifier_build_space', 'race-name':'name' }) db.db.set_object(db.Db.RACE, d) # race-nature (nature) # industry-nature ( first ) # unused-resource ( second ) # bonus-multiply ( population-growth # bonus-speed ( fly ? ) # bonus-build-war # bonus-build-peace # bonus-iq (tech) # bonus-surface (wtf) # bonus-stealth # bonus-detectors # bonus-mining # bonus-price # bonus-ground-units # bonus-space-units # bonus-attack # bonus-dr # bonus-hp # race-name elif XmlHandler.UserPlanets == name: self.read_level = XmlHandler.UserPlanets db.eraseObject(db.Db.PLANET, ['owner_id=%s'%(self.user['id'],),], self.turn) elif XmlHandler.KnownPlanets == name: db.eraseObject(db.Db.OPEN_PLANET, ['user_id=%s'%(self.user['id'],),]) elif XmlHandler.Planet == name: data = getAttrs(attrs, {'x':'x', 'owner-id':'owner_id', 'y':'y', 'name':'name','o':'o','e':'e','m':'m','t':'t','temperature':'t','s':'s','surface':'s', 'age':'age', 'open':'is_open'}) if XmlHandler.UserPlanets == self.read_level: data['owner_id'] = self.user['id'] db.db.set_object(db.Db.PLANET, data) data = getAttrs(attrs, {'x':'x', 'y':'y', 'population':'population', 'corruption':'corruption', 'open':'is_open'}) data['owner_id'] = self.user['id'] db.set_open_planet(get_coord(data), self.user['id']) db.db.set_object(db.Db.USER_PLANET, data) else: if 'is_open' in data and int(data['is_open']) == 1: db.set_open_planet(get_coord(data), self.user['id']) actual_turn = 0 if 'turn' in data: actual_turn = int(data['turn']) del data['turn'] if 'age' in data: actual_turn = self.turn - int(data['age']) del data['age'] db.db.smart_update_object(db.Db.PLANET, actual_turn, data) elif XmlHandler.Fleet == name: fleetDict = {'x':'x','y':'y','id':'id','in-transit':'in_transit','fleet-id':'id','player-id':'owner_id','from-x':'from_x','from-y':'from_y','name':'name', 'tta':'tta', 'turns-till-arrival':'tta', 'hidden':'is_hidden'} data = getAttrs(attrs, fleetDict) db.eraseObject(db.Db.UNIT, ['fleet_id=%s'%(fleetDict['id'],),], self.turn) #save fleet-id to fill unit table self.obj_id = data['id'] tta = 0 if 'tta' in data: tta = int(data['tta']) if tta > 0: data['arrival_turn'] = int(self.user['turn'])+tta del data['tta'] data['owner_id'] = self.user['id'] if tta>0: #data['turn'] = turn db.db.set_object(db.Db.FLYING_FLEET, data) elif 'in_transit' in data: safeRemove(data, ['from_x', 'from_y', 'tta', 'in_transit']) #data['turn'] = turn db.db.set_object(db.Db.FLEET, data) elif XmlHandler.AlienFleet == name: #TODO: alien fleet / flying or not here ( 1st delete all alien fleets visible by user before adding any of them fleetDict = {'x':'x','y':'y','fleet-id':'id','player-id':'owner_id','from-x':'from_x','from-y':'from_y','name':'name', 'tta':'tta', 'turns-till-arrival':'tta', 'hidden':'is_hidden'} data = getAttrs(attrs, fleetDict) #db.eraseObject(db.Db.ALIEN_UNIT, ['fleet_id=%s'%(fleetDict['id'],),], self.turn) tta = 0 if 'tta' in data: tta = int(data['tta']) del data['tta'] if tta > 0: data['arrival_turn'] = int(self.user['turn'])+tta data['user_id'] = self.user['id'] if 'owner_id' in data: print 'got owner of flying alient fleet: %s'%(data,) del data['owner_id'] self.obj_id = None #data['turn']=self.turn db.db.set_object(db.Db.FLYING_ALIEN_FLEET, data) else: safeRemove(data, ['from_x', 'from_y', 'tta']) #save fleet-id to fill alien-unit table self.obj_id = data['id'] db.setData(db.Db.FLEET, data, self.turn) elif XmlHandler.Garrison == name: self.pos = getAttrs(attrs, {'x':'x', 'y':'y'}) self.obj_id = None db.eraseObject(db.Db.GARRISON_QUEUE_UNIT, ['%s=%s'%(k,v) for k,v in self.pos.iteritems()], self.turn) #db.eraseObject(db.Db.GARRISON_UNIT, ['%s=%s'%(k,v) for k,v in self.pos.iteritems()], self.turn) elif XmlHandler.AlienUnit == name: if self.obj_id: data = getAttrs(attrs, {'class-id':'class', 'id':'id', 'weight':'weight', 'carapace':'carapace', 'color':'color'}) data['fleet_id'] = self.obj_id db.setData(db.Db.ALIEN_UNIT, data, self.turn) elif XmlHandler.Unit == name: data = getAttrs(attrs, {'bc':'class', 'id':'id', 'hp':'hp'}) if self.obj_id: data['fleet_id'] = self.obj_id db.setData('unit', data, self.turn) elif self.pos: data.update(self.pos) data['x'] = self.pos['x'] data['y'] = self.pos['y'] db.setData(db.Db.UNIT, data, self.turn) #db.setData('garrison_unit', data, self.turn) elif XmlHandler.BuildingClass == name: data = getAttrs(attrs, {'name':'name', 'description':'description', 'is-war':"is_war", 'support-second':"support_second", 'bomb-dr':"defence_bomb", 'transport-capacity':"transport_capacity", 'is-transportable':"is_transportable", 'bomb-number':"bomb_number", 'fly-range':"fly_range", 'bonus-m':"bonus_m", 'is-ground-unit':"is_ground_unit", 'weight':"weight", 'scan-strength':"scan_strength", 'laser-dr':"defence_laser", 'laser-ar':"aim_laser", 'serial':"is_serial", 'carapace':"carapace", 'bonus-surface':"bonus_s", 'laser-damage':"damage_laser", 'offensive':"is_offensive", 'is-building':"is_building", 'is-space-ship':"is_spaceship", 'build-speed':"build_speed", 'detect-range':"detect_range", 'maxcount':"max_count", 'class':"class", 'cost-main':"cost_main", 'stealth-lvl':"stealth_level", 'bonus-o':"bonus_o", 'requires-pepl':"require_people", 'bomb-damage':"damage_bomb", 'bomb-ar':"aim_bomb", 'cost-money':"cost_money", 'req-tehn-level':"require_tech_level", 'color':"color", 'fly-speed':"fly_speed", 'support-main':"support_main", 'building-id':"id", 'bonus-e':"bonus_e", 'carrier-capacity':"carrier_capacity", 'bonus-production':"bonus_production", 'laser-number':"laser_number", 'cost-pepl':"cost_people", 'cost-second':"cost_second", 'hit-points':"hp"}) data['owner_id'] = self.user['id'] self.parent_attrs = data db.setData('proto',data) #if 'name' in data: # #log.info('specific data: %s'%(data,)) elif XmlHandler.BuildingClassAction == name and self.parent_attrs: data = getAttrs(attrs, {'action':'type', 'maxcount':'max_count', 'cost-pepl':"cost_people", 'cost-main':"cost_main", 'cost-money':"cost_money", 'cost-second':"cost_second", 'planet-can-be':"planet_can_be"}) data['proto_id'] = self.parent_attrs['id'] data['proto_owner_id'] = self.user['id'] db.setData('proto_action',data) elif XmlHandler.Iframe == name: self.iframe = True elif XmlHandler.PerformAction == name and self.iframe: data = getAttrs(attrs, {'id':'id', 'result':'result', 'return-id':'return-id'}) print 'got attrs %s, data %s'%(attrs, data) act_id = int(data['id']) print 'got action id %s'%(act_id,) ret_id = 0 if 'return-id' in data: ret_id = data['return-id'] if 'result' in data and unicode(data['result'])==unicode('ok'): print 'final result ret-id %s'%(ret_id,) db.setData('requested_action', {'id':act_id, 'user_id':self.user['id'], 'return_id':ret_id, 'is_ok':1}) db.perform_pending_action(act_id, ret_id) #self.actions.append( (act_id, ret_id) ) elif XmlHandler.Diplomacy == name: self.dip = True elif XmlHandler.DipRelation == name and self.dip: data = getAttrs(attrs, {'player':'player_id', 'name':'name'}) db.setData(db.Db.PLAYER, data) dip_data = getAttrs(attrs, {'player':'player_id', 'type':'status'}) dip_data['owner_id'] = self.user['id'] db.setData(db.Db.DIP, dip_data) elif XmlHandler.UserFleets == name: db.eraseObject(db.Db.FLEET, ['owner_id=%s'%(self.user['id'],),], self.turn) db.eraseObject(db.Db.FLYING_FLEET, ['owner_id=%s'%(self.user['id'],),], self.turn) self.pos = None elif XmlHandler.AlienFleets == name: db.eraseObject(db.Db.FLYING_ALIEN_FLEET, ['user_id=%s'%(self.user['id'],)], self.turn) self.pos = None
def useItem(discordID, item): item = getSingular(item) if (getItemExistsPosition(discordID, item) != -1): # BALLOON if (item == "balloon"): luck = random.randint(0, 100) if 0 <= luck <= 4: removeFromInventory(discordID, item, 1) addToInventory(discordID, "popped balloon", 1) return [ True, "You tried to play with the balloon, but a bully came over and popped it." ] elif 5 <= luck <= 14: removeFromInventory(discordID, item, 1) addToInventory(discordID, "popped balloon", 1) return [ True, "You squeezed your balloon too hard and it popped!" ] elif 15 <= luck <= 25: removeFromInventory(discordID, item, 1) addToInventory(discordID, "popped balloon", 1) return [ True, "You tried to draw a smiley face on a balloon but it popped." ] elif 26 <= luck <= 32: removeFromInventory(discordID, item, 1) addToInventory(discordID, "popped balloon", 1) return [ True, "As you were reaching your hand to your balloon, it went pop before you even touched it! Nooo!" ] elif 33 <= luck <= 45: removeFromInventory(discordID, item, 1) addToInventory(discordID, "popped balloon", 1) return [ True, "You were playing with your balloon, but suddenly it hit the grass and popped." ] elif 46 <= luck <= 64: return [ True, "You were very rough with the balloon while playing with it, but at least it didn't pop!" ] elif 65 <= luck <= 75: addToInventory(discordID, "balloon", 1) return [ True, "While playing with your balloon, you found another one! You added the extra balloon to your inventory!" ] elif 76 <= luck <= 85: shows = [ "first season of Game of Thrones", "second season of Game of Thrones", "episode of Gravity Falls", "episode of The Office", "episode of Diners, Drive-Ins and Dives", "VOD of TheYordleScout", "anthology of Spider-Man movies" ] randShow = shows[random.randint(0, len(shows))] return [ True, f"You tried to sit on the balloon to pop it but forgot that you were sitting on it and watched the entire {randShow}." ] elif 86 <= luck <= 100: return [True, "Yay! You had fun playing with your balloon!"] # XP bottle if (item == "XP bottle"): randomXP = random.randint(1, 6) playerXP = db.getData("experience", "users", f"discordid='{str(discordID)}'")[0] removeFromInventory(discordID, item, 1) db.setData("users", f"experience={playerXP+randomXP}", f"discordid='{str(discordID)}'") return [ True, f"You drank the XP potion and gained {randomXP} XP from it." ] if (item == "mystery box"): randItemID = random.randint(0, len(items)) if (addToInventory(discordID, items[randItemID]['name'], 1)): removeFromInventory(discordID, "mystery box", 1) return [ True, f"You open a mystery box and find {ia.indefinite_article(items[randItemID]['name'])} **{items[randItemID]['name']}** inside!" ] if (item == "cup of tea"): #add HP here removeFromInventory(discordID, item, 1) return [ True, f"You drink a cup of tea. It tastes great and restores some HP." ] return [True, f"Nothing interesting happened from using your {item}."] return [False, "You don't have such an item to use it."]