-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbot.py
More file actions
1224 lines (1073 loc) · 48 KB
/
bot.py
File metadata and controls
1224 lines (1073 loc) · 48 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
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import logging
import random
import discord
from discord import app_commands
from discord.ext import tasks
from dotenv import load_dotenv
from fetch_and_store import run as fetch_and_store_hackathons
from backend.models import GuildConfig
from backend.db import SessionLocal
from backend.crud import (
search_hackathons,
get_hackathons_by_platform,
get_upcoming_hackathons,
subscribe_user,
get_all_subscriptions,
get_user_subscriptions,
unsubscribe_user,
update_guild_preferences,
pause_notifications,
resume_notifications,
)
# 1. Configuration & Logging
load_dotenv()
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[logging.StreamHandler()],
)
intents = discord.Intents.default()
intents.guilds = True # needed to see guilds and channels
# 2. Helper Functions (Basic)
def format_hackathon_embed(hackathon):
"""Create a Discord embed for a hackathon notification."""
emojis = ["🎉", "🚀", "💡", "🔥", "💻", "🏆", "🌟", "⚡", "🔮", "🛠️"]
random_emoji = random.choice(emojis)
msg = f"# {random_emoji} **{hackathon.title}**\n\n"
msg += "---\n"
msg += f"**Duration:** {hackathon.start_date.strftime('%B %d')} - {hackathon.end_date.strftime('%B %d, %Y')}\n"
msg += f"**Location:** {hackathon.location}\n"
msg += f"**Mode:** {hackathon.mode}\n"
msg += f"**Status:** {hackathon.status}\n"
if hackathon.prize_pool:
if "\n" in hackathon.prize_pool or hackathon.prize_pool.startswith("-"):
msg += f"**Prizes:**\n{hackathon.prize_pool}\n"
else:
msg += f"**Prizes:** {hackathon.prize_pool}\n"
if hackathon.team_size:
msg += f"**Team Size:** {hackathon.team_size}\n"
if hackathon.eligibility:
msg += f"**Eligibility:** {hackathon.eligibility}\n"
msg += "---\n"
embed = None
if hackathon.banner_url:
embed = discord.Embed()
embed.set_image(url=hackathon.banner_url)
view = discord.ui.View()
# Register button
if hackathon.url:
view.add_item(
discord.ui.Button(
label="🚀 Check Details", url=hackathon.url, style=discord.ButtonStyle.primary
)
)
return msg, embed, view
# 3. UI Classes (Views & Paginators)
class SetupView(discord.ui.View):
def __init__(self, guild_id: str):
super().__init__()
self.guild_id = guild_id
self.platforms = []
self.themes = []
self.channel = None
@discord.ui.select(
placeholder="Select Platforms [Default: All]",
min_values=0,
max_values=7,
options=[
discord.SelectOption(label="Devfolio", value="devfolio"),
discord.SelectOption(label="Devpost", value="devpost"),
discord.SelectOption(label="Unstop", value="unstop"),
discord.SelectOption(label="DoraHacks", value="dorahacks"),
discord.SelectOption(label="Hack2Skill", value="hack2skill"),
discord.SelectOption(label="Kaggle", value="kaggle"),
discord.SelectOption(label="MLH", value="mlh"),
],
)
async def select_platforms(self, interaction: discord.Interaction, select: discord.ui.Select):
self.platforms = select.values
await interaction.response.defer()
@discord.ui.select(
placeholder="Select Themes [Default: All]",
min_values=0,
max_values=8,
options=[
discord.SelectOption(label="AI/ML", value="ai"),
discord.SelectOption(label="Blockchain/Web3", value="blockchain"),
discord.SelectOption(label="Web Development", value="web"),
discord.SelectOption(label="Mobile App", value="mobile"),
discord.SelectOption(label="Data Science", value="data"),
discord.SelectOption(label="IoT", value="iot"),
discord.SelectOption(label="Cloud", value="cloud"),
discord.SelectOption(label="Cybersecurity", value="security"),
],
)
async def select_themes(self, interaction: discord.Interaction, select: discord.ui.Select):
self.themes = select.values
await interaction.response.defer()
@discord.ui.select(
cls=discord.ui.ChannelSelect,
channel_types=[discord.ChannelType.text],
placeholder="Select Notification Channel",
)
async def select_channel(
self, interaction: discord.Interaction, select: discord.ui.ChannelSelect
):
self.channel = select.values[0]
await interaction.response.defer()
@discord.ui.button(label="Save Preferences", style=discord.ButtonStyle.green)
async def save_button(self, interaction: discord.Interaction, button: discord.ui.Button):
if not self.channel:
await interaction.response.send_message(
"❌ Please select a channel first!", ephemeral=True
)
return
db = SessionLocal()
try:
update_guild_preferences(
db, self.guild_id, str(self.channel.id), self.platforms, self.themes
)
github_view = discord.ui.View()
github_view.add_item(
discord.ui.Button(
label="⭐ Star on GitHub",
url="https://github.com/Spartan-71/Discord-Hackathon-Bot",
style=discord.ButtonStyle.link,
)
)
success_embed = discord.Embed(
title="✅ Setup Complete!",
description=(
"Your preferences have been saved successfully!\n\n"
f"**Notification Channel:** {self.channel.mention}\n"
f"**Platforms:** {', '.join(self.platforms) if self.platforms else 'All (Default)'}\n"
f"**Themes:** {', '.join(self.themes) if self.themes else 'All (Default)'}\n\n"
"🎉 You'll start receiving hackathon notifications soon.\n"
),
color=discord.Color.green(),
)
await interaction.response.send_message(
embed=success_embed, view=github_view, ephemeral=True
)
except Exception as e:
await interaction.response.send_message(
f"❌ Error saving preferences: {str(e)}", ephemeral=True
)
finally:
db.close()
class WelcomeView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(
label="⚙️ Quick Setup", style=discord.ButtonStyle.primary, custom_id="welcome_setup"
)
async def setup_button(self, interaction: discord.Interaction, button: discord.ui.Button):
if not interaction.user.guild_permissions.administrator:
await interaction.response.send_message(
"❌ You need Administrator permissions to use this command.\n"
"💡 Ask a server admin to run `/setup` or click this button.",
ephemeral=True,
)
return
embed = discord.Embed(
title="⚙️ HackRadar Setup",
description="Please select your preferences below:\n\n"
"1. **Platforms**: Choose which platforms to track.\n"
"2. **Themes**: Choose which themes to track.\n"
"3. **Channel**: Select where to post notifications.\n\n"
"Click **Save Preferences** when done.",
color=discord.Color.blue(),
)
view = SetupView(str(interaction.guild_id))
await interaction.response.send_message(embed=embed, view=view, ephemeral=True)
class HackathonPaginator(discord.ui.View):
"""Paginator for displaying hackathons with Previous/Next buttons."""
def __init__(self, hackathons, context_type="manual"):
super().__init__(timeout=600)
self.hackathons = hackathons
self.context_type = context_type
self.current_index = 0
self.max_index = len(hackathons) - 1
if context_type == "scheduled":
self.timeout = 3600
self.update_buttons()
def update_buttons(self):
self.previous_button.disabled = self.current_index == 0
self.next_button.disabled = self.current_index == self.max_index
def add_action_buttons(self, view_buttons):
self.clear_items()
if view_buttons:
for item in view_buttons.children:
item.row = 0
self.add_item(item)
self.previous_button.row = 1
self.next_button.row = 1
self.add_item(self.previous_button)
self.add_item(self.next_button)
def get_current_hackathon(self):
return self.hackathons[self.current_index]
def create_embed(self):
hackathon = self.get_current_hackathon()
msg, embed, view = format_hackathon_embed(hackathon)
if embed:
current_footer = embed.footer.text if embed.footer else ""
new_footer = f"📄 {self.current_index + 1}/{len(self.hackathons)}"
if current_footer:
new_footer += f" | {current_footer}"
embed.set_footer(text=new_footer)
return msg, embed, view
@discord.ui.button(
label="◀️ Previous", style=discord.ButtonStyle.gray, custom_id="prev_hack", row=1
)
async def previous_button(self, interaction: discord.Interaction, button: discord.ui.Button):
if self.current_index > 0:
self.current_index -= 1
self.update_buttons()
await self._update_message(interaction)
else:
await interaction.response.send_message(
"⚠️ You're already at the first hackathon!", ephemeral=True
)
@discord.ui.button(label="Next ▶️", style=discord.ButtonStyle.gray, custom_id="next_hack", row=1)
async def next_button(self, interaction: discord.Interaction, button: discord.ui.Button):
if self.current_index < self.max_index:
self.current_index += 1
self.update_buttons()
await self._update_message(interaction)
else:
await interaction.response.send_message(
"⚠️ You're already at the last hackathon!", ephemeral=True
)
async def _update_message(self, interaction: discord.Interaction):
msg, embed, view_buttons = self.create_embed()
self.add_action_buttons(view_buttons)
try:
await interaction.response.edit_message(
content=msg
if msg
else f"📖 Hackathon {self.current_index + 1}/{len(self.hackathons)}:",
embed=embed,
view=self,
)
except discord.NotFound:
await interaction.response.send_message(
"⚠️ Message was deleted. Please run the command again.", ephemeral=True
)
async def on_timeout(self):
for item in self.children:
item.disabled = True
# 4. Notification Helper Functions
async def send_standard_paginated_notification(channel, hackathons):
if len(hackathons) == 1:
hackathon = hackathons[0]
msg, embed, view = format_hackathon_embed(hackathon)
if embed:
await channel.send(content=msg, embed=embed, view=view)
else:
await channel.send(content=msg, view=view)
else:
paginator = HackathonPaginator(hackathons, context_type="manual")
msg, embed, view_buttons = paginator.create_embed()
paginator.add_action_buttons(view_buttons)
await channel.send(
content=f"📅 Found **{len(hackathons)}** hackathon(s). Use buttons to navigate:\n\n{msg}",
embed=embed,
view=paginator,
)
async def send_scheduled_notification_with_pagination(channel, hackathons):
summary_embed = discord.Embed(
title="🚀 New Hackathons Posted!",
description=f"**{len(hackathons)}** new hackathon(s) have been posted. Click the buttons below to view details.",
color=discord.Color.green(),
timestamp=discord.utils.utcnow(),
)
summary_text = ""
for i, hack in enumerate(hackathons[:10], 1):
title = hack.title if len(hack.title) <= 50 else hack.title[:47] + "..."
summary_text += f"**{i}.** [{title}]({hack.url}) - *{hack.source}*\n"
if len(hackathons) > 10:
summary_text += f"\n*...and {len(hackathons) - 10} more. Use buttons below to view all.*"
summary_embed.add_field(name="📋 Hackathons", value=summary_text, inline=False)
summary_embed.set_footer(text="💡 Use the buttons below to navigate through details")
paginator = HackathonPaginator(hackathons, context_type="scheduled")
msg, embed, view_buttons = paginator.create_embed()
paginator.add_action_buttons(view_buttons)
await channel.send(embed=summary_embed)
await channel.send(
content=f"📖 **Detailed View** (1/{len(hackathons)}):", embed=embed, view=paginator
)
async def send_paginated_hackathons(channel, hackathons, context_type="scheduled"):
if not hackathons:
return
if context_type == "scheduled" and len(hackathons) > 1:
await send_scheduled_notification_with_pagination(channel, hackathons)
else:
await send_standard_paginated_notification(channel, hackathons)
async def send_hackathon_notifications(bot, new_hackathons, target_channel=None):
if not new_hackathons:
return
if target_channel:
permissions = target_channel.permissions_for(target_channel.guild.me)
if not (permissions.send_messages and permissions.embed_links):
logging.warning(
f"Missing permissions in target channel {target_channel.id}. Skipping notifications."
)
return
try:
await send_paginated_hackathons(
channel=target_channel, hackathons=new_hackathons, context_type="manual_fetch"
)
logging.info(
f"Sent {len(new_hackathons)} hackathons to channel {target_channel.id} with pagination"
)
except discord.Forbidden:
logging.error(
f"403 Forbidden when sending to channel {target_channel.id}. Check permissions."
)
except Exception as e:
logging.error(
f"Failed to send hackathon notifications to channel {target_channel.id}: {e}"
)
else:
db = SessionLocal()
try:
for guild in bot.guilds:
channel = None
platforms = ["all"]
themes = ["all"]
try:
config = (
db.query(GuildConfig).filter(GuildConfig.guild_id == str(guild.id)).first()
)
if config:
if config.notifications_paused == "true":
logging.info(
f"Notifications are paused for guild {guild.id}. Skipping."
)
continue
channel = guild.get_channel(int(config.channel_id))
if channel and not channel.permissions_for(guild.me).send_messages:
logging.warning(
f"Configured channel {channel.id} in guild {guild.id} is not writable"
)
channel = None
if config.subscribed_platforms:
platforms = config.subscribed_platforms.split(",")
if config.subscribed_themes:
themes = config.subscribed_themes.split(",")
except Exception as e:
logging.error(f"Error fetching guild config for {guild.id}: {e}")
if channel is None:
logging.warning(
f"No configured notification channel found for guild {guild.id}. Skipping."
)
continue
filtered_hackathons = []
for hackathon in new_hackathons:
if "all" not in platforms:
if not any(p.lower() in hackathon.source.lower() for p in platforms):
continue
if "all" not in themes:
hack_tags = [t.lower() for t in hackathon.tags] if hackathon.tags else []
match = False
for theme in themes:
theme_lower = theme.lower()
for tag in hack_tags:
if theme_lower in tag:
match = True
break
if match:
break
if not match:
continue
filtered_hackathons.append(hackathon)
if filtered_hackathons:
try:
await send_paginated_hackathons(
channel=channel,
hackathons=filtered_hackathons,
context_type="scheduled",
)
logging.info(
f"Sent {len(filtered_hackathons)} hackathons to guild {guild.id} with pagination"
)
except Exception as e:
logging.error(
f"Failed to send hackathon notifications in guild {guild.id}: {e}"
)
else:
logging.info(f"No matching hackathons for guild {guild.id} after filtering")
finally:
db.close()
async def notify_subscribers(bot, new_hackathons):
if not new_hackathons:
return
db = SessionLocal()
try:
subscriptions = get_all_subscriptions(db)
if not subscriptions:
return
user_notifications = {}
for hackathon in new_hackathons:
hack_tags = [t.lower() for t in hackathon.tags] if hackathon.tags else []
for sub in subscriptions:
theme_lower = sub.theme.lower()
is_match = False
for tag in hack_tags:
if theme_lower in tag:
is_match = True
break
if is_match:
if sub.user_id not in user_notifications:
user_notifications[sub.user_id] = []
if hackathon not in user_notifications[sub.user_id]:
user_notifications[sub.user_id].append(hackathon)
for user_id, hacks in user_notifications.items():
try:
user = await bot.fetch_user(user_id)
if user:
for hack in hacks:
msg, embed, view = format_hackathon_embed(hack)
alert_msg = (
f"🔔 **New Hackathon Alert!** (Matches your subscription)\n\n{msg}"
)
if embed:
await user.send(content=alert_msg, embed=embed, view=view)
else:
await user.send(content=alert_msg, view=view)
logging.info(f"Sent DM notification for '{hack.title}' to user {user_id}")
except Exception as e:
logging.error(f"Failed to DM user {user_id}: {e}")
finally:
db.close()
# 5. Main Client Class
class MyClient(discord.Client):
def __init__(self, intents: discord.Intents):
super().__init__(intents=intents)
self.tree = app_commands.CommandTree(self)
async def setup_hook(self):
if not check_and_notify_hackathons.is_running():
check_and_notify_hackathons.start(self)
async def on_ready(self):
logging.info(f"Logged on as {self.user}")
logging.info(f"Bot is in {len(self.guilds)} servers:")
for guild in self.guilds:
logging.info(f"- {guild.name} (ID: {guild.id}) members: {guild.member_count}")
logging.info(f" Channels: {len(guild.text_channels)}")
try:
for guild in self.guilds:
try:
self.tree.clear_commands(guild=guild)
await self.tree.sync(guild=guild)
except Exception as e:
logging.error(f"Failed to clear guild commands for {guild.name}: {e}")
synced_global = await self.tree.sync()
logging.info(f"Synced {len(synced_global)} commands globally")
logging.info("Commands are now available in both servers and DMs!")
except Exception as e:
logging.error(f"Error syncing commands: {e}")
async def on_guild_join(self, guild):
logging.info(f"Joined new guild: {guild.name} ({guild.id})")
logging.info("Commands are already available globally (no guild-specific sync needed)")
try:
target_channel = guild.system_channel
if not target_channel:
target_channel = next(
(
ch
for ch in guild.text_channels
if ch.permissions_for(guild.me).send_messages
),
None,
)
if target_channel and target_channel.permissions_for(guild.me).send_messages:
embed = discord.Embed(
title="🎉 Welcome to HackRadar!",
description=(
"Thanks for adding me! I'll help your community stay updated on the latest hackathons.\n\n"
"**What I can do:**\n"
"- Automatic notifications from Devfolio, Devpost, Unstop & more\n"
"- Filter by themes (AI, Blockchain, Web3, etc.)\n"
"- Track upcoming deadlines and events\n"
"- Search hackathons on-demand\n\n"
),
color=discord.Color.green(),
)
embed.add_field(
name="🔍 Try These Commands",
value=(
"`/upcoming 7` - Hackathons starting this week\n"
"`/search AI` - Find AI-related hackathons\n"
"`/help` - See all available commands"
),
inline=False,
)
if self.user:
embed.set_thumbnail(url=self.user.display_avatar.url)
view = WelcomeView()
await target_channel.send(embed=embed, view=view)
logging.info(f"✅ Welcome message sent in {guild.name} (#{target_channel.name})")
except Exception as e:
logging.error(f"Failed to send welcome message in {guild.name}: {e}")
async def on_guild_remove(self, guild):
logging.info(f"Removed from guild: {guild.name} ({guild.id})")
try:
db = SessionLocal()
db.query(GuildConfig).filter(GuildConfig.guild_id == str(guild.id)).delete()
db.commit()
db.close()
logging.info(f"Deleted data for guild {guild.id} after removal")
except Exception as e:
logging.error(f"Failed to cleanup data for guild {guild.id}: {e}")
client = MyClient(intents=intents)
# 6. Slash Commands
@client.tree.command(name="setup", description="Configure bot preferences for this server")
@app_commands.checks.has_permissions(administrator=True)
async def setup(interaction: discord.Interaction):
embed = discord.Embed(
title="⚙️ HackRadar Setup",
description="Please select your preferences below:\n\n"
"1. **Platforms**: Choose which platforms to track.\n"
"2. **Themes**: Choose which themes to track.\n"
"3. **Channel**: Select where to post notifications.\n\n"
"💡 *Leave empty to receive all notifications.*\n\n"
"Click **Save Preferences** when done.",
color=discord.Color.blue(),
)
view = SetupView(str(interaction.guild_id))
await interaction.response.send_message(embed=embed, view=view, ephemeral=True)
@setup.error
async def setup_error(interaction: discord.Interaction, error: app_commands.AppCommandError):
if isinstance(error, app_commands.MissingPermissions):
await interaction.response.send_message(
"❌ You need Administrator permissions to use this command.", ephemeral=True
)
else:
await interaction.response.send_message(
f"❌ An error occurred: {str(error)}", ephemeral=True
)
@client.tree.command(name="search", description="Search hackathons by keywords.")
@app_commands.allowed_installs(guilds=True, users=True)
@app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
@app_commands.describe(keyword="Search term (e.g.,AI, Blockchain, Data Science)")
async def search(interaction: discord.Interaction, keyword: str):
await interaction.response.defer(thinking=True)
db = SessionLocal()
try:
logging.info(f"Search query: {keyword} by user {interaction.user.id}")
results = search_hackathons(db, keyword)
except Exception as e:
logging.error(f"Error searching hackathons: {e}")
await interaction.followup.send(
"❌ An error occurred while searching the database. Please try again later.",
ephemeral=True,
)
return
finally:
db.close()
if not results:
await interaction.followup.send(f"❌ No hackathons found for **{keyword}**", ephemeral=True)
return
if interaction.guild:
if not interaction.guild.me:
await interaction.followup.send(
"⚠️ **I'm not installed in this server!**\n\n"
"You have two options:\n"
"1️⃣ **Use me in DMs**: Send me a direct message and use this command there\n"
"2️⃣ **Add me to this server**: Ask a server admin to invite me\n\n"
"💡 *Tip: All search commands work perfectly in DMs!*",
ephemeral=True,
)
return
if interaction.channel:
permissions = interaction.channel.permissions_for(interaction.guild.me)
if permissions.send_messages and permissions.embed_links:
try:
await interaction.followup.send(
f"🔍 Found **{len(results)}** hackathon(s) for **{keyword}**:"
)
await send_hackathon_notifications(
client, results, target_channel=interaction.channel
)
except discord.Forbidden:
await interaction.followup.send(
"⚠️ **Permission Error**: I don't have permission to send messages in this channel.",
ephemeral=True,
)
except Exception as e:
logging.error(f"Error sending hackathons to channel: {e}")
await interaction.followup.send(
"⚠️ An error occurred while sending the results.", ephemeral=True
)
else:
await interaction.followup.send(
"⚠️ I found hackathons, but I don't have permission to send messages or embeds in this channel.",
ephemeral=True,
)
else:
await interaction.followup.send(
"⚠️ Unable to determine the channel context.", ephemeral=True
)
else:
logging.info(
f"Sending {len(results)} search results to user {interaction.user.id} via DM with pagination"
)
try:
paginator = HackathonPaginator(results, context_type="dm")
msg, embed, view_buttons = paginator.create_embed()
paginator.add_action_buttons(view_buttons)
await interaction.followup.send(
content=f"🔍 Found **{len(results)}** hackathon(s) for **{keyword}**:\n\n{msg}",
embed=embed,
view=paginator,
)
logging.info(f"Sent paginated search results to user {interaction.user.id}")
except Exception as e:
logging.error(f"Failed to send paginated search results: {e}")
await interaction.followup.send(
f"⚠️ Error displaying hackathons. Found {len(results)} results but couldn't display them properly.",
ephemeral=True,
)
async def platform_autocomplete(
interaction: discord.Interaction,
current: str,
) -> list[app_commands.Choice[str]]:
"""Autocomplete for platform names."""
platforms = [
"devfolio",
"devpost",
"unstop",
"mlh",
"dorahacks",
"hack2skill",
"kaggle",
]
# Filter platforms based on what user is typing
return [
app_commands.Choice(name=platform.title(), value=platform)
for platform in platforms
if current.lower() in platform.lower()
]
@client.tree.command(
name="platform", description="Get upcoming hackathons from a specific platform"
)
@app_commands.allowed_installs(guilds=True, users=True)
@app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
@app_commands.describe(name="Select a platform", count="Number of results to return (default 3)")
@app_commands.autocomplete(name=platform_autocomplete)
async def platform(interaction: discord.Interaction, name: str, count: int = 3):
await interaction.response.defer(thinking=True)
db = SessionLocal()
try:
logging.info(f"Platform query: {name} by user {interaction.user.id}")
results = get_hackathons_by_platform(db, name, count)
except Exception as e:
logging.error(f"Error fetching hackathons by platform: {e}")
await interaction.followup.send(
"❌ An error occurred while fetching hackathons. Please try again later.",
ephemeral=True,
)
return
finally:
db.close()
if not results:
await interaction.followup.send(
f"❌ No upcoming hackathons found for platform **{name}**", ephemeral=True
)
return
if interaction.guild:
if not interaction.guild.me:
await interaction.followup.send(
"⚠️ **I'm not installed in this server!**\n\n"
"You have two options:\n"
"1️⃣ **Use me in DMs**: Send me a direct message and use this command there\n"
"2️⃣ **Add me to this server**: Ask a server admin to invite me\n\n"
"💡 *Tip: All search commands work perfectly in DMs!*",
ephemeral=True,
)
return
if interaction.channel:
permissions = interaction.channel.permissions_for(interaction.guild.me)
if permissions.send_messages and permissions.embed_links:
try:
await interaction.followup.send(
f"🔍 Found **{len(results)}** hackathon(s) from **{name}**:"
)
await send_hackathon_notifications(
client, results, target_channel=interaction.channel
)
except discord.Forbidden:
await interaction.followup.send(
"⚠️ **Permission Error**: I don't have permission to send messages in this channel.",
ephemeral=True,
)
except Exception as e:
logging.error(f"Error sending hackathons to channel: {e}")
await interaction.followup.send(
"⚠️ An error occurred while sending the results.", ephemeral=True
)
else:
await interaction.followup.send(
"⚠️ I found hackathons, but I don't have permission to send messages or embeds in this channel.",
ephemeral=True,
)
else:
await interaction.followup.send(
"⚠️ Unable to determine the channel context.", ephemeral=True
)
else:
logging.info(
f"Sending {len(results)} platform results to user {interaction.user.id} via DM with pagination"
)
try:
paginator = HackathonPaginator(results, context_type="dm")
msg, embed, view_buttons = paginator.create_embed()
paginator.add_action_buttons(view_buttons)
await interaction.followup.send(
content=f"🔍 Found **{len(results)}** hackathon(s) from **{name}**:\n\n{msg}",
embed=embed,
view=paginator,
)
logging.info(f"Sent paginated platform results to user {interaction.user.id}")
except Exception as e:
logging.error(f"Failed to send paginated platform results: {e}")
await interaction.followup.send(
f"⚠️ Error displaying hackathons. Found {len(results)} results but couldn't display them properly.",
ephemeral=True,
)
@client.tree.command(name="upcoming", description="Get hackathons starting in the next X days")
@app_commands.allowed_installs(guilds=True, users=True)
@app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
@app_commands.describe(days="Number of days to look ahead (default 7)")
async def upcoming(interaction: discord.Interaction, days: int = 7):
await interaction.response.defer(thinking=True)
db = SessionLocal()
try:
results = get_upcoming_hackathons(db, days)
except Exception as e:
logging.error(f"Error fetching upcoming hackathons: {e}")
await interaction.followup.send(
"❌ An error occurred while fetching upcoming hackathons. Please try again later.",
ephemeral=True,
)
return
finally:
db.close()
if not results:
await interaction.followup.send(
f"❌ No upcoming hackathons found in the next **{days}** days.", ephemeral=True
)
return
if interaction.guild:
if not interaction.guild.me:
await interaction.followup.send(
"⚠️ **I'm not installed in this server!**\n\n"
"You have two options:\n"
"1️⃣ **Use me in DMs**: Send me a direct message and use this command there\n"
"2️⃣ **Add me to this server**: Ask a server admin to invite me\n\n"
"💡 *Tip: All search commands work perfectly in DMs!*",
ephemeral=True,
)
return
if interaction.channel:
permissions = interaction.channel.permissions_for(interaction.guild.me)
if permissions.send_messages and permissions.embed_links:
try:
await send_hackathon_notifications(
client, results, target_channel=interaction.channel
)
except discord.Forbidden:
await interaction.followup.send(
"⚠️ **Permission Error**: I don't have permission to send messages in this channel.",
ephemeral=True,
)
except Exception as e:
logging.error(f"Error sending hackathons to channel: {e}")
await interaction.followup.send(
"⚠️ An error occurred while sending the results.", ephemeral=True
)
else:
await interaction.followup.send(
"⚠️ I found hackathons, but I don't have permission to send messages or embeds in this channel.",
ephemeral=True,
)
else:
await interaction.followup.send(
"⚠️ Unable to determine the channel context.", ephemeral=True
)
else:
logging.info(
f"Sending {len(results)} upcoming results to user {interaction.user.id} via DM with pagination"
)
try:
paginator = HackathonPaginator(results, context_type="dm")
msg, embed, view_buttons = paginator.create_embed()
paginator.add_action_buttons(view_buttons)
await interaction.followup.send(
content=f"📅 Found **{len(results)}** upcoming hackathon(s) in the next **{days}** days:\n\n{msg}",
embed=embed,
view=paginator,
)
logging.info(f"Sent paginated results to user {interaction.user.id}")
except Exception as e:
logging.error(f"Failed to send paginated hackathons: {e}")
await interaction.followup.send(
f"⚠️ Error displaying hackathons. Found {len(results)} results but couldn't display them properly.",
ephemeral=True,
)
@client.tree.command(
name="subscribe", description="Subscribe to hackathon notifications for a specific theme"
)
@app_commands.allowed_installs(guilds=True, users=True)
@app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
@app_commands.describe(theme="The theme to subscribe to (e.g., AI, Blockchain)")
async def subscribe(interaction: discord.Interaction, theme: str):
await interaction.response.defer(ephemeral=True)
db = SessionLocal()
try:
sub, is_new = subscribe_user(db, interaction.user.id, theme)
if is_new:
await interaction.followup.send(
f"✅ You have successfully subscribed to **{theme}** updates!"
)
else:
await interaction.followup.send(f"ℹ️ You are already subscribed to **{theme}**.")
except Exception as e:
await interaction.followup.send(f"❌ Error subscribing: {str(e)}")
logging.error(f"Error in subscribe command: {e}")
finally:
db.close()
@client.tree.command(
name="unsubscribe", description="Unsubscribe from hackathon notifications for a specific theme"
)
@app_commands.allowed_installs(guilds=True, users=True)
@app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
@app_commands.describe(theme="The theme to unsubscribe from")
async def unsubscribe(interaction: discord.Interaction, theme: str):
await interaction.response.defer(ephemeral=True)
db = SessionLocal()
try:
removed = unsubscribe_user(db, interaction.user.id, theme)
if removed:
await interaction.followup.send(
f"✅ You have successfully unsubscribed from **{theme}** updates."
)
else:
await interaction.followup.send(f"ℹ️ You were not subscribed to **{theme}**.")
except Exception as e:
await interaction.followup.send(f"❌ Error unsubscribing: {str(e)}")
logging.error(f"Error in unsubscribe command: {e}")
finally:
db.close()
@client.tree.command(name="subscriptions", description="View all your theme subscriptions")
@app_commands.allowed_installs(guilds=True, users=True)
@app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
async def subscriptions(interaction: discord.Interaction):
await interaction.response.defer(ephemeral=True)
db = SessionLocal()
try:
user_subs = get_user_subscriptions(db, interaction.user.id)
if not user_subs:
embed = discord.Embed(
title="📋 Your Subscriptions",
description="You don't have any active subscriptions yet.\n\nUse `/subscribe [theme]` to start receiving notifications!",
color=discord.Color.blue(),
)