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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -119
app.py CHANGED
@@ -1,144 +1,77 @@
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)
 
 
1
  import os
2
+ import discord
 
3
  import requests
4
  from dotenv import load_dotenv
5
+ from fastapi import FastAPI
6
+ import gradio as gr
7
+ import asyncio
8
+ import threading
9
+ import time
10
 
11
+ # Load environment variables
12
  load_dotenv()
 
 
 
 
13
 
14
+ # Get bot token from .env file
15
+ BOT_TOKEN = os.getenv("BOT_TOKEN")
 
 
 
16
 
17
+ # Set up FastAPI and Gradio
18
+ app = FastAPI()
 
 
 
19
 
20
+ # This will simulate the "Bot is running" message in the background
21
+ @app.get("/")
22
+ async def read_root():
23
+ return {"message": "Bot is running"}
24
 
25
+ # Set up Discord bot client
26
+ intents = discord.Intents.default()
27
+ intents.message_content = True
28
+ client = discord.Client(intents=intents)
 
 
 
29
 
30
+ # API URL for fetching responses from the external service
31
+ url = "https://0zyen.vercel.app/api/chat/completions"
 
 
 
 
 
 
 
 
 
32
 
33
+ # Function to interact with the API
34
+ def get_response_from_api(user_input):
 
 
 
 
 
 
 
 
 
 
35
  payload = {
36
+ "content": user_input,
37
+ "model": "Evil"
38
  }
 
 
39
  response = requests.post(url, json=payload)
 
40
  if response.status_code == 200:
41
+ api_response = response.json()
42
+ return f'prompt\nmodel:evil\n{api_response.get("generated_text", "")}'
43
+ return "Error communicating with API."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
+ # Async function to start the Discord bot
46
+ async def run_discord_bot():
47
+ await client.start(BOT_TOKEN)
48
 
49
+ # Function to keep FastAPI and Discord bot running simultaneously
50
+ def start_fastapi_server():
51
+ import uvicorn
52
+ uvicorn.run(app, host="0.0.0.0", port=7860)
53
 
54
+ # Event handler for when the bot is ready
55
+ @client.event
 
 
 
 
 
 
 
 
 
 
 
56
  async def on_ready():
57
+ print(f"Bot logged in as {client.user}")
58
 
59
+ # Event handler for when the bot receives a message
60
+ @client.event
61
  async def on_message(message):
62
+ if message.author == client.user:
 
63
  return
64
 
65
+ # Interact with the external API
66
+ response_text = get_response_from_api(message.content)
67
+
68
+ # Send the response back to the Discord channel
69
+ await message.channel.send(response_text)
70
 
71
+ # Run both FastAPI server and Discord bot concurrently
72
+ if __name__ == "__main__":
73
+ # Start the FastAPI server in a separate thread
74
+ threading.Thread(target=start_fastapi_server, daemon=True).start()
 
 
 
 
 
 
75
 
76
+ # Run the Discord bot
77
+ asyncio.run(run_discord_bot())