Formatting changes.

This commit is contained in:
tamservo 2023-11-24 15:41:42 -05:00
parent 756c38b0cb
commit 7234b0054d
2 changed files with 164 additions and 227 deletions

View File

@ -1,5 +1,5 @@
beautifulsoup4==4.9.3 beautifulsoup4==4.9.3
discord.py==2.2.3 discord==2.2.3
fastf1==3.0.3 fastf1==3.0.3
jdata==0.5.3 jdata==0.5.3
Requests==2.31.0 Requests==2.31.0

View File

@ -1,7 +1,6 @@
#!/usr/bin/python3 #!/usr/bin/python3
import asyncio import asyncio
from asyncio.subprocess import PIPE, STDOUT
import collections.abc import collections.abc
import json import json
import os import os
@ -21,10 +20,11 @@ class Robottas(commands.Bot):
# and is subject to the MIT License under which it was released. Specifically # and is subject to the MIT License under which it was released. Specifically
# the Livetiming client. # the Livetiming client.
def convert_message(self, raw): @staticmethod
def convert_message(raw):
data = raw.replace("'", '"') \ data = raw.replace("'", '"') \
.replace('True', 'true') \ .replace('True', 'true') \
.replace('False', 'false') .replace('False', 'false')
try: try:
data = json.loads(data) data = json.loads(data)
@ -34,51 +34,42 @@ class Robottas(commands.Bot):
# End section adapted from FastF1 # End section adapted from FastF1
async def on_ready(self): async def on_ready(self):
print('Logged in as: {}'.format(self.user)) print('Logged in as: {}'.format(self.user))
def run_robottas(self): def run_robottas(self):
self.run(self.token) self.run(self.token)
async def send_message(self, message): async def send_message(self, message):
if self.channel is None: if self.channel is None:
return return
await self.channel.send(message) await self.channel.send(message)
@staticmethod
async def send_image(self, ctx, image_file): async def send_image(ctx, image_file):
file_name = os.path.dirname(os.path.realpath(__file__)) file_name = os.path.dirname(os.path.realpath(__file__))
file_name = os.path.join(file_name, image_file) file_name = os.path.join(file_name, image_file)
with open(file_name, "rb") as handle: with open(file_name, "rb") as handle:
df = discord.File(handle, filename=file_name) df = discord.File(handle.read(), filename=file_name)
await ctx.send(file=df) await ctx.send(file=df)
def send_delay_message(self, message): def send_delay_message(self, message):
self.message_queue.append((time.time(), message)) self.message_queue.append((time.time(), message))
async def process_delay_messages(self): async def process_delay_messages(self):
while len(self.message_queue) > 0 and \ while len(self.message_queue) > 0 and \
self.message_queue[0][0] < time.time() - self.delay: self.message_queue[0][0] < time.time() - self.delay:
message = self.message_queue.pop(0)[1] message = self.message_queue.pop(0)[1]
await self.send_message(message) await self.send_message(message)
await asyncio.sleep(1) await asyncio.sleep(1)
async def send_status_report(self, report): async def send_status_report(self, report):
self.send_delay_message(report) self.send_delay_message(report)
async def send_lap_report(self, driver): async def send_lap_report(self, driver):
self.send_delay_message(driver + " laps remaining") self.send_delay_message(driver + " laps remaining")
async def load_flag_message(self, message): async def load_flag_message(self, message):
flag = message['Flag'] flag = message['Flag']
message_text = message['Message'] message_text = message['Message']
@ -86,35 +77,34 @@ class Robottas(commands.Bot):
if flag == 'GREEN': if flag == 'GREEN':
report = f"{self.flag_dict['GREEN_FLAG']}" + \ report = f"{self.flag_dict['GREEN_FLAG']}" + \
f"{message_text}{self.flag_dict['GREEN_FLAG']}" f"{message_text}{self.flag_dict['GREEN_FLAG']}"
elif flag == 'RED': elif flag == 'RED':
report = f"{self.flag_dict['RED_FLAG']}{message_text}" + \ report = f"{self.flag_dict['RED_FLAG']}{message_text}" + \
f"{self.flag_dict['RED_FLAG']}" f"{self.flag_dict['RED_FLAG']}"
elif flag == 'YELLOW': elif flag == 'YELLOW':
report = f"{self.flag_dict['YELLOW_FLAG']}{message_text}" + \ report = f"{self.flag_dict['YELLOW_FLAG']}{message_text}" + \
f"{self.flag_dict['YELLOW_FLAG']}" f"{self.flag_dict['YELLOW_FLAG']}"
elif flag == 'DOUBLE YELLOW': elif flag == 'DOUBLE YELLOW':
report = f"{self.flag_dict['YELLOW_FLAG']}" + \ report = f"{self.flag_dict['YELLOW_FLAG']}" + \
f"{self.flag_dict['YELLOW_FLAG']}" + \ f"{self.flag_dict['YELLOW_FLAG']}" + \
f"{message_text}" + \ f"{message_text}" + \
f"{self.flag_dict['YELLOW_FLAG']}" + \ f"{self.flag_dict['YELLOW_FLAG']}" + \
f"{self.flag_dict['YELLOW_FLAG']}" f"{self.flag_dict['YELLOW_FLAG']}"
elif flag == 'BLACK AND WHITE' and self.report_deleted_lap: elif flag == 'BLACK AND WHITE' and self.report_deleted_lap:
report = f"{message['Message']}" report = f"{message['Message']}"
elif flag == 'CHEQUERED': elif flag == 'CHEQUERED':
report = f"{self.flag_dict['CHECKERED']}" + \ report = f"{self.flag_dict['CHECKERED']}" + \
f"{self.flag_dict['CHECKERED']}" + \ f"{self.flag_dict['CHECKERED']}" + \
f"{self.flag_dict['CHECKERED']}" f"{self.flag_dict['CHECKERED']}"
# Return None or flag message # Return None or flag message
return report return report
async def load_rcm_messages(self, data): async def load_rcm_messages(self, data):
if "Messages" in data.keys(): if "Messages" in data.keys():
report = None report = None
@ -125,15 +115,15 @@ class Robottas(commands.Bot):
category = category.upper() category = category.upper()
if category == "FLAG": if category == "FLAG":
report = await self.load_flag_message( message ) report = await self.load_flag_message(message)
elif category == "OTHER": elif category == "OTHER":
if self.session_type == "RACE" and "DELETED" in message['Message']: if self.session_type == "RACE" and "DELETED" in message['Message']:
pass pass
elif "SLIPPERY" in message['Message'] and \ elif "SLIPPERY" in message['Message'] and \
not self.is_slippery_reported: not self.is_slippery_reported:
self.is_slippery_reported = True self.is_slippery_reported = True
report = "It's slippery out there!" report = "It's slippery out there!"
else: else:
report = message['Message'] report = message['Message']
@ -141,7 +131,7 @@ class Robottas(commands.Bot):
report = message['Message'] report = message['Message']
elif category == "CAREVENT" and \ elif category == "CAREVENT" and \
(self.session_type == "PRACTICE" or \ (self.session_type == "PRACTICE" or
self.session_type == "QUALI"): self.session_type == "QUALI"):
report = message['Message'] report = message['Message']
@ -159,7 +149,6 @@ class Robottas(commands.Bot):
if report is not None: if report is not None:
await self.send_status_report(report) await self.send_status_report(report)
async def load_lap_data(self, data): async def load_lap_data(self, data):
if "CurrentLap" in data.keys(): if "CurrentLap" in data.keys():
current_lap = data["CurrentLap"] current_lap = data["CurrentLap"]
@ -167,23 +156,21 @@ class Robottas(commands.Bot):
if self.current_lap != current_lap: if self.current_lap != current_lap:
self.current_lap = current_lap self.current_lap = current_lap
#Re-evaluate total laps in case it has changed # Re-evaluate total laps in case it has changed
#i.e. shortened due to rain. # i.e. shortened due to rain.
if "TotalLaps" in data.keys(): if "TotalLaps" in data.keys():
self.total_laps = int(data["TotalLaps"]) self.total_laps = int(data["TotalLaps"])
#Notify on lap change if matches a driver # Notify on lap change if matches a driver
key = str(self.total_laps - int(current_lap)) key = str(self.total_laps - int(current_lap))
if key in self.driver_dict.keys(): if key in self.driver_dict.keys():
await self.send_lap_report(self.driver_dict[key]) await self.send_lap_report(self.driver_dict[key])
def load_podium_data(self, data): def load_podium_data(self, data):
if "Lines" in data.keys(): if "Lines" in data.keys():
for position in data["Lines"].keys(): for position in data["Lines"].keys():
if 'RacingNumber' in data["Lines"][position].keys(): if 'RacingNumber' in data["Lines"][position].keys():
self.podium[int(position)] = data["Lines"][position]['RacingNumber'] self.podium[int(position)] = data["Lines"][position]['RacingNumber']
def get_podium(self): def get_podium(self):
if len(self.podium) == 3: if len(self.podium) == 3:
try: try:
@ -214,10 +201,9 @@ class Robottas(commands.Bot):
return "I don't know the podium yet :(" return "I don't know the podium yet :("
def get_q1_cut(self): def get_q1_cut(self):
message = "" message = ""
for i in range(15,20): for i in range(15, 20):
try: try:
message += self.driver_list[i] + " " message += self.driver_list[i] + " "
except: except:
@ -226,11 +212,10 @@ class Robottas(commands.Bot):
message = message.strip() message = message.strip()
return message return message
def get_q2_cut(self): def get_q2_cut(self):
message = "" message = ""
for i in range(10,15): for i in range(10, 15):
try: try:
message += self.driver_list[i] + " " message += self.driver_list[i] + " "
except: except:
@ -239,14 +224,12 @@ class Robottas(commands.Bot):
message = message.strip() message = message.strip()
return message return message
def get_weather(self): def get_weather(self):
if self.weather == "": if self.weather == "":
return "No weather info yet..." return "No weather info yet..."
else: else:
return self.weather return self.weather
async def process_race_events(self, session_data, status_data): async def process_race_events(self, session_data, status_data):
# Hold the next event to report, and the type # Hold the next event to report, and the type
event = None event = None
@ -287,7 +270,7 @@ class Robottas(commands.Bot):
self.current_lap = cur_lap self.current_lap = cur_lap
# Get the laps remaining key to see if there's a driver that matches # Get the laps remaining key to see if there's a driver that matches
laps_key = str( self.total_laps - cur_lap ) laps_key = str(self.total_laps - cur_lap)
# If there's a matching driver, then send a message # If there's a matching driver, then send a message
if laps_key in self.driver_dict.keys(): if laps_key in self.driver_dict.keys():
@ -321,7 +304,6 @@ class Robottas(commands.Bot):
if report is not None: if report is not None:
await self.send_status_report(report) await self.send_status_report(report)
def load_weather_data(self, data): def load_weather_data(self, data):
weather_txt = "Track Weather Report\n" weather_txt = "Track Weather Report\n"
for k in data.keys(): for k in data.keys():
@ -330,7 +312,6 @@ class Robottas(commands.Bot):
self.weather = weather_txt self.weather = weather_txt
def load_timing_stats_data(self, data): def load_timing_stats_data(self, data):
if "Lines" in data.keys(): if "Lines" in data.keys():
lines = data["Lines"] lines = data["Lines"]
@ -347,12 +328,13 @@ class Robottas(commands.Bot):
self.fastest_lap = self.driver_dict[driver_num] self.fastest_lap = self.driver_dict[driver_num]
return return
def load_driver_data(self, data): def load_driver_data(self, data):
for driver in data.keys(): for driver in data.keys():
position = data[driver]["Line"] position = data[driver]["Line"]
self.driver_list[position - 1] = self.driver_dict[driver] if driver in self.driver_dict.keys():
self.driver_list[position - 1] = self.driver_dict[driver]
else:
self.driver_list[position - 1] = driver
async def print_driver_range(self, ctx, start, stop): async def print_driver_range(self, ctx, start, stop):
message = "" message = ""
@ -369,23 +351,21 @@ class Robottas(commands.Bot):
await ctx.send(message) await ctx.send(message)
async def print_driver_list(self, ctx): async def print_driver_list(self, ctx):
#Send 1-10, then 11-20 # Send 1-10, then 11-20
await self.print_driver_range(ctx, 0, 10) await self.print_driver_range(ctx, 0, 10)
await self.print_driver_range(ctx, 10, 20) await self.print_driver_range(ctx, 10, 20)
def load_initial(self, message): def load_initial(self, message):
# Load podium data # Load podium data
if 'R' in message.keys(): if 'R' in message.keys():
if 'TopThree' in message['R'].keys(): if 'TopThree' in message['R'].keys():
top_three = message['R']['TopThree'] top_three = message['R']['TopThree']
if 'Lines' in top_three.keys() and \ if 'Lines' in top_three.keys() and \
len(top_three['Lines']) == 3: len(top_three['Lines']) == 3:
for i in range(3): for i in range(3):
self.podium[i] = top_three['Lines'][i]['RacingNumber'] self.podium[i] = top_three['Lines'][i]['RacingNumber']
# Load driver list # Load driver list
if 'DriverList' in message['R'].keys(): if 'DriverList' in message['R'].keys():
@ -405,7 +385,6 @@ class Robottas(commands.Bot):
if 'TotalLaps' in message['R']['LapCount'].keys(): if 'TotalLaps' in message['R']['LapCount'].keys():
self.total_laps = int(message['R']['LapCount']['TotalLaps']) self.total_laps = int(message['R']['LapCount']['TotalLaps'])
# Load weather data # Load weather data
if 'WeatherData' in message['R'].keys(): if 'WeatherData' in message['R'].keys():
weather_obj = message['R']['WeatherData'] weather_obj = message['R']['WeatherData']
@ -421,7 +400,6 @@ class Robottas(commands.Bot):
flap_obj = message['R']['TimingStats'] flap_obj = message['R']['TimingStats']
self.load_timing_stats_data(flap_obj) self.load_timing_stats_data(flap_obj)
async def process_message(self, message): async def process_message(self, message):
try: try:
if isinstance(message, collections.abc.Sequence): if isinstance(message, collections.abc.Sequence):
@ -457,7 +435,6 @@ class Robottas(commands.Bot):
except Exception as e: except Exception as e:
pass pass
def get_messages_from_db(self): def get_messages_from_db(self):
try: try:
messages = [] messages = []
@ -479,26 +456,22 @@ class Robottas(commands.Bot):
except: except:
return [] return []
async def _race_report(self, ctx):
async def _race_report(self,ctx):
self.report_deleted_lap = False self.report_deleted_lap = False
self.session_type = 'RACE' self.session_type = 'RACE'
await self._report(ctx) await self._report(ctx)
async def _quali_report(self, ctx): async def _quali_report(self, ctx):
self.report_deleted_lap = True self.report_deleted_lap = True
self.session_type = 'QUALI' self.session_type = 'QUALI'
await self._report(ctx) await self._report(ctx)
async def _practice_report(self, ctx):
async def _practice_report(self,ctx):
self.report_deleted_lap = True self.report_deleted_lap = True
self.session_type = 'PRACTICE' self.session_type = 'PRACTICE'
await self._report(ctx) await self._report(ctx)
async def _report(self, ctx): async def _report(self, ctx):
self.is_reporting = True self.is_reporting = True
self.channel = ctx.channel self.channel = ctx.channel
@ -520,20 +493,19 @@ class Robottas(commands.Bot):
# process any messages in the delay queue # process any messages in the delay queue
await self.process_delay_messages() await self.process_delay_messages()
#If collecting, make sure the collection process is running # If collecting, make sure the collection process is running
if self.is_collecting: if self.is_collecting:
if self.collector_proc == None or \ if self.collector_proc == None or \
self.collector_proc.poll() != None: self.collector_proc.poll() != None:
await self.start_collect() await self.start_collect()
@staticmethod
def get_token(self, token_file): def get_token(token_file):
with open(token_file) as tok: with open(token_file) as tok:
return tok.readline().strip() return tok.readline().strip()
async def start_collect(self): async def start_collect(self):
self.stop_collect() await self.stop_collect()
self.is_collecting = True self.is_collecting = True
self.is_slippery_reported = False self.is_slippery_reported = False
dir_path = os.path.dirname(os.path.realpath(__file__)) dir_path = os.path.dirname(os.path.realpath(__file__))
@ -541,7 +513,6 @@ class Robottas(commands.Bot):
command_txt += self.collector_params command_txt += self.collector_params
self.collector_proc = Popen(command_txt.split()) self.collector_proc = Popen(command_txt.split())
async def stop_collect(self): async def stop_collect(self):
self.is_collecting = False self.is_collecting = False
try: try:
@ -550,14 +521,12 @@ class Robottas(commands.Bot):
except: except:
pass pass
def decode_watched(self, w): def decode_watched(self, w):
if w == 0: if w == 0:
return 'Not Watched Yet' return 'Not Watched Yet'
else: else:
return 'Watched Already' return 'Watched Already'
def __init__(self): def __init__(self):
# Set debug or not # Set debug or not
self.debug = True self.debug = True
@ -585,8 +554,8 @@ class Robottas(commands.Bot):
self.podium = ['?', '?', '?'] self.podium = ['?', '?', '?']
# Hold driver list # Hold driver list
self.driver_list = ['?','?','?','?','?','?','?','?','?','?', \ self.driver_list = ['?', '?', '?', '?', '?', '?', '?', '?', '?', '?',
'?','?','?','?','?','?','?','?','?','?'] '?', '?', '?', '?', '?', '?', '?', '?', '?', '?']
# Hold weather info # Hold weather info
self.weather = "" self.weather = ""
@ -604,55 +573,55 @@ class Robottas(commands.Bot):
# Holds dictionary for number to icon # Holds dictionary for number to icon
self.driver_dict = { self.driver_dict = {
'1': '<:VER:1067541523748630570>', '1': '<:VER:1067541523748630570>',
'3': '<:RIC:1067870312949108887>', '3': '<:RIC:1067870312949108887>',
'5': '<:VET:1067964065516884079>', '5': '<:VET:1067964065516884079>',
'11': '<:PER:1067822335123525732>', '11': '<:PER:1067822335123525732>',
'14': '<:ALO:1067876094033793054>', '14': '<:ALO:1067876094033793054>',
'40': ':kiwi:', '40': ':kiwi:',
'44': '<:HAM:1067828533746991165>', '44': '<:HAM:1067828533746991165>',
'55': '<:SAI:1067824776502067270>', '55': '<:SAI:1067824776502067270>',
'63': '<:RUS:1067831294748274728>', '63': '<:RUS:1067831294748274728>',
'16': '<:LEC:1067544797050585198>', '16': '<:LEC:1067544797050585198>',
'18': '<:STR:1067871582854336663>', '18': '<:STR:1067871582854336663>',
'4': '<:NOR:1067840487593082941>', '4': '<:NOR:1067840487593082941>',
'10': '<:GAS:1067836596495327283>', '10': '<:GAS:1067836596495327283>',
'27': '<:HUL:1067880110918742187>', '27': '<:HUL:1067880110918742187>',
'31': '<:OCO:1067834157465612398>', '31': '<:OCO:1067834157465612398>',
'77': '<:BOT:1067819716527276032>', '77': '<:BOT:1067819716527276032>',
'81': '<:PIA:1067844998369914961>', '81': '<:PIA:1067844998369914961>',
'24': '<:ZHO:1067865955117568010>', '24': '<:ZHO:1067865955117568010>',
'22': '<:TSU:1067888851676315660>', '22': '<:TSU:1067888851676315660>',
'20': '<:MAG:1067883814992486510>', '20': '<:MAG:1067883814992486510>',
'23': '<:ALB:1067874026871074887>', '23': '<:ALB:1067874026871074887>',
'2': '<:SAR:1067890949197414410>', '2': '<:SAR:1067890949197414410>',
} }
# Holds dictionary for driver 3 letter code to icon # Holds dictionary for driver 3-letter code to icon
self.name_dict = { self.name_dict = {
'VER': '<:VER:1067541523748630570>', 'VER': '<:VER:1067541523748630570>',
'RIC': '<:RIC:1067870312949108887>', 'RIC': '<:RIC:1067870312949108887>',
'VET': '<:VET:1067964065516884079>', 'VET': '<:VET:1067964065516884079>',
'PER': '<:PER:1067822335123525732>', 'PER': '<:PER:1067822335123525732>',
'ALO': '<:ALO:1067876094033793054>', 'ALO': '<:ALO:1067876094033793054>',
'HAM': '<:HAM:1067828533746991165>', 'HAM': '<:HAM:1067828533746991165>',
'SAI': '<:SAI:1067824776502067270>', 'SAI': '<:SAI:1067824776502067270>',
'RUS': '<:RUS:1067831294748274728>', 'RUS': '<:RUS:1067831294748274728>',
'LEC': '<:LEC:1067544797050585198>', 'LEC': '<:LEC:1067544797050585198>',
'STR': '<:STR:1067871582854336663>', 'STR': '<:STR:1067871582854336663>',
'NOR': '<:NOR:1067840487593082941>', 'NOR': '<:NOR:1067840487593082941>',
'GAS': '<:GAS:1067836596495327283>', 'GAS': '<:GAS:1067836596495327283>',
'HUL': '<:HUL:1067880110918742187>', 'HUL': '<:HUL:1067880110918742187>',
'LAW': ':kiwi:', 'LAW': ':kiwi:',
'OCO': '<:OCO:1067834157465612398>', 'OCO': '<:OCO:1067834157465612398>',
'BOT': '<:BOT:1067819716527276032>', 'BOT': '<:BOT:1067819716527276032>',
'PIA': '<:PIA:1067844998369914961>', 'PIA': '<:PIA:1067844998369914961>',
'ZHO': '<:ZHO:1067865955117568010>', 'ZHO': '<:ZHO:1067865955117568010>',
'TSU': '<:TSU:1067888851676315660>', 'TSU': '<:TSU:1067888851676315660>',
'MAG': '<:MAG:1067883814992486510>', 'MAG': '<:MAG:1067883814992486510>',
'ALB': '<:ALB:1067874026871074887>', 'ALB': '<:ALB:1067874026871074887>',
'SAR': '<:SAR:1067890949197414410>', 'SAR': '<:SAR:1067890949197414410>',
} }
# Holds dictionary for race states to icons # Holds dictionary for race states to icons
self.flag_dict = { self.flag_dict = {
@ -733,25 +702,22 @@ class Robottas(commands.Bot):
await ctx.send("Rooting for :ferry::peach: of course!\n" + await ctx.send("Rooting for :ferry::peach: of course!\n" +
self.name_dict["BOT"] + ":smiling_face_with_3_hearts:") self.name_dict["BOT"] + ":smiling_face_with_3_hearts:")
@self.command() @self.command()
async def rbname(ctx): async def rbname(ctx):
await ctx.send("Hello, my name is Robottas, pronounced :robot::peach:") await ctx.send("Hello, my name is Robottas, pronounced :robot::peach:")
@self.command() @self.command()
async def rbdelay(ctx, delay): async def rbdelay(ctx, delay):
try: try:
secs = int(delay) secs = max(0, int(delay))
if secs < 10 or secs > 300: if secs < 10 or secs > 300:
await ctx.send("Delay must be between 10 and 300.") await ctx.send("Delay must be between 10 and 300.")
else: else:
self.delay = secs self.delay = secs
await ctx.send(f"Delay set to {secs} seconds.") await ctx.send(f"Delay set to {secs} seconds.")
except: except:
await ctx.send(f"Invalid delay value ({secs}).") await ctx.send(f"Invalid delay value passed to rbdelay.")
@self.command() @self.command()
async def rbstop(ctx): async def rbstop(ctx):
@ -760,71 +726,60 @@ class Robottas(commands.Bot):
await self.stop_collect() await self.stop_collect()
await ctx.send(":robot::peach: powering down") await ctx.send(":robot::peach: powering down")
@self.command() @self.command()
async def podium(ctx): async def podium(ctx):
message = self.get_podium() message = self.get_podium()
await ctx.send(message) await ctx.send(message)
@self.command() @self.command()
async def driverlist(ctx): async def driverlist(ctx):
await self.print_driver_list(ctx) await self.print_driver_list(ctx)
@self.command() @self.command()
async def q1cut(ctx): async def q1cut(ctx):
message = self.get_q1_cut() message = self.get_q1_cut()
await ctx.send(message) await ctx.send(message)
@self.command() @self.command()
async def q2cut(ctx): async def q2cut(ctx):
message = self.get_q2_cut() message = self.get_q2_cut()
await ctx.send(message) await ctx.send(message)
@self.command() @self.command()
async def weather(ctx): async def weather(ctx):
message = self.get_weather() message = self.get_weather()
await ctx.send(message) await ctx.send(message)
@self.command() @self.command()
async def race(ctx): async def race(ctx):
if str(ctx.author) == "tamservo#0" or ctx.author.guild_permissions.administrator: if str(ctx.author) == "tamservo#0" or ctx.author.guild_permissions.administrator:
await ctx.send( ":robot::peach: Ready to report for the race!" ) await ctx.send(":robot::peach: Ready to report for the race!")
await self._race_report(ctx) await self._race_report(ctx)
@self.command() @self.command()
async def quali(ctx): async def quali(ctx):
if str(ctx.author) == "tamservo#0" or ctx.author.guild_permissions.administrator: if str(ctx.author) == "tamservo#0" or ctx.author.guild_permissions.administrator:
await ctx.send( ":robot::peach: Ready to report on quali!" ) await ctx.send(":robot::peach: Ready to report on quali!")
await self._quali_report(ctx) await self._quali_report(ctx)
@self.command() @self.command()
async def practice(ctx): async def practice(ctx):
if str(ctx.author) == "tamservo#0" or ctx.author.guild_permissions.administrator: if str(ctx.author) == "tamservo#0" or ctx.author.guild_permissions.administrator:
await ctx.send( ":robot::peach: Ready to report on practice!" ) await ctx.send(":robot::peach: Ready to report on practice!")
await self._practice_report(ctx) await self._practice_report(ctx)
@self.command() @self.command()
async def flap(ctx): async def flap(ctx):
if self.fastest_lap != '': if self.fastest_lap != '':
await ctx.send( self.flag_dict['FLAP'] + self.fastest_lap ) await ctx.send(self.flag_dict['FLAP'] + self.fastest_lap)
else: else:
await ctx.send( "No " + self.flag_dict['FLAP'] + " yet." ) await ctx.send("No " + self.flag_dict['FLAP'] + " yet.")
@self.command()
async def rbtestfile(ctx):
self.is_reporting = True
if str(ctx.author) == "tamservo#0":
await self._test_file(ctx)
# @self.command()
# async def rbtestfile(ctx):
# self.is_reporting = True
# if str(ctx.author) == "tamservo#0":
# await self._test_file(ctx)
@self.command() @self.command()
async def start_collect(ctx): async def start_collect(ctx):
@ -833,37 +788,31 @@ class Robottas(commands.Bot):
# puts records into the database # puts records into the database
await self.start_collect() await self.start_collect()
@self.command() @self.command()
async def danger(ctx): async def danger(ctx):
await ctx.send("That's some dangerous driving! " + self.name_dict["HAM"]) await ctx.send("That's some dangerous driving! " + self.name_dict["HAM"])
@self.command() @self.command()
async def dotd(ctx): async def dotd(ctx):
await ctx.send( "I don't know, probably " + self.name_dict["ALB"] ) await ctx.send("I don't know, probably " + self.name_dict["ALB"])
@self.command() @self.command()
async def flip(ctx): async def flip(ctx):
await ctx.send( random.choice(["Heads","Tails"])) await ctx.send(random.choice(["Heads", "Tails"]))
@self.command() @self.command()
async def gp2(ctx): async def gp2(ctx):
await ctx.send("GP2 engine! GP2! ARGHHH! " + self.name_dict["ALO"]) await ctx.send("GP2 engine! GP2! ARGHHH! " + self.name_dict["ALO"])
@self.command() @self.command()
async def quote(ctx): async def quote(ctx):
try: try:
con = sqlite3.connect('races.db') con = sqlite3.connect('races.db')
cur = con.cursor() cur = con.cursor()
for row in cur.execute('select * from quotes order by Random() limit 1'): for row in cur.execute('select * from quotes order by Random() limit 1'):
message = row[0] + " -- " + row[1] + " " + row[2] message = row[0] + " -- " + row[1] + " " + row[2]
await ctx.send(message) await ctx.send(message)
break # There should only be one row anyway break # There should only be one row anyway
cur.close() cur.close()
con.close() con.close()
@ -871,12 +820,11 @@ class Robottas(commands.Bot):
except: except:
ctx.send("Can't think of a quote for some reason...") ctx.send("Can't think of a quote for some reason...")
@self.command() @self.command()
@commands.has_permissions(administrator=True) @commands.has_permissions(administrator=True)
async def race_watched(ctx, loc, yr): async def race_watched(ctx, loc, yr):
if re.match(self.loc_pattern, loc) and \ if re.match(self.loc_pattern, loc) and \
re.match(self.yr_pattern, yr): re.match(self.yr_pattern, yr):
try: try:
con = sqlite3.connect('races.db') con = sqlite3.connect('races.db')
@ -884,7 +832,7 @@ class Robottas(commands.Bot):
cur.execute('update races ' + cur.execute('update races ' +
'set watched = 1 ' + 'set watched = 1 ' +
'where location = ? ' + 'where location = ? ' +
'year = ?', (loc,yr)) 'year = ?', (loc, yr))
con.commit() con.commit()
cur.close() cur.close()
@ -894,7 +842,6 @@ class Robottas(commands.Bot):
except: except:
await ctx.send(f"Couldn't mark {loc} {yr} as watched for some reason.") await ctx.send(f"Couldn't mark {loc} {yr} as watched for some reason.")
@self.command() @self.command()
async def rand_race(ctx): async def rand_race(ctx):
try: try:
@ -903,7 +850,6 @@ class Robottas(commands.Bot):
for row in cur.execute('select * from races ' + for row in cur.execute('select * from races ' +
'order by Random() ' + 'order by Random() ' +
'limit 1'): 'limit 1'):
watched = self.decode_watched(row[2]) watched = self.decode_watched(row[2])
await ctx.send(f"Location: {row[0]} Year: {row[1]} {watched}") await ctx.send(f"Location: {row[0]} Year: {row[1]} {watched}")
break break
@ -914,7 +860,6 @@ class Robottas(commands.Bot):
except: except:
ctx.send("Can't find a random race for some reason.") ctx.send("Can't find a random race for some reason.")
@self.command() @self.command()
async def rand_race_new(ctx): async def rand_race_new(ctx):
try: try:
@ -924,8 +869,6 @@ class Robottas(commands.Bot):
'where watched = 0 ' + 'where watched = 0 ' +
'order by Random() ' + 'order by Random() ' +
'limit 1'): 'limit 1'):
watched = self.decode_watched(row[2])
await ctx.send(f"Location: {row[0]} Year: {row[1]}") await ctx.send(f"Location: {row[0]} Year: {row[1]}")
break break
@ -935,28 +878,23 @@ class Robottas(commands.Bot):
except: except:
ctx.send("Can't pick a race for some reason.") ctx.send("Can't pick a race for some reason.")
@self.command() @self.command()
async def tyres(ctx): async def tyres(ctx):
await ctx.send("Bono, my tyres are gone " + self.name_dict["HAM"]) await ctx.send("Bono, my tyres are gone " + self.name_dict["HAM"])
# Commands that send images # Commands that send images
@self.command() @self.command()
async def calm(ctx): async def calm(ctx):
await self.send_image(ctx, "images/calm.png") await self.send_image(ctx, "images/calm.png")
@self.command() @self.command()
async def forecast(ctx): async def forecast(ctx):
await self.send_image(ctx, "images/forecast.png") await self.send_image(ctx, "images/forecast.png")
@self.command() @self.command()
async def penalty(ctx): async def penalty(ctx):
await self.send_image(ctx, "images/penalty.png") await self.send_image(ctx, "images/penalty.png")
@self.command() @self.command()
async def undercut(ctx): async def undercut(ctx):
await self.send_image(ctx, "images/undercut.png") await self.send_image(ctx, "images/undercut.png")
@ -965,4 +903,3 @@ class Robottas(commands.Bot):
if __name__ == '__main__': if __name__ == '__main__':
rb = Robottas() rb = Robottas()
rb.run_robottas() rb.run_robottas()