-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
798 lines (656 loc) · 26.6 KB
/
main.py
File metadata and controls
798 lines (656 loc) · 26.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
import random
from tabnanny import check
# todo: songwars handler, file database, marketplace transactional logic, gui prettyness, increase security, roles for people who rate often, dm salesmanship-game nights
# 8/1/2025 log - added logic for rating songs and rating profiles. also set up daily artist of the day event.
# 8/3/2025 log - fixed emoji average ratings, added custom reactions, users now get roles based on their average rating
# 8/8/2025 log -
import discord
from discord.ext import commands
import logging
from dotenv import load_dotenv
import os
from discord.ext import tasks
import datetime
from discord.ui import View, Button
from discord import ButtonStyle
import random
import uuid
import asyncio
import io
import json
from discord import FFmpegPCMAudio
from flask import Flask
from threading import Thread
app = Flask('')
@app.route('/')
def home():
return "I'm alive!"
def run():
app.run(host='0.0.0.0', port=8080)
def keep_alive():
t = Thread(target=run)
t.start()
load_dotenv()
token = os.getenv("DISCORD_TOKEN")
# variables
restrictedWords = ["server dead", "fuck weslay", "fuck we slay" ]
rebootRole = "Reboot"
userRatings = {}
ratingsSystemRoles = ["5 Star Rating",
"4 Star Rating",
"3 Star Rating",
"2 Star Rating",
"1 Star Rating"]
serverwideEvents = ["songwars", "beatwars", "aotd", "newsletter"]
event_active = False
artist_scores = {}
current_artist = None
# define a random member, you can only be rated randomly thru the bot or if an admin instances a rating occasion. every once in a while a member is chosen to be rated
############
# Configuration
#################################
SEARCH_CHANNEL_ID = 1403494542010749050
DATABASE_FILE = "marketplace.json"
handler=logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')
intents = discord.Intents.default()
intents.message_content = True
intents.members = True # looking for more intents go to documentation-- gateway intents
bot = commands.Bot(command_prefix='!', intents=intents)
####################################################################
#############
# functions
##################################
def load_listings():
try:
with open(DATABASE_FILE, "r", encoding="utf-8") as f:
return json.load(f).get("listings", [])
except FileNotFoundError:
return []
# Core: pick and send one random listing with file attachment
async def send_random_beat(channel: discord.TextChannel, user: discord.Member):
listings = load_listings()
if not listings:
return await channel.send("No beats available right now.")
listing = random.choice(listings)
# Build embed
embed = discord.Embed(
title=listing["title"],
description=f"Genre: {listing['genre']}",
color=0x00ffcc
)
price = listing.get("price", 0)
embed.add_field(
name="Price",
value="Free" if price == 0 else f"${price}",
inline=True
)
embed.add_field(
name="Artist",
value=f"<@{listing['author_id']}>",
inline=True
)
embed.set_footer(text=f"Listing ID: {listing['id']}")
# Attach and send the actual audio file
file_path = listing.get("file_url") # should be a local path or CDN URL
if file_path and os.path.isfile(file_path):
file = discord.File(fp=file_path, filename=os.path.basename(file_path))
message = await channel.send(embed=embed, file=file)
else:
message = await channel.send(embed=embed)
# Add reactions
for emoji in ("❤️", "➡️", "🚩"):
await message.add_reaction(emoji)
# Create a temporary voice channel
guild = channel.guild
category = channel.category # optional: place it in same category
temp_vc = await guild.create_voice_channel(
name=f"{user.name}-beat-room",
category=category,
user_limit=2
)
try:
# Connect bot to the new VC
vc = await temp_vc.connect()
audio = FFmpegPCMAudio(file_path)
vc.play(audio)
await channel.send(f"{user.mention}, your beat is playing in **{temp_vc.name}** 🎶")
# Optional: move user into the VC if they're already in one
if user.voice:
await user.move_to(temp_vc)
# Wait for playback to finish
while vc.is_playing():
await asyncio.sleep(1)
await vc.disconnect()
finally:
# Clean up the temporary voice channel
await asyncio.sleep(5) # buffer before deletion
await temp_vc.delete()
####################################################################
#############
# Miscellaneous Commands
##################################
@bot.event
async def on_ready():
print(f"We are ready to go in, {bot.user.name}")
daily_event.start()
@bot.event
async def on_member_join(member):
await member.send(f"Welcome to the server {member.name}")
@bot.command()
async def hello(ctx):
await ctx.send(f"Hello {ctx.author.mention}!")
####################################################################
##################
# Staff Controls
####################################################################
@bot.command(name="noti")
@commands.has_role("staff team")
async def noti(ctx, *args):
ping_everyone = "everyone" in [a.lower() for a in args]
ping_here = "here" in [a.lower() for a in args]
# 2. Extract any role mentions (e.g. <@&123456789>)
role_mentions = [a for a in args if a.startswith("<@&") and a.endswith(">")]
# 3. Build the final ping prefix
pings = []
if ping_everyone:
pings.append("@everyone")
if ping_here:
pings.append("@here")
pings.extend(role_mentions)
# 4. The “message” is everything that isn’t a modifier or mention
ctx.message.delete()
message_words = [
a for a in args
if a.lower() not in ("everyone", "here")
and not (a.startswith("<@&") and a.endswith(">"))
]
if not message_words:
return await ctx.send("❌ You need to include a message after modifiers.")
message = " ".join(message_words)
# 5. Send with the assembled pings + message
await ctx.send(" ".join(pings + [message]))
return None
######################################################################################################
##################
# On Message Controls -> Rating System, Reactions
####################################################################
@bot.event
async def on_message(message):
custom_emojis = {
"1star": discord.utils.get(message.guild.emojis, name="1star"),
"2star": discord.utils.get(message.guild.emojis, name="2star"),
"3star": discord.utils.get(message.guild.emojis, name="3star"),
"4star": discord.utils.get(message.guild.emojis, name="4star"),
"5star": discord.utils.get(message.guild.emojis, name="5star")
}
if message.author == bot.user:
return
msg_content = message.content.lower()
for word in restrictedWords:
if word in msg_content and word == restrictedWords[0]:
await message.delete()
await message.channel.send(f"{message.author.mention} - see how dat go for you")
elif word in msg_content and (word == restrictedWords[1] or word == restrictedWords[2]):
await message.delete()
await message.channel.send(f"{message.author.mention} bitch fuck you")
if (message.channel.id == 1308593135823360103 or message.channel.id == 1401683440276869140) and message.attachments:
for emoji in custom_emojis.values():
if emoji:
await message.add_reaction(emoji)
print("add")
await bot.process_commands(message)
@bot.command()
async def check_ratings(ctx: commands.Context, user: discord.Member = None):
"""
Checks the rating of a specific user or displays 3 random Top 3 rated members.
"""
top_ratings = ratingsSystemRoles[:3] # ["5⭐", "4⭐", "3⭐"]
if user:
rating = next((r for r in ratingsSystemRoles if discord.utils.get(user.roles, name=r)), None)
if rating:
await ctx.send(f"{user.mention} is rated **{rating}** ⭐")
else:
await ctx.send(f"{user.mention} has no rating assigned.")
else:
# Filter top-rated members (excluding bots)
top_rated = [
member for member in ctx.guild.members
if any(role.name in top_ratings for role in member.roles) and not member.bot
]
if top_rated:
selected = random.sample(top_rated, min(3, len(top_rated)))
embed = discord.Embed(
title="🎉 Top 3 Rated Members",
description="Here are three artists going crazy right now: ",
color=discord.Color.gold()
)
for member in selected:
rating = next((r for r in top_ratings if discord.utils.get(member.roles, name=r)), "Unrated")
embed.add_field(name=member.display_name, value=f"⭐ {rating}", inline=False)
await ctx.send(embed=embed)
else:
await ctx.send("No top-rated members found.")
####################################################################
#######################
# JSON Controllers
##################################
def save_listing_to_json(listing: dict, filename: str = "marketplace.json"):
"""
Load the existing JSON database (or create a new one),
append the new listing, and write it back to disk.
"""
data = {"listings": []}
# If the file exists, read its current contents
if os.path.exists(filename):
with open(filename, "r", encoding="utf-8") as f:
try:
data = json.load(f)
except json.JSONDecodeError:
data = {"listings": []}
# Append the new listing
data["listings"].append(listing)
# Write the updated database back to disk
with open(filename, "w", encoding="utf-8") as f:
json.dump(data, f, indent=4)
####################################################################
@bot.command()
async def submit(ctx):
guild = ctx.guild
# Step 1: Create a private submission channel
overwrites = {
guild.default_role: discord.PermissionOverwrite(view_channel=False),
ctx.author: discord.PermissionOverwrite(view_channel=True, send_messages=True),
guild.me: discord.PermissionOverwrite(view_channel=True, send_messages=True),
}
submission_category = discord.utils.get(guild.categories, name="Submissions")
if not submission_category:
submission_category = await guild.create_category("Submissions")
submission_channel = await guild.create_text_channel(
name=f"{ctx.author.name}-submission",
overwrites=overwrites,
category=submission_category
)
await submission_channel.send(
f"{ctx.author.mention}, please upload your beat file (.mp3 or .wav)."
)
# Step 2: Wait for a valid file upload
def check_file(m: discord.Message):
return (
m.channel == submission_channel
and m.author == ctx.author
and m.attachments
and m.attachments[0].filename.lower().endswith((".mp3", ".wav"))
)
try:
msg = await bot.wait_for("message", check=check_file, timeout=120)
attachment = msg.attachments[0]
file_bytes = await attachment.read()
except asyncio.TimeoutError:
await submission_channel.send("No valid file received in time. Submission cancelled.")
await submission_channel.delete()
return
# Step 3: Collect metadata from the user
questions = [
"Enter the **title** of your beat:",
"Enter the **genre** of your beat:",
"Enter the **price** (or type `free`):"
]
answers = []
for question in questions:
await submission_channel.send(question)
try:
response = await bot.wait_for(
"message",
check=lambda m: m.author == ctx.author and m.channel == submission_channel,
timeout=60
)
answers.append(response.content)
except asyncio.TimeoutError:
await submission_channel.send("You took too long to respond. Submission cancelled.")
await submission_channel.delete()
return
title, genre, price_raw = answers
price = 0 if price_raw.lower() == "free" else price_raw
# Step 4: Build the embed and buttons
listing_id = str(uuid.uuid4())[:8]
embed = discord.Embed(
title=title,
description=f"Genre: {genre}\nPrice: {price}",
color=0x00ffcc
)
embed.set_author(
name=ctx.author.display_name,
icon_url=ctx.author.avatar.url if ctx.author.avatar else None
)
embed.set_thumbnail(url=attachment.url)
embed.set_footer(text=f"Listing ID: {listing_id}")
view = View()
view.add_item(Button(
label="❤️ Favorite",
style=ButtonStyle.primary,
custom_id=f"fav_{listing_id}"
))
view.add_item(Button(
label="🚩 Report",
style=ButtonStyle.danger,
custom_id=f"rep_{listing_id}"
))
# Step 5: Route the file + embed to the database channel
database_channel = discord.utils.get(guild.text_channels, name="database")
if not database_channel:
await submission_channel.send("⚠️ Could not find #database. Please contact an admin.")
await submission_channel.delete()
return
# Re-upload the beat so it lives in the database channel
beat_file = discord.File(io.BytesIO(file_bytes), filename=attachment.filename)
sent_msg = await database_channel.send(file=beat_file, embed=embed, view=view)
# Extract the new CDN URL of the uploaded file
if sent_msg.attachments:
file_url = sent_msg.attachments[0].url
else:
file_url = None
# Step 6: Save the listing into marketplace.json
listing_record = {
"id": listing_id,
"title": title,
"genre": genre,
"price": price,
"author_id": ctx.author.id,
"file_url": file_url,
"timestamp": sent_msg.created_at.isoformat()
}
save_listing_to_json(listing_record)
# Step 7: Confirm to the user and clean up
await submission_channel.send(f"✅ Your beat has been submitted! Listing ID: `{listing_id}`")
await submission_channel.delete()
@bot.command(name="search")
async def search_beat(ctx):
if ctx.channel.id != SEARCH_CHANNEL_ID:
return await ctx.send("Please use this command in #beat-search.")
await send_random_beat(ctx.channel, ctx.author)
@bot.event
async def on_reaction_add(reaction, user):
# Block 1: search‐channel embed reactions
if not (user.bot or reaction.message.channel.id != SEARCH_CHANNEL_ID):
# Ensure it’s our embed with a Listing ID footer
embeds = reaction.message.embeds
if not embeds or not embeds[0].footer.text.startswith("Listing ID:"):
return
listing_id = embeds[0].footer.text.split("Listing ID: ")[1]
# Favorite
if reaction.emoji == "❤️":
print(f"[FAVORITE] User {user} loved listing {listing_id}")
# Next song
elif reaction.emoji == "➡️":
await reaction.message.delete()
await send_random_beat(reaction.message.channel, user)
# Report
elif reaction.emoji == "🚩":
print(f"[REPORT] User {user} reported listing {listing_id}")
# Allow the user to react again
try:
await reaction.remove(user)
except Exception:
pass
# Block 2: attachment‐based ratings
message = reaction.message
if user.bot or not message.attachments:
return
emoji_scores = {
"1star": 1,
"2star": 2,
"3star": 3,
"4star": 4,
"5star": 5,
}
score = emoji_scores.get(reaction.emoji.name)
if score is None:
return
author_id = message.author.id
if author_id not in userRatings:
userRatings[author_id] = []
userRatings[author_id].append(score)
print(f"Added score {score} to user {author_id}")
@bot.command(name="rating")
async def rating(ctx, user: discord.Member):
# Fetch stored scores for this user
scores = userRatings.get(user.id)
if not scores:
await ctx.send(f"{user.mention} has no ratings yet.")
return
# Compute average and rounded value
average = sum(scores) / len(scores)
rounded = round(average)
# Define all possible rating role names
rating_role_names = [f"{i} Star Rating" for i in range(1, 6)]
target_role_name = f"{rounded} Star Rating"
# Remove any existing rating roles the user has
guild = ctx.guild
roles_to_remove = [
role for role in user.roles
if role.name in rating_role_names
]
if roles_to_remove:
await user.remove_roles(*roles_to_remove)
# Add the new rating role
new_role = discord.utils.get(guild.roles, name=target_role_name)
if new_role:
await user.add_roles(new_role)
else:
await ctx.send(f"Role **{target_role_name}** not found. Please create it first.")
# Send feedback
await ctx.send(
f"{user.mention} has an average rating of {average:.2f} ⭐ "
f"based on {len(scores)} {'rating' if len(scores) == 1 else 'ratings'}"
)
@bot.command()
@commands.has_role("staff team")
async def dm(ctx, target: discord.Member, *, msg):
try:
await target.send(f"{msg}")
await ctx.send(f"✅ DM sent to {target.mention}")
except discord.Forbidden:
await ctx.send(f"❌ Couldn't send DM to {target.mention} (maybe DMs are disabled)")
@bot.command() # reply command
async def reply(ctx):
await ctx.reply("This is a reply to your message!")
@bot.command() # poll command
async def poll(ctx, *, question):
embed = discord.Embed(title="New Poll", description=question)
poll_message = await ctx.send(embed=embed)
await poll_message.add_reaction("👍")
await poll_message.add_reaction("👎")
@bot.command()
async def purge(ctx, amount: int):
await ctx.channel.purge(limit=20)
from discord.ext import tasks
import datetime
import random
@tasks.loop(hours=24)
async def daily_event():
channel = bot.get_channel(1400969830294749204)
guild = channel.guild
highRank = ratingsSystemRoles[:3] # ["5⭐", "4⭐", "3⭐"]
highestRated = [
member for member in guild.members
if any(role.name in highRank for role in member.roles) and not member.bot
]
if highestRated:
chosen = random.choice(highestRated)
rating = next((role.name for role in chosen.roles if role.name in highRank), "Unrated")
avatarURL = chosen.display_avatar.url
embed = discord.Embed(
title="🎙️ Artist of the Day",
description=f"Let's celebrate **{chosen.display_name}**!",
color=discord.Color.gold()
)
embed.set_thumbnail(url=avatarURL)
embed.add_field(name="Rating", value=f"⭐ {rating}", inline=True)
embed.set_footer(text="Keep creating, keep shining ✨")
await channel.send(embed=embed)
else:
await channel.send("Nobody meets the standards—no Artist of the Day today.")
@daily_event.before_loop
async def before_daily():
now = datetime.datetime.utcnow()
# Target 1:00 AM UTC = 9:00 PM EDT
target = now.replace(hour=1, minute=0, second=0, microsecond=0)
if now > target:
target += datetime.timedelta(days=1)
await discord.utils.sleep_until(target)
@bot.command() # embed
async def status(ctx):
embed = discord.Embed(
title="🟢 Bot Status",
description="All systems are running smoothly.",
color=discord.Color.green()
)
embed.set_footer(text="Updated just now • WeBot System")
await ctx.send(embed=embed)
@bot.command()
async def start_random(ctx):
members = [m for m in ctx.guild.members if not m.bot]
if members:
chosen = random.choice(members)
await ctx.send(f"randomly selected {chosen.name}")
else:
await ctx.send("No members found")
#############################
# Event Handlers
##################################
@bot.command()
@commands.has_role("staff team")
async def event(ctx):
global event_active, artist_scores
# Replace with your actual event channel ID
event_channel = bot.get_channel(1403496122281885696)
if event_active:
await ctx.send("⚠️ An event is already active.")
return
event_active = True
artist_scores = {}
# Only accept messages from the command invoker in the same channel
def check(m):
return m.author == ctx.author and m.channel == ctx.channel
# Prompt for event name
await ctx.send("📛 What's the name of the event?")
event_name_msg = await bot.wait_for("message", check=check)
event_name = event_name_msg.content
# Prompt for number of artists
await ctx.send("🎤 How many artists?")
num_msg = await bot.wait_for("message", check=check)
try:
num_artists = int(num_msg.content)
except ValueError:
await ctx.send("❌ Invalid number.")
event_active = False
return
# Collect artist names
for i in range(num_artists):
await ctx.send(f"🎶 Enter artist #{i + 1}:")
artist_msg = await bot.wait_for("message", check=check)
artist_scores[artist_msg.content] = []
# Create embed announcement
embed = discord.Embed(
title="🎉 Event Started!",
description=f"**{event_name}** is now live!",
color=0x00ff00
)
embed.add_field(
name="🎤 Participating Artists",
value="\n".join(f"- {name}" for name in artist_scores.keys()),
inline=False
)
embed.set_footer(text="🎛️ anyone can judge -> rate songs in #chat")
embed.set_thumbnail(url="https://i.ytimg.com/vi/Tkvf-bTmqOs/maxresdefault.jpg") # image replace
# Send embed to both the command channel and the event channel
await ctx.send(embed=embed)
await event_channel.send(content="@here @everyone", embed=embed)
@bot.command()
@commands.has_role("staff team")
async def nowplaying(ctx, *, artist_name):
global current_artist
if not event_active:
await ctx.send("❌ No active event.")
return
if artist_name not in artist_scores:
await ctx.send("❌ Artist not found.")
return
current_artist = artist_name
await ctx.send(f"🎵 Now playing: **{artist_name}**. Type `over {artist_name} - song` when done.")
@bot.command()
@commands.has_role("staff team")
async def over(ctx, *, song_info):
global current_artist
if not current_artist:
await ctx.send("❌ No artist is currently playing.")
return
def check(m):
return m.author == ctx.author and m.channel == ctx.channel
await ctx.send(f"📛 Song finished: **{song_info}**.\nPlease enter how many votes each star rating received.")
try:
await ctx.send("⭐ How many 1-star ratings?")
one_msg = await bot.wait_for("message", check=check)
await ctx.send("⭐ How many 2-star ratings?")
two_msg = await bot.wait_for("message", check=check)
await ctx.send("⭐ How many 3-star ratings?")
three_msg = await bot.wait_for("message", check=check)
await ctx.send("⭐ How many 4-star ratings?")
four_msg = await bot.wait_for("message", check=check)
await ctx.send("⭐ How many 5-star ratings?")
five_msg = await bot.wait_for("message", check=check)
star_counts = {
1: int(one_msg.content),
2: int(two_msg.content),
3: int(three_msg.content),
4: int(four_msg.content),
5: int(five_msg.content)
}
except ValueError:
await ctx.send("❌ Invalid input. Please enter whole numbers only.")
return
total_votes = sum(star_counts.values())
total_score = sum(stars * count for stars, count in star_counts.items())
if total_votes == 0:
await ctx.send("⚠️ No votes received.")
else:
average = total_score / total_votes
artist_scores[current_artist].append(average)
await ctx.send(f"📊 Average rating for **{song_info}**: **{average:.2f}** stars from {total_votes} votes.")
current_artist = None
@bot.command()
@commands.has_role("staff team")
async def eventover(ctx, *, modifiers):
global event_active, artist_scores
event_active = False
# Calculate average scores
avg_scores = {
artist: sum(scores) / len(scores) if scores else 0
for artist, scores in artist_scores.items()
}
# Sort and get top 3
sorted_artists = sorted(avg_scores.items(), key=lambda x: x[1], reverse=True)
top3 = sorted_artists[:3]
# Build fancy embed
embed = discord.Embed(
title="🏁 **Event Concluded!**",
description="Here are the top-rated artists from this showcase:",
color=discord.Color.red()
)
trophy_emojis = ["🥇", "🥈", "🥉"]
for i, (name, score) in enumerate(top3):
embed.add_field(
name=f"{trophy_emojis[i]} {name}",
value=f"⭐ **{score:.2f}** average rating",
inline=False
)
embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/1403531338199601163/1417319786710302891/IMG_4509.jpg?ex=68ca0d69&is=68c8bbe9&hm=ff9a1a6d26465c94f2ac9da0057f8f933411bfa4220106c6e4d2304e17f970ee&") # Replace if needed
embed.set_footer(text="🎧 Thanks for tuning in — keep supporting your favorite artists!")
await ctx.send(embed=embed)
await ctx.send(f"@here @everyone — {modifiers}")
# server events:
# instanced: song wars, beat wars
# daily: artist of the day- random song is selected with 4 stars or higher to be featured for a day. includes the file, artist and ranking.
# weekly: @ everyone ping with updates, server news, content, and more (this should always be good news, includes a graphic and links)
keep_alive()
bot.run(token, log_handler=handler, log_level=logging.DEBUG)