patched in a "shell prompt" instead of using discord

This commit is contained in:
Sakimori 2021-07-19 21:57:08 -04:00
parent 47b0d4033f
commit cd52db9cf3
6 changed files with 129 additions and 76 deletions

18
discord_emu.py Normal file
View file

@ -0,0 +1,18 @@
class User():
id = 0
name = "IBM 80"
class Channel():
async def send(obj, text=None, embed=None):
if text is not None:
print(text)
if embed is not None:
print(embed)
class Message():
author = User()
channel = Channel()
class Client():
pass

View file

@ -344,12 +344,13 @@ class league_structure(object):
return int(list(self.schedule.keys())[-1]) * self.series_length return int(list(self.schedule.keys())[-1]) * self.series_length
def standings_embed(self): def standings_embed(self):
this_embed = Embed(color=Color.purple(), title=f"{self.name} Season {self.season}") this_embed = f"{self.name} Season {self.season}\n" #Embed(color=Color.purple(), title=f"{self.name} Season {self.season}")
standings = {} standings = {}
for team_name, wins, losses, run_diff in league_db.get_standings(self.name): for team_name, wins, losses, run_diff in league_db.get_standings(self.name):
standings[team_name] = {"wins" : wins, "losses" : losses, "run_diff" : run_diff} standings[team_name] = {"wins" : wins, "losses" : losses, "run_diff" : run_diff}
for subleague in iter(self.league.keys()): for subleague in iter(self.league.keys()):
this_embed.add_field(name="Conference:", value=f"**{subleague}**", inline = False) this_embed += f"Conference: **{subleague}**"
#this_embed.add_field(name="Conference:", value=f"**{subleague}**", inline = False)
for division in iter(self.league[subleague].keys()): for division in iter(self.league[subleague].keys()):
teams = self.division_standings(self.league[subleague][division], standings) teams = self.division_standings(self.league[subleague][division], standings)
@ -366,9 +367,10 @@ class league_structure(object):
else: else:
teams_string += f"**{this_team[0].name}\n**{this_team[1]} - {this_team[2]} WR: - GB: {this_team[4]}\n\n" teams_string += f"**{this_team[0].name}\n**{this_team[1]} - {this_team[2]} WR: - GB: {this_team[4]}\n\n"
this_embed.add_field(name=f"{division} Division:", value=teams_string, inline = False) this_embed += f"\n{division} Division:" + "\n " + teams_string
#this_embed.add_field(name=f"{division} Division:", value=teams_string, inline = False)
this_embed.set_footer(text=f"Standings as of day {self.day-1} / {self.season_length()}") #this_embed.set_footer(text=f"Standings as of day {self.day-1} / {self.season_length()}")
return this_embed return this_embed
def standings_embed_div(self, division, div_name): def standings_embed_div(self, division, div_name):

23
shell.py Normal file
View file

@ -0,0 +1,23 @@
import the_prestige, asyncio
from discord_emu import *
while True:
first = input("Command: ")
command = []
while first != "":
command.append(first)
first = input(": ")
command_string = ""
for line in command:
command_string += line + "\n"
command_string = command_string[:-1]
try:
comm = next(c for c in the_prestige.commands if command_string.split(" ",1)[0].split("\n",1)[0].lower() == c.name)
asyncio.run(comm.execute(Message(), command_string[len(comm.name):], []))
except the_prestige.CommandError as ce:
print(str(ce))
except:
pass

View file

