def show_volume(cluster: str, headers_inc: str):
    """ List Volumes"""
    print("The List of SVMs")
    show_svm(cluster, headers_inc)
    print()
    svm_name = input(
        "Enter the SVM from which the Volumes need to be listed:-")
    print()
    print("Getting Volume Details")
    print("======================")
    url = "https://{}/api/storage/volumes/?svm.name={}".format(
        cluster, svm_name)
    try:
        response = requests.get(url, headers=headers_inc, verify=False)
    except requests.exceptions.HTTPError as err:
        print(str(err))
        sys.exit(1)
    except requests.exceptions.RequestException as err:
        print(str(err))
        sys.exit(1)
    url_text = requests.json()
    if 'error' in url_text:
        print(url_text)
        sys.exit(1)

    tmp = dict(requests.json())
    svms = tmp['records']
    print()
    print("List of Volumes :- ")
    print("===================")
    for i in svms:
        print(i['name'])
    return response.json()
Example #2
0
    def _checkOrder(API_Token, APISecret, UUID):
        """
        Returns true/false based on whether an order needs to be retried
        """

        ts = arrow.now().timestamp * 1000 # Transforms ts from seconds into milliseconds
        uri = "https://api.bittrex.com/v3/orders/%s" % UUID
        contentHash, signature = generateAuth(API_Token, APISecret, ts, "", uri, "GET")

        headers = {
            "Api-Key": API_Token,
            "Api-Timestamp": ts;
            "Api-Content-Hash": contentHash;
            "Api-Signature": signature
        }

        r = requests.get(uri, headers=headers)
        r.raise_for_status()

        res = r.json()

        if res["quantity"] != res['fillQuantity']:
            # Order didn't completely fill; need to signal that the rest should be sold somehow
            #TODO
            return True
        elif res['fillQuantity'] == 0.0:
            # Order was not filled at all; needs to be reattempted immediately
            return False
        else:
            # Order filled completely
            #TODO include timestamp and market in this logging message
            print("Order filled successfully!")
            return True
Example #3
0
def handle_result(requests,
                  success_callback=None,
                  fail_callback=None,
                  print_result=True):
    """处理结果"""
    result = requests.json()
    if print_result:
        print(result)
    if result:
        code = result['code']
        if code == 200:
            # 成功
            data = result['data']
            if success_callback:
                success_callback(data)
            return data
        else:
            # 失败
            msg = result['msg']
            print(msg)
            if fail_callback:
                fail_callback(code, msg)
    else:
        # 结果为空
        if fail_callback:
            fail_callback(0, None)
    return None
Example #4
0
def paste(update, context):
    args = context.args
    BURL = "https://del.dog"
    message = update.effective_message
    if message.reply_to_message:
        data = message.reply_to_message.text
    elif len(args) >= 1:
        data = message.text.split(None, 1)[1]
    else:
        message.reply_text("What am I supposed to do with this?!")
        return

    r = requests.post(f"{BURL}/documents", data=data.encode("utf-8"))

    if r.status_code == 404:
        update.effective_message.reply_text("Failed to reach dogbin")
        r.raise_for_status()

    res = r.json()

    if r.status_code != 200:
        update.effective_message.reply_text(res["message"])
        r.raise_for_status()

    key = res["key"]
    if res["isUrl"]:
        reply = "Shortened URL: {}/{}\nYou can view stats, etc. [here]({}/v/{})".format(
            BURL, key, BURL, key)
    else:
        reply = f"{BURL}/{key}"
    update.effective_message.reply_text(reply,
                                        parse_mode=ParseMode.MARKDOWN,
                                        disable_web_page_preview=True)
Example #5
0
def get_activity_data(workerId, interval=10):
    data = red.get('activity_data_' + str(workerId))
    if data:
        return json.loads(data)

    times = [""]
    itemNum = {'log': [], 'title': u"合計", 'result': 0, 'unit': u"個"}
    shelfIds = [""]

    payload = {'rdf:type': "frameworx:WarehouseActivity",
               'frameworx:workerId': workerId}
    requests = get_requests(payload)

    for d in sorted(requests.json(), key=lambda x: x['dc:date']):
        if d['dc:date']:
            time = get_time(d['dc:date'], interval)
            if d["frameworx:itemNum"]:
                itemNum['result'] += int(d["frameworx:itemNum"])

            if d["frameworx:shelfId"]:
                if d["frameworx:shelfId"] != shelfIds[-1]:
                    shelfIds.append(d["frameworx:shelfId"])

            if time != times[-1]:
                times.append(time)
                itemNum['log'].append(itemNum['result'])

    activity_data = {
            u'時間': times[1:],
            u'商品数': itemNum,
            u'シェルフ': shelfIds[1:]}

    red.set('activity_data_' + str(workerId), json.dumps(activity_data), ex=600)

    return activity_data
Example #6
0
    def _sell(API_Token, APISecret, Market, Balance):
        """
        This will post a "MARKET" order, which should be immediately filled at whatever market rate is.
        """

        data = {
          "marketSymbol": Market["MarketName"],
          "direction": "SELL",
          "type": "MARKET",
          "quantity": Balance,
          "timeInForce": "FILL_OR_KILL",
        }
        ts = arrow.now().timestamp * 1000 # Transforms ts from seconds into milliseconds
        uri = "https://api.bittrex.com/v3/orders"
        contentHash, signature = generateAuth(API_Token, APISecret, ts, str(data), uri, "POST")

        headers = {
            "Api-Key": API_Token,
            "Api-Timestamp": ts;
            "Api-Content-Hash": contentHash;
            "Api-Signature": signature
        }

        r = requests.post(uri, data=data, headers=headers)
        r.raise_for_status()

        res = r.json()
        return res["id"]
