dev-prodId #1

Merged
Taledo merged 22 commits from dev-prodId into main 2026-07-29 08:12:57 +00:00
2 changed files with 99 additions and 93 deletions
Showing only changes of commit 744fcb6ce7 - Show all commits

4
.gitignore vendored
View File

@ -2,6 +2,10 @@
*.token *.token
# Last file # Last file
*.last *.last
# name and url files. not dangerous to share, but not needed.
*.name
*.url
# ---> Python # ---> Python
# Byte-compiled / optimized / DLL files # Byte-compiled / optimized / DLL files

188
main.py
View File

@ -21,11 +21,11 @@ def readToken(filePath):
async def getFromSheet(gsheetToken, data): async def getFromSheet(gsheetToken, data):
params = {"type":data} params = {"type":data}
print(params) #print(params)
async with session.get(gsheetToken, params=params) as response: async with session.get(gsheetToken, params=params) as response:
print("Status:", response.status) #print("Status:", response.status)
text = await response.text() text = await response.text()
print(text) #print(text)
return text return text
@ -33,8 +33,8 @@ async def getFromSheet(gsheetToken, data):
async def postToSheet(data, gsheetToken): async def postToSheet(data, gsheetToken):
async with session.post(gsheetToken, json=data) as response: async with session.post(gsheetToken, json=data) as response:
text = await response.text() text = await response.text()
print(text) #print(text)
print("Status:", response.status) #print("Status:", response.status)
return response.status return response.status
@ -76,19 +76,28 @@ async def getListOfCarriers(state):
return carrierList return carrierList
### used to query the carrier state internally ### used to query the carrier state internally. Why did I make this????
async def getInternalCarrierState(): async def getInternalCarrierState():
response = await getFromSheet(gsheetToken, "carrier") response = await getFromSheet(gsheetToken, "carrier")
return response return response
async def getCarriers(ctx: discord.AutocompleteContext):
state = await getInternalCarrierState()
carrierList = await getListOfCarriers(state)
# print(carrierList)
# return [carrier for carriers in carrierList]
return carrierList
###creates a nice progress bar from two values ###creates a nice progress bar from two values
async def createProgressBar(a,b): async def createProgressBar(a,b):
print(a, b) #print(a, b)
ratio = floor(((b-a)/b) * 10) ratio = floor(((b-a)/b) * 10)
print(ratio) #print(ratio)
progressBar = f"{''* ratio}{'.'*(10-ratio)} ({ratio*10}%)" progressBar = f"{''* ratio}{''*(10-ratio)} {ratio*10}%"
return progressBar return progressBar
@ -138,16 +147,27 @@ async def delLastCommandFile():
open(lastCommandFile, 'w').close() open(lastCommandFile, 'w').close()
bot = commands.Bot() bot = commands.Bot()
# various tokens # various tokens and global vars
discordToken = readToken("discord.token") discordToken = readToken("discord.token")
gsheetToken = readToken("sheet.token") gsheetToken = readToken("sheet.token")
lastCommandFile = "command.last" lastCommandFile = "command.last"
#there's a small chance the files don't exist. If they don't we create an empty file.
try:
with open("station.name", 'r') as f:
stationName = f.readline()
except FileNotFoundError:
open("station.name", 'w').close()
stationName = "REPLACEME"
try:
with open("station.url",'r') as f:
stationUrl = f.readline()
except FileNotFoundError:
open("station.url", 'w').close()
stationUrl = "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
# default command to see if the bot has lived # default command to see if the bot has lived
@bot.listen() @bot.listen()
@ -160,6 +180,7 @@ async def on_connect():
async def on_ready(): async def on_ready():
print("I'm ready, bitch") print("I'm ready, bitch")
writeToWhatsLeftToHaul.start() writeToWhatsLeftToHaul.start()
writeTocarrierState.start()
@ -304,6 +325,8 @@ async def changeSheetUrl(ctx,
url:discord.Option(discord.SlashCommandOptionType.string, description="the new URL") url:discord.Option(discord.SlashCommandOptionType.string, description="the new URL")
): ):
global gsheetToken global gsheetToken
global stationName
global stationURL
await ctx.defer() await ctx.defer()
try: try:
with open("sheet.token",'w') as f: with open("sheet.token",'w') as f:
@ -313,6 +336,20 @@ async def changeSheetUrl(ctx,
gsheetToken = readToken("sheet.token") gsheetToken = readToken("sheet.token")
await delLastCommandFile() await delLastCommandFile()
print("deleted command.last file content") print("deleted command.last file content")
# gets the name and URL from the sheet, then store it in a file so we don't ask the sheet again.
name, url = (await getFromSheet(gsheetToken, "sheet")).split("|")
with open("station.name", 'w') as f:
f.write(name)
stationName = name
with open("station.url", 'w') as f:
f.write(url)
stationURL = url
writeToWhatsLeftToHaul.restart()
except Exception as e: except Exception as e:
await ctx.followup.send(f"something shat the bed") await ctx.followup.send(f"something shat the bed")
@ -322,33 +359,6 @@ async def changeSheetUrl(ctx,
@bot.slash_command(
name="getcarrierstate",
# guild_ids=[401372086746087425],
description= "gets the carriers state from the sheet"
)
async def getCarrierState(ctx):
response = await getInternalCarrierState()
carrierState = await parseCarrierState(response)
await ctx.defer()
text = "Current Carrier State : \n"
for carrier, state in carrierState:
text += f"{carrier} is {state}\n"
await ctx.followup.send(text)
async def getCarriers(ctx: discord.AutocompleteContext):
state = await getInternalCarrierState()
carrierList = await getListOfCarriers(state)
# print(carrierList)
# return [carrier for carriers in carrierList]
return carrierList
@bot.slash_command( @bot.slash_command(
name="setcarrierstate", name="setcarrierstate",
# guild_ids=[401372086746087425], # guild_ids=[401372086746087425],
@ -357,14 +367,15 @@ async def getCarriers(ctx: discord.AutocompleteContext):
@option("carrier", description="The carrier you want to edit", autocomplete=getCarriers) @option("carrier", description="The carrier you want to edit", autocomplete=getCarriers)
@option("state",required=True, description="The carrier you want to edit", choices=["Loading","Unloading","Full","Empty","Inactive"]) @option("state",required=True, description="The carrier you want to edit", choices=["Loading","Unloading","Full","Empty","Inactive"])
async def setCarrierState(ctx, carrier, state): async def setCarrierState(ctx, carrier, state):
response = await getFromSheet(gsheetToken) response = await getFromSheet(gsheetToken, "carrier")
carrierState = await parseCarrierState(response) carrierState = await parseCarrierState(response)
author = str(ctx.author)
newCarrierState = [] newCarrierState = []
print(f"requested values: {carrier} to {state}") #print(f"requested values: {carrier} to {state}")
print(f"current values : {carrierState}") #print(f"current values : {carrierState}")
for carrierS, stateS in carrierState: for carrierS, stateS in carrierState:
if carrier == carrierS: if carrier == carrierS:
@ -372,11 +383,11 @@ async def setCarrierState(ctx, carrier, state):
else: else:
newCarrierState.append((carrierS,stateS)) newCarrierState.append((carrierS,stateS))
print(f"new values : {newCarrierState}") #print(f"new values : {newCarrierState}")
rawState = await toRawState(newCarrierState) rawState = await toRawState(newCarrierState)
print(rawState) #print(rawState)
await ctx.defer() await ctx.defer()
i = 1 i = 1
@ -386,58 +397,21 @@ async def setCarrierState(ctx, carrier, state):
data = { data = {
"postType":"carrier", "postType":"carrier",
"carrierState": rawState "carrierState": rawState
} }
try: try:
response = await postToSheet(data, gsheetToken) response = await postToSheet(data, gsheetToken)
if response == 200: if response == 200:
await ctx.followup.send(f"hey") await ctx.followup.send(f"The carrier {carrier} has been set to {state}")
print(f"{author} set {carrier} state to {state}")
else: else:
await ctx.followup.send(f"i fucked up ") await ctx.followup.send(f"i fucked up ")
except Exception as e: except Exception as e:
await ctx.followup.send(f"help : Error: {e}") await ctx.followup.send(f"help : Error: {e}")
#writes to the whats left to haul channel ever 60 seconds about.. the stuff left to haul.
@bot.slash_command(
name="lefttohaul",
# guild_ids=[401372086746087425],
description= "gets the what's left to haul from the sheet"
)
async def lefttohaul(ctx):
response = await getFromSheet(gsheetToken, "commodity")
await ctx.defer()
text = "\n\n\n### Here's what's left to haul! Get to work!\n"
commodity, values = response.split("|")
commodity = commodity.split(",")
values = values.split(",")
finalDict = {}
for i in range(len(commodity)):
finalDict[commodity[i]] = int(values[i])
finalDict = dict(sorted(finalDict.items(), key=lambda item: item[1], reverse=True))
for key in finalDict:
if finalDict[key] > 0:
text += f"{key} : {finalDict[key]}\n"
await ctx.followup.send(text)
@tasks.loop(seconds=60) @tasks.loop(seconds=60)
async def writeToWhatsLeftToHaul(): async def writeToWhatsLeftToHaul():
response = await getFromSheet(gsheetToken, "commodity") response = await getFromSheet(gsheetToken, "commodity")
@ -452,7 +426,6 @@ async def writeToWhatsLeftToHaul():
values = [int(i) for i in values] values = [int(i) for i in values]
initial = [int (i) for i in initial] initial = [int (i) for i in initial]
print(values, initial)
finalDict = {} finalDict = {}
progressDict = {} progressDict = {}
@ -466,7 +439,6 @@ async def writeToWhatsLeftToHaul():
#finalDict = dict(sorted(finalDict.items(), key=lambda item: item[1], reverse=True)) #finalDict = dict(sorted(finalDict.items(), key=lambda item: item[1], reverse=True))
print(progressDict)
channel = bot.get_channel(1519457137234022460) channel = bot.get_channel(1519457137234022460)
# await channel.purge(limit=1) # await channel.purge(limit=1)
@ -474,12 +446,12 @@ async def writeToWhatsLeftToHaul():
embed = discord.Embed(title="Estimated remaining amounts", embed = discord.Embed(title="Estimated remaining amounts",
colour=discord.Colour(0x29ac08), colour=discord.Colour(0xffdd55),
timestamp=datetime.now()) timestamp=datetime.now())
embed.set_thumbnail(url="https://cdn.discordapp.com/emojis/536647643367997492.png") embed.set_thumbnail(url="https://cdn.discordapp.com/emojis/536647643367997492.png")
embed2 = discord.Embed(title="Current progress", embed2 = discord.Embed(title="Current progress",
colour=discord.Colour(0x29ac08), colour=discord.Colour(0x002f80),
timestamp=datetime.now()) timestamp=datetime.now())
embed2.set_thumbnail(url="https://cdn.discordapp.com/emojis/536647643367997492.png") embed2.set_thumbnail(url="https://cdn.discordapp.com/emojis/536647643367997492.png")
@ -490,10 +462,11 @@ async def writeToWhatsLeftToHaul():
embed2.add_field(name=key, value=str(progressDict[key]), inline=True) embed2.add_field(name=key, value=str(progressDict[key]), inline=True)
embed.set_footer(text="This message updates every 60 seconds(ish). Last updated") embed2.set_footer(text="This message updates every 60 seconds(ish). Last updated")
# if 'station_name' in config.config and 'station_link' in config.config: embed.set_author(name=u'\U0001F517 ' + stationName + u' \U0001F517',
# embed.set_author(name=u'\U0001F517 ' + config.config['station_name'] + u' \U0001F517', url=stationUrl)
# url=config.config['station_link']) embed2.set_author(name=u'\U0001F517 ' + stationName + u' \U0001F517',
url=stationUrl)
channel = bot.get_channel(1519457137234022460) channel = bot.get_channel(1519457137234022460)
@ -510,8 +483,37 @@ async def writeToWhatsLeftToHaul():
#writes the carriers state to... the carrier state channel. Seriously, who is writing this?
@tasks.loop(seconds=60)
async def writeTocarrierState():
response = await getInternalCarrierState()
carrierState = await parseCarrierState(response)
channel = bot.get_channel(1521596285981819101)
embed = discord.Embed(title="Carriers State",
colour=discord.Colour(0x29ac08),
timestamp=datetime.now())
embed.set_thumbnail(url="https://cdn.discordapp.com/emojis/536647643367997492.png")
embed.set_author(name=u'\U0001F517 ' + stationName + u' \U0001F517',
url=stationUrl)
embed.set_footer(text="This message updates every 60 seconds(ish). Last updated")
for carrier, state in carrierState:
embed.add_field(name=carrier, value=state, inline=True)
found = False
async for oldmsg in channel.history(limit=2):
if oldmsg.author == bot.user:
found = True
await oldmsg.edit(embed=embed)
break
if not found:
await channel.send(embed=embed)