def fetch_item(item_id): ''' Args: item_id: The id of the item to fetch Returns: An Item object, from Riot Games API. ''' creds = credentials.getCredentials() url = "https://global.api.pvp.net/api/lol/static-data/na/v1.2/item/" + str( item_id) + "?api_key=" + str(creds.api_key) print("Requesting url: " + str(url)) response = urllib.urlopen(url) data = json.loads(response.read()) if data is not None: if 'id' in data: item_id = data['id'] name = "" desc = "" item_group = "" if 'name' in data: name = data['name'] if 'description' in data: desc = data['description'] if 'group' in data: item_group = data['group'] return Item(item_id, name, desc, item_group)
def fetch_item(item_id): ''' Args: item_id: The id of the item to fetch Returns: An Item object, from Riot Games API. ''' creds = credentials.getCredentials() url = "https://global.api.pvp.net/api/lol/static-data/na/v1.2/item/" + str(item_id) + "?api_key=" + str(creds.api_key) print("Requesting url: " + str(url)) response = urllib.urlopen(url); data = json.loads(response.read()) if data is not None: if 'id' in data: item_id = data['id'] name = "" desc = "" item_group = "" if 'name' in data: name = data['name'] if 'description' in data: desc = data['description'] if 'group' in data: item_group = data['group'] return Item(item_id, name, desc, item_group)
def send_email(recipient, file_name): creds = credentials.getCredentials() from_email = creds["email"] to_email = recipient try: msg = MIMEMultipart() msg['Subject'] = 'ICONS Character sheet' msg['To'] = recipient msg['From'] = creds['email'] body = MIMEText( 'Hello\n\nThank you for taking an interest in my ICONS character. I was never really good at imagingin my characters in great detail so I just made him Billy Maze if he carried the products he was trying to sell in a trench coat with infinite storage space.\n\nDrew' ) msg.attach(body) attach_file(msg, file_name, 'character.pdf') smtpObj = smtplib.SMTP("smtp.gmail.com", 587) smtpObj.verify(recipient) smtpObj.ehlo() smtpObj.starttls() smtpObj.login(creds["email"], creds["password"]) smtpObj.sendmail(from_email, to_email, msg.as_string()) smtpObj.close() print("Successfully sent email") return None except Exception as exception: print(exception) print("Error: unable to send email") return "Unable to send email at this time please try again later."
def fetch_champion(champion_id): ''' Args: champion_id: The id of the champion to fetch Returns: A champion object, from Riot Games API. ''' creds = credentials.getCredentials() url = "https://global.api.pvp.net/api/lol/static-data/na/v1.2/champion/" + str(champion_id) + "?api_key=" + str(creds.api_key) print("Requesting url: " + str(url)) response = urllib.urlopen(url); data = json.loads(response.read()) if data is not None: if 'id' in data: champion_id = data['id'] name = "" title = "" if 'name' in data: name = data['name'] if 'title' in data: title = data['title'] return Champion(champion_id, name, title)
def fetch_all_champions(): ''' Returns: A list of all champion objects, from Riot Games API. ''' creds = credentials.getCredentials() url = "https://global.api.pvp.net/api/lol/static-data/na/v1.2/champion?api_key=" + str(creds.api_key) print("Requesting url: " + str(url)) response = urllib.urlopen(url); data = json.loads(response.read())['data'] champs = [] for key in data: info = data[key] if info is not None: if 'id' in info: champion_id = info['id'] name = "" title = "" if 'name' in info: name = info['name'] if 'title' in info: title = info['title'] champs.append(Champion(champion_id, name, title)) return champs
def getFavorites(user): api_key = credentials.getCredentials("~/.flickr")[0].split()[0] url = ( "http://api.flickr.com/services/rest/?method=flickr.favorites.getPublicList&api_key=" + api_key + "&nojsoncallback=1&format=json&user_id=" ) url += getUserID(user) req = urllib2.urlopen(url) return json.loads(req.read())
def getUserID(username): api_key = credentials.getCredentials("~/.flickr")[0].split()[0] url = ( "http://api.flickr.com/services/rest/?method=flickr.people.findByUsername&api_key=" + api_key + "&nojsoncallback=1&format=json&username="******"user"]["id"]
def fetch_all_items(): ''' Returns: A list of all items objects, from Riot Games API. ''' creds = credentials.getCredentials() url = "https://global.api.pvp.net/api/lol/static-data/na/v1.2/item?api_key=" + str( creds.api_key) print("Requesting url: " + str(url)) response = urllib.urlopen(url) data = json.loads(response.read())['data'] items = [] for key in data: info = data[key] if info is not None: if 'id' in info: item_id = info['id'] name = "" desc = "" item_group = "" if 'name' in info: name = info['name'] if 'description' in info: desc = info['description'] if 'group' in info: item_group = info['group'] items.append(Item(item_id, name, desc, item_group)) return items
def fetch_all_items(): ''' Returns: A list of all items objects, from Riot Games API. ''' creds = credentials.getCredentials() url = "https://global.api.pvp.net/api/lol/static-data/na/v1.2/item?api_key=" + str(creds.api_key) print("Requesting url: " + str(url)) response = urllib.urlopen(url); data = json.loads(response.read())['data'] items = [] for key in data: info = data[key] if info is not None: if 'id' in info: item_id = info['id'] name = "" desc = "" item_group = "" if 'name' in info: name = info['name'] if 'description' in info: desc = info['description'] if 'group' in info: item_group = info['group'] items.append(Item(item_id, name, desc, item_group)) return items
import requests import json from credentials import getCredentials # set to your own subscription key valuedir subscription_key = getCredentials() #hidden due to sensitive info assert subscription_key # replace <My Endpoint String> with the string from your endpoint URL face_api_url = "https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect" #face_api_url = 'https://codeforgood.cognitiveservices.azure.com/face/v1.0' headers = {'Ocp-Apim-Subscription-Key': subscription_key} params = { 'returnFaceId': 'true', 'returnFaceLandmarks': 'false', 'returnFaceAttributes': 'age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise', } #print(emotions) neg_emotions = ["anger", "contempt", "fear", "sadness", "surprise", "disgust"] def getSentiment(img_url): image_url = img_url response = requests.post(face_api_url,
import ent import save import credentials import check # Get the credentials registered in database auth = credentials.getCredentials() page = None for user in auth: page = ent.getNotesPage(user) # Login to ENT and save if (page["error"] == None): save.createcsv(page["page"], user) else: print(page["error"] + " " + str(user[1])) check.checker(auth)
cases = container[0].text.strip() deaths = container[1].text.strip() recovered = container[2].text.strip() brasil = ("🇧🇷 Total de casos no Brasil: \n"+ \ "Casos confirmados: " + cases + "\n" + \ "Óbitos: " + deaths+ "\n" + \ "Recuperações: " + recovered + "\n\n") page = requests.get("https://www.worldometers.info/coronavirus/") soup = BeautifulSoup(page.text, 'html.parser') container = soup.findAll("div", {"class": "maincounter-number"}) cases = container[0].text.strip() deaths = container[1].text.strip() recovered = container[2].text.strip() mundo = ("🌍 Total de casos no Mundo: \n"+ \ "Casos confirmados: " + cases + "\n" + \ "Óbitos: " + deaths+ "\n" + \ "Recuperações: " + recovered + "\n\n") print(brasil) print(mundo) hashtag = "#coronavirus #corona #covid19 #coronavirusbrasil" api = getCredentials('twitter') update = api.update_with_media("world.jpg", brasil + "\n" + mundo + "\n" + hashtag) print(update)
values = {"email": username, "password": password} data = urllib.urlencode(values) req = urllib2.Request(url, data) response = urllib2.urlopen(req) return response.read() def getLikes(username, password): auth(username, password) url = "http://www.tumblr.com/api/likes" likes = [] for i in range(0, 4): values = { "email": username, "password": password, "num": 50, "start": i * 50 } data = urllib.urlencode(values) req = urllib2.Request(url, data) response = urllib2.urlopen(req) for l in parseString(response.read()).getElementsByTagName("post"): likes.append(l.getAttribute("url")) return likes # Testing Code # details = credentials.getCredentials( "~/.tumblr") # ~/.tumblr is username/password print getLikes(details[0], details[1])
from gpio_client import gpio_client import json import sys from credentials import getCredentials from rpc_call import rpc import helper GPIO_CONTAINER = "gpio" # GPIO Container Name USER = "******" PW = "admin" ipv6 = helper.get_base_ipv6_address() # Login to MICA-Base-SSO-Service and fetch auth token r = rpc("https://[" + ipv6 + "]/base_service/") cred = getCredentials(USER, PW, 1.5) auth_token = r.call("get_auth_token", cred)["result"][1] gc = gpio_client(ipv6, GPIO_CONTAINER, auth_token) # make JSON RPC to GPIO Websocket server (see gpio_client.py for more information) gc.get_pin_states() gc.set_configuration(0, 0) gc.get_base_net_config()
def fetch_match(match_id, region): ''' Args: match_id: The id of the match to fetch region: The region of the match Returns: A Match object, from Riot Games API. ''' creds = credentials.getCredentials() url = 'https://na.api.pvp.net/api/lol/' + region + '/v2.2/match/' + str(match_id) + '?api_key=' + str(creds.api_key) print("Requesting url: " + str(url)) response = urllib.urlopen(url); data = json.loads(response.read()) version = "" duration = "" for key in data: if key == 'matchVersion': version = data[key] elif key == 'matchDuration': duration = data[key] elif key == 'teams': teams = data[key] banned_champs = [] for t in teams: bans = t['bans'] for b in bans: champion_id = b['championId'] banned_champs.append(champion_id) elif key == 'participants': participants = data[key] list_participants = [] # for each participant for p in participants: #print(p) for key in p: if key == 'participantId': participant_id = p[key] elif key == 'championId': champion_id = p[key] elif key == 'teamId': team_id = p[key] elif key == 'timeline': lane = p[key]['lane'] elif key == 'stats': stats = p[key] # item info items = [stats['item0'], stats['item1'], stats['item2'], stats['item3'], stats['item4'], stats['item5'], stats['item6']] # stats kills = stats['kills'] deaths = stats['deaths'] assists = stats['assists'] magic_damage = stats['magicDamageDealt'] magic_damage_champs = stats['magicDamageDealtToChampions'] magic_damage_taken = stats['magicDamageTaken'] champ_level = stats['champLevel'] gold_earned = stats['goldEarned'] win = stats['winner'] # construct items of participant inventory = [] slot = 0 if items is not None: for item in items: inventory.append(ParticipantItem(match_id, participant_id, item, slot, win)) slot += 1 # construct stats of participant stat = ParticipantStat(match_id, participant_id) stat.__setKDA__(kills, deaths, assists) stat.__setDamage__(magic_damage, magic_damage_champs, magic_damage_taken) stat.__setOther__(champ_level, gold_earned, win) # construct participant object participant = Participant(match_id, participant_id, champion_id, team_id, win, lane, inventory, stat) list_participants.append(participant) return Match(match_id, version, duration, region, list_participants, banned_champs)
def auth(username, password): url = "http://www.tumblr.com/api/authenticate" values = {"email": username, "password": password} data = urllib.urlencode(values) req = urllib2.Request(url, data) response = urllib2.urlopen(req) return response.read() def getLikes(username, password): auth(username, password) url = "http://www.tumblr.com/api/likes" likes = [] for i in range(0,4): values = {"email": username, "password": password, "num": 50, "start": i*50} data = urllib.urlencode(values) req = urllib2.Request(url, data) response = urllib2.urlopen(req) for l in parseString(response.read()).getElementsByTagName("post"): likes.append(l.getAttribute("url")) return likes # Testing Code # details = credentials.getCredentials("~/.tumblr") # ~/.tumblr is username/password print getLikes(details[0], details[1])
def checker(auth): print("check des notes...") #read last csv file create temps = time.time() while True: try: for user in auth: csvfile = open('data/' + user[1] + '.csv', 'r') csvfile = csvfile.read() csvfile = csvfile.replace("\n\n", "\n") csvfile = csvfile.replace('"', "") csvfile = csvfile[52:] #read current data on website auth = credentials.getCredentials() data = ent.getNotesPage(user) data = data['page'] num1 = data.find('Moyenne') num2 = data.find('Gestion des absences') data = data[num1:num2 - 15] #UE|CodeModule|Module|Evaluation|Note|(Min/Max)|Coef data = data.replace("| ", "|") data = data.replace("| ", "|") data = data.replace("![-](imgs/minus_img.png)", "") data = data.replace("Moyenne générale:", "|||Moyenne générale:") data = data.replace("|", ",") data = data + "\n" #comparing print(strftime("%H:%M:%S") + " comparing for " + str(user[1])) ca = ct.Counter(data.split("\n")) cb = ct.Counter(csvfile.split("\n")) diff = ca - cb changes = "\n".join(diff.keys()) if (changes != ""): print("mail send : " + str(changes)) import smtplib from email.mime.text import MIMEText credential = yaml.load(open('credentials.yml'), Loader=yaml.FullLoader) message = MIMEText(changes.replace(",", " ")) message['Subject'] = 'Nouvelle note' message['From'] = credential['mail']['from'] message['To'] = user[2] server = smtplib.SMTP(credential['mail']['server']) server.starttls() server.login(credential['mail']['from'], credential['mail']['password']) server.send_message(message) server.quit() #update new marks page = None page = ent.getNotesPage(user) save.createcsv(page["page"], user) from ftplib import FTP import os import fileinput credential = yaml.load(open('credentials.yml'), Loader=yaml.FullLoader) ftp = FTP() ftp.set_debuglevel(2) ftp.connect(credential['ftp']['server'], 21) ftp.login(credential['ftp']['user'], credential['ftp']['password']) ftp.cwd('www/data') fp = open('data/' + str(user[1]) + '.csv', 'rb') ftp.storbinary( 'STOR %s' % os.path.basename('data/' + str(user[1]) + '.csv'), fp, 1024) fp.close() except Exception as e: print(e) # Mise a jour des nouveaux utilisateurs de la base de données if time.time() - temps > 3600: temps = time.time() auth = credentials.getCredentials() for user in auth: page = ent.getNotesPage(user) save.createcsv(page["page"], user) print("update bdd : ") print(auth) time.sleep(300)
def getUserID(username): api_key = credentials.getCredentials("~/.flickr")[0].split()[0] url = "http://api.flickr.com/services/rest/?method=flickr.people.findByUsername&api_key=" + api_key + "&nojsoncallback=1&format=json&username="******"user"]["id"]
def construct(ll, query, fltr): fltr = fltr.lower() # get local credentials cr = credentials.getCredentials() # get list of rids that match this query around the location ids = parse_url.parse(cr.client_id, cr.client_secret, ll, query) if len(ids) == 0: return None in_clause = "(" for i in ids: in_clause += "'"; in_clause += str(i) in_clause += "'"; in_clause += ", " in_clause = in_clause[:-2] in_clause += ")" db = credentials.getDatabase() cur = db.cursor() query = "" if fltr == 'top': #top rid votes query = "SELECT R.rid, SUM(T.vote) FROM restaurants R LEFT JOIN transactions T ON R.rid=T.rid WHERE R.rid IN " + in_clause + " GROUP BY R.rid ORDER BY SUM(T.vote) DESC" elif fltr == 'hot': # Most votes in the last 7 days query = "SELECT R.rid, HOT.total_votes FROM restaurants R LEFT JOIN (SELECT T.rid as hid, SUM(T.vote) AS total_votes FROM transactions T WHERE T.creation > DATE_SUB(NOW(), INTERVAL 14 DAY) GROUP BY T.rid ORDER BY SUM(T.vote)) as HOT ON R.rid=HOT.hid WHERE R.rid IN " + in_clause + " GROUP BY R.rid ORDER BY HOT.total_votes DESC;" # query = '''SELECT R.rid, HOT.total_votes # FROM restaurants R # LEFT JOIN ( # SELECT T.rid as hid, SUM(T.vote) AS total_votes # FROM transactions T # WHERE T.creation > DATE_SUB(NOW(), INTERVAL 14 DAY) # GROUP BY T.rid # ORDER BY SUM(T.vote) # ) as HOT # ON R.rid=HOT.hid # WHERE R.rid IN ? # GROUP BY R.rid # ORDER BY HOT.total_votes DESC;''' elif fltr == 'not': # Opposite of hot query = "SELECT R.rid, HOT.total_votes FROM restaurants R LEFT JOIN (SELECT T.rid as hid, SUM(T.vote) AS total_votes FROM transactions T WHERE T.creation > DATE_SUB(NOW(), INTERVAL 14 DAY) GROUP BY T.rid ORDER BY SUM(T.vote)) as HOT ON R.rid=HOT.hid WHERE R.rid IN " + in_clause + " GROUP BY R.rid ORDER BY HOT.total_votes ASC;" elif fltr == 'new': # The most recently voted on rids query = "SELECT R.rid, SUM(T.vote) FROM restaurants R LEFT JOIN transactions T ON R.rid=T.rid WHERE T.rid IN " + in_clause + " GROUP BY R.rid ORDER BY T.creation DESC;" elif fltr == 'old': # The most neglected rids query = "SELECT R.rid, SUM(T.vote) FROM restaurants R LEFT JOIN transactions T ON R.rid=T.rid WHERE T.rid IN " + in_clause + " GROUP BY R.rid ORDER BY T.creation ASC;" elif fltr == 'bot': # opposite of top query = "SELECT R.rid, SUM(T.vote) FROM restaurants R LEFT JOIN transactions T ON R.rid=T.rid WHERE R.rid IN " + in_clause + " GROUP BY R.rid ORDER BY SUM(T.vote) ASC" else: # return all restaurants we get from this call query = "SELECT R.rid, SUM(T.vote) FROM restaurants R LEFT JOIN transactions T ON R.rid=T.rid WHERE R.rid IN " + in_clause + " GROUP BY R.rid ORDER BY SUM(T.vote) DESC" cur.execute(query) restaurants = [] for tup in cur: rid = tup[0] count = tup[1] if count == None: count = 0 rest_dict = restaurant.load(rid).__json__() rest_dict["votes"] = str(count) # construct new restaurant restaurants.append(rest_dict) db.commit() db.close() print("Result size: ", len(restaurants)) return restaurants
def getFavorites(user): api_key = credentials.getCredentials("~/.flickr")[0].split()[0] url = "http://api.flickr.com/services/rest/?method=flickr.favorites.getPublicList&api_key=" + api_key + "&nojsoncallback=1&format=json&user_id=" url += getUserID(user) req = urllib2.urlopen(url) return json.loads(req.read())