Example #7
0
    def validate(self, data):
        verifier = data.get('oauth_verifier', None)
        request_token = data.get('request_token', None)
        consumer_key = getattr(settings, "TWITTER_CONSUMER_KEY", None)
        consumer_secret = getattr(settings, "TWITTER_CONSUMER_SECRET", None)
        callback_url = getattr(settings, "TWITTER_CALLBACK_URL", None)
        if not consumer_key:
            raise ValidationError(detail={'client_id': 'Cannot find TWITTER_CONSUMER_KEY in django settings'})
        if not consumer_secret:
            raise ValidationError(detail={'client_secret': 'Cannot find TWITTER_CONSUMER_SECRET in django settings'})
        if not callback_url:
            raise ValidationError(detail={'callback_url': 'Cannot find TWITTER_CALLBACK_URL in django settings'})
        if not verifier:
            raise ValidationError(detail={'oauth_verifier': 'This field is required.'})
        if not request_token:
            raise ValidationError(detail={'request_token': 'This field is required.'})

        auth = tweepy.OAuthHandler(
            settings.TWITTER_CONSUMER_KEY,
            settings.TWITTER_CONSUMER_SECRET
        )
        auth.request_token = request_token
        key, secret = auth.get_access_token(verifier)

        url = "https://api.twitter.com/1.1/account/verify_credentials.json?&include_email=true"
        auth = OAuth1(consumer_key, consumer_secret, key, secret)
        r = requests.get(url=url, auth=auth)
        twitter_data = r.json()
        twitter_id = twitter_data.get('id')
        fullname = twitter_data.get('name')
        email = twitter_data.get('email')
        avatar_url = twitter_data.get('profile_image_url')
        social_username = twitter_data.get('screen_name') or None

        try:
            User.objects.get(email=email)
            email = "*****@*****.**" % (fullname.replace(" ", "").lower(), str(uuid.uuid4())[:8])
        except User.DoesNotExist:
            pass

        username = twitter_data.get('screen_name') or email
        try:
            User.objects.get(username=username)
            username = email
        except User.DoesNotExist:
            pass

        return {
            'key': key,
            'secret': secret,
            'twitter_id': twitter_id,
            'fullname': fullname,
            'email': email,
            'username': username,
            'avatar_url': avatar_url,
            'social_username': social_username,
        }
Example #8
0
 def return_weather(place):
     words = place.split(" ")
     r = data = requests.get(
         'http://api.openweathermap.org/data/2.5/weather?q=' +
         words[1] + '&APPID=0216d3975efcbccb926efbaf5d521b86')
     weatherDetails = r.json()
     temp = weatherDetails["main"]["temp"]
     weatherDescription = weatherDetails["weather"][0]["description"]
     msg = "It is {temp} degrees with {desc}".format(
         temp=temp, desc=weatherDescription)
     return msg
Example #9
0
    def apiCall(self, url_suffix):
        """
        Takes the constructed url suffix
        Returns a json string containing the information
        from the call to the league of legends API"""

        url = '{0}/{1}/{2}&api_key={3}'.format(self.base_url, self.region,
                                               url_suffix, self.api_key)

        response = requests.get(url)
        content = requests.json(response)

        return content
Example #10
0
def import_and_replace(dataset):

    logger.info(f'Importing {dataset} into tinybird...')

    s = get_session(mode='append')
    url = f'https://raw.githubusercontent.com/datadista/datasets/master/COVID%2019/ccaa_covid19_{dataset}_long.csv'
    params = {"name": f"ccaa_covid19_{dataset}", "mode": "replace", "url": url}

    r = s.post(url=URL, params=params)

    if r.status_code != 200:
        raise Exception(r.json()['error'])

    logger.info(f'{dataset} imported into tinybird!')
Example #11
0
    def apiCall(self, url_suffix):
        """
        Takes the constructed url suffix
        Returns a json string containing the information
        from the call to the league of legends API"""

        url = '{0}/{1}/{2}&api_key={3}'.format(
            self.base_url,
            self.region,
            url_suffix,
            self.api_key)

        response = requests.get(url)
        content = requests.json(response)

        return content
Example #12
0
    def validate(self, data):
        verifier = data.get('oauth_verifier', None)
        request_token = data.get('request_token', None)
        access_token = data.get('access_token', None)
        consumer_key = getattr(settings, "TWITTER_CONSUMER_KEY", None)
        consumer_secret = getattr(settings, "TWITTER_CONSUMER_SECRET", None)
        callback_url = getattr(settings, "TWITTER_CALLBACK_URL", None)
        if not consumer_key:
            raise ValidationError(detail={'client_id': 'Cannot find TWITTER_CONSUMER_KEY in django settings'})
        if not consumer_secret:
            raise ValidationError(detail={'client_secret': 'Cannot find TWITTER_CONSUMER_SECRET in django settings'})
        if not callback_url:
            raise ValidationError(detail={'callback_url': 'Cannot find TWITTER_CALLBACK_URL in django settings'})
        if not verifier:
            raise ValidationError(detail={'oauth_verifier': 'This field is required.'})
        if not request_token:
            raise ValidationError(detail={'request_token': 'This field is required.'})

        auth = tweepy.OAuthHandler(
            settings.TWITTER_CONSUMER_KEY,
            settings.TWITTER_CONSUMER_SECRET
        )
        auth.request_token = request_token
        key, secret = auth.get_access_token(verifier)

        try:
            AccessToken.objects.get(token=access_token)
        except AccessToken.DoesNotExist:
            raise NotAuthenticated()

        url = "https://api.twitter.com/1.1/account/verify_credentials.json?&include_email=true"
        auth = OAuth1(consumer_key, consumer_secret, key, secret)
        r = requests.get(url=url, auth=auth)
        twitter_data = r.json()
        twitter_id = twitter_data.get('id')
        user_profile = get_user_profile_from_token("Bearer %s" % access_token)
        social_username = twitter_data.get('screen_name') or None

        return {
            'key': key,
            'secret': secret,
            'twitter_id': twitter_id,
            'user_profile': user_profile,
            'social_username': social_username,
        }
