Some checks failed
Gitea Actions Demo / Explore-Gitea-Actions (push) Failing after 13m53s
## HTTP Client Refactoring - Create unified HttpClient module (src/http_client.rs) - Refactor 24 files to use shared HTTP client - Replace .unwrap() with proper error handling - Eliminate code duplication in HTTP requests ## Project Restructuring - Rename package: ai → aibot - Add dual binary support: aibot (main) + ai (compatibility alias) - Migrate config directory: ~/.config/ai/ → ~/.config/syui/ai/bot/ - Implement backward compatibility with automatic migration ## Testing Infrastructure - Add unit tests for HttpClient - Create test infrastructure with cargo-make - Add test commands: test, test-quick, test-verbose ## Documentation - Complete migration guide with step-by-step instructions - Updated development guide with new structure - HTTP client API reference documentation - Comprehensive refactoring summary ## Files Changed - Modified: 24 source files (HTTP client integration) - Added: src/http_client.rs, src/alias.rs, src/tests/ - Added: 5 documentation files in docs/ - Added: migration setup script 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
332 lines
7.7 KiB
Markdown
332 lines
7.7 KiB
Markdown
# ai.bot 開発ガイド
|
||
|
||
## プロジェクト概要
|
||
|
||
ai.botは、Rust製のBluesky(AT Protocol)ボットです。メンション応答、コマンド実行、OpenAI統合などの機能を提供します。
|
||
|
||
**重要**: 2025年6月6日より、パッケージ名とCLI名が統一されました:
|
||
- **新CLI名**: `aibot` (推奨)
|
||
- **旧CLI名**: `ai` (互換性維持)
|
||
- **設定ディレクトリ**: `~/.config/syui/ai/bot/` (旧: `~/.config/ai/`)
|
||
|
||
詳細は[移行ガイド](./migration-guide.md)を参照してください。
|
||
|
||
## アーキテクチャ
|
||
|
||
### 主要コンポーネント
|
||
|
||
1. **HTTPクライアント** (`src/http_client.rs`)
|
||
- AT Protocol API呼び出しの統一インターフェース
|
||
- 認証処理の自動化
|
||
- エラーハンドリングの標準化
|
||
|
||
2. **コマンドシステム** (`src/main.rs`)
|
||
- Seahorseを使用したCLIインターフェース
|
||
- 各機能への振り分け
|
||
|
||
3. **AT Protocolモジュール**
|
||
- 投稿、フォロー、いいね等の基本機能
|
||
- 認証・セッション管理
|
||
- フィード・通知処理
|
||
|
||
4. **ゲームシステム** (`src/game/`)
|
||
- カードゲーム機能
|
||
- ユーザー管理
|
||
- ゲームデータ処理
|
||
|
||
5. **外部連携**
|
||
- OpenAI API統合 (`src/openai.rs`)
|
||
- 画像処理機能
|
||
|
||
## 開発環境セットアップ
|
||
|
||
### 必要なツール
|
||
```bash
|
||
# Rust(最新安定版)
|
||
rustup update stable
|
||
|
||
# Cargo make(タスクランナー)
|
||
cargo install cargo-make
|
||
|
||
# 開発用依存関係は自動インストール
|
||
```
|
||
|
||
**注意**: 初回は`cargo install cargo-make`でcargo-makeのインストールが必要です。
|
||
|
||
### 設定ファイル
|
||
```
|
||
~/.config/syui/ai/bot/config.toml # 基本設定
|
||
~/.config/syui/ai/bot/refresh # リフレッシュトークン
|
||
~/.config/syui/ai/bot/access # アクセストークン
|
||
```
|
||
|
||
**注意**: 旧設定ディレクトリ(`~/.config/ai/`)も自動的に参照・移行されます。
|
||
|
||
## 開発ワークフロー
|
||
|
||
### 1. コード変更
|
||
```bash
|
||
# フォーマット
|
||
cargo fmt
|
||
|
||
# コンパイル確認
|
||
cargo check
|
||
|
||
# テスト実行
|
||
cargo test
|
||
```
|
||
|
||
### 2. 統合ワークフロー
|
||
```bash
|
||
# 全体フロー(フォーマット→ビルド→テスト)
|
||
cargo make my-flow
|
||
```
|
||
|
||
### 3. 個別テスト
|
||
```bash
|
||
cargo make test-quick # 素早いテスト
|
||
cargo make test-verbose # 詳細出力テスト
|
||
```
|
||
|
||
## API呼び出しパターン
|
||
|
||
### HttpClientの使用方法
|
||
|
||
#### 基本的なGETリクエスト
|
||
```rust
|
||
use crate::http_client::HttpClient;
|
||
|
||
pub async fn get_user_profile(handle: String) -> String {
|
||
let client = HttpClient::new();
|
||
let url = format!("https://bsky.social/xrpc/app.bsky.actor.getProfile?actor={}", handle);
|
||
|
||
match client.get_with_auth(&url).await {
|
||
Ok(response) => response,
|
||
Err(e) => {
|
||
eprintln!("Error getting profile: {}", e);
|
||
"err".to_string()
|
||
}
|
||
}
|
||
}
|
||
```
|
||
|
||
#### JSONを送信するPOSTリクエスト
|
||
```rust
|
||
use crate::http_client::HttpClient;
|
||
use serde_json::json;
|
||
|
||
pub async fn create_post(text: String) -> String {
|
||
let client = HttpClient::new();
|
||
let url = "https://bsky.social/xrpc/com.atproto.repo.createRecord";
|
||
|
||
let payload = json!({
|
||
"repo": "user.handle",
|
||
"collection": "app.bsky.feed.post",
|
||
"record": {
|
||
"text": text,
|
||
"createdAt": chrono::Utc::now().to_rfc3339()
|
||
}
|
||
});
|
||
|
||
match client.post_json_with_auth(&url, &payload).await {
|
||
Ok(response) => response,
|
||
Err(e) => {
|
||
eprintln!("Error creating post: {}", e);
|
||
"err".to_string()
|
||
}
|
||
}
|
||
}
|
||
```
|
||
|
||
## テストの書き方
|
||
|
||
### ユニットテスト
|
||
```rust
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
|
||
#[tokio::test]
|
||
async fn test_http_client_creation() {
|
||
let client = HttpClient::new();
|
||
// テストロジック
|
||
}
|
||
|
||
#[test]
|
||
fn test_data_parsing() {
|
||
// 同期テスト
|
||
}
|
||
}
|
||
```
|
||
|
||
### 統合テスト
|
||
```rust
|
||
#[tokio::test]
|
||
#[ignore] // 通常は無視、環境変数設定時のみ実行
|
||
async fn test_real_api() {
|
||
if std::env::var("RUN_INTEGRATION_TESTS").is_ok() {
|
||
// 実際のAPI呼び出しテスト
|
||
}
|
||
}
|
||
```
|
||
|
||
## エラーハンドリングガイドライン
|
||
|
||
### 推奨パターン
|
||
```rust
|
||
// Good: 適切なエラーハンドリング
|
||
match api_call().await {
|
||
Ok(response) => response,
|
||
Err(e) => {
|
||
eprintln!("Error in operation: {}", e);
|
||
"err".to_string()
|
||
}
|
||
}
|
||
|
||
// Bad: unwrapの使用
|
||
api_call().await.unwrap()
|
||
```
|
||
|
||
### エラーレスポンス
|
||
- API呼び出し失敗時は`"err"`文字列を返す
|
||
- ログにエラー詳細を出力
|
||
- 上位レイヤーでエラー処理を継続
|
||
|
||
## 新機能追加の手順
|
||
|
||
### 1. AT Protocol関連機能
|
||
```bash
|
||
# 1. モジュールファイルを作成
|
||
touch src/new_feature.rs
|
||
|
||
# 2. main.rsに追加
|
||
# pub mod new_feature;
|
||
|
||
# 3. HttpClientを使用して実装
|
||
# 4. テストを追加
|
||
# 5. main.rsのコマンドに追加
|
||
```
|
||
|
||
### 2. 基本的なテンプレート
|
||
```rust
|
||
use crate::http_client::HttpClient;
|
||
use crate::{data_toml, url};
|
||
use serde_json::json;
|
||
|
||
pub async fn new_feature_request(param: String) -> String {
|
||
let client = HttpClient::new();
|
||
let endpoint_url = url(&"endpoint_name");
|
||
|
||
let payload = json!({
|
||
"param": param
|
||
});
|
||
|
||
match client.post_json_with_auth(&endpoint_url, &payload).await {
|
||
Ok(response) => response,
|
||
Err(e) => {
|
||
eprintln!("Error in new_feature: {}", e);
|
||
"err".to_string()
|
||
}
|
||
}
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
|
||
#[tokio::test]
|
||
async fn test_new_feature() {
|
||
// テスト実装
|
||
}
|
||
}
|
||
```
|
||
|
||
## デバッグ方法
|
||
|
||
### 1. ログ出力
|
||
```rust
|
||
eprintln!("Debug: {}", variable);
|
||
println!("Info: {}", message);
|
||
```
|
||
|
||
### 2. テスト実行
|
||
```bash
|
||
# 特定のテストのみ
|
||
cargo test test_name
|
||
|
||
# 詳細出力
|
||
cargo test -- --nocapture
|
||
|
||
# 特定モジュール
|
||
cargo test module_name
|
||
```
|
||
|
||
### 3. HTTPリクエストのデバッグ
|
||
HttpClientモジュール内でリクエスト/レスポンスをログ出力することで、API呼び出しの詳細を確認できます。
|
||
|
||
## パフォーマンス考慮事項
|
||
|
||
### HttpClientの再利用
|
||
```rust
|
||
// Good: 一度作成して再利用
|
||
let client = HttpClient::new();
|
||
for item in items {
|
||
client.get_with_auth(&url).await;
|
||
}
|
||
|
||
// Bad: 毎回新規作成
|
||
for item in items {
|
||
let client = HttpClient::new();
|
||
client.get_with_auth(&url).await;
|
||
}
|
||
```
|
||
|
||
### 非同期処理
|
||
- 可能な限り並列処理を活用
|
||
- await呼び出しを最小限に
|
||
- tokio::joinやfutures::join_allの活用
|
||
|
||
## トラブルシューティング
|
||
|
||
### よくある問題
|
||
|
||
1. **認証エラー**
|
||
- トークンの有効期限切れ
|
||
- 設定ファイルの不備
|
||
|
||
2. **コンパイルエラー**
|
||
- 型不整合(特にライフタイム)
|
||
- 未使用のimport
|
||
|
||
3. **実行時エラー**
|
||
- ネットワーク接続問題
|
||
- API仕様変更
|
||
|
||
### 解決方法
|
||
```bash
|
||
# 設定確認(新ディレクトリ)
|
||
ls -la ~/.config/syui/ai/bot/
|
||
# 旧ディレクトリも確認
|
||
ls -la ~/.config/ai/
|
||
|
||
# トークンリフレッシュ
|
||
./target/debug/aibot refresh
|
||
# または互換性コマンド
|
||
./target/debug/ai refresh
|
||
|
||
# 詳細ログ
|
||
RUST_LOG=debug ./target/debug/aibot [command]
|
||
```
|
||
|
||
## コントリビューション
|
||
|
||
1. コードフォーマット必須: `cargo fmt`
|
||
2. テスト追加必須: 新機能には対応テスト
|
||
3. エラーハンドリング必須: `.unwrap()`の使用禁止
|
||
4. ドキュメント更新: 重要な変更は本ドキュメントも更新
|
||
|
||
## 関連ドキュメント
|
||
|
||
- [リファクタリングサマリー](./refactoring-summary.md)
|
||
- [AT Protocol仕様](https://atproto.com/)
|
||
- [Rust公式ドキュメント](https://doc.rust-lang.org/) |