@ -4,7 +4,7 @@
<SchemaVersion>2.0</SchemaVersion> <SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>2738449b-4b76-4ed0-aa18-3494aaa9e184</ProjectGuid> <ProjectGuid>2738449b-4b76-4ed0-aa18-3494aaa9e184</ProjectGuid>
<ProjectHome>.</ProjectHome> <ProjectHome>.</ProjectHome>
<StartupFile>the_prestige.py</StartupFile> <StartupFile>shell.py</StartupFile>
<SearchPath> <SearchPath>
</SearchPath> </SearchPath>
<WorkingDirectory>.</WorkingDirectory> <WorkingDirectory>.</WorkingDirectory>
@ -33,6 +33,9 @@
<Compile Include="debug storage.py"> <Compile Include="debug storage.py">
<SubType>Code</SubType> <SubType>Code</SubType>
</Compile> </Compile>
<Compile Include="discord_emu.py">
<SubType>Code</SubType>
</Compile>
<Compile Include="gametext.py" /> <Compile Include="gametext.py" />
<Compile Include="leagues.py"> <Compile Include="leagues.py">
<SubType>Code</SubType> <SubType>Code</SubType>
@ -53,6 +56,9 @@
<SubType>Code</SubType> <SubType>Code</SubType>
</Compile> </Compile>
<Compile Include="roman.py" /> <Compile Include="roman.py" />
<Compile Include="shell.py">
<SubType>Code</SubType>
</Compile>
<Compile Include="the_draft.py" /> <Compile Include="the_draft.py" />
<Compile Include="the_prestige.py" /> <Compile Include="the_prestige.py" />
<Compile Include="weather.py" /> <Compile Include="weather.py" />

View file