Example #13
0
def get_data(query: str, delim: str = ","):
    assert isinstance(query, str)
    if os.path.isfile(query):
        with open(query) as f:
            data = eval(f.read())
    else:
        req = requests.get(query)
        try:
            data = requests.json()
        except Exception:
            data = req.content.decode()
            assert data is not None, "could not connect"
            try:
                data = eval(data)
            except Exception:
                data = data.split("\n")
        req.close()
    return data
Example #14
0
def req(url):
    try:
        r = requests.get(url, headers=headers, timeout=10)
    except ConnectionResetError:
        print('connection reset error')
        time.sleep(2)
        return
    except requests.exceptions.Timeout:
        print('requests.exceptions timeout error')
        time.sleep(2)
        return
    except requests.exceptions.ConnectionError:
        print('connectionerror')
        time.sleep(2)
        return
    try:
        return r.json()
    except ValueError:
        time.sleep(2)
        return
Example #15
0
def getAnimeDetails(searchText):
    try:
        htmlSearchText = escape(searchText)
        
        request = requests.get("https://anilist.co/api/anime/search/" + htmlSearchText, params={'access_token':access_token})
        
        if request.status_code == 401:
            setup()
            request = requests.get("https://anilist.co/api/anime/search/" + htmlSearchText, params={'access_token':access_token})

        #Of the given list of shows, we try to find the one we think is closest to our search term
        closestAnime = getClosestAnime(searchText, request.json())

        if (closestAnime is not None):
            return closestAnime
        else:
            return requests.json()[0]
            
    except Exception as e:
        #traceback.print_exc()
        return None
Example #16
0
def get_sensor_data(workerId, interval=10):
    data = red.get('sensor_data_' + str(workerId))
    if data:
        return json.loads(data)

    times = [""]
    temperature = {'log': [], 'title': u"平均", 'result': 0, 'unit': u"℃"}
    humidity = {'log': [], 'title': u"平均", 'result': 0, 'unit': "%"}
    tmp_temperature = []
    tmp_humidity = []

    payload = {'rdf:type': "frameworx:WarehouseSensor",
               'frameworx:workerId': workerId}
    requests = get_requests(payload)

    for d in requests.json():
        if d['dc:date']:
            time = get_time(d['dc:date'], interval)
            tmp_temperature.append(d["frameworx:temperature"])
            tmp_humidity.append(d["frameworx:humidity"])
            if time != times[-1]:
                times.append(time)
                temperature['log'].append(sum(tmp_temperature)/len(tmp_temperature))
                humidity['log'].append(sum(tmp_humidity)/len(tmp_humidity))
                tmp_temperature = []
                tmp_humidity = []

    if len(temperature['log']) > 0:
        temperature['result'] = round(sum(temperature['log'])/len(temperature['log']), 1)
    if len(humidity['log']) > 0:
        humidity['result'] = round(sum(humidity['log'])/len(humidity['log']), 1)

    sensor_data = {
            u'時間': times[1:],
            u'気温': temperature,
            u'湿度': humidity}

    red.set('sensor_data_' + str(workerId), json.dumps(sensor_data), ex=600)

    return sensor_data
Example #17
0
def get_vital_data(workerId, interval=10):
    data = red.get('vital_data_' + str(workerId))
    if data:
        return json.loads(data)

    times = [""]
    calorie = {'log': [], 'title': u"合計", 'result': 0, 'unit': u"kcal"}
    step = {'log': [], 'title': u"合計", 'result': 0, 'unit': u"歩"}
    heartrate = {'log': [], 'title': u"平均", 'result': 0, 'unit': "bpm"}
    tmp_heartrates = []

    payload = {'rdf:type': "frameworx:WarehouseVital",
               'frameworx:workerId': workerId}
    requests = get_requests(payload)

    for d in requests.json():
        if d['dc:date']:
            time = get_time(d['dc:date'], interval)
            tmp_heartrates.append(d["frameworx:heartrate"])
            calorie['result'] = int(d["frameworx:calorie"])
            step['result'] = int(d["frameworx:step"])
            if time != times[-1]:
                times.append(time)
                calorie['log'].append(calorie['result'])
                step['log'].append(step['result'])
                heartrate['log'].append(sum(tmp_heartrates)/len(tmp_heartrates))
                tmp_heartrates = []

    if len(heartrate['log']) > 0:
        heartrate['result'] = sum(heartrate['log'])/len(heartrate['log'])

    vital_data = {
            u'時間': times[1:],
            u'カロリー': calorie,
            u'歩数': step,
            u'脈拍': heartrate}

    red.set('vital_data_' + str(workerId), json.dumps(vital_data), ex=600)

    return vital_data
