tdorssers / teslapy Goto Github PK
View Code? Open in Web Editor NEWA Python module to use the Tesla Motors Owner API
License: MIT License
A Python module to use the Tesla Motors Owner API
License: MIT License
I use the endpoint CHARGING_HISTORY in my project but it stopped working since march. It returns an 404 error. However, other endpoints like vehicle.get_charge_history() work great. Did I do anything wrong?
I tried:
vehicle.api('CHARGING_HISTORY')['response']
tesla.api('CHARGING_HISTORY')['response']
return:
404 Client Error: 404. Not Found 1c646759c29905f76e5ab5f24874ad13 for url: https://owner-api.teslamotors.com/bff/v2/mobile-app/charging/history
import teslapy
with teslapy.Tesla(tesla_mail, tesla_pass) as tesla:
tesla.fetch_token()
vehicles = tesla.vehicle_list()
vehicles[0].sync_wake_up()
test = vehicles[0]['charge_state']['charging_state']
This should give me the charging state, but it doesn't. It doesn't work for any value. Commands work though and state returns "online":
vehicles[0].command('STOP_CHARGE')
vehicles[0]['state']
I've been using Teslapy for about 6 months. Awesome. I use it to adjust charging based on solar panel output.
I recently built up an Ubuntu machine. The code hangs when executing a command. See the attached output when I stop the code. This code runs on other machines (e.g. Windows) but won't run on this Ubuntu machine.
All the packages identified in requirements.txt seem to be up to minimum versions required.
Any guidance on what I need to do to rectify this?
Thanks.
As far as I understand it shouldn't do it, but even after a successful login, the next time it asks for the captcha:
import teslapy
def solve_captcha(svg):
import webbrowser
import tempfile
# Use web browser to display SVG image
with tempfile.NamedTemporaryFile(suffix='.svg', delete=False) as f:
f.write(svg)
webbrowser.open('file://' + f.name)
indigo.server.log('#### Tesla: Login Captcha required')
indigo.actionGroup.execute(932264821) # notification
import time
time.sleep(10)
return str(indigo.variables[373373398].value)
try:
with teslapy.Tesla(tesla_mail, tesla_pass) as tesla:
tesla.captcha_solver = solve_captcha
tesla.fetch_token()
vehicles = tesla.vehicle_list()
except:
indigo.server.log('#### Tesla: Login failed')
2021-04-08 20:53:56,123 - teslapy - WARNING - compose_image requires options for the image to be accurate
Exception in Tkinter callback
Traceback (most recent call last):
File "/Users/arvin/opt/anaconda3/lib/python3.8/tkinter/init.py", line 1883, in call
return self.func(*args)
File "/Users/arvin/opt/anaconda3/lib/python3.8/tkinter/init.py", line 804, in callit
func(*args)
File "gui.py", line 644, in process_update_dashboard
self.dashboard.update_widgets()
File "gui.py", line 316, in update_widgets
self.ft.text(door[ve['ft']])
IndexError: list index out of range
Hi,
I'll get a traceback, as the GPS information of my car seems to resolve to a location which contains an Umlaut (in this case 'ΓΌ').
Happy to provide further details and thanks for this fairly cool tool!
Traceback (most recent call last):
File "menu.py", line 259, in <module>
main()
File "menu.py", line 256, in main
menu(vehicles[idx])
File "menu.py", line 151, in menu
show_vehicle_data(vehicle.get_vehicle_data())
File "menu.py", line 87, in show_vehicle_data
print('GPS: {:.75}'.format(str(location)))
UnicodeEncodeError: 'ascii' codec can't encode character u'\xdf' in position 10: ordinal not in range(128)
Got the following crash this morning. I've 'bolded' the line that I think in my source code generated the crash. I'm using a refresh token to connect. It runs without issue for several hours. Not sure if it's about the access token expiring. The next expiration is today at 11:02:00 PM local time. I'll see if it does it then.
The source is at https://github.com/SylvainGa/TeslaRainCheck
Apr 15 11:31:06 weewx python3[20670]: Traceback (most recent call last):
Apr 15 11:31:06 weewx python3[20670]: File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 600, in urlopen
Apr 15 11:31:06 weewx python3[20670]: chunked=chunked)
Apr 15 11:31:06 weewx python3[20670]: File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 384, in _make_request
Apr 15 11:31:06 weewx python3[20670]: six.raise_from(e, None)
Apr 15 11:31:06 weewx python3[20670]: File "<string>", line 3, in raise_from
Apr 15 11:31:06 weewx python3[20670]: File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 380, in _make_request
Apr 15 11:31:06 weewx python3[20670]: httplib_response = conn.getresponse()
Apr 15 11:31:06 weewx python3[20670]: File "/usr/lib/python3.7/http/client.py", line 1352, in getresponse
Apr 15 11:31:06 weewx python3[20670]: response.begin()
Apr 15 11:31:06 weewx python3[20670]: File "/usr/lib/python3.7/http/client.py", line 310, in begin
Apr 15 11:31:06 weewx python3[20670]: version, status, reason = self._read_status()
Apr 15 11:31:06 weewx python3[20670]: File "/usr/lib/python3.7/http/client.py", line 279, in _read_status
Apr 15 11:31:06 weewx python3[20670]: raise RemoteDisconnected("Remote end closed connection without"
Apr 15 11:31:06 weewx python3[20670]: http.client.RemoteDisconnected: Remote end closed connection without response
Apr 15 11:31:06 weewx python3[20670]: During handling of the above exception, another exception occurred:
Apr 15 11:31:06 weewx python3[20670]: Traceback (most recent call last):
Apr 15 11:31:06 weewx python3[20670]: File "/usr/lib/python3/dist-packages/requests/adapters.py", line 449, in send
Apr 15 11:31:06 weewx python3[20670]: timeout=timeout
Apr 15 11:31:06 weewx python3[20670]: File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 638, in urlopen
Apr 15 11:31:06 weewx python3[20670]: _stacktrace=sys.exc_info()[2])
Apr 15 11:31:06 weewx python3[20670]: File "/usr/lib/python3/dist-packages/urllib3/util/retry.py", line 367, in increment
Apr 15 11:31:06 weewx python3[20670]: raise six.reraise(type(error), error, _stacktrace)
Apr 15 11:31:06 weewx python3[20670]: File "/usr/lib/python3/dist-packages/six.py", line 692, in reraise
Apr 15 11:31:06 weewx python3[20670]: raise value.with_traceback(tb)
Apr 15 11:31:06 weewx python3[20670]: File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 600, in urlopen
Apr 15 11:31:06 weewx python3[20670]: chunked=chunked)
Apr 15 11:31:06 weewx python3[20670]: File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 384, in _make_request
Apr 15 11:31:06 weewx python3[20670]: six.raise_from(e, None)
Apr 15 11:31:06 weewx python3[20670]: File "<string>", line 3, in raise_from
Apr 15 11:31:06 weewx python3[20670]: File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 380, in _make_request
Apr 15 11:31:06 weewx python3[20670]: httplib_response = conn.getresponse()
Apr 15 11:31:06 weewx python3[20670]: File "/usr/lib/python3.7/http/client.py", line 1352, in getresponse
Apr 15 11:31:06 weewx python3[20670]: response.begin()
Apr 15 11:31:06 weewx python3[20670]: File "/usr/lib/python3.7/http/client.py", line 310, in begin
Apr 15 11:31:06 weewx python3[20670]: version, status, reason = self._read_status()
Apr 15 11:31:06 weewx python3[20670]: File "/usr/lib/python3.7/http/client.py", line 279, in _read_status
Apr 15 11:31:06 weewx python3[20670]: raise RemoteDisconnected("Remote end closed connection without"
Apr 15 11:31:06 weewx python3[20670]: urllib3.exceptions.ProtocolError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))
Apr 15 11:31:06 weewx python3[20670]: During handling of the above exception, another exception occurred:
Apr 15 11:31:06 weewx python3[20670]: Traceback (most recent call last):
Apr 15 11:31:06 weewx python3[20670]: File "/home/pi/tesla/check_tesla_windows_mqtt.py", line 216, in <module>
Apr 15 11:31:06 weewx python3[20670]: client.loop_forever()
Apr 15 11:31:06 weewx python3[20670]: File "/usr/local/lib/python3.7/dist-packages/paho/mqtt/client.py", line 1756, in loop_forever
Apr 15 11:31:06 weewx python3[20670]: rc = self._loop(timeout)
Apr 15 11:31:06 weewx python3[20670]: File "/usr/local/lib/python3.7/dist-packages/paho/mqtt/client.py", line 1164, in _loop
Apr 15 11:31:06 weewx python3[20670]: rc = self.loop_read()
Apr 15 11:31:06 weewx python3[20670]: File "/usr/local/lib/python3.7/dist-packages/paho/mqtt/client.py", line 1556, in loop_read
Apr 15 11:31:06 weewx python3[20670]: rc = self._packet_read()
Apr 15 11:31:06 weewx python3[20670]: File "/usr/local/lib/python3.7/dist-packages/paho/mqtt/client.py", line 2439, in _packet_read
Apr 15 11:31:06 weewx python3[20670]: rc = self._packet_handle()
Apr 15 11:31:06 weewx python3[20670]: File "/usr/local/lib/python3.7/dist-packages/paho/mqtt/client.py", line 3033, in _packet_handle
Apr 15 11:31:06 weewx python3[20670]: return self._handle_publish()
Apr 15 11:31:06 weewx python3[20670]: File "/usr/local/lib/python3.7/dist-packages/paho/mqtt/client.py", line 3327, in _handle_publish
Apr 15 11:31:06 weewx python3[20670]: self._handle_on_message(message)
Apr 15 11:31:06 weewx python3[20670]: File "/usr/local/lib/python3.7/dist-packages/paho/mqtt/client.py", line 3570, in _handle_on_message
Apr 15 11:31:06 weewx python3[20670]: on_message(self, self._userdata, message)
Apr 15 11:31:06 weewx python3[20670]: File "/home/pi/tesla/check_tesla_windows_mqtt.py", line 87, in on_message
**Apr 15 11:31:06 weewx python3[20670]: vehicles = tesla.vehicle_list()**
Apr 15 11:31:06 weewx python3[20670]: File "./TeslaPy/teslapy/__init__.py", line 351, in vehicle_list
Apr 15 11:31:06 weewx python3[20670]: return [Vehicle(v, self) for v in self.api('VEHICLE_LIST')['response']]
Apr 15 11:31:06 weewx python3[20670]: File "./TeslaPy/teslapy/__init__.py", line 347, in api
Apr 15 11:31:06 weewx python3[20670]: **{arg_name: kwargs})
Apr 15 11:31:06 weewx python3[20670]: File "./TeslaPy/teslapy/__init__.py", line 141, in request
Apr 15 11:31:06 weewx python3[20670]: response = super(Tesla, self).request(method, url, **kwargs)
Apr 15 11:31:06 weewx python3[20670]: File "/usr/lib/python3/dist-packages/requests_oauthlib/oauth2_session.py", line 360, in request
Apr 15 11:31:06 weewx python3[20670]: headers=headers, data=data, **kwargs)
Apr 15 11:31:06 weewx python3[20670]: File "/usr/lib/python3/dist-packages/requests/sessions.py", line 533, in request
Apr 15 11:31:06 weewx python3[20670]: resp = self.send(prep, **send_kwargs)
Apr 15 11:31:06 weewx python3[20670]: File "/usr/lib/python3/dist-packages/requests/sessions.py", line 646, in send
Apr 15 11:31:06 weewx python3[20670]: r = adapter.send(request, **kwargs)
Apr 15 11:31:06 weewx python3[20670]: File "/usr/lib/python3/dist-packages/requests/adapters.py", line 498, in send
Apr 15 11:31:06 weewx python3[20670]: raise ConnectionError(err, request=request)
Apr 15 11:31:06 weewx python3[20670]: requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))
Apr 15 11:31:07 weewx systemd[1]: check_tesla_windows_mqtt.service: Main process exited, code=exited, status=1/FAILURE
Apr 15 11:31:07 weewx systemd[1]: check_tesla_windows_mqtt.service: Failed with result 'exit-code'.
Was the deletion of the file in 13a432c intentional?
Just found this repo. Seems very well put together. I tried using the cli.py as well as importing the teslapy in my own python script. It fails with the following error.
Traceback (most recent call last):
File "./test.py", line 3, in <module>
tesla.fetch_token()
File "/docker/homeassistant/config/python_scripts/TeslaPy/teslapy.py", line 69, in fetch_token
response = self.api('AUTHENTICATE', data=data)
File "/docker/homeassistant/config/python_scripts/TeslaPy/teslapy.py", line 162, in api
return self.request(endpoint['TYPE'], uri, data=kwargs)
File "/docker/homeassistant/config/python_scripts/TeslaPy/teslapy.py", line 55, in request
response.raise_for_status() # Raise HTTPError, if one occurred
File "/usr/lib/python3/dist-packages/requests/models.py", line 940, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 401 Client Error: invalid_request. The request is missing a required parameter, includes an unsupported parameter value, or is otherwise malformed for url: https://owner-api.teslamotors.com/oauth/token
I tried to recreate the cache.json with a valid token, but that did not seem to work either.
HTTPSConnectionPool(host='auth.tesla.com', port=443): Max retries exceeded with url: /oauth2/v3/authorize?
Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available."
The new command CHARGING_AMPS obviously has to have a parameter to set the intended current. Does anybody know the name of this parameter and its value range (maybe, e.g. simply 5..16 for Model 3)? When it is known, it should be added to the according table in the Commands section of the README.md file.
import teslapy
def solve_captcha(svg):
import webbrowser
import tempfile
# Use web browser to display SVG image
with tempfile.NamedTemporaryFile(suffix='.svg', delete=False) as f:
f.write(svg)
webbrowser.open('file://' + f.name)
indigo.server.log('#### Tesla: Login Captcha required')
indigo.actionGroup.execute(932264821) # notification
import time
time.sleep(10)
return str(indigo.variables[64356346].value)
try:
with teslapy.Tesla(tesla_mail, tesla_pass, cache_file='/Users/server/Skripte/TeslaPy/cache.json') as tesla:
tesla.captcha_solver = solve_captcha
tesla.fetch_token()
vehicles = tesla.vehicle_list()
except:
indigo.server.log('#### Tesla: Login failed')
This code worked, but since yesterday it fails to login. No browser is opened for the captcha though. Any ideas?
Car is online and accessible through the app.
The error appears instantly.
If I delete the cache file there is no difference.
Hello,
I have a simple script that runs fine on my PC, but when I copy it across to my raspberry pi, I get the following error:
File "TeslaDisplay.py", line 19, in <module> tesla.fetch_token() File "/home/pi/Scripts/TeslaDisplay/teslapy/teslapy.py", line 71, in fetch_token email=self.email, password=self.password) File "/home/pi/Scripts/TeslaDisplay/teslapy/teslapy.py", line 165, in api return self.request(endpoint['TYPE'], uri, data=kwargs) File "/home/pi/Scripts/TeslaDisplay/teslapy/teslapy.py", line 58, in request response.raise_for_status() # Raise HTTPError, if one occurred File "/home/pi/.local/lib/python3.7/site-packages/requests/models.py", line 943, in raise_for_status raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 400 Client Error: endpoint_deprecated:_please_update_your_app for url: https://owner-api.teslamotors.com/oauth/token
Any ideas what I might be missing?
I seem to be getting ValueError: Credentials rejected
. It might be due to Tesla adding a captcha lately.
hey all, seeing a very weird failure here. i had to change my pw and re-auth, updated to 2.0 via pip3, also pulled down the repo locally.
Name: TeslaPy
Version: 2.0.0
Summary: A Python module to use the Tesla Motors Owner API
Home-page: https://github.com/tdorssers/TeslaPy
Author: Tim Dorssers
Author-email: [email protected]
License: UNKNOWN
Location: /usr/local/lib/python3.6/site-packages
Requires: requests-oauthlib, requests, websocket-client
unfortunately after updating, i can only get my scripts to work if in the current directory.
sample script
root@pigts:/var/www/scripts/notify/TeslaPy# cat teslakev.py
import teslapy
with teslapy.Tesla('XXXXX') as tesla:
tesla.fetch_token()
vehicles = tesla.vehicle_list()
vehicles[1].sync_wake_up()
print(vehicles[1].get_vehicle_data()['drive_state'])
command output :
root@pigts:~# python3 /var/www/scripts/notify/TeslaPy/teslakev.py
Traceback (most recent call last):
File "/var/www/scripts/notify/TeslaPy/teslakev.py", line 5, in <module>
vehicles = tesla.vehicle_list()
File "/var/www/scripts/notify/TeslaPy/teslapy/__init__.py", line 281, in vehicle_list
return [Vehicle(v, self) for v in self.api('VEHICLE_LIST')['response']]
File "/var/www/scripts/notify/TeslaPy/teslapy/__init__.py", line 276, in api
return self.request('GET', uri, params=kwargs)
File "/var/www/scripts/notify/TeslaPy/teslapy/__init__.py", line 119, in request
response.raise_for_status() # Raise HTTPError, if one occurred
File "/usr/local/lib/python3.6/site-packages/requests/models.py", line 940, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url: https://owner-api.teslamotors.com/api/1/vehicles
root@pigts:~# cd /var/www/scripts/notify/TeslaPy/
root@pigts:/var/www/scripts/notify/TeslaPy# python3 teslakev.py
{
"gps_as_of": XXX,
"heading": 258,
"latitude": XXX,
"longitude": -XXX,
"native_latitude": XXX,
"native_location_supported": 1,
"native_longitude": -XXX,
"native_type": "wgs",
"power": 0,
"shift_state": null,
"speed": null,
"timestamp": 1632799082968
}
Two days ago, I noticed one of my devices which uses your software was failing to retrieve data from Tesla about my vehicle. I checked my official Tesla phone app, and for the first time since installing it, was requesting I re-enter my username and password.
I dug a little deeper, and both my custom script which uses the library, as well as the included gui.py
script fail with the following error:
401 Client Error: Unauthorized for url: https://owner-api.teslamotors.com/api/1/vehicles
Is anyone else noticing such problems?
I am trying to use the API endpoint STORM_MODE_SETTINGS
and it is expecting bool value.
Running cli.py ... -a STORM_MODE_SETTINGS -k enabled=True
gets this error
requests.exceptions.HTTPError: 400 Client Error: https://powergate.prd.sn.tesla.services:443/api/v2/energy_site/storm_mode => Unable to read user settings payload --(Error)--> [[ json: cannot unmarshal string into Go struct field StormModeSettings.enabled of type bool ]] for url: https://owner-api.teslamotors.com/api/1/energy_sites/XXX/storm_mode
Is there way to pass a boolean value?
Thanks
I have been using this module for a while with no issues until recently, I have made no changes to previously working code and now I am getting a 444 Client Error: CUSTOM for url: https://owner-api.teslamotors.com/oauth/token when calling fetch_token() at first I thought that it was an issue with the tesla server, but the tesla app and another third party app I use are both connecting fine. any ideas what I can try to get a token?
Hello,
Looks like tesla changed something.
Traceback (most recent call last):
File "/usr/local/scripts/teslacli/teslacli.py", line 40, in <module>
main()
File "/usr/local/scripts/teslacli/teslacli.py", line 31, in main
tesla = fetch_tesla()
File "/usr/local/scripts/teslacli/teslacli.py", line 16, in fetch_tesla
tesla.fetch_token()
File "/usr/local/scripts/teslacli/venv/lib/python3.9/site-packages/teslapy/__init__.py", line 210, in fetch_token
raise ValueError('. '.join(msgs))
ValueError: Credentials rejected. Captcha is required. Captcha does not match
The first GET to oauth2/v3/authorize does not ask for a captcha, but after POST'ing username / password it rejects the login, and a new form is presented. Looks identical to the previous, but now a captcha is requested. teslapy doesn't handle this correctly.
Had to copy this in (__init__.py
after line 198) to check for it:
form = HTMLForm(response.text)
# Retrieve captcha image if required
if 'captcha' in form:
response = oauth.get(self.sso_base + 'captcha')
response.raise_for_status() # Raise HTTPError, if one occurred
form['captcha'] = self.captcha_solver(response.content)
if not form['captcha']:
raise ValueError('Missing captcha response')
# Submit login credentials to get authorization code through redirect
form.update({'identity': self.email, 'credential': self.password})
response = oauth.post(self.sso_base + 'oauth2/v3/authorize',
data=form, allow_redirects=False)
The docs refer to support for captcha, and sure enough I get a prompt for captcha...
But how do I solve it?
I'm using a raspberry pi with no GUI...
can't find docs on how to handle the captcha. Is an image saved somewhere for me to download and go view?
I am finding an odd result with the ChargerPhases value.
If the charger is single phase, such as my home charger, it returns the correct value of 1
If the charger is 3 phase (and I believe it is, as it shows 16A 3 phase in the car and is charging at 11kw which is what it would if it was 3 phase, it returns a value of 2. I have this at 2 different locations.
The code I am using is
ChargerPhases = int(car.get_vehicle_data()['charge_state']['charger_phases'])
Hi,
First of all, thanks for all this good work, it's really interesting to follow this kind of community projects.
I did not find a let's say "end user" documented way to use this set of scripts so I may be wrong by handling it the way I am.
I'm simply using the cli.py script to try to authenticate myself and to get vehicles info but it's not working and I'm getting the follwing error:
python cli.py -e <email> -w -g --chrome
requests.exceptions.ConnectionError: ('Connection aborted.', BadStatusLine('No status line received - the server has closed the connection',))
What would I miss? Again, maybe I'm handling that the wrong way but the idea is just to be able to use the cli Python script to retrieve interactively infos from my vehicle. I don't intend to use those scripts in my own code or whatsoever.
Thanks a lot for your feedback.
With the git version, menu.py starts displaying data, and then encounters an error:
...
...
Driver Seat Heater: 0 Passenger Seat Heater: 0
Is Front Defroster On: False Is Rear Defroster On: False
--------------------------------------------------------------------------------
Traceback (most recent call last):
File "./menu.py", line 329, in <module>
main()
File "./menu.py", line 312, in main
menu(vehicles[idx])
File "./menu.py", line 176, in menu
show_vehicle_data(vehicle.get_vehicle_data())
File "./menu.py", line 61, in show_vehicle_data
print(fmt.format(ve['vehicle_name'], vehicle.dist_units(ve['odometer'])))
TypeError: unsupported format string passed to NoneType.__format__
$ python3 --version
Python 3.7.3
Hey, first, I would like to thank you for this great piece of software! I really enjoyed it until Tesla broke our ability to simply connect to their API using a Python script. Scheduling my climate control and heated seats to be hot when I get into my car in the winter morning of northern Canada was a great addition.
More of a question here but, now that we have to live with the reCaptcha and a real browser to get a valid token, I was asking myself if there's some way of reusing the cache.json file generated on my laptop inside a docker container. Basically, from what I've tested, I can't reuse it.
Am I doing something wrong or is there something store inside the token that prevent it from being reused on another computer?
Thanks for your help!
I was able to successfully use TeslaPy and cli.py to generate a token earlier this week. Using the same Raspberry Pi platform I tried to use it again just now but the URL I was redirected to after logging in was generic - https://auth.tesla.com/static/404.html - not the long URL that can be pasted back into the script to generate the token. I looked like the longer URL flashed on the screen for a split second, but I can't figure out any way to find it in Chrome. It isn't in the browser history. Did Tesla make a change to the auth site that has broken the TeslaPy login process?
It would be nice to be able in a web application to show the auth url then wait for the user to provide the url including the code through a form submission. Any idea how I could achieve that?
I disabled MFA on my tesla account yet I still can't run menu.py
Here is the error I get:
Enter email: MY_TESLA_EMAIL
Traceback (most recent call last):
File "menu.py", line 336, in
main()
File "menu.py", line 306, in main
vehicles = tesla.vehicle_list()
File "C:\Users\aviad\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\teslapy_init_.py", line 327, in vehicle_list
return [Vehicle(v, self) for v in self.api('VEHICLE_LIST')['response']]
File "C:\Users\aviad\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\teslapy_init_.py", line 312, in api
self.fetch_token()
File "C:\Users\aviad\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\teslapy_init_.py", line 183, in fetch_token
url = self.authorization_url()
File "C:\Users\aviad\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\teslapy_init_.py", line 162, in authorization_url
response.raise_for_status() # Raise HTTPError, if one occurred
File "C:\Users\aviad\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\requests\models.py", line 960, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 500 Server Error: Internal Server Error for url: https://auth.tesla.com/oauth2/v3/authorize?response_type=code&client_id=ownerapi&redirect_uri=https%3A%2F%2Fauth.tesla.com%2Fvoid%2Fcallback&scope=openid+email+offline_access&state=X2yy3x9XLOKcGwS3WQzW7aSRRUh9CL&code_challenge=sHsqezDB3WXgqipH5Cx8jDcx1YTwEQtV3hjHVEj7k3I&code_challenge_method=S256&login_hint=MY_TESLA_EMAIL
I'm trying to run the menu.py and get this error after I enter my email address
Enter email: [email protected]
[pywebview] loaded event is deprecated and will be removed in 4.0. Use events.loaded instead
2022-04-30 15:41:20,351 - pywebview - WARNING - loaded event is deprecated and will be removed in 4.0. Use events.loaded instead
Traceback (most recent call last):
File "c:\SourceVector\TeslaPy-master\TeslaPy-master\menu.py", line 345, in
main()
File "c:\SourceVector\TeslaPy-master\TeslaPy-master\menu.py", line 311, in main
vehicles = tesla.vehicle_list()
File "c:\SourceVector\TeslaPy-master\TeslaPy-master\teslapy_init_.py", line 369, in vehicle_list
return [Vehicle(v, self) for v in self.api('VEHICLE_LIST')['response']]
File "c:\SourceVector\TeslaPy-master\TeslaPy-master\teslapy_init_.py", line 354, in api
self.fetch_token()
File "c:\SourceVector\TeslaPy-master\TeslaPy-master\teslapy_init_.py", line 221, in fetch_token
kwargs['authorization_response'] = self.authenticator(url)
File "c:\SourceVector\TeslaPy-master\TeslaPy-master\menu.py", line 280, in custom_auth
window.loaded += on_loaded
AttributeError: can't set attribute
PS C:\SourceVector>
Any ideas?
I'm using Python 3.8.8
If I run this in debug mode, I have this error
Exception has occurred: TypeError
vars() argument must have dict attribute
File "C:\SourceVector\TeslaPy-master\TeslaPy-master\menu.py", line 25, in
raw_input = vars(builtins).get('raw_input', input) # Py2/3 compatibility
Thanks
Hi,
recently I'm getting this error :
Traceback (most recent call last):
File "/home/gettoken.py", line 29, in
main(sys.argv[1],sys.argv[2])
File "/home/gettoken.py", line 24, in main
s = tesla.fetch_token()
File "/opt/rh/rh-python36/root/usr/lib64/python3.6/site-packages/teslapy/init.py", line 227, in fetch_token
raise ValueError('. '.join(msgs))
ValueError: Credentials rejected. Recaptcha is required
It seems that this error is raised before asking for the captcha solver? I'm using this code to solve captchas online via 2captcha, tit worked perfectlly until yesterday, and now seems that solve_captcha it's not executing
def solve_captcha(svg):
#print("solver")
with open('captcha.svg', 'wb') as f:
f.write(svg)
solver = CaptchaSolver('2captcha', api_key='xxxx')
cairosvg.svg2png(url='captcha.svg', write_to='captcha.png')
raw_data = open('captcha.png', 'rb').read()
solv = solver.solve_captcha(raw_data)
#print(solv)
return solv
def main(user, pwd):
with teslapy.Tesla(user, pwd) as tesla:
tesla.captcha_solver = solve_captcha
s = tesla.fetch_token()
print(tesla.token)
return tesla.token
thanks!
I'm not exactly sure what percentage_charged
means, but dividing 4731 Wh / 13774 Wh
gives me 34% charge state, which is also displayed in the app. The 3.868...
is wrong in my opinion.
{
...
"energy_left": 4731.894736842106,
"total_pack_energy": 13774,
"percentage_charged": 3.8685643327920523,
...
}
got a remote reset
Hello!
trying to run a basic getting started script as shown in the examples:
import teslapy
with teslapy.Tesla('[email protected]') as tesla:
vehicles = tesla.vehicle_list()
print(vehicles[0]['display_name'] + ' last seen ' + vehicles[0].last_seen() +
' at ' + str(vehicles[0]['charge_state']['battery_level']) + '% SoC')
After I login, I copy/paste the URL from the web browser and I get this error:
Use browser to login. Page Not Found will be shown at success.
Enter URL after authentication: https://auth.tesla.com/void/callback?code=blah&state=blah&issuer=https%3A%2F%2Fauth.tesla.com%2Foauth2%2Fv3
Traceback (most recent call last):
File "/Users/me/myprojects/tesla/./test.py", line 6, in <module>
print(vehicles[0]['display_name'] + ' last seen ' + vehicles[0].last_seen() +
File "/opt/homebrew/lib/python3.9/site-packages/teslapy/__init__.py", line 639, in last_seen
raise ValueError('Timestamp is in the future')
ValueError: Timestamp is in the future
Using:
python 3.9.13
macOS 12.4
M1 Pro
Would be useful to be able to override the default file based cache with your own implementation (DB, Redis, memcached etc.)
I've had a data collection program running for many months now without issue and has picked up successfully with the cached tokens after every restart. Today it failed with the following:
Traceback (most recent call last):
File "/mnt/seagate/private/Python/tesla/Julia.py", line 393, in
vehicles = tesla.vehicle_list()
File "/usr/local/lib/python2.7/dist-packages/teslapy/init.py", line 384, in vehicle_list
return [Vehicle(v, self) for v in self.api('VEHICLE_LIST')['response']]
File "/usr/local/lib/python2.7/dist-packages/teslapy/init.py", line 379, in api
return self.request('GET', uri, params=kwargs)
File "/usr/local/lib/python2.7/dist-packages/teslapy/init.py", line 148, in request
response.raise_for_status() # Raise HTTPError, if one occurred
File "/home/pi/.local/lib/python2.7/site-packages/requests/models.py", line 940, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url: https://owner-api.teslamotors.com/api/1/vehicles
I also tried using another program which is closely based on one of your sample programs and it fails with same error.
I updated to the very latest TeslaPy (2.3.0) but no change.
The token was refreshed on 2022-01-07 19:54:58 and has an expiry of 2022-02-21 19:54:58 (dates are in UK format).
As this has just started to fail I'm not sure if this is a temporary fault with the Tesla infrastructure or if there has been a significant change again.
The official Tesla App is still working correctly at the moment.
Would appreciate any advice on how to further diagnose this problem.
Hi,
Running py file with SSH works perfectly.
Running the same py file from HA using shell_command results with : No module named 'teslapy' - fails on the import command
My config:
shell_command:
enable_sentry: cd /config/scripts && python3 enable_sentry.py
enable_sentry.py file
try:
import teslapy
except Exception as Argument:
with open('logerror.txt', 'w') as f:
f.write(str(Argument))
System Health
version: core-2022.2.3
installation_type: Home Assistant OS
dev: false
hassio: true
docker: true
user: root
virtualenv: false
python_version: 3.9.7
os_name: Linux
os_version: 5.10.63-v8
arch: aarch64
host_os: Home Assistant OS 7.2
update_channel: stable
supervisor_version: supervisor-2022.01.1
docker_version: 20.10.9
disk_total: 109.3 GB
disk_used: 34.1 GB
healthy: true
supported: true
board: rpi4-64
supervisor_api: ok
version_api: ok
installed_addons: Samba share (9.5.1), Mosquitto broker (6.0.1), Terminal & SSH (9.3.0), File editor (5.3.3), Duck DNS (1.14.0), Frigate NVR (2.3), PostgreSQL (1.0.0), Grafana (7.4.1), TeslaMate (0.17.1)
I'd like to thank you for this body of work. Very well crafted!
Setting the drivers temperature works as expected. Newest version 2.5.0
{"name":"change_climate_temperature_setting","data":{"driver_temp":20.555555555555554},"result":true}
{"name":"change_climate_temperature_setting","data":{"passenger_temp":20.555555555555554},"result":true}
Hey! I'd like to use this library with a refresh token I supply.
I saw this example in the README, but it still brings up the browser auth. Do you have any idea why?
import teslapy
with teslapy.Tesla('[email protected]') as tesla:
if not tesla.authorized:
tesla.refresh_token(refresh_token='my-refresh-token')
hey all, wanted to give this a shot, got everything installed but i'm having issues with logging in. i didnt have MFA enabled, using cli.py was still requesting a captcha. i logged into tesla, configured MFA anyhow and verified the captcha works using an authenticator app. no matter what i try, the cli.py script is returning invalid credentials. i've waited multiple iterations of credentials to verify too. thanks!
Captcha: 364833
Traceback (most recent call last):
File "cli.py", line 100, in <module>
main()
File "cli.py", line 61, in main
tesla.fetch_token()
File "/var/www/scripts/TeslaPy/teslapy/__init__.py", line 203, in fetch_token
raise ValueError('Credentials rejected')
ValueError: Credentials rejected
Would be great if this could support the streaming API as well, as it allows for more efficient updates than constantly polling the normal API endpoints.
While the unofficial Tesla API documentation doesn't document the streaming API, the code apparently does support it. There are various other projects as well that support the streaming API.
Hi,
I'm interested in using the telsapy for accessing more information about the Tesla Powerwall battery but having a bit of trouble.
I'm new to Python, and api, so it's all a bit of jumble for me at the moment.
So, I've download Python (on Windows) and did the following
python -m pip install teslapy
python -m pip install requests_oauthlib geopy
No problem with doing that, all successful.
I've copied the cli.py file (actually I copied the text into Notepad and saved it as cli.py in the c:\python directory.
But when I execute the following command (where myemailaddress and mypassword is what I used to get access to the Tesla app on Android)
python cli.py -e myemailaddress -p mypassword -b
I get the following reply:-
Traceback (most recent call last):
File "C:\Python\cli.py", line 90, in
main()
File "C:\Python\cli.py", line 59, in main
selected = prod = tesla.vehicle_list() + tesla.battery_list()
AttributeError: 'Tesla' object has no attribute 'battery_list'
Is there something I'm supposed to put in the cli.py? What is wrong with line 59 and 90?
So, I don't know where the problem is or what I should be expecting (hoping it was something like the Powerwall data section posted)
Be much appreciated if someone can point me with troubleshooting as this is my first attempt at Python programming.
Thanks,
Graham
Anyone managed to get Safety Score data? I see the end points in endpoints.json, but they don't seem to work with e.g. the cli.py example.
import teslapy
with teslapy.Tesla('{my_email}, '{my_password}') as tesla:
tesla.fetch_token()
vehicles = tesla.vehicle_list()
print(vehicles)
Traceback (most recent call last):
File "", line 2, in
File "/Users/jas/github/TeslaPy/teslapy/teslapy.py", line 139, in fetch_token
response = self._check_mfa(oauth, transaction_id)
File "/Users/jas/github/TeslaPy/teslapy/teslapy.py", line 158, in _check_mfa
raise ValueError('passcode_getter
callback is not set')
ValueError: passcode_getter
callback is not set
I generate a specific refresh token like this:
import teslapy
import sys
with teslapy.Tesla(input('Enter Tesla login email: '), cache_loader=lambda: {}, cache_dumper=lambda x: None) as tesla:
if not tesla.authorized:
print('Use browser to login. Page Not Found will be shown at success.')
print('Open this URL: ' + tesla.authorization_url())
try:
token = tesla.fetch_token(authorization_response=input('Enter URL after authentication: '))
print(f"Refresh Token: {token['refresh_token']}")
except Exception as e:
print(f"Authorisation failed: {e}")
sys.exit(1)
else:
print(f"Refresh Token: {tesla.token['refresh_token']}")
Note how I disable cache_loader
and cache_dumper
here, so TeslaPy does not cache a successful authentication in between.
Now I use the returned refresh_token
in another script to authenticate:
import teslapy
with teslapy.Tesla(input('Enter Tesla login email: ')) as tesla:
if not tesla.authorized:
try:
tesla.refresh_token(refresh_token = input('Your refresh token: '))
except Exception as e:
raise Exception("Refreshing the access token failed; is the refresh_token still valid?") from e
and this gives me the following error:
File "/usr/local/lib/python3.9/site-packages/teslapy/__init__.py", line 209, in refresh_token
super(Tesla, self).refresh_token(token_url, **kwargs)
File "/usr/local/lib/python3.9/site-packages/requests_oauthlib/oauth2_session.py", line 452, in refresh_token
self.token = self._client.parse_request_body_response(r.text, scope=self.scope)
File "/usr/local/lib/python3.9/site-packages/oauthlib/oauth2/rfc6749/clients/base.py", line 448, in parse_request_body_response
self.token = parse_token_response(body, scope=scope)
File "/usr/local/lib/python3.9/site-packages/oauthlib/oauth2/rfc6749/parameters.py", line 441, in parse_token_response
validate_token_parameters(params)
File "/usr/local/lib/python3.9/site-packages/oauthlib/oauth2/rfc6749/parameters.py", line 448, in validate_token_parameters
raise_from_error(params.get('error'), params)
File "/usr/local/lib/python3.9/site-packages/oauthlib/oauth2/rfc6749/errors.py", line 399, in raise_from_error
raise cls(**kwargs)
oauthlib.oauth2.rfc6749.errors.ServerError: (server_error) Internal server error
What am I doing wrong?
Hi,
since the SSO Token query opens a Webbrowser on the same machine to get the Access-Token after a successful login, it was no longer possible to do this on my Linux Terminal-only Device to obtain a new Token via this method.
I am unsure if I might did not get everything right, maybe there is still the old method available, but I could not find it at least.
I helped myself by just add "print(url)" to init.py where TeslaPy is waiting for the Users response with the URL. Then I could just copy the request-URL to my Desktop Machine and did the Token-Query Process there and copy the response back into the stdin.
So it would be great to get this easy response URL output to the current version, might be others with Terminal only Linux Servers out there :-)
I have a powerwall and try to get historic data via tesla.battery_list()[0].get_history_data()
.
The built request for this however seems to be invalid. I get the following reported:
HTTPError: 400 Client Error: kind `savings` is not supported for url: https://owner-api.teslamotors.com/api/1/energy_sites/2653779/history?kind=savings&period=day&end_date=2022-04-14T00%3A13%3A08.000Z
compose_image seems to be passing invalid query params to the Tesla image compositor.
Here is the URL being accessed for my vehicle:
Note the image is not right.
Here is the URL that tesla.com uses for my vehicle (which renders accurately):
Since this is not really an issue of the code - rather a missing part in the manual - I open a new one.
How do I pass the captcha to the login as seen below?
captcha = 'btBg'
This part worked before:
with teslapy.Tesla(tesla_mail, tesla_pass) as tesla:
tesla.fetch_token()
vehicles = tesla.vehicle_list()
Thanks, I really didn't find any documentation for this.
Additionally, how often do I have to do this when using the code above. Will it remember the login or not?
I'm trying to implement a cache_loader
and cache_dumper
with ruamel.yaml
, but while I can use my functions directly, using them with the Tesla class fails.
(I realize that doing this in YAML vs the normal JSON doesn't add any value, I'm just doing it for experimentation and fun!)
My code:
from teslapy import Tesla
from ruamel.yaml import YAML
def load_cache():
yaml = YAML(typ="safe", pure=True) # ensure we return a real dict()
with open("cache.yml") as f:
return yaml.load(f)
def save_cache(cache):
yaml = YAML(typ="safe", pure=True)
yaml.default_flow_style = False
with open("cache.yml", "w") as f:
yaml.dump(cache, f)
with Tesla(
email="[email protected]", cache_loader=load_cache, cache_dumper=save_cache
) as tesla:
tesla.fetch_token()
When I run this, I get this:
File "/home/philipsd6/.cache/pypoetry/virtualenvs/tesla-scripts-5VgpqDjT-py3.10/lib/python3.10/site-packages/requests_oauthlib/oauth2_session.py", line 502, in request
token = self.refresh_token(
File "/home/philipsd6/.cache/pypoetry/virtualenvs/tesla-scripts/lib/python3.10/site-packages/teslapy/__init__.py", line 210, in refresh_token
self._token_updater() # Save new token
File "/home/philipsd6/.cache/pypoetry/virtualenvs/tesla-scripts/lib/python3.10/site-packages/teslapy/__init__.py", line 274, in _token_updater
self.cache_dumper(cache)
File "/home/philipsd6/devel/teslapy/./tesla_test.py", line 46, in save_cache
yaml.dump(cache, f)
File "/home/philipsd6/.cache/pypoetry/virtualenvs/tesla-scripts/lib/python3.10/site-packages/ruamel/yaml/main.py", line 574, in dump
return self.dump_all([data], stream, transform=transform)
File "/home/philipsd6/.cache/pypoetry/virtualenvs/tesla-scripts/lib/python3.10/site-packages/ruamel/yaml/main.py", line 583, in dump_all
self._context_manager.dump(data)
File "/home/philipsd6/.cache/pypoetry/virtualenvs/tesla-scripts/lib/python3.10/site-packages/ruamel/yaml/main.py", line 915, in dump
self._yaml.representer.represent(data)
File "/home/philipsd6/.cache/pypoetry/virtualenvs/tesla-scripts/lib/python3.10/site-packages/ruamel/yaml/representer.py", line 80, in represent
node = self.represent_data(data)
File "/home/philipsd6/.cache/pypoetry/virtualenvs/tesla-scripts/lib/python3.10/site-packages/ruamel/yaml/representer.py", line 103, in represent_data
node = self.yaml_representers[data_types[0]](self, data)
File "/home/philipsd6/.cache/pypoetry/virtualenvs/tesla-scripts/lib/python3.10/site-packages/ruamel/yaml/representer.py", line 321, in represent_dict
return self.represent_mapping('tag:yaml.org,2002:map', data)
File "/home/philipsd6/.cache/pypoetry/virtualenvs/tesla-scripts/lib/python3.10/site-packages/ruamel/yaml/representer.py", line 214, in represent_mapping
node_value = self.represent_data(item_value)
File "/home/philipsd6/.cache/pypoetry/virtualenvs/tesla-scripts/lib/python3.10/site-packages/ruamel/yaml/representer.py", line 103, in represent_data
node = self.yaml_representers[data_types[0]](self, data)
File "/home/philipsd6/.cache/pypoetry/virtualenvs/tesla-scripts/lib/python3.10/site-packages/ruamel/yaml/representer.py", line 321, in represent_dict
return self.represent_mapping('tag:yaml.org,2002:map', data)
File "/home/philipsd6/.cache/pypoetry/virtualenvs/tesla-scripts/lib/python3.10/site-packages/ruamel/yaml/representer.py", line 214, in represent_mapping
node_value = self.represent_data(item_value)
File "/home/philipsd6/.cache/pypoetry/virtualenvs/tesla-scripts/lib/python3.10/site-packages/ruamel/yaml/representer.py", line 113, in represent_data
node = self.yaml_representers[None](self, data)
File "/home/philipsd6/.cache/pypoetry/virtualenvs/tesla-scripts/lib/python3.10/site-packages/ruamel/yaml/representer.py", line 354, in represent_undefined
raise RepresenterError(_F('cannot represent an object: {data!s}', data=data))
ruamel.yaml.representer.RepresenterError: cannot represent an object: {'access_token': '...redacted', 'refresh_token': '...redacted'}
But calling the functions manually works fine with no errors:
In [3]: cache = load_cache()
In [4]: cache.keys()
Out[4]: dict_keys(['[email protected]'])
In [5]: save_cache(cache)
The code fails when vehicle is in service and awake.
For example, selecting 3 at the menu.py prompt to wake up the vehicle produces
this:
Traceback (most recent call last):
File "TeslaPy/./menu.py", line 332, in
main()
File "TeslaPy/./menu.py", line 315, in main
menu(vehicles[idx])
File "TeslaPy/./menu.py", line 173, in menu
if not vehicle.mobile_enabled():
File "TeslaPy/teslapy/init.py", line 479, in mobile_enabled
return self.tesla.get(uri)['response']
File "/usr/lib/python3.9/site-packages/requests/sessions.py", line 555, in get
return self.request('GET', url, **kwargs)
File "TeslaPy/teslapy/init.py", line 121, in request
response.raise_for_status() # Raise HTTPError, if one occurred
File "/usr/lib/python3.9/site-packages/requests/models.py", line 943, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 405 Client Error: vehicle is currently in service for url: https://owner-api.teslamotors.com/api/1/vehicles/1492************/mobile_enabled
Restarting menu.py crashes right away until the vehicle goes back to sleep.
My code is published as: https://github.com/israndy/SuperchargerLog
I continue to receive this error, and because it happens daily I am not sure how to track it down, I just see this output after the last successful step the program did run:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/urllib3/connectionpool.py", line 703, in urlopen
httplib_response = self._make_request(
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/urllib3/connectionpool.py", line 449, in _make_request
six.raise_from(e, None)
File "", line 3, in raise_from
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/urllib3/connectionpool.py", line 444, in _make_request
httplib_response = conn.getresponse()
And it goes on for page after page of errors.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
π Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. πππ
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google β€οΈ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.