wpms commited on
Commit
8f4fcbc
·
verified ·
1 Parent(s): 5c6a09f

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +127 -45
main.py CHANGED
@@ -4,6 +4,7 @@ import os
4
  import asyncio
5
  from flask import Flask
6
  from threading import Thread
 
7
 
8
  # Bot setup
9
  intents = discord.Intents.default()
@@ -13,40 +14,104 @@ intents.presences = True
13
 
14
  bot = commands.Bot(command_prefix="!", intents=intents, help_command=None)
15
 
 
 
 
 
 
 
 
 
 
 
 
16
  # Keep-alive server for Hugging Face
17
  app = Flask(__name__)
18
 
19
  @app.route('/')
20
  def home():
 
 
 
 
 
 
 
 
 
21
  return f"""
22
  <html>
23
- <head><title>{bot.user.name if bot.user else 'Discord Bot'} - Status</title></head>
24
- <body style="font-family: Arial; padding: 40px; background: #1a1a2e; color: white;">
25
- <h1>🤖 Discord Bot Status</h1>
26
- <p><strong>Status:</strong> {'Online ✅' if bot.is_ready() else 'Connecting...'}</p>
27
- <p><strong>Bot Name:</strong> {bot.user.name if bot.user else 'Loading...'}</p>
28
- <p><strong>Latency:</strong> {round(bot.latency * 1000, 2) if bot.is_ready() else '...'} ms</p>
29
- <p><strong>Servers:</strong> {len(bot.guilds) if bot.is_ready() else '...'}</p>
30
- <hr>
31
- <h3>Commands:</h3>
32
- <ul>
33
- <li><code>!ping</code> - Check bot latency</li>
34
- <li><code>!server</code> - Server info</li>
35
- <li><code>!user @mention</code> - User info</li>
36
- <li><code>!clear [amount]</code> - Clear messages</li>
37
- <li><code>!say [message]</code> - Bot says something</li>
38
- <li><code>!embed [title] | [description]</code> - Create embed</li>
39
- <li><code>!poll [question]</code> - Create poll</li>
40
- <li><code>!avatar @mention</code> - Get user avatar</li>
41
- <li><code>!help</code> - Show all commands</li>
42
- </ul>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  </body>
44
  </html>
45
  """
46
 
47
  @app.route('/health')
48
  def health():
49
- return {"status": "healthy", "bot_ready": bot.is_ready()}, 200
50
 
51
  def run_flask():
52
  app.run(host='0.0.0.0', port=7860)
@@ -54,6 +119,10 @@ def run_flask():
54
  # Event: Bot ready
55
  @bot.event
56
  async def on_ready():
 
 
 
 
57
  print(f'✅ Logged in as {bot.user.name} ({bot.user.id})')
58
  print(f'📊 Connected to {len(bot.guilds)} servers')
