Hotbit cancel all orders request endpoint does not work | Python - python

I´ve tried to create a cancelAllOrder function for my Class.
When I use the cancel All button manually I get this result:
Endpoint: https://www.hotbit.io/v1/order/cancel_all?platform=web
The payload tab looks like this:
and the answer should looks like this: {Code: 1100, Msg: "all orders are sucessfully cancelled", Content: null}
I used this Information and turned it into this code:
def cancelAll0(self, market, order_ids):
payload = [{'market': market.replace('/', ''), 'order_id': o} for o in order_ids]
print(payload)
resp = self.session.post('https://www.hotbit.io/v1/order/cancel_all?platform=web', data=payload, headers=self.headers, cookies=self.cookies)
return resp.json()
Headers and Cookies should be good as everything else (like creating orders, requesting balance, etc.) works fine.
When I use it, I get this:
print(client.cancelAll0("ETH/USDT", order_ids=order_ids))
Output:
[{'market': 'ETHUSDT', 'order_id': 135217230000}, {'market': 'ETHUSDT', 'order_id': 135217120000}]
{'Code': 1201, 'Msg': "invalid character 'm' looking for beginning of value", 'Content': None}
As I get a response, just not the one I wanted, I think something is wrong with my payload. I checked the format of the Array but it should be correct.

Related

How do I make an API call and authenticate it with a given API key using Python?