Example #18
0
def get_position_data(workerId, interval=10):
    data = red.get('position_data_' + str(workerId))
    if data:
        return json.loads(data)

    times = [""]
    positions = []
    distance = {'log': [], 'title': u"合計", 'result': 0, 'unit': u"m"}

    payload = {'rdf:type': "frameworx:WarehousePosition",
               'frameworx:workerId': workerId}
    requests = get_requests(payload)

    for d in requests.json():
        if d['dc:date']:
            time = get_time(d['dc:date'], interval)
            tmp_position = {'x': d['frameworx:x'], 'y': d['frameworx:y']}

            if len(positions) == 0:
                positions.append(tmp_position)

            distance['result'] += int(numpy.sqrt((tmp_position['x'] - positions[-1]['x']) ** 2 + (tmp_position['y'] - positions[-1]['y']) ** 2))
            positions.append(tmp_position)

            if time != times[-1]:
                times.append(time)
                distance['log'].append(distance['result']/100)

    distance['result'] /= 100

    position_data = {
            u'時間': times[1:],
            u'距離': distance,
            u'位置': positions[1:]}

    red.set('position_data_' + str(workerId), json.dumps(position_data), ex=600)

    return position_data
Example #19
0
def get_paste_content(update, context):
    args = context.args
    BURL = 'https://del.dog'
    message = update.effective_message
    chat = update.effective_chat  # type: Optional[Chat]

    if len(args) >= 1:
        key = args[0]
    else:
        message.reply_text("Please supply a dogbin url!")
        return

    format_normal = f'{BURL}/'
    format_view = f'{BURL}/v/'

    if key.startswith(format_view):
        key = key[len(format_view):]
    elif key.startswith(format_normal):
        key = key[len(format_normal):]

    r = requests.get(f'{BURL}/raw/{key}')

    if r.status_code != 200:
        try:
            res = r.json()
            update.effective_message.reply_text(res['message'])
        except Exception:
            if r.status_code == 404:
                update.effective_message.reply_text(
                    "Failed to reach dogbin")
            else:
                update.effective_message.reply_text(
                    "Unknown error occured")
        r.raise_for_status()

    update.effective_message.reply_text('```' + escape_markdown(r.text) +
                                        '```',
                                        parse_mode=ParseMode.MARKDOWN)
Example #20
0
def get_location_data(workerId):
    data = red.get('location_data_' + str(workerId))
    if data:
        return json.loads(data)
    location_data = []

    tmp_data = get_activity_data(workerId)

    payload = {'rdf:type': "frameworx:WarehouseLocation"}
    requests = get_requests(payload)

    for l in tmp_data[u"シェルフ"]:
        location = {}
        for d in requests.json():
            if d['frameworx:shelfId'] == l:
                location['id'] = l
                location['x'] = d['frameworx:x']
                location['y'] = d['frameworx:y']
                location_data.append(location)

    red.set('location_data_' + str(workerId), json.dumps(location_data), ex=600)

    return location_data
Example #21
0
def main():
print('------𝑋.𝑋.𝑋-ꪶ͢𝐺𝑅𝐼𝑵𝐺𝛩ꫂ🇦🇱-------')
print('####################')
print('####consulta cep####')
print('####################')

cep_input = input('digite o cep que deseja consulta: ')

if len(cep_input) != 8:
   print('quantidade de digitos invalida')
exit()

requests = requests.get('https://viacep.com.br/ws/{}/json'.format(cep_input))

address_data = requests.json()
if 'erro' not in address_data:
 print('===>cep encontrado<===')
print('CEP: {}'.format(address_data['cep']))
print('lougradora {}'.format(address_data['lougradora']))
print('bairro {}'.format(address_data['bairro']))
print('cidade: {}'.format(address_data['localidade']))
print('Estado: {}'.format(address_data['uf']))

else:
Example #22
0
# CST 205 - Multimedia Design & Programming
# Purpose: API call which returns json about state population figures. Results
#		   are reprocessed into a local dictionary.
#

import requests
import urllib
import json

URL = "https://datausa.io/api/data?drilldowns=State&measures=Population&year=latest"

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.3'}

requests = requests.get(url = URL, headers=headers)

pop_dict = requests.json()

#print(pop_dict['data'][0]['State'])

#print(pop_dict)

population = {}

for i in range(len(pop_dict['data'])):
	state_name = pop_dict['data'][i]['State']
	population_number = pop_dict['data'][i]['Population']
	population[state_name] = population_number

#print(population)

#print(population)
import matplotlib.pyplot as plt
import requests as r

#import json

distanceList = []
stepList = []
#Your ThingSpeak channel API key and channel number
url = 'https://api.thingspeak.com/channels/XXXXXX/feeds.json?api_key=XXXXXXXXXXXXXXXX&results=16'

r = r.get(url)

print("Status: ", r.status_code)

rDict = r.json()

for data in rDict["feeds"]:
    distanceList.append(float(data["field1"]))
    stepList.append(int(data["field2"]))

#with open('UltralydData.json', 'w') as filObjekt:
#    json.dump(rDict, filObjekt, indent=4)
#
#
#with open('UltralydData', 'r') as filObjekt:
#    UltralydDataDict = json.load(filObjekt)

plt.plot(stepList, distanceList)
plt.ylabel('Distance')
plt.xlabel("Steps")
from Api_Key import api_key
import requests
import pymongo
import pprint as pprint
import json

# Initialize PyMongo to work with MongoDBs
conn = 'mongodb://localhost:27017'
client = pymongo.MongoClient(conn)

