import asyncio import json import sys import os import threading from dotenv import load_dotenv from discord import Intents, ChannelType, ButtonStyle, Interaction from discord.ext import commands from discord.ui import View, button, Button import gradio as gr from gradio_client import Client load_dotenv() bot_ready = asyncio.Event() DISCORD_BOT_TOKEN = os.environ.get("CHAINCRAFT_DISCORD_BOT_TOKEN") if DISCORD_BOT_TOKEN is None: raise ValueError("CHAINCRAFT_DISCORD_BOT_TOKEN environment variable is not set") HF_TOKEN = os.environ.get("CHAINCRAFT_HF_ACCESS_TOKEN", None) if HF_TOKEN is None: raise ValueError("CHAINCRAFT_HF_ACCESS_TOKEN environment variable is not set") # Bot use is restricted to this guild CHAINCRAFT_GUILD_ID = os.environ.get("CHAINCRAFT_GUILD_ID", None) if CHAINCRAFT_GUILD_ID is None: raise ValueError("CHAINCRAFT_GUILD_ID environment variable is not set") chaincraft_client = Client("ericwood73/ChainCraft", hf_token=HF_TOKEN) intents = Intents.default() intents.message_content = True bot = commands.Bot(command_prefix="/", intents=intents) active_chaincraft_threads = set() approve_button_custom_id = "btn_approve" command_name = os.environ.get("CHAINCRAFT_COMMAND_NAME", "chaincraft") class ApproveButton(View): def __init__(self, thread): super().__init__() self.thread = thread @button(style=ButtonStyle.green, label="Approve") async def approve(self, interaction: Interaction, _: Button): end_chaincraft(self.thread) await interaction.response.send_message('Approved!', ephemeral=True) await self.thread.send("The game design has been approved and the conversation has ended.") self.value = True self.stop() @bot.event async def on_ready(): print(f"Logged in as {bot.user} (ID: {bot.user.id})") synced = await bot.tree.sync() print(f"Synced commands: {', '.join([s.name for s in synced])}.") bot_ready.set() print("------") @bot.hybrid_command( name=command_name, description="Enter a prompt to design a game!", ) async def chaincraft_design(ctx, prompt: str): """Chaincraft design generation""" try: await try_chaincraft_design(ctx, prompt, private=False) except Exception as e: print(f"Error: {e}") @bot.hybrid_command( name=f"{command_name}_pvt", description="Enter a prompt to design a game privately!", ) async def chaincraft_design_private(ctx, prompt: str): """Chaincraft design generation in a private thread""" try: await try_chaincraft_design(ctx, prompt, private=True) except Exception as e: print(f"Error: {e}") @bot.event async def on_message(message): """Checks channel and continues chaincraft conversation if it's the right Discord Thread""" try: if not message.author.bot and message.channel.id in active_chaincraft_threads: await continue_chaincraft(message) except Exception as e: print(f"Error handling message {message.content}: {e}") async def try_chaincraft_design(ctx, prompt, private): """Generates a game design based on a given prompt""" try: if ctx.guild.id != int(CHAINCRAFT_GUILD_ID): return thread_msg = f"**{prompt}** - {ctx.author.mention}" if private: try: thread = await ctx.channel.create_thread(name=prompt[:100], type=ChannelType.private_thread) await ctx.send(f"{thread_msg}. Private thread created. [Click here to jump to the thread.](<{thread.jump_url}>)") # Send confirmation message with thread link await thread.add_user(bot.user) # Add the bot to the thread await thread.send(thread_msg) except Exception as e: print(f"Error creating private thread: {e}") return else: try: message = await ctx.send(thread_msg) thread = await message.create_thread(name=prompt[:100]) except Exception as e: print(f"Error creating public thread: {e}") return active_chaincraft_threads.add(thread.id) await chaincraft_initial_generation(prompt, thread) except Exception as e: print(f"Error in try_chaincraft_design: {e}") async def chaincraft_execute(prompt, thread): """Job.submit inside of run_in_executor = more consistent bot behavior""" state = get_state(thread) try: job = chaincraft_client.submit( user_message=prompt, approved=False, current_state=json.dumps(state), api_name="/submit_design_ui_input" ) except Exception as e: print(f"Error executing chaincraft: {e}") return while not job.done(): await asyncio.sleep(1) # non-blocking sleep response = job.outputs() if not response: await thread.send("I'm sorry, I couldn't generate a response. Please try again.") end_chaincraft(thread) return (game_specification, ai_questions, updated_state) = response[-1] set_state(thread, updated_state) output_message = f""" Game Design Specification: {game_specification} AI Questions: {ai_questions} """ approve_button_view = ApproveButton(thread) # If the response is longer than 2000 characters, split it into chunks chunks = [] continuation_message = "\n...Continued in next message..." while len(output_message) > 2000: split_index = output_message[:2000 - len(continuation_message)].rfind('\n') if split_index == -1: # No line break found split_index = 2000 - len(continuation_message) chunks.append(output_message[:split_index]) output_message = output_message[split_index:] chunks.append(output_message) # Append the last chunk async def send_chunks(thread, chunks, approve_button_view, continuation_message): for i in range(len(chunks)): # If this is not the last chunk, add a note that more is coming if i != len(chunks) - 1: chunks[i] += continuation_message await thread.send(chunks[i]) else: # Send the last message with the button await thread.send(content=chunks[i], view=approve_button_view) try: await send_chunks(thread, chunks, approve_button_view, continuation_message) except Exception as e: print(f"Error sending chunks: {e}") def get_state(thread): # Get the state of the thread from the json file state_json = f"{thread.id}.json" try: with open(state_json, "r") as json_file: state = json.load(json_file) except FileNotFoundError: # If the file doesn't exist, return an empty state state = {} return state def set_state(thread, state_json): # Set the state of the thread in the json file state_json_file = f"{thread.id}.json" with open(state_json_file, "w") as json_file: if isinstance(state_json, str): json_file.write(state_json) else: json.dump(state_json, json_file) def end_chaincraft(thread): # Remove the thread from the active threads active_chaincraft_threads.remove(thread.id) # Remove the state file state_json = f"{thread.id}.json" if os.path.exists(state_json): os.remove(state_json) async def chaincraft_initial_generation(prompt, thread): await chaincraft_execute(prompt, thread) async def continue_chaincraft(message): """Continues an in-progress ChainCraft design conversation. If approved, ends the conversation.""" try: if not message.author.bot: prompt = message.content state = get_state(message.channel) # Check to see if conversation is ongoing or ended (approved=true) if not state or state["approved"]: end_chaincraft(message.channel) await message.reply("The game design has been approved and the conversation has ended.") return await chaincraft_execute(prompt, message.channel) except Exception as e: print(f"Error continuing chaincraft conversation: {e}") welcome_message = """ ## Add this bot to your server by clicking this link: https://discord.com/oauth2/authorize?client_id=1248694575930015885&permissions=377957125120&integration_type=0&scope=bot ## How to use it? The bot can be triggered via `/chaincraft` followed by your text prompt. This will open a new thread in the channel where the command was issued. Other users will be able to see the thread and participate in the conversation. Don't want other users ruining your game design? Use `/chaincraft_pvt` instead to launch the conversation in a private thread. To continue the conversation, simply ask additional questions in the thread - no need for repeating the command! ⚠️ Note ⚠️: Please make sure this bot's command does have the same name as another command in your server. ⚠️ Note ⚠️: Bot commands do not work in DMs with the bot as of now. """ def run_gradio_app(): with gr.Blocks() as bot_app: gr.Markdown(f""" # Discord bot for ChainCraft {welcome_message} """) bot_app.launch() print("Gradio app start") # Create a new thread for the gradio app gradio_thread = threading.Thread(target=run_gradio_app) gradio_thread.start() # asyncio.run(run_bot()) bot.run(DISCORD_BOT_TOKEN)