This commit is contained in:
tsuk 2024-01-21 00:17:47 -08:00
commit 1e31c286df
4 changed files with 299 additions and 276 deletions

View file

@ -2,6 +2,7 @@ import os
import io import io
import base64 import base64
import time import time
import json
import asyncssh import asyncssh
from PIL import Image, PngImagePlugin from PIL import Image, PngImagePlugin
from discord.ext import commands, tasks from discord.ext import commands, tasks
@ -16,6 +17,7 @@ class PhixxyCom(commands.Cog):
self.working_dir = "tmp/phixxy.com/" self.working_dir = "tmp/phixxy.com/"
self.data_dir = "data/phixxy.com/" self.data_dir = "data/phixxy.com/"
self.folder_setup() self.folder_setup()
self.stable_diffusion_log = "data/stable_diffusion/stable_diffusion.log"
self.phixxy_loop.start() self.phixxy_loop.start()
def folder_setup(self): def folder_setup(self):
@ -27,6 +29,16 @@ class PhixxyCom(commands.Cog):
except: except:
print("PhixxyCom failed to make directories") print("PhixxyCom failed to make directories")
def find_prompt_from_filename(self, sd_log, filename):
with open(sd_log, 'r') as f:
lines = f.readlines()
for line in reversed(lines):
if filename in line:
prompt = line[line.index("Prompt: ") + 7:line.index("Filename: ")]
prompt = ''.join(prompt.rsplit(',', 1)) # Remove the last comma
return prompt
return "Unknown Prompt"
async def upload_sftp(self, local_filename, server_folder, server_filename): async def upload_sftp(self, local_filename, server_folder, server_filename):
remotepath = server_folder + server_filename remotepath = server_folder + server_filename
async with asyncssh.connect(self.SERVER, username=self.USERNAME, password=self.PASSWORD) as conn: async with asyncssh.connect(self.SERVER, username=self.USERNAME, password=self.PASSWORD) as conn:
@ -141,8 +153,7 @@ class PhixxyCom(commands.Cog):
for filename in os.listdir(folder): for filename in os.listdir(folder):
if filename[-4:] == '.png': if filename[-4:] == '.png':
filepath = folder + filename filepath = folder + filename
prompt = "Unknown Prompt" # Will have to update this later prompt = self.find_prompt_from_filename(self.stable_diffusion_log, filename)
html_file = "phixxy.com/ai-images/index.html" html_file = "phixxy.com/ai-images/index.html"
html_insert = '''<!--REPLACE THIS COMMENT--> html_insert = '''<!--REPLACE THIS COMMENT-->
<div> <div>

View file