# api link
url = "https://public.opendatasoft.com/api/records/1.0/search/?dataset=mass-shootings-in-america&rows=308&facet=city&facet=state&facet=shooter_sex&facet=shooter_race&facet=type_of_gun_general&facet=fate_of_shooter_at_the_scene&facet=shooter_s_cause_of_death&facet=school_related&facet=place_type&facet=relationship_to_incident_location&facet=targeted_victim_s_general&facet=possible_motive_general&facet=history_of_mental_illness_general&facet=military_experience"

#pulling json data from api link
requests = requests.get(url)
response = requests.json()

#inserts data(response) into database
collection.insert_one(response)

#pull data from database and assign variable shootings

shootings = db.shootings.find()

Example #25
0
def sort():
    resp = {
        'success': True,
        'data': sorted(requests.json()['data'], key=lambda x: int(x['_id']))
    }
    return jsonify(resp)
Example #26
0
def check_balance(coin, add):
    if coin == 'BCC':
        site = 'https://www.blockexperts.com/api?coin=bcc&action=getbalance&address=' + add
        hdr = {
            'User-Agent':
            'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
            'Accept':
            'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
            'Accept-Encoding': 'none',
            'Accept-Language': 'en-US,en;q=0.8',
            'Connection': 'keep-alive'
        }
        response = requests.get(site, headers=hdr, timeout=5)
        html = response.text
        return float(html)
    elif coin == 'BCH':
        response = requests.get('https://api.blocktrail.com/v1/BCC/address/' +
                                add + '?api_key=MY_APIKEY',
                                timeout=5)
        return response.json()['balance'] / 1e8
    elif coin == 'BTC':
        #response = urllib2.urlopen('https://blockchain.info/q/addressbalance/'+add, timeout = 5)
        site = 'https://blockexplorer.com/api/addr/' + add + '/balance'
        hdr = {
            'User-Agent':
            'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
            'Accept':
            'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
            'Accept-Encoding': 'none',
            'Accept-Language': 'en-US,en;q=0.8',
            'Connection': 'keep-alive'
        }
        response = requests.get(site, headers=hdr, timeout=5)
        html = response.text
        return int(html) / 1e8
    elif coin == 'ETC':
        response = requests.get(
            'https://etcchain.com/api/v1/getAddressBalance?address=' + add,
            timeout=5)
        return response.json()['balance']
    elif coin == 'ETH':
        response = requests.get(
            'https://api.etherscan.io/api?module=account&action=balance&address='
            + add + '&tag=latest&apikey=NA23E58FGS35PG5UV2IZI3DKGVWFSXW5GV',
            timeout=5)
        return int(response.json()['result']) / 1e18
    elif coin == 'MIOTA':
        data = {'command': 'getBalances', 'addresses': [add], 'threshold': 100}
        headers = {'content-type': 'application/json'}
        request = requests.get("http://service.iotasupport.com:14265",
                               data=data,
                               headers=headers,
                               timeout=5)
        return float(requests.json()['balances'][0])
    elif coin == 'NEO':
        #response = urllib2.urlopen('https://api.neonwallet.com/v1/address/balance/'+add, timeout = 5)
        response = requests.get(
            'http://antchain.org/api/v1/address/get_value/' + add, timeout=5)
        html = response.read()
        #return int(json.loads(html)['NEO']['balance'])
        return int(response.json()['asset'][0]['value'])
    elif (coin == 'DASH') or (coin == 'LTC') or (coin == 'DOGE'):
        response = requests.get('https://api.blockcypher.com/v1/' +
                                coin.lower() + '/main/addrs/' + add +
                                '/balance',
                                timeout=5)
        return int(response.json()['balance']) / 1e8
    elif coin == 'XRP':
        response = requests.get('https://data.ripple.com/v2/accounts/' + add +
                                '/balances',
                                timeout=5)
        return float(response.json()['balances'][0]['value'])
    elif coin == 'XEM':
        response = requests.get(
            'http://78.47.64.35:7890/account/get?address=' + add, timeout=5)
        return int(response.json()['account']['balance']) / 1e6
    elif coin == 'ZEC':
        site = 'https://api.zcha.in/v2/mainnet/accounts/' + add
        hdr = {
            'User-Agent':
            'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
            'Accept':
            'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
            'Accept-Encoding': 'none',
            'Accept-Language': 'en-US,en;q=0.8',
            'Connection': 'keep-alive'
        }
        response = requests.get(site, headers=hdr, timeout=5)
        return response.json()['balance']
    else:
        raise ValueError("invalid coin")
Example #27
0
import requests
import mysql.connector

cityName = "San Jose"
State = "CA"

mydb = mysql.connector.connect(
  host="localhost",
  user="******",
  database="weather"
)
mycursor = mydb.cursor()
mycursor.execute('SELECT lat, lng FROM weather.uscities where city = "' +cityName +'" AND state_id = "' + State+'";')
myresult = mycursor.fetchall()

for x in myresult:
  longitude=(x[0])
  latitude=(x[1])

response = requests.get("https://api.weather.gov/points/" + str(longitude) + ',' + str(latitude))
print(response.json())
forecast_url = response.json()['properties']['forecast']
requests = requests.get(forecast_url)
detail_forecast = requests.json()['properties']['periods']

for n in detail_forecast:
    if n['isDaytime'] == True:
        print("====For ", n['name'], " ", n['startTime'], "=====")
        print("Temperature is: ", n['temperature'])
        print("Predicted forecast: ", n['detailedForecast'])
        print("")
