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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +1 -136
app.py CHANGED
@@ -1,136 +1 @@
1
- import discord
2
- import os
3
- import json
4
- import sys
5
- import random
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 name and response dynamically"""
64
- command_name = f"command_{random.randint(1000, 9999)}"
65
- response_text = f"This is a dynamically generated command named '{command_name}'."
66
-
67
- # Creating the new command and appending it to app.py
68
- command_code = f"""
69
- @bot.event
70
- async def on_message(message):
71
- if message.author == bot.user:
72
- return
73
-
74
- if message.content.startswith('!{command_name}'):
75
- await message.channel.send("{response_text}")
76
- """
77
- try:
78
- # Append to app.py
79
- with open("app.py", "a", encoding="utf-8") as f:
80
- f.write(command_code)
81
- print(f"Successfully added the command '!{command_name}' to app.py")
82
-
83
- # Optional: Reload bot after adding command
84
- os.execv(sys.executable, ['python'] + sys.argv)
85
-
86
- except Exception as e:
87
- print(f"Error while adding command to app.py: {e}")
88
-
89
- # === Error Handling and Diagnosis ===
90
-
91
- def diagnose_and_save_error(error_message):
92
- """Function to diagnose and log errors into app.py for future review"""
93
- log_entry = {
94
- "timestamp": datetime.utcnow().isoformat(),
95
- "error_message": error_message
96
- }
97
- with open("app.py", "a", encoding="utf-8") as f:
98
- f.write("\n# Error Log\n")
99
- f.write(json.dumps(log_entry) + "\n")
100
-
101
- # === Events ===
102
-
103
- @bot.event
104
- async def on_ready():
105
- print(f"Bot is running in background as {bot.user}")
106
-
107
- @bot.event
108
- async def on_message(message):
109
- # Ignore own messages
110
- if message.author == bot.user:
111
- return
112
-
113
- # Trigger to create a new dynamic command based on some interaction
114
- if "generate" in message.content.lower(): # You can change the condition here
115
- print("Generating a new command based on interaction!")
116
- generate_dynamic_command()
117
-
118
- # Example: normal AI chat
119
- try:
120
- user_input = message.content
121
- response = await get_ai_response(user_input)
122
- if response.strip() != "":
123
- await message.channel.send(response[:2000]) # Discord limit is 2000 chars
124
- save_conversation(user_input, response)
125
- except Exception as e:
126
- print(f"Error responding to message: {e}")
127
- diagnose_and_save_error(f"Error responding to message: {e}")
128
-
129
- # === Start ===
130
- try:
131
- bot.run(TOKEN)
132
- except Exception as e:
133
- print(f"Bot crashed: {e}")
134
- diagnose_and_save_error(f"Bot crashed: {e}")
135
- # Optional: You can auto-restart after crash
136
- # os.execv(sys.executable, ['python'] + sys.argv)
 
1
+ print("hi")