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 getInventory(discordID): discordID = '\'' + str(discordID) + '\'' inv = db.getData("inventory", "users", "WHERE discordid=" + discordID)[0] slots = inv.split('||') for i in range(0, len(slots)): slots[i] = slots[i].split('::') return slots
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 getCurrentJob(discordID): discordID = '\'' + str(discordID) + '\'' jobid = db.getData("jobid", "users", "WHERE discordid=" + discordID)[0] if jobid == "No Results": return "You have no account set up. Type !xp to begin." else: return f'Your current job is {jobs[jobid]["name"]}.'
def getDollars(discordID): discordID = '\'' + str(discordID) + '\'' result = str(db.getData("dollars", "users", "WHERE discordid=" + discordID)[0]) if result == "No Results": return "You have no account set up. Type !xp to begin." else: return f'You have {result} dollars in your pocket.'
def get(self): year = request.args.get('year') month = request.args.get('month') YM = year+month monthCode = getData("bar_code", YM) return monthCode
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 site_changed(): data = getData('main_feed') remote_data = urllib2.urlopen('https://www.annauniv.edu/more.php').read() remote_hash = hashlib.md5(remote_data).hexdigest() if data["md5"] != remote_hash: print("Change in site!") main_feed() return True else: return False
def recent_feed(): feed = AtomFeed('Main Feed', feed_url=request.url, url=request.url_root) if site_changed(): main_feed() data = getData('main_feed') for d in data['feed']: feed.add(d['text'], url=d['link'], updated=dateutil.parser.parse(data['date'])) return feed.get_response()
def getAllUsers(): ret_users = [] users = db.getData() for user in users: cur_user = { "id": user[0], "name": user[1], "age": user[2], "image": user[3] } ret_users.append(cur_user) return jsonify(ret_users)
def decryptWhisper(self, text): """ decrypt a whisper post using the correct privatekey from the database """ text = text.split(':', 1)[1].split('|', 1) pubK = text[0] whisper = text[1].decode('base64', 'strict') privK = db.getData(self, pubK, None) if privK is None: return 'Couldn\'t find the private key to decrypt this whisper' privK = RSA.importKey(privK, self.password) cipher = PKCS1_OAEP.new(privK) return cipher.decrypt(whisper)
def decryptWhisper(self, text): """ decrypt a whisper post using the correct privatekey from the database """ text = text.split(':', 1)[1].split('|',1) pubK = text[0] whisper = text[1].decode('base64','strict') privK = db.getData(self,pubK,None) if privK is None: return 'Couldn\'t find the private key to decrypt this whisper' privK = RSA.importKey(privK, self.password) cipher = PKCS1_OAEP.new(privK) return cipher.decrypt(whisper)
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 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 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 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 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 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 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 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 printAllAssignedToMe(username, passwd, rectype, email): # Create client object c = pysnow.Client(instance=config.servicenow['instance'], user=username, password=passwd, use_ssl=False) # Create PrettyTable object uid = getUserID(c, email) x = PrettyTable() if rectype == "incident": # Create query for ServiceNow qb = pysnow.QueryBuilder().field('active').equals('true').AND().field( 'assigned_to').equals(uid) incident = c.resource(api_path='/table/incident') x.field_names = [ 'Number', 'Caller', 'Description', 'Category', 'Assignment Group', 'Opened At', 'Contacted' ] response = incident.get(query=qb, limit=50, stream=True, fields=[ 'sys_id', 'opened_at', 'assignment_group', 'number', 'state', 'assigned_to', 'short_description', 'caller_id', 'contact_type', 'priority', 'subcategory', 'u_kick_back_counter' ]) for record in response.all(): # Check if record exists in database query = db.getData(record['number']) if query == "": db.saveData(record['number'], "No") x.add_row([ record['number'], getUser(c, record), record['short_description'], record['subcategory'], getGroup(c, record), record['opened_at'], "No" ]) else: x.add_row([ record['number'], getUser(c, record), record['short_description'], record['subcategory'], getGroup(c, record), record['opened_at'], query.contacted ]) elif rectype == "task": qb = pysnow.QueryBuilder().field('active').equals('true').AND().field( 'assigned_to').equals(uid) task = c.resource(api_path='/table/task') x.field_names = [ 'Number', 'Description', 'Assignment Group', 'Opened At', 'Contacted' ] response = task.get(query=qb, limit=50, stream=True, fields=[ 'sys_id', 'opened_at', 'assignment_group', 'number', 'state', 'assigned_to', 'short_description', 'contact_type', 'priority' ]) for record in response.all(): if record['number'].startswith('TASK'): query = db.getData(record['number']) if query == "": db.saveData(record['number'], "No") x.add_row([ record['number'], record['short_description'], getGroup(c, record), record['opened_at'], "No" ]) else: x.add_row([ record['number'], record['short_description'], getGroup(c, record), record['opened_at'], query.contacted ]) x.sortby = "Opened At" #x.reversesort = True return x
from telebot import TeleBot, types from decouple import config from scrapper import scrape from db import subscribe, unsubscribe, users, relevantsub, getData, setData from apscheduler.schedulers.background import BackgroundScheduler from nlp import relevant import requests import time import os #the token is stored in a file named .env in My system. Add your own token or .env file token = config('TOKEN') bot = TeleBot(token) notifs = getData() def get_contents(): """ Checks for changes in ktu site and returns the new notifs """ global notifs contents = [] scraped = scrape() if scraped != []: datas = notifs for scrap in scraped: k = 0 for data in datas: # Can't do a "not in" comparison with dictionary element coz download links inside it are # unique to each request if data['title'] == scrap['title'] and data['date'] == scrap[
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."]
def api_message(): #if request.headers['Content-Type'] == 'application/json': data = db.getData("hello world") data_return = {} data_return["data"] = data[0][1] return json.dumps(data_return)
def getUsers(): users = getData('get_users') return users
def hello_world(): songs = db.getData() return render_template('index.html', songs=songs)
def get(self): year = request.args.get('year') month = request.args.get('month') YM = year+month item = getData("bar_code", YM) tranditional_item = getData("tranditional_code", YM) Mtranditional_item = getData("Mtranditional_code", YM) result = [] result_qr = [] result_tr = [] result_Mtr = [] # print(item) if(len(item) > 0): for it in item: describe = getDatabarID(str(it[0])) D = {} describe_list = [] describe_dict = {} D["Date"] = str(it[1][0:4]) + "/" + str(it[1][4:6]) + "/" + str(it[1][6:8]) D["Number"] = str(it[3]) + str(it[4]) D["Win"] = str(it[5]) for des in describe: describe_dict = {} describe_dict["name"] = str(des[2]) describe_dict["price"] = str(des[3]) describe_list.append(describe_dict) D["detail"] = describe_list result_qr.append(D) # if(count == len(item)-1): # print(getDatabarID(str(it[0]))) # result.append(getDatabarID(str(it[0]))) if(len(tranditional_item) > 0): for tran in tranditional_item: T = {} T['Number'] = tran[2] T['Win'] = tran[3] result_tr.append(T) if(len(Mtranditional_item) > 0): for Mtran in Mtranditional_item: MT = {} MT['Number'] = Mtran[2] MT['Win'] = Mtran[3] result_Mtr.append(MT) result.append(result_qr) result.append(result_tr) result.append(result_Mtr) # print(result) detail_json = json.dumps(result) # print(detail_json) result = json.loads(detail_json) # print(result) return result
def workedToday(discordID): discordID = '\'' + str(discordID) + '\'' lastWorked = datetime.datetime.strftime(db.getData('lastWorked', 'users', 'WHERE discordid=' + discordID)[0], '%Y-%m-%d') now = datetime.datetime.now().strftime('%Y-%m-%d') return True if (lastWorked == now) else False