Skip to content

Commit 5c7e509

Browse files
authored
Merge pull request #17 from pictures2333/master
fix some bug of ctf channel join button and show more information in /ctf_menu
2 parents 970e19d + a956129 commit 5c7e509

File tree

10 files changed

+139
-33
lines changed

10 files changed

+139
-33
lines changed

.env.example

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@ DISCORD_BOT_TOKEN=your_discord_bot_token_here
33

44
# CTF Tracking Configuration
55
CHECK_INTERVAL_MINUTES=30
6-
ANNOUNCEMENT_CHANNEL_NAME=your_channel_name_here
6+
ANNOUNCEMENT_CHANNEL_ID=your_channel_id_here
7+
CTF_CHANNEL_CATETORY_ID=your_category_id_here
78

89
# Misc
910
TIMEZONE="Asia/Taipei"

README.md

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,9 @@ Then edit the `.env` file with your specific settings. Focus on these key variab
7474
|----------|-------------|---------|
7575
| `DISCORD_BOT_TOKEN` | Your Discord bot token | `MTIzNDU2Nzg5...` |
7676
| `CHECK_INTERVAL_MINUTES` | How often to check for new CTFs | `30` (default) |
77-
| `ANNOUNCEMENT_CHANNEL_ID` | Channel name for announcements | `ctf-announcements` |
77+
| `ANNOUNCEMENT_CHANNEL_ID` | Channel id for announcements | `911612541829009418` |
78+
| `CTF_CHANNEL_CATETORY_ID` | Category id for CTF event channel creations | `1454642939559940329` |
79+
| `TIMEZONE` | time zone for displaying | `Asia/Taipei` (default) |
7880

7981
*Other configuration options can remain at their default values.*
8082

@@ -119,4 +121,4 @@ Once running, the bot will:
119121

120122
1. Automatically check CTFtime.org for new CTF events
121123
2. Post announcements in your designated Discord channel
122-
3. Use `data/known_events.json` to track announced events and avoid duplicates
124+
3. Use `data/database.db` to track announced events, avoid duplicates, record CTF event channel, and more.

pyproject.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ dependencies = [
1414
"sqlalchemy>=2.0.45",
1515
"aiosqlite>=0.22.1",
1616
"pydantic-settings>=2.12.0",
17+
"fastapi>=0.128.0",
18+
"uvicorn>=0.40.0",
1719
]
1820

1921
[dependency-groups]

setup_env.sh

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -112,10 +112,23 @@ fi
112112
echo ""
113113
echo "Announcement Channel ID:"
114114
echo " The Discord channel where CTF announcements will be posted"
115-
echo " The channel name that on your server"
115+
echo " The channel id that on your server"
116116
while true; do
117-
read -p " Paste your Discord Channel Name: " ANNOUNCEMENT_CHANNEL_NAME
118-
if [ -n "$ANNOUNCEMENT_CHANNEL_NAME" ]; then
117+
read -p " Paste your Discord Channel ID: " ANNOUNCEMENT_CHANNEL_ID
118+
if [ -n "$ANNOUNCEMENT_CHANNEL_ID" ]; then
119+
break
120+
else
121+
echo " Error: Discord Channel Name cannot be empty. Please try again."
122+
fi
123+
done
124+
125+
echo ""
126+
echo "CTF Channel Category ID:"
127+
echo " The Discord category where CTF channels will be created"
128+
echo " The category id that on your server"
129+
while true; do
130+
read -p " Paste your Discord Category ID: " CTF_CHANNEL_CATETORY_ID
131+
if [ -n "$CTF_CHANNEL_CATETORY_ID" ]; then
119132
break
120133
else
121134
echo " Error: Discord Channel Name cannot be empty. Please try again."
@@ -135,7 +148,8 @@ echo ""
135148
echo "Please review your configuration:"
136149
echo " Discord Bot Token: ${DISCORD_BOT_TOKEN:0:30}********** (hidden)"
137150
echo " Check Interval: $CHECK_INTERVAL_MINUTES minutes"
138-
echo " Announcement Channel Name: $ANNOUNCEMENT_CHANNEL_NAME"
151+
echo " Announcement Channel ID: $ANNOUNCEMENT_CHANNEL_ID"
152+
echo " CTF Channel Category ID: $CTF_CHANNEL_CATETORY_ID"
139153
echo " Time Zone: $TIMEZONE"
140154
echo ""
141155

@@ -166,7 +180,8 @@ DISCORD_BOT_TOKEN=$DISCORD_BOT_TOKEN
166180
167181
# CTF Tracking Configuration
168182
CHECK_INTERVAL_MINUTES=$CHECK_INTERVAL_MINUTES
169-
ANNOUNCEMENT_CHANNEL_NAME=$ANNOUNCEMENT_CHANNEL_NAME
183+
ANNOUNCEMENT_CHANNEL_ID=$ANNOUNCEMENT_CHANNEL_ID
184+
CTF_CHANNEL_CATETORY_ID=$CTF_CHANNEL_CATETORY_ID
170185
171186
# Misc
172187
TIMEZONE="$TIMEZONE"

src/cogs/bgtask_interactions.py

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -18,21 +18,13 @@
1818

1919
# utils
2020
async def get_announcement_channel(bot:commands.Bot) -> discord.TextChannel:
21-
channel_name = settings.ANNOUNCEMENT_CHANNEL_NAME
22-
23-
channel = None
24-
for guild in bot.guilds:
25-
for text_channel in guild.text_channels:
26-
if text_channel.name.lower() == channel_name.lower():
27-
channel = text_channel
28-
break
29-
if channel:
30-
break
21+
channel_id = settings.ANNOUNCEMENT_CHANNEL_ID
22+
channel = bot.get_channel(channel_id)
3123

