Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,176 +2,199 @@ import asyncio
|
|
| 2 |
import json
|
| 3 |
import os
|
| 4 |
import threading
|
| 5 |
-
from threading import Event
|
| 6 |
|
| 7 |
import discord
|
| 8 |
import gradio as gr
|
| 9 |
from discord.ext import commands
|
| 10 |
from gradio_client import Client
|
| 11 |
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
intents = discord.Intents.all()
|
| 19 |
bot = commands.Bot(command_prefix="/", intents=intents)
|
| 20 |
|
|
|
|
| 21 |
|
| 22 |
@bot.event
|
| 23 |
async def on_ready():
|
| 24 |
print(f"Logged in as {bot.user} (ID: {bot.user.id})")
|
| 25 |
synced = await bot.tree.sync()
|
| 26 |
print(f"Synced commands: {', '.join([s.name for s in synced])}.")
|
| 27 |
-
|
| 28 |
print("------")
|
| 29 |
|
| 30 |
|
| 31 |
@bot.hybrid_command(
|
| 32 |
-
name="
|
| 33 |
-
description="Enter a prompt to
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
)
|
| 35 |
-
async def
|
| 36 |
-
"""
|
| 37 |
try:
|
| 38 |
-
await
|
| 39 |
except Exception as e:
|
| 40 |
print(f"Error: {e}")
|
| 41 |
|
| 42 |
|
| 43 |
@bot.event
|
| 44 |
async def on_message(message):
|
| 45 |
-
"""Checks channel and continues
|
| 46 |
try:
|
| 47 |
-
if not message.author.bot:
|
| 48 |
-
await
|
| 49 |
except Exception as e:
|
| 50 |
print(f"Error: {e}")
|
| 51 |
|
| 52 |
-
|
| 53 |
-
async def
|
| 54 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
try:
|
| 56 |
-
if ctx.guild.id =
|
| 57 |
-
|
| 58 |
-
return
|
| 59 |
-
global codellama_threadid_userid_dictionary
|
| 60 |
-
global codellama_threadid_conversation
|
| 61 |
|
| 62 |
message = await ctx.send(f"**{prompt}** - {ctx.author.mention}")
|
| 63 |
-
|
|
|
|
|
|
|
|
|
|
| 64 |
|
| 65 |
-
|
| 66 |
-
output_code = await
|
| 67 |
-
codellama_threadid_userid_dictionary[thread.id] = ctx.author.id
|
| 68 |
await thread.send(output_code)
|
| 69 |
except Exception as e:
|
| 70 |
print(f"Error: {e}")
|
| 71 |
|
| 72 |
-
|
| 73 |
-
def codellama_initial_generation(prompt, thread):
|
| 74 |
"""Job.submit inside of run_in_executor = more consistent bot behavior"""
|
| 75 |
-
global
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
with open(
|
| 80 |
-
json.dump(
|
| 81 |
-
|
| 82 |
-
job =
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
try:
|
| 104 |
if not message.author.bot:
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
with open(chat_history, "r") as json_file:
|
| 115 |
-
conversation = json.load(json_file)
|
| 116 |
-
total_characters = 0
|
| 117 |
-
for item in conversation:
|
| 118 |
-
for string in item:
|
| 119 |
-
total_characters += len(string)
|
| 120 |
-
|
| 121 |
-
if total_characters < 15000:
|
| 122 |
-
job = codellama_client.submit(prompt, chat_history, fn_index=0)
|
| 123 |
-
while job.done() is False:
|
| 124 |
-
pass
|
| 125 |
-
else:
|
| 126 |
-
result = job.outputs()[-1]
|
| 127 |
-
with open(result, "r") as json_file:
|
| 128 |
-
data = json.load(json_file)
|
| 129 |
-
response = data[-1][-1]
|
| 130 |
-
with open(chat_history, "r") as json_file:
|
| 131 |
-
conversation = json.load(json_file)
|
| 132 |
-
conversation.append((prompt, response))
|
| 133 |
-
with open(chat_history, "w") as json_file:
|
| 134 |
-
json.dump(conversation, json_file)
|
| 135 |
-
codellama_threadid_conversation[message.channel.id] = chat_history
|
| 136 |
-
|
| 137 |
-
if len(response) > 1300:
|
| 138 |
-
response = response[:1300] + "...\nTruncating response due to discord api limits."
|
| 139 |
-
|
| 140 |
-
await message.reply(response)
|
| 141 |
-
|
| 142 |
-
total_characters = 0
|
| 143 |
-
for item in conversation:
|
| 144 |
-
for string in item:
|
| 145 |
-
total_characters += len(string)
|
| 146 |
-
|
| 147 |
-
if total_characters >= 15000:
|
| 148 |
-
await message.reply("Conversation ending due to length, feel free to start a new one!")
|
| 149 |
-
|
| 150 |
-
except Exception as e:
|
| 151 |
-
print(f"Error: {e}")
|
| 152 |
|
|
|
|
| 153 |
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
print("DISCORD_TOKEN NOT SET")
|
| 157 |
-
event.set()
|
| 158 |
-
else:
|
| 159 |
-
bot.run(DISCORD_TOKEN)
|
| 160 |
|
|
|
|
| 161 |
|
| 162 |
-
|
| 163 |
-
|
| 164 |
|
| 165 |
welcome_message = """
|
| 166 |
## Add this bot to your server by clicking this link:
|
| 167 |
|
| 168 |
-
https://discord.com/
|
| 169 |
|
| 170 |
## How to use it?
|
| 171 |
|
| 172 |
-
The bot can be triggered via `/
|
| 173 |
-
|
| 174 |
-
|
| 175 |
|
| 176 |
To continue the conversation, simply ask additional questions in the thread - no need for repeating the command!
|
| 177 |
|
|
@@ -181,10 +204,16 @@ To continue the conversation, simply ask additional questions in the thread - no
|
|
| 181 |
"""
|
| 182 |
|
| 183 |
|
| 184 |
-
with gr.Blocks() as
|
| 185 |
gr.Markdown(f"""
|
| 186 |
-
# Discord bot
|
| 187 |
{welcome_message}
|
| 188 |
""")
|
| 189 |
|
| 190 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
import json
|
| 3 |
import os
|
| 4 |
import threading
|
|
|
|
| 5 |
|
| 6 |
import discord
|
| 7 |
import gradio as gr
|
| 8 |
from discord.ext import commands
|
| 9 |
from gradio_client import Client
|
| 10 |
|
| 11 |
+
bot_ready = asyncio.Event()
|
| 12 |
+
DISCORD_BOT_TOKEN = os.environ.get("DISCORD_BOT_TOKEN")
|
| 13 |
+
if DISCORD_BOT_TOKEN is None:
|
| 14 |
+
raise ValueError("DISCORD_BOT_TOKEN environment variable is not set")
|
| 15 |
+
|
| 16 |
+
HF_TOKEN = os.environ.get("HF_TOKEN", None)
|
| 17 |
+
if HF_TOKEN is None:
|
| 18 |
+
raise ValueError("HF_TOKEN environment variable is not set")
|
| 19 |
+
|
| 20 |
+
# Bot use is restricted to this guild
|
| 21 |
+
CHAINCRAFT_GUILD_ID = os.environ.get("CHAINCRAFT_GUILD_ID", None)
|
| 22 |
+
if CHAINCRAFT_GUILD_ID is None:
|
| 23 |
+
raise ValueError("CHAINCRAFT_GUILD_ID environment variable is not set")
|
| 24 |
+
|
| 25 |
+
chaincraft_client = Client("ericwood73/ChainCraft", HF_TOKEN)
|
| 26 |
+
|
| 27 |
intents = discord.Intents.all()
|
| 28 |
bot = commands.Bot(command_prefix="/", intents=intents)
|
| 29 |
|
| 30 |
+
active_chaincraft_threads = set()
|
| 31 |
|
| 32 |
@bot.event
|
| 33 |
async def on_ready():
|
| 34 |
print(f"Logged in as {bot.user} (ID: {bot.user.id})")
|
| 35 |
synced = await bot.tree.sync()
|
| 36 |
print(f"Synced commands: {', '.join([s.name for s in synced])}.")
|
| 37 |
+
bot_ready.set()
|
| 38 |
print("------")
|
| 39 |
|
| 40 |
|
| 41 |
@bot.hybrid_command(
|
| 42 |
+
name="chaincraft",
|
| 43 |
+
description="Enter a prompt to design a game!",
|
| 44 |
+
)
|
| 45 |
+
async def chaincraft_design(ctx, prompt: str):
|
| 46 |
+
"""Chaincraft design generation"""
|
| 47 |
+
try:
|
| 48 |
+
await try_chaincraft_design(ctx, prompt, private=False)
|
| 49 |
+
except Exception as e:
|
| 50 |
+
print(f"Error: {e}")
|
| 51 |
+
|
| 52 |
+
@bot.hybrid_command(
|
| 53 |
+
name="chaincraft_pvt",
|
| 54 |
+
description="Enter a prompt to design a game privately!",
|
| 55 |
)
|
| 56 |
+
async def chaincraft_design_private(ctx, prompt: str):
|
| 57 |
+
"""Chaincraft design generation in a private thread"""
|
| 58 |
try:
|
| 59 |
+
await try_chaincraft_design(ctx, prompt, private=True)
|
| 60 |
except Exception as e:
|
| 61 |
print(f"Error: {e}")
|
| 62 |
|
| 63 |
|
| 64 |
@bot.event
|
| 65 |
async def on_message(message):
|
| 66 |
+
"""Checks channel and continues chaincraft conversation if it's the right Discord Thread"""
|
| 67 |
try:
|
| 68 |
+
if not message.author.bot and message.channel.id in active_chaincraft_threads:
|
| 69 |
+
await continue_chaincraft(message)
|
| 70 |
except Exception as e:
|
| 71 |
print(f"Error: {e}")
|
| 72 |
|
| 73 |
+
@bot.event
|
| 74 |
+
async def on_button_click(interaction):
|
| 75 |
+
"""Handle a button click"""
|
| 76 |
+
if interaction.component.label == "Approve":
|
| 77 |
+
# If the "Approve" button was clicked, treat this as an approval
|
| 78 |
+
await continue_chaincraft("", approved=True)
|
| 79 |
+
await interaction.respond(type=InteractionType.ChannelMessageWithSource, content="Approved!")
|
| 80 |
+
|
| 81 |
+
async def try_chaincraft_design(ctx, prompt, private):
|
| 82 |
+
"""Generates a game design based on a given prompt"""
|
| 83 |
try:
|
| 84 |
+
if ctx.guild.id != CHAINCRAFT_GUILD_ID:
|
| 85 |
+
return
|
|
|
|
|
|
|
|
|
|
| 86 |
|
| 87 |
message = await ctx.send(f"**{prompt}** - {ctx.author.mention}")
|
| 88 |
+
if private:
|
| 89 |
+
thread = await message.create_thread(name=prompt[:100], type=discord.ChannelType.private_thread)
|
| 90 |
+
else:
|
| 91 |
+
thread = await message.create_thread(name=prompt[:100])
|
| 92 |
|
| 93 |
+
active_chaincraft_threads.add(thread.id)
|
| 94 |
+
output_code = await chaincraft_initial_generation(prompt, thread)
|
|
|
|
| 95 |
await thread.send(output_code)
|
| 96 |
except Exception as e:
|
| 97 |
print(f"Error: {e}")
|
| 98 |
|
| 99 |
+
async def chaincraft_execute(prompt, thread):
|
|
|
|
| 100 |
"""Job.submit inside of run_in_executor = more consistent bot behavior"""
|
| 101 |
+
global chaincraft_threadid_state
|
| 102 |
+
|
| 103 |
+
state_json = f"{thread.id}.json"
|
| 104 |
+
state = {}
|
| 105 |
+
with open(state_json, "w") as json_file:
|
| 106 |
+
json.dump(state, json_file)
|
| 107 |
+
|
| 108 |
+
job = chaincraft_client.submit(
|
| 109 |
+
user_message=prompt,
|
| 110 |
+
approved=False,
|
| 111 |
+
current_state=state,
|
| 112 |
+
api_name="/submit_design_ui_input"
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
while not job.done():
|
| 116 |
+
await asyncio.sleep(1) # non-blocking sleep
|
| 117 |
+
|
| 118 |
+
(game_specification, ai_questions, updated_state) = job.outputs()
|
| 119 |
+
|
| 120 |
+
with open(state_json, "w") as json_file:
|
| 121 |
+
json.dump(updated_state, json_file)
|
| 122 |
+
|
| 123 |
+
chaincraft_threadid_state[thread.id] = state_json
|
| 124 |
+
output_message = f"""
|
| 125 |
+
Game Design Specification:
|
| 126 |
+
{game_specification}
|
| 127 |
+
AI Questions:
|
| 128 |
+
{ai_questions}
|
| 129 |
+
"""
|
| 130 |
+
|
| 131 |
+
# Create an "Approve" button
|
| 132 |
+
approve_button = Button(style=ButtonStyle.green, label="Approve")
|
| 133 |
+
|
| 134 |
+
# Send the message with the button
|
| 135 |
+
await thread.send(content=output_message, components=[approve_button])
|
| 136 |
+
|
| 137 |
+
def get_state(thread):
|
| 138 |
+
# Get the state of the thread from the json file
|
| 139 |
+
state_json = f"{thread.id}.json"
|
| 140 |
+
try:
|
| 141 |
+
with open(state_json, "r") as json_file:
|
| 142 |
+
state = json.load(json_file)
|
| 143 |
+
except FileNotFoundError:
|
| 144 |
+
# If the file doesn't exist, return an empty state
|
| 145 |
+
state = {}
|
| 146 |
+
return state
|
| 147 |
+
|
| 148 |
+
def end_chaincraft(thread):
|
| 149 |
+
# Remove the thread from the active threads
|
| 150 |
+
active_chaincraft_threads.remove(thread.id)
|
| 151 |
+
|
| 152 |
+
# Remove the state file
|
| 153 |
+
state_json = f"{thread.id}.json"
|
| 154 |
+
if os.path.exists(state_json):
|
| 155 |
+
os.remove(state_json)
|
| 156 |
+
|
| 157 |
+
def chaincraft_initial_generation(prompt, thread):
|
| 158 |
+
return chaincraft_execute(prompt, thread)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
async def continue_chaincraft(message, approved=False):
|
| 162 |
+
"""Continues an in-progress ChainCraft design conversation. If approved, ends the conversation."""
|
| 163 |
+
if approved:
|
| 164 |
+
end_chaincraft(message.channel)
|
| 165 |
+
await message.reply("The game design has been approved and the conversation has ended.")
|
| 166 |
try:
|
| 167 |
if not message.author.bot:
|
| 168 |
+
prompt = message.content
|
| 169 |
+
state = get_state(message.channel)
|
| 170 |
+
|
| 171 |
+
# Check to see if conversation is ongoing or ended (approved=true)
|
| 172 |
+
state = json.loads(state)
|
| 173 |
+
if not state or state["approved"]:
|
| 174 |
+
end_chaincraft(message.channel)
|
| 175 |
+
await message.reply("The game design has been approved and the conversation has ended.")
|
| 176 |
+
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 177 |
|
| 178 |
+
response = await chaincraft_execute(prompt, message.channel)
|
| 179 |
|
| 180 |
+
if len(response) > 2000:
|
| 181 |
+
response = response[:2000] + "...\nTruncating response due to discord api limits."
|
|
|
|
|
|
|
|
|
|
|
|
|
| 182 |
|
| 183 |
+
await message.reply(response)
|
| 184 |
|
| 185 |
+
except Exception as e:
|
| 186 |
+
print(f"Error: {e}")
|
| 187 |
|
| 188 |
welcome_message = """
|
| 189 |
## Add this bot to your server by clicking this link:
|
| 190 |
|
| 191 |
+
https://discord.com/oauth2/authorize?client_id=1248694575930015885&permissions=377957125120&integration_type=0&scope=bot
|
| 192 |
|
| 193 |
## How to use it?
|
| 194 |
|
| 195 |
+
The bot can be triggered via `/chaincraft` followed by your text prompt. This will open a new thread in the channel where
|
| 196 |
+
the command was issued. Other users will be able to see the thread and participate in the conversation. Don't want other
|
| 197 |
+
users ruining your game design? Use `/chaincraft_pvt` instead to launch the conversation in a private thread.
|
| 198 |
|
| 199 |
To continue the conversation, simply ask additional questions in the thread - no need for repeating the command!
|
| 200 |
|
|
|
|
| 204 |
"""
|
| 205 |
|
| 206 |
|
| 207 |
+
with gr.Blocks() as bot_app:
|
| 208 |
gr.Markdown(f"""
|
| 209 |
+
# Discord bot for ChainCraft
|
| 210 |
{welcome_message}
|
| 211 |
""")
|
| 212 |
|
| 213 |
+
async def run_bot():
|
| 214 |
+
await bot.start(DISCORD_BOT_TOKEN)
|
| 215 |
+
await bot_ready.wait()
|
| 216 |
+
|
| 217 |
+
threading.Thread(target=bot_app.launch).start()
|
| 218 |
+
|
| 219 |
+
asyncio.run(run_bot())
|