@ -1,5 +1,4 @@
#plugin file for sparkytron 3000 #plugin file for sparkytron 3000
from discord.ext import commands from discord.ext import commands
import discord import discord
import random import random
@ -7,27 +6,40 @@ import os
import json import json
import math import math
import time import time
import aiohttp
class PokemonGame(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.working_dir = "tmp/pokemon/"
self.data_dir = "data/pokemon/"
self.folder_setup()
async def get_json(url): def folder_setup(self):
http_session = aiohttp.ClientSession() try:
async with http_session.get(url) as resp: if not os.path.exists(self.working_dir):
os.mkdir(self.working_dir)
if not os.path.exists(self.data_dir):
os.mkdir(self.data_dir)
except:
print("PokemonGame failed to make directories")
async def get_json(self, url):
async with self.bot.http_session.get(url) as resp:
json_data = await resp.json() json_data = await resp.json()
return json_data return json_data
@commands.command( @commands.command(
description="Pokemon", description="Pokemon",
help="Pokemon game", help="Pokemon game",
brief="Pokemon Game", brief="Pokemon Game",
aliases=['pkmn'], aliases=['pkmn'],
hidden=True hidden=True
) )
async def pokemon(ctx, arg1=None, arg2=None, arg3=None, arg4=None): async def pokemon(self, ctx, *args):
async def starter_picker(id): #id = pokedex number async def starter_picker(id): #id = pokedex number
url = "https://pokeapi.co/api/v2/pokemon-species/" + str(id) url = "https://pokeapi.co/api/v2/pokemon-species/" + str(id)
json_data = await get_json(url) json_data = await self.get_json(url)
if (json_data["evolves_from_species"] == None) and (not json_data['is_mythical']) and (not json_data['is_legendary']): if (json_data["evolves_from_species"] == None) and (not json_data['is_mythical']) and (not json_data['is_legendary']):
return True return True
else: else:
@ -59,7 +71,7 @@ async def pokemon(ctx, arg1=None, arg2=None, arg3=None, arg4=None):
async def generate_starter(discord_id): async def generate_starter(discord_id):
random.seed(discord_id) random.seed(discord_id)
json_data = await get_json('https://pokeapi.co/api/v2/pokemon-species/') json_data = await self.get_json('https://pokeapi.co/api/v2/pokemon-species/')
pokemon_count = json_data['count'] pokemon_count = json_data['count']
base_pokemon = False base_pokemon = False
while not base_pokemon: while not base_pokemon:
@ -70,7 +82,7 @@ async def pokemon(ctx, arg1=None, arg2=None, arg3=None, arg4=None):
async def get_pkmn_from_id(id): async def get_pkmn_from_id(id):
url = 'https://pokeapi.co/api/v2/pokemon/' + str(id) url = 'https://pokeapi.co/api/v2/pokemon/' + str(id)
json_data = await get_json(url) json_data = await self.get_json(url)
return json_data return json_data
async def give_buddy_food(pkmn_data): async def give_buddy_food(pkmn_data):
@ -127,8 +139,8 @@ async def pokemon(ctx, arg1=None, arg2=None, arg3=None, arg4=None):
embed.add_field(name="Buddy XP", value=buddy_xp, inline=True) embed.add_field(name="Buddy XP", value=buddy_xp, inline=True)
embed.add_field(name="Types", value=type_str, inline=False) embed.add_field(name="Types", value=type_str, inline=False)
return embed return embed
try:
if arg1=='start': if args[0]=='start':
if not os.path.isdir("databases/pokemon/"): if not os.path.isdir("databases/pokemon/"):
os.makedirs("databases/pokemon/") os.makedirs("databases/pokemon/")
if not os.path.isfile("databases/pokemon/"+str(ctx.author.id)+'.json'): if not os.path.isfile("databases/pokemon/"+str(ctx.author.id)+'.json'):
@ -137,7 +149,7 @@ async def pokemon(ctx, arg1=None, arg2=None, arg3=None, arg4=None):
json_data = await get_pkmn_from_id(starter_id) json_data = await get_pkmn_from_id(starter_id)
is_shiny = await shiny_roll() is_shiny = await shiny_roll()
nature = random.randint(0,19) nature = random.randint(0,19)
nature_data = await get_json('https://pokeapi.co/api/v2/nature/') nature_data = await self.get_json('https://pokeapi.co/api/v2/nature/')
nature = nature_data['results'][nature]['name'] nature = nature_data['results'][nature]['name']
json_data['shiny'] = is_shiny json_data['shiny'] = is_shiny
json_data['nickname'] = None json_data['nickname'] = None
@ -155,8 +167,8 @@ async def pokemon(ctx, arg1=None, arg2=None, arg3=None, arg4=None):
await ctx.channel.send("You already have a pokemon!") await ctx.channel.send("You already have a pokemon!")
return return
elif arg1 == 'nick' or arg1 == 'nickname': elif args[0] == 'nick' or args[0] == 'nickname':
nickname = arg2 nickname = args[1]
json_data = await load_pokemon(ctx.author.id) json_data = await load_pokemon(ctx.author.id)
json_data['nickname'] = nickname json_data['nickname'] = nickname
await save_pokemon(ctx.author.id, json_data) await save_pokemon(ctx.author.id, json_data)
@ -164,15 +176,15 @@ async def pokemon(ctx, arg1=None, arg2=None, arg3=None, arg4=None):
await ctx.channel.send(message) await ctx.channel.send(message)
return return
elif arg1 == 'feed': elif args[0] == 'feed':
json_data = await load_pokemon(ctx.author.id) json_data = await load_pokemon(ctx.author.id)
json_data, fed = await give_buddy_food(json_data) json_data, fed = await give_buddy_food(json_data)
if fed: if fed:
await save_pokemon(ctx.author.id, json_data) await save_pokemon(ctx.author.id, json_data)
if json_data['nickname']: if json_data['nickname']:
message = "You " + arg1 + ' ' + json_data['nickname'] message = "You " + args[0] + ' ' + json_data['nickname']
else: else:
message = "You " + arg1 + ' ' + json_data['name'] message = "You " + args[0] + ' ' + json_data['name']
await ctx.channel.send(message) await ctx.channel.send(message)
return return
else: else:
@ -183,15 +195,15 @@ async def pokemon(ctx, arg1=None, arg2=None, arg3=None, arg4=None):
await ctx.channel.send(message) await ctx.channel.send(message)
return return
elif arg1 == 'hug': elif args[0] == 'hug':
json_data = await load_pokemon(ctx.author.id) json_data = await load_pokemon(ctx.author.id)
json_data, hugged = await give_buddy_affection(json_data) json_data, hugged = await give_buddy_affection(json_data)
if hugged: if hugged:
await save_pokemon(ctx.author.id, json_data) await save_pokemon(ctx.author.id, json_data)
if json_data['nickname']: if json_data['nickname']:
message = "You " + arg1 + ' ' + json_data['nickname'] message = "You " + args[0] + ' ' + json_data['nickname']
else: else:
message = "You " + arg1 + ' ' + json_data['name'] message = "You " + args[0] + ' ' + json_data['name']
await ctx.channel.send(message) await ctx.channel.send(message)
return return
else: else:
@ -201,7 +213,7 @@ async def pokemon(ctx, arg1=None, arg2=None, arg3=None, arg4=None):
message = "You hugged " + json_data['name'] + " but " + json_data['name'] + " has been hugged recently." message = "You hugged " + json_data['name'] + " but " + json_data['name'] + " has been hugged recently."
await ctx.channel.send(message) await ctx.channel.send(message)
return return
except:
#Default !pokemon behavior (Load and show pokemon embed) #Default !pokemon behavior (Load and show pokemon embed)
discord_id = ctx.author.id discord_id = ctx.author.id
buddy_json = await load_pokemon(discord_id) buddy_json = await load_pokemon(discord_id)
@ -212,14 +224,29 @@ async def pokemon(ctx, arg1=None, arg2=None, arg3=None, arg4=None):
message = await ctx.channel.send(embed=embed) message = await ctx.channel.send(embed=embed)
return return
@commands.command( async def pkmn_msg(self, discord_id):
path = "databases/pokemon/"+str(discord_id)+'.json'
if os.path.isfile(path):
with open(path, 'r') as f:
json_data = json.loads(f.readline())
json_data['buddy_xp'] += random.randint(1,5)
json_data = json.dumps(json_data)
with open(path, 'w') as f:
f.writelines(json_data)
@commands.Cog.listener()
async def on_message(self, message: discord.Message):
await self.pkmn_msg(message.author.id)
@commands.command(
description="Pokedex", description="Pokedex",
help="Get information on pokemon", help="Get information on pokemon",
brief="Pokedex", brief="Pokedex",
aliases=['pdex'], aliases=['pdex'],
hidden=False hidden=False
) )
async def pokedex(ctx): async def pokedex(self, ctx):
pokemon = ctx.message.content.split(" ", maxsplit=1)[1] pokemon = ctx.message.content.split(" ", maxsplit=1)[1]
try: try:
shiny = False shiny = False
@ -229,7 +256,7 @@ async def pokedex(ctx):
url = "https://pokeapi.co/api/v2/pokemon/" + pokemon url = "https://pokeapi.co/api/v2/pokemon/" + pokemon
dex_url = "https://pokeapi.co/api/v2/pokemon-species/" + pokemon dex_url = "https://pokeapi.co/api/v2/pokemon-species/" + pokemon
#try: #try:
data = await get_json(url) data = await self.get_json(url)
name = data['name'] name = data['name']
height_str = str(int(data['height'])/10) + 'm' height_str = str(int(data['height'])/10) + 'm'
weight_str = str(int(data['weight'])/10) + 'kg' weight_str = str(int(data['weight'])/10) + 'kg'
@ -243,7 +270,7 @@ async def pokedex(ctx):
sprite = data["sprites"]["front_default"] sprite = data["sprites"]["front_default"]
if shiny: if shiny:
sprite = data["sprites"]["front_shiny"] sprite = data["sprites"]["front_shiny"]
dex_data = await get_json(dex_url) dex_data = await self.get_json(dex_url)
generation = dex_data['generation']['name'].upper().replace("GENERATION","Generation") generation = dex_data['generation']['name'].upper().replace("GENERATION","Generation")
for entry in dex_data['flavor_text_entries']: for entry in dex_data['flavor_text_entries']:
if entry['language']['name'] == 'en': if entry['language']['name'] == 'en':
@ -270,5 +297,4 @@ async def pokedex(ctx):
await ctx.channel.send(message) await ctx.channel.send(message)
async def setup(bot): async def setup(bot):
bot.add_command(pokedex) await bot.add_cog(PokemonGame(bot))
bot.add_command(pokemon)

View file

@ -257,11 +257,12 @@ class StableDiffusion(commands.Cog):
folder = self.working_dir + "sfw/" folder = self.working_dir + "sfw/"
except: except:
folder = self.working_dir folder = self.working_dir
my_filename = folder + str(time.time_ns()) + ".png" my_filename = str(time.time_ns()) + ".png"
image.save(my_filename, pnginfo=pnginfo) filepath = folder + my_filename
image.save(filepath, pnginfo=pnginfo)
with open(my_filename, "rb") as fh: with open(filepath, "rb") as fh:
f = discord.File(fh, filename=my_filename) f = discord.File(fh, filename=filepath)
log_data = f'Author: {ctx.author.name}, Prompt: {prompt}, Filename: {my_filename}\n' log_data = f'Author: {ctx.author.name}, Prompt: {prompt}, Filename: {my_filename}\n'
with open(f"{self.data_dir}stable_diffusion.log", 'a') as log_file: with open(f"{self.data_dir}stable_diffusion.log", 'a') as log_file:

View file

@ -8,7 +8,6 @@ import time
import os import os
import asyncio import asyncio
from dotenv import load_dotenv from dotenv import load_dotenv
import aiohttp import aiohttp
#Stable Diffusion #Stable Diffusion
@ -35,7 +34,6 @@ bot = commands.Bot(command_prefix='!', intents=intents)
#discord setup END #discord setup END
async def handle_error(error): async def handle_error(error):
print(error) print(error)
current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
@ -44,6 +42,7 @@ async def handle_error(error):
f.write(log_line) f.write(log_line)
return error return error
def create_channel_config(filepath): def create_channel_config(filepath):
config_dict = { config_dict = {
"personality":"average", "personality":"average",
@ -215,17 +214,6 @@ async def on_reaction_add(reaction, user):
await message.add_reaction(emoji) await message.add_reaction(emoji)
async def pkmn_msg(discord_id):
path = "databases/pokemon/"+str(discord_id)+'.json'
if os.path.isfile(path):
with open(path, 'r') as f:
json_data = json.loads(f.readline())
json_data['buddy_xp'] += random.randint(1,5)
json_data = json.dumps(json_data)
with open(path, 'w') as f:
f.writelines(json_data)
@bot.event @bot.event
async def on_message(ctx): async def on_message(ctx):
#log stuff #log stuff
@ -233,9 +221,6 @@ async def on_message(ctx):
channel_vars = await get_channel_config(ctx.channel.id) channel_vars = await get_channel_config(ctx.channel.id)
chat_history_string = await log_chat_and_get_history(ctx, logfile, channel_vars) chat_history_string = await log_chat_and_get_history(ctx, logfile, channel_vars)
#add pokemon xp
await pkmn_msg(ctx.author.id)
#handle non-text channels (dms, etc) #handle non-text channels (dms, etc)
if ctx.channel.type.value != 0 and ctx.author.id != 242018983241318410: if ctx.channel.type.value != 0 and ctx.author.id != 242018983241318410:
#This used to notify the user it cannot respond in this channel, but that spammed threads #This used to notify the user it cannot respond in this channel, but that spammed threads
@ -243,7 +228,7 @@ async def on_message(ctx):
await react_to_msg(ctx, channel_vars["react_to_msgs"]) #emoji reactions await react_to_msg(ctx, channel_vars["react_to_msgs"]) #emoji reactions
if channel_vars["commands_enabled"] or (ctx.author.id == 242018983241318410 and ctx.content[0] == "!"): if channel_vars["commands_enabled"] or (ctx.author.id == 242018983241318410 and ctx.content[0] == "?"):
await bot.process_commands(ctx) await bot.process_commands(ctx)
if not channel_vars["commands_enabled"]: if not channel_vars["commands_enabled"]:
await ctx.channel.send("This command only ran because you set it to allow to run even when commands are disabled") await ctx.channel.send("This command only ran because you set it to allow to run even when commands are disabled")