Alibrown commited on
Commit
1e1319f
·
verified ·
1 Parent(s): 3ffdfd6

Update app/app.py

Browse files
Files changed (1) hide show
  1. app/app.py +19 -159
app/app.py CHANGED
@@ -1,170 +1,30 @@
1
- # Discord Bot Boilerplate by S. Volkan Kücükbudak
2
- # Dev Link: https://github.com/VolkanSah/HF-Discord-Bot
3
- # HF-Demo: https://huggingface.co/spaces/Alibrown/AI-Discord-free/
4
- # You can use it for free (privat and commercial) do not sell my script, only your own work!
5
- from flask import Flask, request, jsonify
6
  import os
7
  import logging
8
- from waitress import serve
9
- from nacl.signing import VerifyKey
10
- from nacl.exceptions import BadSignatureError
11
- import threading
12
- import requests
13
- import time
14
 
15
  # Logging konfigurieren
16
- logging.basicConfig(
17
- level=logging.INFO,
18
- format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
19
- )
20
  logger = logging.getLogger(__name__)
21
 
22
- # Konfiguration
23
- PUBLIC_KEY = os.getenv('Public_Key', '').strip()
24
- APPLICATION_ID = os.getenv('Application_ID', '').strip()
25
- BOT_TOKEN = os.getenv('BOT_TOKEN', '').strip()
26
- PORT = int(os.getenv('PORT', 7860)) # Hugging Face nutzt standardmäßig Port 7860
27
 
28
- app = Flask(__name__)
29
 
30
- # Schlüssel zur Überprüfung von Anfragen initialisieren
31
- try:
32
- verify_key = VerifyKey(bytes.fromhex(PUBLIC_KEY)) if PUBLIC_KEY else None
33
- logger.info("Successfully initialized verify_key")
34
- except Exception as e:
35
- logger.error(f"Error initializing verify_key: {str(e)}")
36
- verify_key = None
37
 
