-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
438 lines (379 loc) Β· 16.1 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
from datetime import datetime
import json
import traceback
import requests
import teslapy
import os
import discord
import logging
import dotenv
from discord import app_commands, Interaction
import base64
from typing import List # Fix for precedent versions of Python
dotenv.load_dotenv()
allowed_user_ids = [int(a) for a in os.environ["ALLOWED_USERIDS"].split(",")]
logger = logging.getLogger("tesla-over-discord")
class Formatting(logging.Formatter):
light_blue = '\033[1;36m'
blue = "\033[1;34m"
yellow = "\x1b[33;20m"
red = "\x1b[31;20m"
bold_red = "\x1b[31;1m"
reset = "\x1b[0m"
format = "\033[1;30m{asctime} [c]{levelname:<8} \033[0;35m{name} \033[0m{message}"
FORMATS = {
logging.DEBUG: format.replace('[c]',light_blue),
logging.INFO: format.replace('[c]',blue),
logging.WARNING: format.replace('[c]',yellow),
logging.ERROR: format.replace('[c]',red),
logging.CRITICAL: format.replace('[c]',bold_red)
}
def format(self, record):
log_fmt = self.FORMATS.get(record.levelno)
formatter = logging.Formatter(log_fmt, datefmt='%Y-%m-%d %H:%M:%S', style='{')
return formatter.format(record)
# formatter = logging.Formatter('', datefmt=,style='{')
handler = logging.StreamHandler()
handler.setFormatter(Formatting())
logger.addHandler(handler)
logger.setLevel(logging.INFO)
selected_car = None
tesla = None
vehicles: List[teslapy.Vehicle] = []
intents = discord.Intents.default()
intents.members = True
class App(discord.Client):
def __init__(self, *, intents: discord.Intents) -> None:
logger.info("Initializing App")
super().__init__(intents=intents)
self.tree = app_commands.CommandTree(self)
async def setup_hook(self) -> None:
await self.tree.sync()
app = App(intents=intents)
@app.event
async def on_interaction(interaction: Interaction) -> None:
if interaction.user.id in allowed_user_ids:
pass
else:
await interaction.response.send_message("You are not an authorized user!")
async def wakeup():
await app.change_presence(activity=discord.Game(name="Waking up..."), status=discord.Status.idle)
vehicles[0].sync_wake_up(timeout=120)
await app.change_presence(status=discord.Status.online)
async def get_vehicle_data():
global selected_car
vehicle: teslapy.Vehicle = vehicles[selected_car]
await wakeup()
vehicle_data = vehicle.get_vehicle_data()
logger.debug(vehicle_data)
return json.loads(str(vehicle_data))
@app.event
async def on_ready() -> None:
global selected_car, tesla, vehicles
logger.info("Discord bot is ready")
# Initializing TeslaPy
logger.info("Initializing TeslaPy")
tesla = teslapy.Tesla(email=os.environ["TESLA_EMAIL"])
if not tesla.authorized:
print('Your are currently not logged in to Tesla')
print('Please follow this link, then paste the URL after you are logged in.')
print(tesla.authorization_url())
print('\nURL after login: ', end='')
url = input()
tesla.fetch_token(authorization_response=url)
print('You are now logged in to Tesla')
vehicles = tesla.vehicle_list()
logger.info('Successfully logged in\nRecognized vehicles:')
for vehicle in vehicles:
print(f' - {vehicle["display_name"]}')
logger.info("TeslaPy is ready")
logger.debug('Bot is now fully ready.')
logger.warning('will only work with the first car found in the list. This will change in the future and will support multiple cars.')
selected_car = 0
sentrymode = app_commands.tree.Group(
name="sentrymode",
description="Sentry Mode related commands"
)
def authorized_users_only(interaction: Interaction, **kwargs) -> bool:
return interaction.user.id in allowed_user_ids
@sentrymode.command(
name="activate",
description="Activate Sentry Mode"
)
@app_commands.check(authorized_users_only)
async def activate(interaction: Interaction) -> None:
global selected_car
logger.debug("activate command called")
await interaction.response.defer()
vehicle: teslapy.Vehicle = vehicles[selected_car]
await wakeup()
vehicle.command('SET_SENTRY_MODE', on=True)
await interaction.followup.send("π΄ Sentry Mode **activated**")
@sentrymode.command(
name="deactivate",
description="Deactivate Sentry Mode"
)
@app_commands.check(authorized_users_only)
async def deactivate(interaction: Interaction) -> None:
global selected_car
logger.debug("deactivate command called")
await interaction.response.defer()
vehicle: teslapy.Vehicle = vehicles[selected_car]
await wakeup()
vehicle.command('SET_SENTRY_MODE', on=False)
await interaction.followup.send("βοΈ Sentry Mode **deactivated**")
app.tree.add_command(sentrymode)
commands = app_commands.tree.Group(
name="commands",
description="Basic commands for controlling your Tesla"
)
@commands.command(
name='flash-lights',
description="Flash the headlights"
)
@app_commands.check(authorized_users_only)
async def flash_headlights(interaction: Interaction) -> None:
global selected_car
logger.debug("flash-headlights command called")
await interaction.response.defer()
vehicle: teslapy.Vehicle = vehicles[selected_car]
await wakeup()
vehicle.command('FLASH_LIGHTS')
await interaction.followup.send("π¦ Flashed headlights")
@commands.command(
name='honk-horn',
description="Honk the horn"
)
@app_commands.check(authorized_users_only)
async def honk_horn(interaction: Interaction) -> None:
global selected_car
logger.debug("honk-horn command called")
await interaction.response.defer()
vehicle: teslapy.Vehicle = vehicles[selected_car]
await wakeup()
vehicle.command('HONK_HORN')
await interaction.followup.send("π’ **Honking** horn")
@app.tree.command(
name="wake-up",
description='Interally wakes up the car'
)
@app_commands.check(authorized_users_only)
async def wake_up(interaction: Interaction) -> None:
global selected_car
logger.debug("wake-up command called")
await interaction.response.defer()
vehicle: teslapy.Vehicle = vehicles[selected_car]
await wakeup()
await interaction.followup.send("π Your car **" + get_vehicle_data()['display_name'] + "**now **woke up**")
@commands.command(
name="fart",
description="Make the car fart"
)
@app_commands.check(authorized_users_only)
async def fart(interaction: Interaction) -> None:
global selected_car
logger.debug("fart command called")
await interaction.response.defer()
vehicle: teslapy.Vehicle = vehicles[selected_car]
await wakeup()
vehicle.command('REMOTE_BOOMBOX')
await interaction.followup.send("π¨ **Farted**")
@commands.command(
name="ventilate",
description="Ventilate the car (opens the windows slightly)"
)
@app_commands.check(authorized_users_only)
async def ventilate(interaction: Interaction) -> None:
global selected_car
logger.debug("ventilate command called")
await interaction.response.defer()
vehicle: teslapy.Vehicle = vehicles[selected_car]
await wakeup()
# Check if the windows are already opened
close = False
if (await get_vehicle_data())['vehicle_state']['fd_window'] != 0:
close = True
vehicle.command('WINDOW_CONTROL', command='vent' if not close else "close", lat=0, lon=0)
await interaction.followup.send("πͺ **Ventilating** (opening windows)" if not close else "πͺ **Closing windows**")
app.tree.add_command(commands)
climate = app_commands.tree.Group(
name="climate",
description="Climate related commands"
)
@climate.command(
name="heat",
description="Start the climate"
)
@app_commands.check(authorized_users_only)
async def start_climate(interaction: Interaction) -> None:
global selected_car
logger.debug("start command called")
await interaction.response.defer()
vehicle: teslapy.Vehicle = vehicles[selected_car]
await wakeup()
vehicle.command('CLIMATE_ON')
await interaction.followup.send("π‘οΈ **Starting climate**")
@app.tree.command(
name="trunk",
description="Open/Close the trunk or the frunk."
)
@app_commands.choices(which=[
app_commands.Choice(name="Rear", value="Rear"),
app_commands.Choice(name="Front", value="Front"),
])
@app_commands.check(authorized_users_only)
async def open_chests(interaction: Interaction, which: app_commands.Choice[str]) -> None:
global selected_car
logger.debug("open_chests command called")
await interaction.response.defer()
vehicle: teslapy.Vehicle = vehicles[selected_car]
# await wakeup() # Not required for trunk & frunk opening
if which.value == "Rear":
vehicle.command('ACTUATE_TRUNK', which_trunk="rear")
elif which.value == "Front":
vehicle.command('ACTUATE_TRUNK', which_trunk='front')
await interaction.followup.send(f"πͺ Actuating **{which.value} trunk**")
@climate.command(
name="stop",
description="Stop the climate"
)
@app_commands.check(authorized_users_only)
async def stop_climate(interaction: Interaction) -> None:
global selected_car
logger.debug("stop command called")
await interaction.response.defer()
vehicle: teslapy.Vehicle = vehicles[selected_car]
await wakeup()
vehicle.command('CLIMATE_OFF')
await interaction.followup.send("π‘οΈ **Stopping climate**")
app.tree.add_command(climate)
@app.tree.command(
name="info",
description="Get informations about your car"
)
@app_commands.check(authorized_users_only)
async def info(interaction: Interaction) -> None:
global selected_car
logger.debug("info command called")
await interaction.response.defer()
vehicle: teslapy.Vehicle = vehicles[selected_car]
data = await get_vehicle_data()
embed = discord.Embed()
embed.color = 0xe12026
embed.set_author(name='Model ' + vehicle['vin'][3])
logger.debug(data)
embed.title = f"{data['display_name']}"
# Vehicle Image
# FIXME: Option Codes deprecated
if data['option_codes'] is None or data['option_codes'] == []:
if 'CUSTOM_OPTIONS' in os.environ.keys():
opt_codes = os.environ['CUSTOM_OPTIONS'].split(',')
else: opt_codes = data['option_codes']
logger.debug(opt_codes)
img = vehicle.compose_image(size=1024, options=','.join(opt_codes))
img_url=requests.post(
'https://freeimage.host/api/1/upload',
data={
'key': '6d207e02198a847aa98d0a2a901485a5', # This is a public key, safe to put in the source code. Change it if you want.
'action': 'upload',
'format': 'json',
'source': base64.b64encode(img).decode('utf-8'),
}
).json()['image']['url']
embed.set_image(url=img_url)
embed.description = ('π' if data['vehicle_state']['locked'] else 'π') +'Your car is **'+('locked' if data['vehicle_state']['locked'] else 'unlocked')+'**'
embed.description += '\n' + ('β' if not data['vehicle_state']['sentry_mode'] else 'π΄') + ' Sentry Mode is **'+('enabled' if data['vehicle_state']['sentry_mode'] else 'disabled')+'**'
if data['climate_state']['is_climate_on']:
embed.description += '\nπ‘οΈ Climate is **on** (going to **' + str(data['climate_state']['driver_temp_settings']) + 'Β°C**)'
if data['charge_state']['charge_port_door_open']:
embed.description += '\nποΈ Charge port is **open**'
if data['vehicle_state']['software_update']['status'] != '':
try: # TODO: Not tested yet
embed.description += f'\n\nποΈ **A software update** ({data["vehicle_state"]["version"]}) **is available**'
except:
logger.error(traceback.format_exc())
# Vehicle Data
# Get loaction
l = requests.get(f'https://nominatim.openstreetmap.org/reverse.php?lat={data["drive_state"]["latitude"]}&lon={data["drive_state"]["longitude"]}&format=jsonv2').json()
embed.add_field(name='πΊοΈ Location', value=f"{l['address']['municipality']}\n||**{l['address']['road']}** || *(click to reveal)*")
embed.add_field(name='π‘οΈ Car Temperature', value=f"{int(data['climate_state']['inside_temp'])}Β°C")
embed.add_field(name='π Ext. Temperature', value=f"{int(data['climate_state']['outside_temp'])}Β°C")
charge_status = None
if data['charge_state']['charging_state'] == 'Disconnected':
charge_status = ('π' if int(data['charge_state']['battery_level'])>20 else 'πͺ«') + ' Not Charging'
elif data['charge_state']['charging_state'] == 'Complete':
charge_status = 'π© Charge Complete'
elif data['charge_state']['charging_state'] == 'Charging':
charge_status = 'β‘ Charging'
elif data['charge_state']['charging_state'] == 'Stopped':
charge_status = 'π₯ Charge Interrupted'
elif data['charge_state']['charging_state'] == 'Starting':
charge_status = 'π¦ Starting Charge'
elif data['charge_state']['charging_state'] == 'NoPower':
charge_status = 'β οΈ No Power'
elif data['charge_state']['charging_state'] == 'Disconnected':
charge_status = 'π Disconnected'
else:
charge_status = 'β Unknown State'
try: os.mkdir('logs')
except: pass
with open('logs/charging_states.log', 'a') as f:
f.write(f"{data['charge_state']['charging_state']}")
charge_status_value = f"**Battery Level:** {int(data['charge_state']['battery_level'])}% ({int(data['charge_state']['battery_range']*1.609)} km)"
def format_minutes(minutes):
hours = minutes // 60
remaining_minutes = minutes % 60
if hours > 0:
return f"{hours} hour{'s' if hours > 1 else ''} and {remaining_minutes} minute{'s' if remaining_minutes > 1 else ''}"
else:
return f"{remaining_minutes} minute{'s' if remaining_minutes > 1 else ''}"
if data['charge_state']['charging_state'] in ["Charging"]:
charge_status_value += f" β **+{int(data['charge_state']['charge_energy_added'])+1} kWh** ({int(data['charge_state']['charge_miles_added_rated']*1.609)+1} km)"
charge_status_value += f"\n**Charging Rate:** {'{:.2f}'.format((int(data['charge_state']['charger_actual_current'])*int(data['charge_state']['charger_voltage'])/1000))} kW ({int(data['charge_state']['charge_rate']*1.609+1)} km/hr)"
charge_status_value += f"\n**"+format_minutes(int(data['charge_state']['minutes_to_full_charge']))+"** until the limit is reached"
embed.add_field(name=charge_status, value=charge_status_value)
formatted_odometer = format(int(data['vehicle_state']['odometer']*1.609)+1, ',d').replace(',', ' ')
status = 'Parked'
if data['drive_state']['shift_state'] is not None:
if data['drive_state']['shift_state'] == 'D':
status = 'Driving'
elif data['drive_state']['shift_state'] == 'R':
status = 'Reversing'
elif data['drive_state']['shift_state'] == 'P':
status = 'Parked'
elif data['drive_state']['shift_state'] == 'N':
status = 'Neutral'
else:
status = 'Unknown'
if status != 'Parked':
embed.description += f"\n**Driving Speed:** {int(data['drive_state']['speed']*1.609)} km/h"
embed.set_footer(text='Software '+data['vehicle_state']['car_version'].split(' ')[0] + ' β ' + str(formatted_odometer) + ' km β '+status)
# TODO: finish
await interaction.followup.send(embed=embed)
@app.tree.command(
name="unlock",
description='Unlocks your Tesla'
)
@app_commands.check(authorized_users_only)
async def unlock(interaction: Interaction) -> None:
global selected_car
logger.debug("unlock command called")
await interaction.response.defer()
vehicle: teslapy.Vehicle = vehicles[selected_car]
await wakeup()
vehicle.command('UNLOCK')
await interaction.followup.send('π **'+vehicle['display_name']+'** is now unlocked')
@app.tree.command(
name="lock",
description='Locks your Tesla'
)
@app_commands.check(authorized_users_only)
async def unlock(interaction: Interaction) -> None:
global selected_car
logger.debug("lock command called")
await interaction.response.defer()
vehicle: teslapy.Vehicle = vehicles[selected_car]
await wakeup()
vehicle.command('LOCK')
await interaction.followup.send('π **'+vehicle['display_name']+'** is now locked')
app.run(os.environ["DISCORD_TOKEN"])