MINEOGO's picture
Update app.py
d65737b verified
raw
history blame
4.09 kB
import discord
import os
import json
import sys
import random
from dotenv import load_dotenv
from huggingface_hub import InferenceClient
from datetime import datetime
# Load token from .env
load_dotenv()
TOKEN = os.getenv("BOT_TOKEN")
# Hugging Face client setup
client_ai = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
# Discord client setup
intents = discord.Intents.default()
intents.messages = True
intents.message_content = True
bot = discord.Client(intents=intents)
# Settings for AI generation
SYSTEM_PROMPT = "You are a helpful and friendly chatbot."
MAX_TOKENS = 512
TEMPERATURE = 0.7
TOP_P = 0.95
# Create data folder if it doesn't exist
os.makedirs("data", exist_ok=True)
CONVERSATION_LOG = "data/conversations.jsonl"
# === Functions ===
async def get_ai_response(message_content):
messages = [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": message_content}
]
full_response = ""
for part in client_ai.chat_completion(
messages,
max_tokens=MAX_TOKENS,
stream=True,
temperature=TEMPERATURE,
top_p=TOP_P,
):
if part.choices[0].delta.content:
full_response += part.choices[0].delta.content
return full_response
def save_conversation(user_message, bot_response):
log_entry = {
"timestamp": datetime.utcnow().isoformat(),
"user_message": user_message,
"bot_response": bot_response
}
with open(CONVERSATION_LOG, "a", encoding="utf-8") as f:
f.write(json.dumps(log_entry) + "\n")
def generate_dynamic_command():
"""Generate a command name and response dynamically"""
command_name = f"command_{random.randint(1000, 9999)}"
response_text = f"This is a dynamically generated command named '{command_name}'."
# Creating the new command and appending it to app.py
command_code = f"""
@bot.event
async def on_message(message):
if message.author == bot.user:
return
if message.content.startswith('!{command_name}'):
await message.channel.send("{response_text}")
"""
try:
# Append to app.py
with open("app.py", "a", encoding="utf-8") as f:
f.write(command_code)
print(f"Successfully added the command '!{command_name}' to app.py")
# Optional: Reload bot after adding command
os.execv(sys.executable, ['python'] + sys.argv)
except Exception as e:
print(f"Error while adding command to app.py: {e}")
# === Error Handling and Diagnosis ===
def diagnose_and_save_error(error_message):
"""Function to diagnose and log errors into app.py for future review"""
log_entry = {
"timestamp": datetime.utcnow().isoformat(),
"error_message": error_message
}
with open("app.py", "a", encoding="utf-8") as f:
f.write("\n# Error Log\n")
f.write(json.dumps(log_entry) + "\n")
# === Events ===
@bot.event
async def on_ready():
print(f"Bot is running in background as {bot.user}")
@bot.event
async def on_message(message):
# Ignore own messages
if message.author == bot.user:
return
# Trigger to create a new dynamic command based on some interaction
if "generate" in message.content.lower(): # You can change the condition here
print("Generating a new command based on interaction!")
generate_dynamic_command()
# Example: normal AI chat
try:
user_input = message.content
response = await get_ai_response(user_input)
if response.strip() != "":
await message.channel.send(response[:2000]) # Discord limit is 2000 chars
save_conversation(user_input, response)
except Exception as e:
print(f"Error responding to message: {e}")
diagnose_and_save_error(f"Error responding to message: {e}")
# === Start ===
try:
bot.run(TOKEN)
except Exception as e:
print(f"Bot crashed: {e}")
diagnose_and_save_error(f"Bot crashed: {e}")
# Optional: You can auto-restart after crash
# os.execv(sys.executable, ['python'] + sys.argv)