@ -1,4 +1,5 @@
import discord, json, math, os, roman, games, asyncio, random, main_controller, threading, time, urllib, leagues, datetime, gametext, real_players, archetypes import json, math, os, roman, games, asyncio, random, main_controller, threading, time, urllib, leagues, datetime, gametext, real_players, archetypes
import discord_emu as discord
import database as db import database as db
import onomancer as ono import onomancer as ono
from league_storage import league_exists, season_save, season_restart, get_mods, get_team_mods, set_mods from league_storage import league_exists, season_save, season_restart, get_mods, get_team_mods, set_mods
@ -1715,70 +1716,70 @@ def config():
with open(config_filename) as config_file: with open(config_filename) as config_file:
return json.load(config_file) return json.load(config_file)
@client.event #@client.event
async def on_ready(): #async def on_ready():
global watching # global watching
db.initialcheck() # db.initialcheck()
print(f"logged in as {client.user} with token {config()['token']} to {len(client.guilds)} servers") # print(f"logged in as {client.user} with token {config()['token']} to {len(client.guilds)} servers")
if not watching: # if not watching:
watching = True # watching = True
watch_task = asyncio.create_task(game_watcher()) # watch_task = asyncio.create_task(game_watcher())
await watch_task # await watch_task
@client.event #@client.event
async def on_reaction_add(reaction, user): #async def on_reaction_add(reaction, user):
if reaction.message in setupmessages.keys(): # if reaction.message in setupmessages.keys():
game = setupmessages[reaction.message] # game = setupmessages[reaction.message]
try: # try:
if str(reaction.emoji) == "🔼" and not user == client.user: # if str(reaction.emoji) == "🔼" and not user == client.user:
new_player = games.player(ono.get_stats(db.get_user_player(user)["name"])) # new_player = games.player(ono.get_stats(db.get_user_player(user)["name"]))
game.teams["away"].add_lineup(new_player) # game.teams["away"].add_lineup(new_player)
await reaction.message.channel.send(f"{new_player} {new_player.star_string('batting_stars')} takes spot #{len(game.teams['away'].lineup)} on the away lineup.") # await reaction.message.channel.send(f"{new_player} {new_player.star_string('batting_stars')} takes spot #{len(game.teams['away'].lineup)} on the away lineup.")
elif str(reaction.emoji) == "🔽" and not user == client.user: # elif str(reaction.emoji) == "🔽" and not user == client.user:
new_player = games.player(ono.get_stats(db.get_user_player(user)["name"])) # new_player = games.player(ono.get_stats(db.get_user_player(user)["name"]))
game.teams["home"].add_lineup(new_player) # game.teams["home"].add_lineup(new_player)
await reaction.message.channel.send(f"{new_player} {new_player.star_string('batting_stars')} takes spot #{len(game.teams['home'].lineup)} on the home lineup.") # await reaction.message.channel.send(f"{new_player} {new_player.star_string('batting_stars')} takes spot #{len(game.teams['home'].lineup)} on the home lineup.")
except: # except:
await reaction.message.channel.send(f"{user.display_name}, we can't find your idol. Maybe you don't have one yet?") # await reaction.message.channel.send(f"{user.display_name}, we can't find your idol. Maybe you don't have one yet?")
@client.event #@client.event
async def on_message(msg): #async def on_message(msg):
if msg.author == client.user or not msg.webhook_id is None: # if msg.author == client.user or not msg.webhook_id is None:
return # return
command_b = False # command_b = False
for prefix in config()["prefix"]: # for prefix in config()["prefix"]:
if msg.content.startswith(prefix): # if msg.content.startswith(prefix):
command_b = True # command_b = True
command = msg.content.split(prefix, 1)[1] # command = msg.content.split(prefix, 1)[1]
if not command_b: # if not command_b:
return # return
if msg.channel.id == config()["soulscream channel id"]: # if msg.channel.id == config()["soulscream channel id"]:
await msg.channel.send(ono.get_scream(msg.author.display_name)) # await msg.channel.send(ono.get_scream(msg.author.display_name))
else: # else:
try: # try:
comm = next(c for c in commands if command.split(" ",1)[0].split("\n",1)[0].lower() == c.name) # comm = next(c for c in commands if command.split(" ",1)[0].split("\n",1)[0].lower() == c.name)
send_text = command[len(comm.name):] # send_text = command[len(comm.name):]
first_line = send_text.split("\n")[0] # first_line = send_text.split("\n")[0]
flags = [] # flags = []
if "-" in first_line: # if "-" in first_line:
check = first_line.split("-")[1:] # check = first_line.split("-")[1:]
for flag in [_ for _ in check if _ != ""]: # for flag in [_ for _ in check if _ != ""]:
try: # try:
flags.append((flag.split(" ")[0][0].lower(), flag.split(" ",1)[1].strip())) # flags.append((flag.split(" ")[0][0].lower(), flag.split(" ",1)[1].strip()))
except IndexError: # except IndexError:
flags.append((flag.split(" ")[0][0].lower(), None)) # flags.append((flag.split(" ")[0][0].lower(), None))
if comm.isauthorized(msg.author): #only execute command if authorized # if comm.isauthorized(msg.author): #only execute command if authorized
await comm.execute(msg, send_text, flags) # await comm.execute(msg, send_text, flags)
except StopIteration: # except StopIteration:
await msg.channel.send("Can't find that command, boss; try checking the list with `m;help`.") # await msg.channel.send("Can't find that command, boss; try checking the list with `m;help`.")
except CommandError as ce: # except CommandError as ce:
await msg.channel.send(str(ce)) # await msg.channel.send(str(ce))
async def setup_game(channel, owner, newgame): async def setup_game(channel, owner, newgame):
@ -2226,7 +2227,7 @@ def build_draft_embed(names, title="The Draft", footer="You must choose"):
def build_team_embed(team): def build_team_embed(team):
embed = discord.Embed(color=discord.Color.purple(), title=team.name) # embed = discord.Embed(color=discord.Color.purple(), title=team.name)
lineup_string = "" lineup_string = ""
for player in team.lineup: for player in team.lineup:
lineup_string += f"{player.name} {player.star_string('batting_stars')}\n" lineup_string += f"{player.name} {player.star_string('batting_stars')}\n"
@ -2234,15 +2235,15 @@ def build_team_embed(team):
rotation_string = "" rotation_string = ""
for player in team.rotation: for player in team.rotation:
rotation_string += f"{player.name} {player.star_string('pitching_stars')}\n" rotation_string += f"{player.name} {player.star_string('pitching_stars')}\n"
embed.add_field(name="Rotation:", value=rotation_string, inline = False) #embed.add_field(name="Rotation:", value=rotation_string, inline = False)
embed.add_field(name="Lineup:", value=lineup_string, inline = False) #embed.add_field(name="Lineup:", value=lineup_string, inline = False)
embed.add_field(name="█a██:", value=str(abs(hash(team.name)) % (10 ** 4))) #embed.add_field(name="█a██:", value=str(abs(hash(team.name)) % (10 ** 4)))
embed.set_footer(text=team.slogan) #embed.set_footer(text=team.slogan)
return embed return lineup_string + "\n" + rotation_string
def build_star_embed(player_json): def build_star_embed(player_json):
starkeys = {"batting_stars" : "Batting", "pitching_stars" : "Pitching", "baserunning_stars" : "Baserunning", "defense_stars" : "Defense"} starkeys = {"batting_stars" : "Batting", "pitching_stars" : "Pitching", "baserunning_stars" : "Baserunning", "defense_stars" : "Defense"}
embed = discord.Embed(color=discord.Color.purple(), title=player_json["name"]) #embed = discord.Embed(color=discord.Color.purple(), title=player_json["name"])
if player_json["name"] == "Tim Locastro": #the tim easter egg if player_json["name"] == "Tim Locastro": #the tim easter egg
for key in ["batting_stars", "pitching_stars", "baserunning_stars", "defense_stars"]: for key in ["batting_stars", "pitching_stars", "baserunning_stars", "defense_stars"]:
@ -2253,18 +2254,21 @@ def build_star_embed(player_json):
stars = half_star + 0.5 stars = half_star + 0.5
player_json[key] = stars player_json[key] = stars
text = player_json["name"] + "\n"
for key in starkeys.keys(): for key in starkeys.keys():
embedstring = "" embedstring = ""
starstring = str(player_json[key]) starstring = str(player_json[key])
starnum = int(starstring[0]) starnum = int(starstring[0])
addhalf = ".5" in starstring addhalf = ".5" in starstring
embedstring += "" * starnum embedstring += "H" * starnum
if addhalf: if addhalf:
embedstring += "" embedstring += "n"
elif starnum == 0: # why check addhalf twice, amirite elif starnum == 0: # why check addhalf twice, amirite
embedstring += "⚪️" embedstring += "O"
embed.add_field(name=starkeys[key], value=embedstring, inline=False) text += starkeys[key] + "\n " + embedstring + "\n"
return embed #embed.add_field(name=starkeys[key], value=embedstring, inline=False)
return text
def team_from_collection(newteam_json): def team_from_collection(newteam_json):
# verify collection against our own restrictions # verify collection against our own restrictions
@ -2785,4 +2789,4 @@ async def league_subscriber_update(league, start_channel, message):
else: else:
await channel.send(message) await channel.send(message)
client.run(config()["token"]) #client.run(config()["token"])

View file

@ -635,7 +635,7 @@ class WeatherChains():
magic = [Twilight, ThinnedVeil, MeteorShower, Starlight, Dusk] #weathers involving breaking the fabric of spacetime magic = [Twilight, ThinnedVeil, MeteorShower, Starlight, Dusk] #weathers involving breaking the fabric of spacetime
sudden = [Tornado, Hurricane, Twilight, Starlight, Midnight, Downpour, Smog] #weathers that always happen and leave over 1-3 games sudden = [Tornado, Hurricane, Twilight, Starlight, Midnight, Downpour, Smog] #weathers that always happen and leave over 1-3 games
disaster = [Hurricane, Tornado, Downpour, Blizzard] #storms disaster = [Hurricane, Tornado, Downpour, Blizzard] #storms
aftermath = [Midnight, Starlight, MeteorShower, SummerMist, LeafEddies, Dusk] #calm epilogues aftermath = [Midnight, Starlight, MeteorShower, SummerMist, Dusk] #calm epilogues
dictionary = { dictionary = {
#Supernova : (magic + sudden + disaster, None), supernova happens leaguewide and shouldn't need a chain, but here just in case #Supernova : (magic + sudden + disaster, None), supernova happens leaguewide and shouldn't need a chain, but here just in case