59
  await bot.change_presence(
@@ -81,18 +150,14 @@ async def on_member_join(member):
81
  async def on_message(message):
82
  if message.author.bot:
83
  return
84
-
85
- # Auto-react to mentions
86
  if bot.user in message.mentions:
87
  await message.add_reaction('👋')
88
-
89
  await bot.process_commands(message)
90
 
91
  # ============ COMMANDS ============
92
 
93
  @bot.command()
94
  async def ping(ctx):
95
- """Check bot latency"""
96
  latency = round(bot.latency * 1000, 2)
97
  embed = discord.Embed(
98
  title="🏓 Pong!",
@@ -103,7 +168,6 @@ async def ping(ctx):
103
 
104
  @bot.command()
105
  async def server(ctx):
106
- """Show server information"""
107
  guild = ctx.guild
108
  embed = discord.Embed(
109
  title=f"📊 {guild.name} Info",
@@ -121,7 +185,6 @@ async def server(ctx):
121
 
122
  @bot.command()
123
  async def user(ctx, member: discord.Member = None):
124
- """Show user information"""
125
  member = member or ctx.author
126
  embed = discord.Embed(
127
  title=f"👤 {member.name} Info",
@@ -139,11 +202,9 @@ async def user(ctx, member: discord.Member = None):
139
  @bot.command()
140
  @commands.has_permissions(manage_messages=True)
141
  async def clear(ctx, amount: int = 5):
142
- """Clear messages (default: 5)"""
143
  if amount < 1 or amount > 100:
144
  await ctx.send("❌ Please specify a number between 1 and 100!")
145
  return
146
-
147
  deleted = await ctx.channel.purge(limit=amount + 1)
148
  embed = discord.Embed(
149
  description=f"🗑️ Deleted **{len(deleted)-1}** messages!",
@@ -155,17 +216,14 @@ async def clear(ctx, amount: int = 5):
155
 
156
  @bot.command()
157
  async def say(ctx, *, message):
158
- """Make the bot say something"""
159
  await ctx.message.delete()
160
  await ctx.send(message)
161
 
162
  @bot.command()
163
  async def embed(ctx, *, content):
164
- """Create a custom embed. Usage: !embed Title | Description"""
165
  parts = content.split("|", 1)
166
  title = parts[0].strip()
167
  description = parts[1].strip() if len(parts) > 1 else ""
168
-
169
  embed = discord.Embed(
170
  title=title,
171
  description=description,
@@ -176,7 +234,6 @@ async def embed(ctx, *, content):
176
 
177
  @bot.command()
178
  async def poll(ctx, *, question):
179
- """Create a poll"""
180
  embed = discord.Embed(
181
  title="📊 Poll",
182
  description=f"**{question}**",
@@ -190,7 +247,6 @@ async def poll(ctx, *, question):
190
 
191
  @bot.command()
192
  async def avatar(ctx, member: discord.Member = None):
193
- """Get user avatar"""
194
  member = member or ctx.author
195
  embed = discord.Embed(
196
  title=f"🖼️ {member.name}'s Avatar",
@@ -203,13 +259,11 @@ async def avatar(ctx, member: discord.Member = None):
203
 
204
  @bot.command()
205
  async def help(ctx):
206
- """Show all commands"""
207
  embed = discord.Embed(
208
  title="🤖 Bot Commands",
209
  description="Here are all available commands:",
210
  color=discord.Color.blue()
211
  )
212
-
213
  commands_list = [
214
  ("!ping", "Check bot latency"),
215
  ("!server", "Server information"),
@@ -221,10 +275,8 @@ async def help(ctx):
221
  ("!avatar @mention", "Get user avatar"),
222
  ("!help", "Show this message")
223
  ]
224
-
225
  for cmd, desc in commands_list:
226
  embed.add_field(name=cmd, value=desc, inline=False)
227
-
228
  embed.set_footer(text=f"Requested by {ctx.author.name}")
229
  await ctx.send(embed=embed)
230
 
@@ -242,16 +294,46 @@ async def on_command_error(ctx, error):
242
  else:
243
  print(f"Error: {error}")
244
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
245
  # Run bot
246
  if __name__ == "__main__":
247
- # Start Flask server in background
248
  flask_thread = Thread(target=run_flask)
249
  flask_thread.daemon = True
250
  flask_thread.start()
251
 
252
- # Run Discord bot
253
- TOKEN = os.getenv("DISCORD_TOKEN")
254
- if not TOKEN:
255
- print("❌ DISCORD_TOKEN not found! Please set it in Hugging Face secrets.")
256
- else:
257
- bot.run(TOKEN)
 
4
  import asyncio
5
  from flask import Flask
6
  from threading import Thread
7
+ import time
8
 
9
  # Bot setup
10
  intents = discord.Intents.default()
 
14
 
15
  bot = commands.Bot(command_prefix="!", intents=intents, help_command=None)
16
 
17
+ # Global variables for web status
18
+ bot_status = {
19
+ "ready": False,
20
+ "name": "Loading...",
21
+ "id": "...",
22
+ "latency": 0,
23
+ "servers": 0,
24
+ "error": None,
25
+ "start_time": time.time()
26
+ }
27
+
28
  # Keep-alive server for Hugging Face
29
  app = Flask(__name__)
30
 
31
  @app.route('/')
32
  def home():
33
+ status_text = "Online ✅" if bot_status["ready"] else ("Error ❌" if bot_status["error"] else "Connecting...")
34
+ status_color = "#00ff00" if bot_status["ready"] else ("#ff0000" if bot_status["error"] else "#ffa500")
35
+
36
+ error_html = f"""
37
+ <div style="background: #ff4444; color: white; padding: 15px; border-radius: 8px; margin: 20px 0;">
38
+ <strong>⚠️ Error:</strong> {bot_status["error"]}
39
+ </div>
40
+ """ if bot_status["error"] else ""
41
+
42
  return f"""
43
  <html>
44
+ <head>
45
+ <title>{bot_status["name"]} - Discord Bot Status</title>
46
+ <meta http-equiv="refresh" content="10">
47
+ <style>
48
+ body {{ font-family: 'Segoe UI', Arial, sans-serif; padding: 40px; background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%); color: white; min-height: 100vh; }}
49
+ .container {{ max-width: 800px; margin: 0 auto; }}
50
+ .status-card {{ background: rgba(255,255,255,0.1); padding: 30px; border-radius: 15px; backdrop-filter: blur(10px); margin-bottom: 20px; }}
51
+ .status-indicator {{ display: inline-block; width: 15px; height: 15px; border-radius: 50%; background: {status_color}; margin-right: 10px; animation: pulse 2s infinite; }}
52
+ @keyframes pulse {{ 0% {{ opacity: 1; }} 50% {{ opacity: 0.5; }} 100% {{ opacity: 1; }} }}
53
+ .info-grid {{ display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-top: 20px; }}
54
+ .info-item {{ background: rgba(255,255,255,0.05); padding: 15px; border-radius: 8px; }}
55
+ .info-label {{ color: #aaa; font-size: 12px; text-transform: uppercase; }}
56
+ .info-value {{ font-size: 18px; font-weight: bold; margin-top: 5px; }}
57
+ .commands {{ background: rgba(255,255,255,0.05); padding: 20px; border-radius: 10px; }}
58
+ .command {{ background: rgba(0,0,0,0.3); padding: 8px 12px; border-radius: 5px; margin: 5px 0; font-family: monospace; }}
59
+ .token-error {{ background: #ff4444; color: white; padding: 20px; border-radius: 10px; margin: 20px 0; }}
60
+ </style>
61
+ </head>
62
+ <body>
63
+ <div class="container">
64
+ <div class="status-card">
65
+ <h1>🤖 Discord Bot Status</h1>
66
+ <div style="font-size: 24px; margin: 20px 0;">
67
+ <span class="status-indicator"></span>
68
+ <strong>{status_text}</strong>
69
+ </div>
70
+ {error_html}
71
+ <div class="info-grid">
72
+ <div class="info-item">
73
+ <div class="info-label">Bot Name</div>
74
+ <div class="info-value">{bot_status["name"]}</div>
75
+ </div>
76
+ <div class="info-item">
77
+ <div class="info-label">Bot ID</div>
78
+ <div class="info-value">{bot_status["id"]}</div>
79
+ </div>
80
+ <div class="info-item">
81
+ <div class="info-label">Latency</div>
82
+ <div class="info-value">{round(bot_status["latency"] * 1000, 2) if bot_status["ready"] else "..."} ms</div>
83
+ </div>
84
+ <div class="info-item">
85
+ <div class="info-label">Servers</div>
86
+ <div class="info-value">{bot_status["servers"]}</div>
87
+ </div>
88
+ </div>
89
+ </div>
90
+
91
+ <div class="commands">
92
+ <h3>📋 Available Commands:</h3>
93
+ <div class="command">!ping</div>
94
+ <div class="command">!server</div>
95
+ <div class="command">!user @mention</div>
96
+ <div class="command">!clear [amount]</div>
97
+ <div class="command">!say [message]</div>
98
+ <div class="command">!embed [title] | [description]</div>
99
+ <div class="command">!poll [question]</div>
100
+ <div class="command">!avatar @mention</div>
101
+ <div class="command">!help</div>
102
+ </div>
103
+
104
+ <div style="margin-top: 30px; text-align: center; color: #888; font-size: 12px;">
105
+ Last updated: {time.strftime("%Y-%m-%d %H:%M:%S")} | Auto-refresh: 10s
106
+ </div>
107
+ </div>
108
  </body>
109
  </html>
110
  """
111
 
112
  @app.route('/health')
113
  def health():
114
+ return {"status": "healthy", "bot_ready": bot_status["ready"], "bot_name": bot_status["name"]}, 200
115
 
116
  def run_flask():
117
  app.run(host='0.0.0.0', port=7860)
 
119
  # Event: Bot ready
120
  @bot.event
121
  async def on_ready():
122
+ bot_status["ready"] = True
123
+ bot_status["name"] = bot.user.name
124
+ bot_status["id"] = str(bot.user.id)
125
+ bot_status["error"] = None
126
  print(f'✅ Logged in as {bot.user.name} ({bot.user.id})')
127
  print(f'📊 Connected to {len(bot.guilds)} servers')
128
  await bot.change_presence(
 
150
  async def on_message(message):
151
  if message.author.bot:
152
  return
 
 
153
  if bot.user in message.mentions:
154
  await message.add_reaction('👋')
 
155
  await bot.process_commands(message)
156
 
157
  # ============ COMMANDS ============
158
 
159
  @bot.command()
160
  async def ping(ctx):
 
161
  latency = round(bot.latency * 1000, 2)
162
  embed = discord.Embed(
163
  title="🏓 Pong!",
 
168
 
169
  @bot.command()
170
  async def server(ctx):
 
171
  guild = ctx.guild
172
  embed = discord.Embed(
173
  title=f"📊 {guild.name} Info",
 
185
 
186
  @bot.command()
187
  async def user(ctx, member: discord.Member = None):
 
188
  member = member or ctx.author
189
  embed = discord.Embed(
190
  title=f"👤 {member.name} Info",
 
202
  @bot.command()
203
  @commands.has_permissions(manage_messages=True)
204
  async def clear(ctx, amount: int = 5):
 
205
  if amount < 1 or amount > 100:
206
  await ctx.send("❌ Please specify a number between 1 and 100!")
207
  return
 
208
  deleted = await ctx.channel.purge(limit=amount + 1)
209
  embed = discord.Embed(
210
  description=f"🗑️ Deleted **{len(deleted)-1}** messages!",
 
216
 
217
  @bot.command()
218
  async def say(ctx, *, message):
 
219
  await ctx.message.delete()
220
  await ctx.send(message)
221
 
222
  @bot.command()
223
  async def embed(ctx, *, content):
 
224
  parts = content.split("|", 1)
225
  title = parts[0].strip()
226
  description = parts[1].strip() if len(parts) > 1 else ""
 
227
  embed = discord.Embed(
228
  title=title,
229
  description=description,
 
234
 
235
  @bot.command()
236
  async def poll(ctx, *, question):
 
237
  embed = discord.Embed(
238
  title="📊 Poll",
239
  description=f"**{question}**",
 
247
 
248
  @bot.command()
249
  async def avatar(ctx, member: discord.Member = None):
 
250
  member = member or ctx.author
251
  embed = discord.Embed(
252
  title=f"🖼️ {member.name}'s Avatar",
 
259
 
260
  @bot.command()
261
  async def help(ctx):
 
262
  embed = discord.Embed(
263
  title="🤖 Bot Commands",
264
  description="Here are all available commands:",
265
  color=discord.Color.blue()
266
  )
 
267
  commands_list = [
268
  ("!ping", "Check bot latency"),
269
  ("!server", "Server information"),
 
275
  ("!avatar @mention", "Get user avatar"),
276
  ("!help", "Show this message")
277
  ]
 
278
  for cmd, desc in commands_list:
279
  embed.add_field(name=cmd, value=desc, inline=False)
 
280
  embed.set_footer(text=f"Requested by {ctx.author.name}")
281
  await ctx.send(embed=embed)
282
 
 
294
  else:
295
  print(f"Error: {error}")
296
 
297
+ async def start_bot():
298
+ TOKEN = os.getenv("DISCORD_TOKEN")
299
+ if not TOKEN:
300
+ error_msg = "DISCORD_TOKEN not found! Please set it in Hugging Face secrets."
301
+ bot_status["error"] = error_msg
302
+ bot_status["name"] = "Token Missing"
303
+ print(f"❌ {error_msg}")
304
+ return
305
+
306
+ max_retries = 5
307
+ retry_count = 0
308
+
309
+ while retry_count < max_retries:
310
+ try:
311
+ print(f"🔄 Attempting to connect to Discord... (Attempt {retry_count + 1}/{max_retries})")
312
+ await bot.start(TOKEN)
313
+ break
314
+ except discord.LoginFailure as e:
315
+ error_msg = f"Invalid Discord token! Please check your token. Error: {str(e)}"
316
+ bot_status["error"] = error_msg
317
+ bot_status["name"] = "Invalid Token"
318
+ print(f"❌ {error_msg}")
319
+ break
320
+ except Exception as e:
321
+ retry_count += 1
322
+ error_msg = f"Connection error: {str(e)}. Retrying in 10 seconds..."
323
+ bot_status["error"] = error_msg
324
+ bot_status["name"] = "Connection Error"
325
+ print(f"⚠️ {error_msg}")
326
+ if retry_count < max_retries:
327
+ await asyncio.sleep(10)
328
+ else:
329
+ bot_status["error"] = f"Failed to connect after {max_retries} attempts. Discord API might be down or network blocked."
330
+ bot_status["name"] = "Connection Failed"
331
+ print(f"❌ {bot_status['error']}")
332
+
333
  # Run bot
334
  if __name__ == "__main__":
 
335
  flask_thread = Thread(target=run_flask)
336
  flask_thread.daemon = True
337
  flask_thread.start()
338
 
339
+ asyncio.run(start_bot())