def enviar_vox(idchat, texto):
    # Llamar el metodo sendMessage del bot, passando el texto y la id del chat
    data = {'idchat': '72600457', 'voice': 'AwADBAADPAYAAvFWCVFZFfPyZdGLfhYE'}
    requests.get(URL + "/sendVoice",  params=data)
    print(requests.json())
Example #29
0
#

import requests
import urllib
import json

URL = "https://api.imgflip.com/get_memes"

headers = {
    'User-Agent':
    'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.3'
}

requests = requests.get(url=URL, headers=headers)

meme_images = requests.json()

# for i in range(len(meme_images['data']['memes'])):
# 	print(meme_images['data']['memes'][i])

memes_list = meme_images['data']['memes']

#print(memes_list)

meme_dictionary = {}

for i in range(len(memes_list)):
    mid = memes_list[i]['id']
    url = memes_list[i]['url']
    name = memes_list[i]['name']
    meme_dictionary[mid] = {'url': url, 'name': name}
Example #30
0
import requests as r
import pandas as pd
from crypto_record import record
from datetime import datetime
from Config import PATH_CONFIG
from os import getcwd as cwd
import os
import pathlib
from pathlib import Path

headers = {"X-CMC_PRO_API_KEY": '80bf0944-68cf-48da-a665-92218a6ae1eb'}

r = r.get("https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest", headers=headers)

json = r.json()

time = datetime.now()

columns = ['date', 'name', 'symbol', 'rank', 'price', 'volume', 'ch1h', 'ch24h', 'ch7d', 'cap']