This is my code to extract player data from an endpoint containing basketball data for a Data Science project.NOTE: I changed the name of the actual API key I was given since it's subscription. And I change the username/password because for privacy purposes. Using the correct credentials, I wouldn't receive a syntax error but the status code always returns 401. Since it wasn't accepting the API key, I added my account username, password, and the HTTP authentication header as well, but the status code still returns 401.
In case this is relevant, this is the website's recommendation in the developer portal: **The API key can be passed either as a query parameter or using the following HTTP request header.
Please let me know what changes I can make to my code. Any help is appreciated.
Ocp-Apim-Subscription-Key: {key}**
PS: My code got fragmented while posting this, but it is all in one function.
def getData():
user_name = "name#gmail.com"
api_endpoint = "https://api.sportsdata.io/v3/nba/stats/json/PlayerGameStatsByDate/2020-FEB7"
api_key = "a45;lkf"
password = "ksaljd"
header = "Ocp-Apim-Subscription-Key"
PARAMS = {'user': user_name, 'pass': password, 'header': header, 'key': api_key}
response = requests.get(url = api_endpoint, data = PARAMS)
print(response.status_code)
file = open("Data.csv", "w")
file.write(response.text)
file.close()
def _get_auth_headers() -> dict:
return {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': "`Insert key here`"
}
api_endpoint = "https://api.sportsdata.io/v3/nba/stats/json/PlayerGameStatsByDate/2020-FEB7"
PARAMS = {
# Your params here
}
response = requests.get(
api_endpoint,
headers=_get_auth_headers(),
params=PARAMS
)
Instead of just a string, you need to pass dict in the headers parameter and auth param exist so you can use it as follow:
def getData():
[...]
header = {
"Ocp-Apim-Subscription-Key": api_key
}
[...]
response = requests.get(url = api_endpoint, data = PARAMS, headers=header, auth = (user_name, password))
According to the API documentation you don't need to provide email and password. You're only need to add your API Key to header:
import requests
r = requests.get(url='https://api.sportsdata.io/v3/nba/stats/json/PlayerGameStatsByDate/2020-FEB7', headers={'Ocp-Apim-Subscription-Key': 'API_KEY'})
print(r.json())
Output:
[{
'StatID': 768904,
'TeamID': 25,
'PlayerID': 20000788,
'SeasonType': 1,
'Season': 2020,
'Name': 'Tim Hardaway Jr.',
'Team': 'DAL',
'Position': 'SF',
'Started': 1,
'FanDuelSalary': 7183,
'DraftKingsSalary': 7623,
'FantasyDataSalary': 7623,
...

Accessing nested data in a supposed dict

Alright, I'm stumped. I have googled everything I can think of from nested Dicts, Dicts inside Lists inside Dicts, to JSON referencing and have no idea how to get to this data.
I have this AWS Lambda handler that is reading Slack events and simply reversing someone's message and then spitting it out back to Slack. However, the bot can respond to itself (creating an infinite loop). I thought I had this solved, however, that was for the legacy stuff. I am Python stupid, so how do reference this data?
Data (slack_body_dict print from below):
{'token': 'NgapUeqidaGeTf4ONWkUQQiP', 'team_id': 'T7BD9RY57', 'api_app_id': 'A01LZHA7R9U', 'event': {'client_msg_id': '383aeac2-a436-4bad-8e19-7fa68facf916', 'type': 'message', 'text': 'rip', 'user': 'U7D1RQ9MM', 'ts': '1612727797.024200', 'team': 'T7BD9RY57', 'blocks': [{'type': 'rich_text', 'block_id': 'gA7K', 'elements': [{'type': 'rich_text_section', 'elements': [{'type': 'text', 'text': 'rip'}]}]}], 'channel': 'D01MK0JSNDP', 'event_ts': '1612727797.024200', 'channel_type': 'im'}, 'type': 'event_callback', 'event_id': 'Ev01MN8LJ117', 'event_time': 1612727797, 'authorizations': [{'enterprise_id': None, 'team_id': 'T7BD9RY57', 'user_id': 'U01MW6UK55W', 'is_bot': True, 'is_enterprise_install': False}], 'is_ext_shared_channel': False, 'event_context': '1-message-T7BD9RY57-D01MK0JSNDP'}
There is an 'is_bot' there under 'authorizations' I want to check. I assume this will let the bot stop responding to itself. However, for the life of me, I cannot reference it. It seems to be nested in there.
I have tried the following:
def lambda_handler(api_event, api_context):
print(f"Received event:\n{api_event}\nWith context:\n{api_context}")
# Grab relevant information form the api_event
slack_body_raw = api_event.get('body')
slack_body_dict = json.loads(slack_body_raw)
request_headers = api_event["headers"]
print(f"!!!!!!!!!!!!!!!!!!!!!!!body_dict:\n{slack_body_dict}")
print(f"#######################is_bot:\n{slack_body_dict('is_bot')}")
print(f"#######################is_bot:\n{slack_body_dict("is_bot")}")
print(f"#######################is_bot:\n{slack_body_dict(['is_bot']}")
print(f"#######################is_bot:\n{slack_body_dict(["is_bot"]}")
print(f"#######################is_bot:\n{slack_body_dict['authorizations']['is_bot']}")
As you can see I have absolutely no clue how to get to that variable to tell if it is true or false. Every 'is_bot' print reference results in an error. Can someone tell me how to reference that variable or give me something to google? Appreciate it. Code is below in case it is relevant.
import json
import os
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
def is_challenge(slack_event_body: dict) -> bool:
"""Is the event a challenge from slack? If yes return the correct response to slack
Args:
slack_event_body (dict): The slack event JSON
Returns:
returns True if it is a slack challenge event returns False otherwise
"""
if "challenge" in slack_event_body:
LOGGER.info(f"Challenge Data: {slack_event_body['challenge']}")
return True
return False
def lambda_handler(api_event, api_context):
# Grab relevant information form the api_event
slack_body_raw = api_event.get('body')
slack_body_dict = json.loads(slack_body_raw)
request_headers = api_event["headers"]
# This is to appease the slack challenge gods
if is_challenge(slack_body_dict):
challenge_response_body = {
"challenge": slack_body_dict["challenge"]
}
return helpers.form_response(200, challenge_response_body)
# This parses the slack body dict to get the event JSON
slack_event_dict = slack_body_dict["event"]
# Build the slack client.
slack_client = WebClient(token=os.environ['BOT_TOKEN'])
# We need to discriminate between events generated by
# the users, which we want to process and handle,
# and those generated by the bot.
if slack_body_dict['is_bot']: #THIS IS GIVING ME THE ERROR. I WANT TO CHECK IF BOT HERE.
logging.warning("Ignore bot event")
else:
# Get the text of the message the user sent to the bot,
# and reverse it.
text = slack_event_dict["text"]
reversed_text = text[::-1]
# Get the ID of the channel where the message was posted.
channel_id = slack_event_dict["channel"]
try:
response = slack_client.chat_postMessage(
channel=channel_id,
text=reversed_text
)
except SlackApiError as e:
# You will get a SlackApiError if "ok" is False
assert e.response["error"] # str like 'invalid_auth', 'channel_not_found'
The structure of the data is:
{
"authorizations": [
{
"is_bot": true
}
]
}
So you would need to first index "authorizations", then to get the first item 0, and lastly "is_bot".
data["authorizations"][0]["is_bot"]
Alternativly, you could iterate over all the authorizations and check if any (or all) of them are marked as a bot like so:
any(auth["is_bot"] for auth in slack_body_dict["authorizations"])

Find oldest to youngest record Python

I am trying to retrieve data from the first available date to present date from an API. I've tried using min and max in parameter.
def getcomplete(cid, pid, tag, type):
api_endpoint = ''
headers = {'token': get_token()['access_token'], 'Content-Type': 'application/json'}
params = {'cid': str(cid),
'from-date': datetime.datetime.min,
'to-date': datetime.datetime.max,
'tag': str(tag),
'type': str(type),
'pid': str(pid)
}
r = requests.post(url=api_endpoint, headers=headers, params=params)
return r.json()
getcomplete(10,12,'x','y')
This returns {'status': 'success', 'message': 'success', 'data': []}.
Is there anything wrong with the written function.
Thanks
Pythons min() and max() have an optional default parameter. This will prevent them from throwing errors
min("", default="")

JDownloader API json.decoder.JSONDecodeError

I am using the python API of JDownloader myjdapi
With the device.linkgrabber.query_links() I got the following object:
{'enabled': True, 'name': 'EQJ_X8gUcAMQX13.jpg', 'packageUUID': 1581524887390, 'uuid': 1581524890696, 'url': 'https://pbs.twimg.com/media/x.jpg?name=orig', 'availability': 'ONLINE'}
Now I want to move to the download list with the function:
device.linkgrabber.move_to_downloadlist('1581524890696', '1581524887390')
The move_to_downloadlist function (githubrepo) says:
def move_to_downloadlist(self, link_ids, package_ids):
"""
Moves packages and/or links to download list.
:param package_ids: Package UUID's.
:type: list of strings.
:param link_ids: Link UUID's.
"""
params = [link_ids, package_ids]
resp = self.device.action(self.url + "/moveToDownloadlist", params)
return resp
But I get always json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
The official API said its a 200 Error, and the reason can be anything.
How I can fix that?
The parameter names are link_ids and package_ids, that's plural. That would be a good indication that lists are expected here, not single values.
Try this:
device.linkgrabber.move_to_downloadlist(['1581524890696'], ['1581524887390'])

Dict not able to return data from college scorecard API

So I've been working on a page which displays a school's name, url, city, state, zip, and student size via College Scorecard API but I'm getting tons of errors instead. However, the program is able to read the JSON data just fine. For example, when I run this:
key = "key_string_here"
url_base = "https://api.data.gov/ed/collegescorecard/v1/schools/"
# Makes a get request to collegescorecard API
r = requests.get("https://api.data.gov/ed/collegescorecard/v1/schools/?
school.operating=1&2015.academics.program_available.assoc_or_bachelors=true&
2015.student.size__range=1..&school.degrees_awarded.predominant__range=1..3
&school.degrees_awarded.highest__range=2..4&id=240444&api_key=api_key_here")
school = r.json()
for item in school:
url = ("https://api.data.gov/ed/collegescorecard/v1/schools?"
"school.operating=1&2015.academics.program_available"
".assoc_or_bachelors=true&2015.student.size__range=1.."
"&school.degrees_awarded.predominant__range=1..3"
"&school.degrees_awarded.highest__range=2..4&id=240444&"
"api_key="+key+"&fields=school.name, school.school_url,"
"school.city,school.zip,school.state,2015.student.size")
req = urllib2.Request(url)
response = urllib2.urlopen(req)
response2 = response.read()
json_data=json.loads(response2)
print response2
I get the correct data:
{"metadata":{"total":1,"page":0,"per_page":20},"results":[{"school.n
ame":"University of Wisconsin-Madison","school.zip":"53706-1380","sc
hool.state":"WI","2015.student.size":29579,"school.school_url":"www.
wisc.edu","school.city":"Madison"}]}
However, when I try to parse the JSON data in a dictionary, like this:
params = dict(
school_name="University of Wisconsin-Madison",
school_url="www.wisc.edu",
city="Madison",
state="WI",
zip="53706-1380",
size="29579"
)
resp = requests.get(url=url, params=params)
data = resp.json()
print data
I get this in response:
{u'errors': [{u'input': u'city', u'message': u"The input parameter '
city' is not known in this dataset.", u'error': u'parameter_not_foun
d'}, {u'input': u'state', u'message': u"The input parameter 'state'
is not known in this dataset.", u'error': u'parameter_not_found'}, {
u'input': u'school_url', u'message': u"The input parameter 'school_u
rl' is not known in this dataset.", u'error': u'parameter_not_found'
}, {u'input': u'school_name', u'message': u"The input parameter 'sch
ool_name' is not known in this dataset.", u'error': u'parameter_not_
found'}, {u'input': u'size', u'message': u"The input parameter 'size
' is not known in this dataset.", u'error': u'parameter_not_found'},
{u'input': u'53706-1380', u'message': u"The provided zipcode, '5370
6-1380', is not valid.", u'parameter': u'zip', u'error': u'zipcode_e
rror'}]}
What am I doing wrong? How can I fix this problem?
BONUS: Any suggestions to improve my web page?
In response to chillin:
vagrant#vagrant:/vagrant/scripts$ python school_data.py
File "school_data.py", line 29
"school_url"="www.wisc.edu",
SyntaxError: keyword can't be an expression
Edit II:
File "school_data.py", line 28
school_url: "www.wisc.edu",
^
SyntaxError: invalid syntax
Edit III:
vagrant#vagrant:/vagrant/scripts$ python school_data.py
File "school_data.py", line 28
"school.school_url"="www.wisc.edu",
SyntaxError: keyword can't be an expression
Untested, written on mobile, but I think this should be the same as what you have in your first request. If I was you, I would copy the code below to a new .py file and then run it. That way, if it raises an error, you know something is wrong with my code (and not some other part of your code). Hope it works or gets you closer to a solution.
import requests
key = "replace me with your API key"
url_base = "https://api.data.gov/ed/collegescorecard/v1/schools/"
p = {"school.operating" : "1", "2015.academics.program_available.assoc_or_bachelors" : "true", "2015.student.size__range" : "1..", "school.degrees_awarded.predominant__range" : "1..3", "school.degrees_awarded.highest__range" : "2..4", "id" : "240444", "api_key" : key}
resp = requests.get(url=url_base, params=p)
data = resp.json()
print data

Categories

Resources