Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
9c89286
Regalia 向けの サービスを実装
nishinoyama Mar 7, 2025
3f4ab31
contestant サービスの定義
nishinoyama Mar 7, 2025
ba17942
contestants サービスをBotに持たせる
nishinoyama Mar 7, 2025
f12bc82
regalia の contestant と team のAPIの型に対応
nishinoyama Mar 10, 2025
78211a2
コードの順番を調整
nishinoyama Mar 10, 2025
9a5aeb7
configファイルもしくは、regaliaのチームを取得する方式に
nishinoyama Mar 10, 2025
ebd4dcb
configファイルもしくは、regaliaの問題群を取得する方式に
nishinoyama Mar 10, 2025
d0652e8
serviceの命名の修正
nishinoyama Mar 10, 2025
ef01d9f
環境変数を読んで起動するコンテナイメージを作る
tosuke Mar 11, 2025
323dae0
feature/regalia-service でもビルドする
tosuke Mar 11, 2025
6ce327d
Merge pull request #48 from ictsc/feature/containerize
tosuke Mar 11, 2025
d1df503
特に regalia の興味のない部分の dead_code を allow
nishinoyama Mar 11, 2025
fa00187
log や err ハンドルを調整
nishinoyama Mar 11, 2025
fcccaa3
helpチャンネルを破壊しない
nishinoyama Mar 11, 2025
414ff0d
.env を gitignore
nishinoyama Mar 11, 2025
ca8a40c
clippy した
nishinoyama Mar 11, 2025
808be51
api URL の修正
nishinoyama Mar 11, 2025
c5003f7
syncコマンド実行時の文面の修正
nishinoyama Mar 12, 2025
d9e14d2
regaliaが無を返す場合に対応
nishinoyama Mar 12, 2025
882368c
Regalia の ListDeployments を読めるように
nishinoyama Mar 13, 2025
e508ae2
Regalia の Deploy を叩けるようにした
nishinoyama Mar 13, 2025
2aa0b64
RegaliaRedeployment から botのRedeployStatus への変換を修正
nishinoyama Mar 13, 2025
7b1115f
スコアサーバー未登録に対するエラーの追加
nishinoyama Mar 13, 2025
3546893
SIGTERM を受け取れるようにし、そのまま終了するようにした
nishinoyama Mar 14, 2025
661f6c5
SIGINT でも落ちるようにした
nishinoyama Mar 14, 2025
425bf0e
join コマンドですっとぼける
nishinoyama Mar 14, 2025
e19cbe8
redeploy コマンドそのものを無効化
nishinoyama Mar 14, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 23 additions & 4 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,13 @@ name: Build and publish ictsc-discord-bot Docker image

on:
push:
branches: [master]
branches:
- master
- feature/regalia-service
pull_request:
branches: [master]
branches:
- master
- feature/regalia-service

jobs:
build-and-publish:
Expand All @@ -15,6 +19,18 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Buildx
uses: docker/setup-buildx-action@v3

- name: Docker metadata
id: meta
uses: docker/metadata-action@v5
with:
images: |
ghcr.io/${{ github.repository }}
tags: |
type=ref,event=branch
type=sha

- name: Sign in to GitHub Packages
uses: docker/login-action@v3
Expand All @@ -27,5 +43,8 @@ jobs:
uses: docker/build-push-action@v5
with:
context: .
push: true
tags: ghcr.io/${{ github.repository }}:${{ github.sha }}
push: ${{ github.event_name != 'pull_request' }}
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
/target

bot.yaml
.env
24 changes: 24 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,13 @@ chrono = { version = "0.4.31", features = ["serde"] }
chrono-tz = "0.8.4"
clap = { version = "4.4.2", features = ["derive"] }
derive_builder = "0.12.0"
reqwest = { version = "0.11.9", features = ["json"] }
reqwest = { version = "0.11.9", features = ["json", "gzip"] }
serde = "1.0.131"
serde_derive = "1.0.131"
serde_json = "1.0.108"
serde_yaml = "0.8.21"
serenity = { version = "0.12.2", default-features = false, features = ["client", "collector", "gateway", "rustls_backend", "model", "unstable_discord_api"] }
thiserror = "1.0.30"
tokio = { version = "1.0", features = ["macros", "rt-multi-thread"] }
tokio = { version = "1.0", features = ["macros", "rt-multi-thread", "signal"] }
tracing = "0.1.30"
tracing-subscriber = "0.3.8"
36 changes: 28 additions & 8 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,12 +1,32 @@
FROM rust:1.82
FROM rust:1.82.0-bullseye AS builder