38
- def verify_discord_request():
39
- try:
40
- signature = request.headers.get('X-Signature-Ed25519')
41
- timestamp = request.headers.get('X-Signature-Timestamp')
42
-
43
- if not signature or not timestamp:
44
- return False
45
-
46
- body = request.data.decode('utf-8')
47
- verify_key.verify(f"{timestamp}{body}".encode(), bytes.fromhex(signature))
48
- return True
49
- except Exception as e:
50
- logger.error(f"Verification error: {str(e)}")
51
- return False
52
-
53
- @app.route("/", methods=["GET"])
54
- def health_check():
55
- """Hugging Face nutzt diesen Endpoint um zu prüfen ob der Space läuft"""
56
- return jsonify({
57
- "status": "running",
58
- "message": "Discord bot is running!",
59
- "public_key_present": bool(PUBLIC_KEY),
60
- "verify_key_initialized": verify_key is not None
61
- })
62
-
63
- @app.route("/interactions", methods=["POST"])
64
- def interactions():
65
- if not verify_key:
66
- logger.error("verify_key not initialized")
67
- return "Configuration error", 500
68
-
69
- if not verify_discord_request():
70
- return "Invalid request signature", 401
71
-
72
- try:
73
- data = request.json
74
-
75
- # Discord Ping Verification
76
- if data.get("type") == 1:
77
- logger.info("Responding to ping verification")
78
- return jsonify({"type": 1})
79
-
80
- # Slash Commands
81
- if data.get("type") == 2:
82
- command = data.get("data", {}).get("name")
83
- logger.info(f"Received command: {command}")
84
-
85
- if command == "settings":
86
- return jsonify({
87
- "type": 4,
88
- "data": {
89
- "content": "✅ Bot ist aktiv und verifiziert!"
90
- }
91
- })
92
-
93
- return jsonify({"type": 1})
94
-
95
- except Exception as e:
96
- logger.error(f"Error processing request: {str(e)}")
97
- return "Internal server error", 500
98
-
99
- def health_check_worker():
100
- """Background worker der regelmäßig den Health-Check Endpoint aufruft"""
101
- while True:
102
- try:
103
- response = requests.get(f"http://localhost:{PORT}/")
104
- logger.info(f"Health check status: {response.status_code}")
105
- except Exception as e:
106
- logger.error(f"Health check failed: {str(e)}")
107
- time.sleep(30)
108
-
109
- def register_commands():
110
- """Registriere Befehle bei Discord"""
111
- url = f"https://discord.com/api/v10/applications/{APPLICATION_ID}/commands"
112
- headers = {
113
- "Authorization": f"Bot {BOT_TOKEN}"
114
- }
115
- json = {
116
- "name": "settings",
117
- "description": "Prüft den Status des Bots",
118
- "type": 1
119
- }
120
-
121
- response = requests.post(url, headers=headers, json=json)
122
- if response.status_code == 200:
123
- logger.info("Command successfully registered")
124
- else:
125
- logger.error(f"Failed to register command: {response.status_code} - {response.json()}")
126
-
127
- def setup_discord_channel_and_role(guild_id):
128
- """Erstellt einen Log-Channel und eine Rolle in der angegebenen Guild"""
129
- headers = {
130
- "Authorization": f"Bot {BOT_TOKEN}"
131
- }
132
-
133
- # Channel erstellen
134
- channel_url = f"https://discord.com/api/v10/guilds/{guild_id}/channels"
135
- channel_json = {
136
- "name": "bot-logs",
137
- "type": 0 # Text-Channel
138
- }
139
- channel_response = requests.post(channel_url, headers=headers, json=channel_json)
140
-
141
- if channel_response.status_code == 201:
142
- logger.info("Log-Channel successfully created")
143
- else:
144
- logger.error(f"Failed to create log-channel: {channel_response.status_code} - {channel_response.json()}")
145
-
146
- # Rolle erstellen
147
- role_url = f"https://discord.com/api/v10/guilds/{guild_id}/roles"
148
- role_json = {
149
- "name": "Bot Commander",
150
- "permissions": "8" # Administrator-Rechte
151
- }
152
- role_response = requests.post(role_url, headers=headers, json=role_json)
153
-
154
- if role_response.status_code == 201:
155
- logger.info("Role successfully created")
156
- else:
157
- logger.error(f"Failed to create role: {role_response.status_code} - {role_response.json()}")
158
 
 
159
  if __name__ == "__main__":
160
- logger.info(f"Starting Discord bot on port {PORT}...")
161
-
162
- # Starte Health-Check Worker in separatem Thread
163
- health_thread = threading.Thread(target=health_check_worker, daemon=True)
164
- health_thread.start()
165
-
166
- # Registriere Slash-Command
167
- register_commands()
168
-
169
- # Starte Server
170
- serve(app, host="0.0.0.0", port=PORT)
 
1
+ import discord
2
+ from discord.ext import commands
 
 
 
3
  import os
4
  import logging
 
 
 
 
 
 
5
 
6
  # Logging konfigurieren
7
+ logging.basicConfig(level=logging.INFO)
 
 
 
8
  logger = logging.getLogger(__name__)
9
 
10
+ # Bot-Setup
11
+ intents = discord.Intents.default()
12
+ intents.message_content = True # Erforderlich, um Nachrichteninhalt lesen zu können
 
 
13
 
14
+ bot = commands.Bot(command_prefix="!", intents=intents)
15
 
16
+ @bot.event
17
+ async def on_ready():
18
+ logger.info(f'Bot ist eingeloggt als {bot.user}!')
 
 
 
 
19
 
20
+ @bot.command(name="hello")
21
+ async def hello(ctx):
22
+ await ctx.send("Hello, I'm your bot!")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
+ # Den Bot starten
25
  if __name__ == "__main__":
26
+ bot_token = os.getenv("BOT_TOKEN")
27
+ if not bot_token:
28
+ logger.error("BOT_TOKEN ist nicht gesetzt!")
29
+ else:
30
+ bot.run(bot_token)