3224
if not channel:
33-
logger.error(f"Can't find channel named '{channel_name}'")
25+
logger.error(f"Can't find channel id={channel_id}")
3426
logger.error(f"Please check:")
35-
logger.error(f"1. Channel name is correct: {channel_name}")
27+
logger.error(f"1. Channel ID is correct: {channel_id}")
3628
logger.error(f"2. Bot has permission to view the channel")
3729
logger.error(f"3. The channel exists in the server where the Bot is located")
3830
await bot.close()
@@ -85,6 +77,7 @@ async def task_checks(self):
8577
await crud.create_event(session, new_events_db)
8678

8779
for event in new_events_ctftime:
80+
event_id = event["id"]
8881
embed = await create_event_embed(event, "有新的 CTF 競賽!")
8982

9083
view = discord.ui.View(timeout=None)

src/cogs/ctf.py

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -112,11 +112,11 @@ async def callback(self, interaction: discord.Interaction):
112112
channel_name = self.children[0].value
113113

114114
# find category
115-
category_name = "Incoming/Running CTF"
115+
category_id = settings.CTF_CHANNEL_CATETORY_ID
116116
guild = interaction.guild
117-
category = discord.utils.get(interaction.guild.categories, name=category_name)
117+
category = discord.utils.get(interaction.guild.categories, id=category_id)
118118
if category is None:
119-
await interaction.followup.send(content=f"Category '{category_name}' not found.", ephemeral=True)
119+
await interaction.followup.send(content=f"Category id={category_id} not found", ephemeral=True)
120120
return
121121

122122
# create channel
@@ -205,17 +205,26 @@ async def ctf_menu(self, ctx:discord.ApplicationContext):
205205
known_events:List[Event] = await crud.read_event(session)
206206

207207
# embed
208+
time_now = datetime.now().timestamp()
209+
208210
embed = discord.Embed(
209211
title=f"{settings.EMOJI} CTF events tracked",
210212
color=discord.Color.green()
211213
)
212214
for event in known_events:
215+
mark = ""
216+
if not(event.channel_id is None):
217+
mark += "[⭐️]"
218+
if event.start <= time_now and event.finish >= time_now:
219+
mark += "[🏃]"
220+
213221
embed.add_field(
214-
name=f"[id={event.event_id}] {event.title}",
222+
name=f"{mark}[id={event.event_id}] {event.title}",
215223
value=f"start at {datetime.fromtimestamp(event.start).astimezone(ZoneInfo(settings.TIMEZONE))}\n\
216224
finish at {datetime.fromtimestamp(event.finish).astimezone(ZoneInfo(settings.TIMEZONE))}",
217225
inline=False
218226
)
227+
embed.set_footer(text="[🏃] running ctf\n[⭐️] channel created")
219228

220229
await ctx.response.send_message(embed=embed, view=CTFMenuView(self.bot), ephemeral=True)
221230

src/config.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,17 +7,14 @@ class Settings(BaseSettings):
77
# CTFTime tracking configuration
88
CTFTIME_API_URL:str="https://ctftime.org/api/v1/events/"
99
TEAM_API_URL:str="https://ctftime.org/api/v1/teams/"
10-
CTFTIME_SEARCH_DAYS:int=+90
1110
DATABASE_SEARCH_DAYS:int=-90 # known events: finish > now_day+(-90)
12-
ANNOUNCEMENT_CHANNEL_NAME:str
11+
ANNOUNCEMENT_CHANNEL_ID:int
12+
CTF_CHANNEL_CATETORY_ID:int
1313
CHECK_INTERVAL_MINUTES:int
1414

1515
# Database configuration
1616
DATABASE_URL:str="sqlite+aiosqlite:///data/database.db"
1717

18-
# Notification (todo)
19-
#NOTIFY_BEFORE_EVENT:int = 1 * 24 * 60 * 60
20-
2118
# Misc
2219
TIMEZONE:str
2320
EMOJI:str="🚩"

src/utils/ctf_api.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ async def fetch_ctf_events(event_id:Optional[int]=None) -> List[Dict[str, Any]]:
1212
params = {
1313
"limit": 20,
1414
"start": int(datetime.now().timestamp()),
15-
"finish": int((datetime.now() + timedelta(days=settings.CTFTIME_SEARCH_DAYS)).timestamp()),
15+
#"finish": int((datetime.now() + timedelta(days=settings.CTFTIME_SEARCH_DAYS)).timestamp()),
1616
}
1717

1818
url = settings.CTFTIME_API_URL

src/utils/join_channel.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
from src import crud
1010
from src.utils.ctf_api import fetch_ctf_events
1111
from src.utils.embed_creator import create_event_embed
12+
from src.config import settings
1213

1314
logger = logging.getLogger(__name__)
1415

@@ -59,11 +60,11 @@ async def join_channel(
5960
event_api:Event = events_api[0]
6061

6162
# create channel
62-
category_name = "Incoming/Running CTF"
63+
category_id = settings.CTF_CHANNEL_CATETORY_ID
6364
guild = interaction.guild
64-
category = discord.utils.get(interaction.guild.categories, name=category_name)
65+
category = discord.utils.get(interaction.guild.categories, id=category_id)
6566
if category is None:
66-
await interaction.followup.send(content=f"Category '{category_name}' not found.", ephemeral=True)
67+
await interaction.followup.send(content=f"Category id={category_id} not found", ephemeral=True)
6768
return
6869

6970
overwrites = {

uv.lock

Lines changed: 86 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)