WORKDIR /app
RUN cargo new --bin bot
WORKDIR /bot

COPY . .
# Build dependencies
RUN --mount=type=bind,source=Cargo.lock,target=Cargo.lock \
--mount=type=bind,source=Cargo.toml,target=Cargo.toml \
cargo build --release && rm src/*.rs

RUN --mount=type=cache,target=/usr/local/cargo/registry \
--mount=type=cache,target=/app/target \
cargo build --release && \
cp /app/target/release/bot /bot
# Build app
RUN --mount=type=bind,source=src,target=src \
--mount=type=bind,source=Cargo.lock,target=Cargo.lock \
--mount=type=bind,source=Cargo.toml,target=Cargo.toml \
cargo build --release

ENTRYPOINT ["/bot"]
FROM debian:bullseye-slim AS runtime

# Install libs
RUN --mount=type=cache,target=/var/lib/apt/ \
--mount=type=cache,target=/var/cache/apt/ \
apt-get update && apt-get install -y ca-certificates gettext-base

# Create non-root user
RUN useradd -r -s /bin/false bot && mkdir /etc/bot && chown bot:bot /etc/bot

COPY --chown=bot:bot bot.yaml.template /bot.yaml.template
COPY --chown=bot:bot docker-entrypoint.sh /docker-entrypoint.sh
COPY --chown=bot:bot --from=builder /bot/target/release/bot /bot

USER bot
ENTRYPOINT ["/docker-entrypoint.sh"]
15 changes: 15 additions & 0 deletions bot.yaml.template
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
staff:
password: "${STAFF_PASSWORD}"

discord:
token: "${DISCORD_TOKEN}"
application_id: ${DISCORD_APPLICATION_ID}
guild_id: ${DISCORD_GUILD_ID}
disabled_commands: []

redeploy:
regalia:
baseurl: "${ADMIN_APIBASE}"
token: "${ADMIN_TOKEN}"
notifiers: []
# vim: ft=yaml :
20 changes: 20 additions & 0 deletions docker-entrypoint.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#!/bin/bash

if [ -n "$ADMIN_TOKEN_FILE" ]; then
if [ -f "$ADMIN_TOKEN_FILE" ]; then
ADMIN_TOKEN="$(cat "$ADMIN_TOKEN_FILE")"
export ADMIN_TOKEN
fi
fi

export DISCORD_APPLICATION_ID=${DISCORD_APPLICATION_ID:-0}
export DISCORD_GUILD_ID=${DISCORD_GUILD_ID:-0}
export RUST_LOG=${RUST_LOG:-info,bot=trace}

envsubst < /bot.yaml.template > /etc/bot/bot.yaml

if [ $# -gt 0 ]; then
exec /bot "$@"
else
exec /bot --filename /etc/bot/bot.yaml start
fi
12 changes: 7 additions & 5 deletions src/bot/channels.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,9 @@ impl Bot {
tracing::info!("delete all channels");
for (channel_id, channel) in self.guild_id.channels(&self.discord_client).await? {
tracing::debug!(?channel, "delete channel");
if channel.name() == HELP_CHANNEL_NAME {
continue;
}
channel_id.delete(&self.discord_client).await?;
}
Ok(())
Expand Down Expand Up @@ -231,11 +234,11 @@ impl Bot {
?definition,
"channel is created but not synced, update channel"
);
self.edit_channel(channel, &definition).await?;
self.edit_channel(channel, definition).await?;
continue;
}

if matched_channels.len() != 0 {
if !matched_channels.is_empty() {
tracing::debug!(
?matched_channels,
"several matched channels are found, delete them"
Expand All @@ -246,16 +249,15 @@ impl Bot {
}

tracing::debug!(?definition, "create channel");
self.create_channel(&definition).await?;
self.create_channel(definition).await?;
}

tracing::debug!("delete not-defined channels");
for channel in channels.iter_mut() {
let found = definitions
.as_ref()
.iter()
.find(|d| d.name == channel.name)
.is_some();
.any(|d| d.name == channel.name);

if !found {
tracing::debug!(?channel, "delete category");
Expand Down
14 changes: 6 additions & 8 deletions src/bot/commands/join.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ type JoinCommandResult<'t, T> = std::result::Result<T, JoinCommandError<'t>>;
impl Bot {
pub fn create_join_command() -> CreateCommand {
CreateCommand::new("join")
.description("チームに参加します。")
.description("チームに参加します。(本戦では使用しません。)")
.add_option(
CreateCommandOption::new(
CommandOptionType::String,
Expand All @@ -45,12 +45,12 @@ impl Bot {
pub async fn handle_join_command(&self, interaction: &CommandInteraction) -> Result<()> {
let role_name = match self.validate_join_command(interaction) {
Ok(role_name) => role_name,
Err(err) => {
Err(_err) => {
self.respond(
interaction,
CreateInteractionResponseMessage::new()
.ephemeral(true)
.content(err.to_string()),
.content("このコマンドは現在利用できません。"),
)
.await?;
return Ok(());
Expand Down Expand Up @@ -123,20 +123,18 @@ impl Bot {
let sender_member_role_id_set = HashSet::from_iter(sender_member.roles.clone());

let target_role_id_set: HashSet<_> = self
.find_roles_by_name_cached(&role_name)
.find_roles_by_name_cached(role_name)
.await?
.iter()
.map(|role| role.id)
.collect();

let role_ids_granted: Vec<_> = target_role_id_set
.difference(&sender_member_role_id_set)
.map(|id| id.clone())
.difference(&sender_member_role_id_set).copied()
.collect();

let role_ids_revoked: Vec<_> = sender_member_role_id_set
.difference(&target_role_id_set)
.map(|id| id.clone())
.difference(&target_role_id_set).copied()
.collect();

self.grant_roles(&mut sender_member, role_ids_granted)
Expand Down
6 changes: 5 additions & 1 deletion src/bot/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ mod ask;
mod join;
mod ping;
mod redeploy;
mod sync;

use anyhow::Result;
use serenity::client::Context;
Expand All @@ -17,6 +18,8 @@ impl Bot {
tracing::debug!("Syncing join command");
Command::create_global_command(&self.discord_client, Bot::create_join_command()).await?;

tracing::debug!("Syncing sync command");
Command::create_global_command(&self.discord_client, Bot::create_sync_command()).await?;
Ok(())
}

Expand Down Expand Up @@ -88,7 +91,8 @@ impl Bot {
"ask" => self.handle_ask_command(interaction).await,
"join" => self.handle_join_command(interaction).await,
"ping" => self.handle_ping_command(interaction).await,
"redeploy" => self.handle_redeploy_command(ctx, interaction).await,
// "redeploy" => self.handle_redeploy_command(ctx, interaction).await,
"sync" => self.handle_sync_command(interaction).await,
_ => Err(anyhow::anyhow!("unknown command: {}", name)),
};

Expand Down
15 changes: 6 additions & 9 deletions src/bot/commands/redeploy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,19 +137,16 @@ impl Bot {
}

async fn get_team_for(&self, user: &User) -> RedeployCommandResult<Team> {
let member = self.get_member(&user).await?;
let member = self.get_member(user).await?;

for role_id in member.roles {
let role = self.find_roles_by_id_cached(role_id).await.unwrap();
match role {
Some(role) => {
for team in &self.teams {
if role.name == team.role_name {
return Ok(team.clone());
}
if let Some(role) = role {
for team in &self.teams {
if role.name == team.role_name {
return Ok(team.clone());
}
},
None => (),
}
}
}

Expand Down
Loading