MINEOGO commited on
Commit
aac6f11
·
verified ·
1 Parent(s): 3bfab9a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +144 -1
app.py CHANGED
@@ -1 +1,144 @@
1
- print("hi")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import discord
2
+ import os
3
+ import json
4
+ import sys
5
+ import requests
6
+ from dotenv import load_dotenv
7
+ from huggingface_hub import InferenceClient
8
+ from datetime import datetime
9
+
10
+ # Load token from .env
11
+ load_dotenv()
12
+ TOKEN = os.getenv("BOT_TOKEN")
13
+
14
+ # Hugging Face client setup
15
+ client_ai = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
16
+
17
+ # Discord client setup
18
+ intents = discord.Intents.default()
19
+ intents.messages = True
20
+ intents.message_content = True
21
+ bot = discord.Client(intents=intents)
22
+
23
+ # Settings for AI generation
24
+ SYSTEM_PROMPT = "You are a helpful and friendly chatbot."
25
+ MAX_TOKENS = 512
26
+ TEMPERATURE = 0.7
27
+ TOP_P = 0.95
28
+
29
+ # Create data folder if it doesn't exist
30
+ os.makedirs("data", exist_ok=True)
31
+ CONVERSATION_LOG = "data/conversations.jsonl"
32
+
33
+ # === Functions ===
34
+
35
+ async def get_ai_response(message_content):
36
+ messages = [
37
+ {"role": "system", "content": SYSTEM_PROMPT},
38
+ {"role": "user", "content": message_content}
39
+ ]
40
+
41
+ full_response = ""
42
+ for part in client_ai.chat_completion(
43
+ messages,
44
+ max_tokens=MAX_TOKENS,
45
+ stream=True,
46
+ temperature=TEMPERATURE,
47
+ top_p=TOP_P,
48
+ ):
49
+ if part.choices[0].delta.content:
50
+ full_response += part.choices[0].delta.content
51
+ return full_response
52
+
53
+ def save_conversation(user_message, bot_response):
54
+ log_entry = {
55
+ "timestamp": datetime.utcnow().isoformat(),
56
+ "user_message": user_message,
57
+ "bot_response": bot_response
58
+ }
59
+ with open(CONVERSATION_LOG, "a", encoding="utf-8") as f:
60
+ f.write(json.dumps(log_entry) + "\n")
61
+
62
+ def generate_dynamic_command():
63
+ """Generate a command using the external API (0zyen)"""
64
+ url = "https://0zyen.vercel.app/api/chat/completions"
65
+ payload = {
66
+ "content": """create a discord bot command of "!test" that'll say "hello" , you must say nothing else but the command using discord.py only without any backticks!, it must be ready to use like integrate it quickly""",
67
+ "model": "GPT-4.1-nano"
68
+ }
69
+
70
+ # Get response from the external API
71
+ response = requests.post(url, json=payload)
72
+
73
+ if response.status_code == 200:
74
+ generated_text = response.json().get('generated_text', '')
75
+
76
+ # Clean the response text by removing backticks and replacing \n with actual new lines
77
+ cleaned_text = generated_text.replace('```', '').replace('\\n', '\n').strip()
78
+
79
+ # Generate the command and save it to app.py
80
+ command_code = f"""
81
+ @bot.command()
82
+ async def test(ctx):
83
+ {cleaned_text}
84
+ """
85
+ try:
86
+ # Append to app.py
87
+ with open("app.py", "a", encoding="utf-8") as f:
88
+ f.write(command_code)
89
+ print(f"Successfully added the command to app.py")
90
+
91
+ # Optional: Reload bot after adding command
92
+ os.execv(sys.executable, ['python'] + sys.argv)
93
+
94
+ except Exception as e:
95
+ print(f"Error while adding command to app.py: {e}")
96
+
97
+ # === Error Handling and Diagnosis ===
98
+
99
+ def diagnose_and_save_error(error_message):
100
+ """Function to diagnose and log errors into app.py for future review"""
101
+ log_entry = {
102
+ "timestamp": datetime.utcnow().isoformat(),
103
+ "error_message": error_message
104
+ }
105
+ with open("app.py", "a", encoding="utf-8") as f:
106
+ f.write("\n# Error Log\n")
107
+ f.write(json.dumps(log_entry) + "\n")
108
+
109
+ # === Events ===
110
+
111
+ @bot.event
112
+ async def on_ready():
113
+ print(f"Bot is running in background as {bot.user}")
114
+
115
+ @bot.event
116
+ async def on_message(message):
117
+ # Ignore own messages
118
+ if message.author == bot.user:
119
+ return
120
+
121
+ # Trigger to create a new dynamic command based on some interaction
122
+ if "generate" in message.content.lower() or "add commands" in message.content.lower() or "add cmd" in message.content.lower():
123
+ print("Generating a new command based on interaction!")
124
+ generate_dynamic_command()
125
+
126
+ # Example: normal AI chat
127
+ try:
128
+ user_input = message.content
129
+ response = await get_ai_response(user_input)
130
+ if response.strip() != "":
131
+ await message.channel.send(response[:2000]) # Discord limit is 2000 chars
132
+ save_conversation(user_input, response)
133
+ except Exception as e:
134
+ print(f"Error responding to message: {e}")
135
+ diagnose_and_save_error(f"Error responding to message: {e}")
136
+
137
+ # === Start ===
138
+ try:
139
+ bot.run(TOKEN)
140
+ except Exception as e:
141
+ print(f"Bot crashed: {e}")
142
+ diagnose_and_save_error(f"Bot crashed: {e}")
143
+ # Optional: You can auto-restart after crash
144
+ # os.execv(sys.executable, ['python'] + sys.argv)