for coin in json['data']:


	quote = coin['quote']['USD']
	# get data to datetime
	# dt = datetime.strptime("21/11/08 16:30", "%d/%m/%y %H:%M")
	rec = record(date   = time.strftime("%Y-%m-%d %H:%M"),  
				 name   = coin['name'],
				 symbol = coin['symbol'],
				 rank   = coin['cmc_rank'],
Example #31
0
import requests

api_key = "eb6969714d99e1858cd7b03f0e2c34ec"
city = "Orlando"
url = "http://api.openweathermap.org/data/2.5/weather?q="+city+"&appid="+api_key

request = requests.get(url)
json = requests.json()
print(json)
Example #32
0
import requests
import json

print('####################')
print('### Digite A moeda ###')
print("####################")
print('Ex.: USD-BRL,EUR-BRL,BTC-BRL')

moeda= input('Digite o Cep para a consulta:')

requests= requests.get('https://economia.awesomeapi.com.br/json/{}'.format(moeda))

dadosMoeda= requests.json()

#print(dadosMoeda)
print(dadosMoeda)


import json
import requests
from datetime import datetime

currency = 'JPY'

global_url = "https://api.coinmarketcap.com/v2/global/?convert=" + currency
# global_url = "https://pro.coinmarketcap.com/migrate/"

requests = requests.get(global_url)
results = requests.json()
# print(json.dumps(results,sort_keys=True, indent=4))

active_currencies = results['data']['active_cryptocurrencies']
print(active_currencies)

active_markets = results['data']['active_markets']
bitcoin_percentage = results['data']['bitcoin_percentage_of_market_cap']
last_updated = results['data']['last_updated']
global_cap = int(results['data']['quotes'][currency]['total_market_cap'])
global_volume = int(results['data']['quotes'][currency]['total_volume_24h'])

active_currencies_string = '{:,}'.format(active_currencies)
active_markets_string = '{:,}'.format(active_markets)
global_cap_string = '{:,}'.format(global_cap)
global_volume_string = '{:,}'.format(global_volume)

last_updated_string = datetime.fromtimestamp(last_updated).strftime(
    '%B %d , %Y at %I:%M%p')

print()
Example #34
0
import json
import requests

# Requests for a different API
requests = requests.get(
    "http://musicbrainz.org/ws/2/artist/5b11f4ce-a62d-471e-81fc-a69a8278c7da?fmt=json"
)

Data_json = requests.json()

Data_str = json.dumps(Data_json, indent=2)

# Printing required details
print(requests)
print('Encoding:', requests.encoding)
print('STATUS_CODE: ', requests.status_code)
print('HEADERS: ', requests.headers)
print('TEXT: ', requests.text)
print('CONTENT: ', requests.content)
print('JSON: ', requests.json)
Example #35
0
today = str(date.today())

credential = {"username": "******", "password": "******"}
credentialLogin = requests.post("https://siteOnddeEstaOsDados.com/especifica_em_q_parte_do_site_vc_quer_buscar", json=credential)
credentialLoginJson = credentialLogin.json()
credentialTokenValue = credentialLoginJson['token']

________________________________________________________________________________________________________________________________________________

import pandas as pd
import requests
import json
import os
from datetime import date
today = str(date.today())

credential = {"username": "******", "password": "******"}
credentialLogin = requests.post("https://siteOnddeEstaOsDados.com/especifica_em_q_parte_do_site_vc_quer_buscar", json=credential)
credentialLoginJson = credentialLogin.json()
credentialTokenValue = credentialLoginJson['token']
headers = {'Authorization':'JWT '+credentialTokenValue}

requests = requests.get("https://siteOnddeEstaOsDados.com/especifica_em_q_parte_do_site_vc_quer_buscar?Credencial_q_tavez_precise", headers=headers)
requests

#saída: 
response 200 # no meu caso significa q deu tudo certo :)

requests_Jason = requests.json()
requests_Text = json.dumps(requests_Jason, sort_keys=True, indent=4)
print(requests_Text)
Example #36
0
import requests
import json

# API operation
city_name = "Mishima"
api_key = "api_key"
web_api = "http://api.openweathermap.org/data/2.5/weather?units=metric&q={city}&APPID={key}"
url = web_api.format(city=city_name, key=api_key)
print(url)

# Json operation
requests = requests.get(url)
data = requests.json()
data = data["weather"][0]["main"]
json_text = json.dumps(data, indent=4)
print(json_text)
Example #37
0
import requests


print("################")
print("###### Consulta")
print("################")
print()

cep_input = input("Digite CEP")

if len(cep_input) != 8:
    print("quantidade invalida")
    exit()

requests = requests.get('https://viacep.com.br/ws/{}/json/'.format(cep_input))

address_data = requests.json()

if 'erro' not in address_data:
    print("Cep valido")

    print("Cep: {}".format(address_data['cep']))
print(requests.json())
Example #38
0
def bot():
    incoming_msg = request.values.get('Body', '')
    #print(incoming_msg)
    resp = MessagingResponse()
    msg = resp.message()
    responded = False

    if 'start' in incoming_msg:
        text = f'🤖 _Halo Saya Adalah Recsec Bot, Ada Yang Bisa Saya Bantu?_\n\n*Admin :*\n\n📞 : 085885105039\n📱 : _fb.me/rezzapriatna12_ \n\n🚀 *Fitur* \n\n✅ _Youtube Downloader_ \n✅ _Facebook Downloader_ \n✅ _Instagram Downloader_ \n✅ _Google Search_ \n✅ _Text To Speech_ \n✅ _Stalking Profil Instagram_ \n✅ _Translate_ \n\n\n _Untuk Menampilkan Command Ketik_ *Menu*'
        msg.body(text)
        responded = True
    if 'info-covid' in incoming_msg or 'Info-covid' in incoming_msg:
        import requests as r, json
        req = r.get(
            'https://coronavirus-19-api.herokuapp.com/countries/indonesia')
        reqq = r.get(
            'https://coronavirus-19-api.herokuapp.com/countries/world')
        jss = reqq.json()
        js = req.json()
        text = f'*Info Coronavirus Indonesia*\n\n\n*Positif* : {js["cases"]} \n*Sembuh* : {js["recovered"]} \n*Meninggal* : {js["deaths"]}  \n\n\n*Global* \n\n\n*Positif* : {jss["cases"]} \n*Sembuh* : {jss["recovered"]} \n*Meninggal* : {jss["deaths"]}'
        msg.body(text)
        responded = True

        import requests as r
        import re
        par = incoming_msg[3:]
        html = r.get(par)
        video_url = re.search('sd_src:"(.+?)"', html.text).group(1)
        msg.media(video_url)
        responded = True

    if '/IG' in incoming_msg:
        import requests as r
        par = incoming_msg[3:]
        a = r.get(par + '?__a=1')
        b = a.json()
        c = b['graphql']['shortcode_media']
        d = (c['video_url'])
        msg.media(d)
        responded = True

    if '/GL' in incoming_msg:
        from googlesearch import search
        query = incoming_msg[3:]
        for i in search(query, tld="com", num=10, stop=10, pause=2):
            text = f'==========Results==========\n\n *Reff* : ' + i
            msg.body(text)
            responded = True

    if '/TR-en-id' in incoming_msg:
        par = incoming_msg[9:]
        translator = Translator()
        result = translator.translate(par, src='en', dest='id')
        msg.body(result.text)
        responded = True

    if '/TR-id-en' in incoming_msg:
        par = incoming_msg[9:]
        translator = Translator()
        result = translator.translate(par, src='id', dest='en')
        msg.body(result.text)
        responded = True

    if '/TR-id-kor' in incoming_msg:
        par = incoming_msg[10:]
        translator = Translator()
        result = translator.translate(par, src='id', dest='ko')
        msg.body(result.text)
        responded = True

    if '/TR-kor-id' in incoming_msg:
        par = incoming_msg[10:]
        translator = Translator()
        result = translator.translate(par, src='ko', dest='id')
        msg.body(result.text)
        responded = True

    if '/FL' in incoming_msg:
        import requests as r
        import re
        par = incoming_msg[3:]
        html = r.get(par)
        video_url = re.search('sd_src:"(.+?)"', html.text).group(1)
        reqq = r.get('http://tinyurl.com/api-create.php?url=' + video_url)
        msg.body('*VIDEO BERHASIL DI CONVERT*\n\nLINK : ' + reqq.text +
                 '\n\n_Cara Download Lihat Foto Diatas_')
        msg.media(
            'https://user-images.githubusercontent.com/58212770/78709692-47566900-793e-11ea-9b48-69c72f9bec1e.png'
        )
        responded = True

    if '/TTS' in incoming_msg:
        par = incoming_msg[5:]
        msg.media('https://api.farzain.com/tts.php?id=' + par +
                  '&apikey=JsaChFteVJakyjBa0M5syf64z&')
        responded = True

    if '/SG' in incoming_msg:
        import requests
        import json
        par = incoming_msg[4:]
        p = requests.get('http://api.farzain.com/ig_profile.php?id=' + par +
                         '&apikey=JsaChFteVJakyjBa0M5syf64z')
        js = p.json()['info']
        ms = (js['profile_pict'])
        jp = p.json()['count']
        text = f'Nama : *{js["full_name"]}* \nUsername : {js["username"]} \nBio : *{js["bio"]}* \nSitus Web : *{js["url_bio"]}* \nPengikut : *{jp["followers"]}* \nMengikuti : *{jp["following"]}* \nTotal Postingan : *{jp["post"]}* '
        msg.body(text)
        msg.media(ms)
        responded = True

    if '/YT' in incoming_msg:
        import pafy
        import requests as r
        par = incoming_msg[4:]
        audio = pafy.new(par)
        gen = audio.getbestaudio(preftype='m4a')
        genn = audio.getbestvideo(preftype='mp4')
        req = r.get('http://tinyurl.com/api-create.php?url=' + gen.url)
        popo = r.get('http://tinyurl.com/api-create.php?url=' + genn.url)
        msg.body(
            '_=========================_\n\n     _Video Berhasil Diconvert_\n\n_=========================_\n\n'
            '*' + gen.title + '*'
            '\n\n*Link Download Music* :' + req.text +
            '\n\n*Link Download Video* :' + popo.text)
        responded = True

    if '/SY' in incoming_msg:
        import requests as r
        par = incoming_msg[3:]
        req = r.get('http://api.farzain.com/yt_search.php?id=' + par +
                    '&apikey=JsaChFteVJakyjBa0M5syf64z&')
        js = req.json()[1]
        text = f'*Judul* :  _{js["title"]}_ \n\n*Url Video* : _{js["url"]}_\n\n*Video ID* : _{js["videoId"]}\n\n_Note : Jika Ingin Download Video Ini Atau Convert Ke Musik, Salin Link Diatas Dan Gunakan Command /YT_'
        msg.body(text)
        msg.media((js['videoThumbs']))
        responded = True

    if '/JS' in incoming_msg:
        import requests as r
        par = incoming_msg[3:]
        req = r.get('http://api.farzain.com/shalat.php?id=' + par +
                    '&apikey=JsaChFteVJakyjBa0M5syf64z&')
        js = req.json()['respon']
        text = f'*Waktu Sholat* \n\n*Subuh*  : {js["shubuh"]} \n*Dzuhur* : {js["dzuhur"]} \n*Ashar*   : {js["ashar"]} \n*Magrib*  : {js["maghrib"]} \n*Isya*    : {js["isya"]}'
        msg.body(text)
        responded = True

    if 'jadwal-imsak' in incoming_msg:
        msg.media(
            'https://user-images.githubusercontent.com/58212770/80048733-35c6b100-853b-11ea-8043-ec0614a40039.jpeg'
        )
        responded = True

    if 'help' in incoming_msg:
        text = f'💻 *Help For Instagram*\n\n/IG <Link Video> Contoh : \n/IG https://www.instagram.com/p/BWhyIhRDBCw/\n\n\n*Note* : Link Harus Seperti Di Contoh Kalo link Akhirannya Ada ?utm_source=ig_web_copy_link hapus bagian itu\n\n 💻 *Help For Facebook*\n\n/FB _link video_ Contoh :\n\n/FB https://www.facebook.com/100010246050928/posts/1143182719366586/?app=fbl \n\n💻 *Help For Google Search* \n\n /GL <Query> Contoh :  \n\n/GL rezzaapr \n\n💻 *Help For Instagram Stalking \n\n/SG <username> Contoh : \n\n/SG rzapr \n\n💻 *Help For Translate* \n\nTR-id-en Translate indonesia Ke inggris\n\n/TR-en-id Translate Inggris Ke Indonesia\n\n/TR-id-kor Translate Indonesia Ke Korea \n\n/TR-kor-id Translate Korea Ke Indonesia \n\n💻 *Help For Text To Speech* \n\n/TTS WhatsappBotRezzaapr\n\nJika Ingin Menggunakan Spasi Ganti Dengan %20\n\nContoh : /TTS Whatsapp%20Bot%Rezzaapr'
        msg.body(text)
        responded = True

    if '!' in incoming_msg:
        import requests as r
        us = incoming_msg[2:]
        import requests
        import json
        url = 'https://wsapi.simsimi.com/190410/talk/'
        body = {
            'utext': us,
            'lang': 'id',
            'country': ['ID'],
            'atext_bad_prob_max': '0.7'
        }
        headers = {
            'content-type': 'application/json',
            'x-api-key': 'LKgWy5I-HoG8K0CmpWl.SNncus1UOpwBiA1XAZzA'
        }
        r = requests.post(url, data=json.dumps(body), headers=headers)
        js = r.json()
        msg.body(js['atext'])
        responded = True

    if responded == False:
        msg.body(
            'Maaf Saya Hanya Bot Tidak Mengenal Perintah Itu :), Silahkan Kirim start Untuk Menunju Ke Menu'
        )

    return str(resp)
Example #39
0
                    with open(
                            '/Users/michel.bueno/Documents/Work/Desafio_Globo/dados.csv',
                            'w') as csvfile:
                        columns = ['Email', 'Website', 'Hemisphere']
                        writing = csv.DictWriter(csvfile,
                                                 fieldnames=columns,
                                                 delimiter=',',
                                                 lineterminator='\n')

                        writing.writeheader()
                        writing.writerow({
                            'Email': email,
                            'Website': website,
                            'Hemisphere': hemisphere
                        })


if __name__ == '__main__':
    user = argv[1]

    try:
        requests = requests.get(
            'https://jsonplaceholder.typicode.com/{}'.format(user))
        address_data = requests.json()

        email = address_data[0]['email']
        website = address_data[0]['website']
        hemisphere = address_data[0]['email']
        dados(email, website, hemisphere)
    except requests.exceptions.RequestException as e:
        print(e)