File size: 4,088 Bytes
1f1ec90
 
 
d65737b
 
1f1ec90
1708129
1f1ec90
1708129
1f1ec90
 
 
1708129
1f1ec90
 
1708129
1f1ec90
 
 
 
 
1708129
1f1ec90
 
 
 
 
1708129
1f1ec90
 
 
1708129
d65737b
 
1f1ec90
 
 
 
 
1708129
1f1ec90
 
1708129
1f1ec90
1708129
1f1ec90
 
1708129
1f1ec90
 
 
1708129
1f1ec90
 
 
 
 
 
 
 
1708129
d65737b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f1ec90
 
 
1708129
1f1ec90
 
d65737b
1f1ec90
 
1708129
d65737b
 
 
 
 
 
1f1ec90
 
 
 
 
 
 
 
d65737b
1708129
d65737b
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
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)