Skip to content

Commit

Permalink
Merge pull request #2 from GiganticMinecraft/feat/load-config
Browse files Browse the repository at this point in the history
feat: コンフィグの読み込みロジックを追加
  • Loading branch information
m1sk9 authored Oct 11, 2023
2 parents e9b1c0b + e8e064b commit b41c43d
Show file tree
Hide file tree
Showing 6 changed files with 132 additions and 5 deletions.
49 changes: 48 additions & 1 deletion Cargo.lock

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

3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ dotenvy = { version = "0.15.7" }
once_cell = { version = "1.18.0" }
tracing = { version = "0.1.37" }
tracing-subscriber = { version = "0.3.17" }
serde = { version = "1.0.188", features = ["derive"] }
serde_yaml = { version = "0.9.25" }
envy = { version = "0.4.2" }

[dependencies.serenity]
version = "0.11.6"
Expand Down
1 change: 1 addition & 0 deletions assets/config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
reactions: ["👍", "👎"]
36 changes: 36 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
use anyhow::Context;
use once_cell::sync::OnceCell;
use serde::{Deserialize, Serialize};
use std::fs::File;
use std::io::BufReader;
use tracing::log::info;

#[derive(Default, Deserialize, Debug)]
pub struct IdeaReactionConfig {
pub reactions: Vec<String>,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct IdeaReactionEnv {
pub discord_api_token: String,
pub target_channel_id: u64,
pub target_guild_id: u64,
pub target_webhook_id: u64,
}

pub fn load_config() -> anyhow::Result<IdeaReactionConfig> {
let config: IdeaReactionConfig = serde_yaml::from_reader(BufReader::new(
File::open("./assets/config.yaml").context("Failed to open config file")?,
))
.context("Failed to parse config file")?;

// TODO: このチェックを厳格化する
if config.reactions.is_empty() {
panic!("No reactions found in config file");
}

info!("Loaded config: {:?}", config.reactions);
Ok(config)
}

pub static ENV_CONFIG: OnceCell<IdeaReactionEnv> = OnceCell::new();
37 changes: 35 additions & 2 deletions src/events.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use crate::config::ENV_CONFIG;
use serenity::async_trait;
use serenity::client::Context;
use serenity::model::gateway::Ready;
use serenity::model::gateway::{Activity, Ready};
use serenity::model::prelude::{ChannelId, GuildId, Webhook};
use serenity::prelude::EventHandler;
use tracing::log::info;

Expand All @@ -9,6 +11,37 @@ pub struct EvHandler;
#[async_trait]
impl EventHandler for EvHandler {
async fn ready(&self, ctx: Context, bot: Ready) {
info!("{} is connected!", bot.user.name);
let env_config = ENV_CONFIG.get().unwrap();
info!(
"{name}({id}) is connected!",
name = bot.user.name,
id = bot.user.id
);

let guild = GuildId(env_config.target_guild_id);
let channel = guild.channels(&ctx.http).await.unwrap();

match channel.get(&ChannelId(env_config.target_channel_id)) {
Some(channel) => {
info!("Watching channel: {}", channel.name);
ctx.set_activity(Activity::watching(&channel.name)).await;

let webhook = channel.webhooks(&ctx.http).await.unwrap();
let target_webhook = webhook
.iter()
.find(|webhook| webhook.id == env_config.target_webhook_id);
match target_webhook {
Some(w) => {
info!("Watching webhook: {}", w.name.clone().unwrap());
}
None => {
panic!("Target webhook is not found");
}
}
}
None => {
panic!("Target channel is not found");
}
}
}
}
11 changes: 9 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,24 @@
use crate::client::discord::create_discord_client;
use crate::config::{load_config, IdeaReactionEnv, ENV_CONFIG};
use dotenvy::dotenv;
use std::env;

mod client;
mod config;
mod events;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
dotenv().ok();
tracing_subscriber::fmt().compact().init();

let token = env::var("DISCORD_API_TOKEN").expect("Expected a token in the environment");
let mut client = create_discord_client(&token).await?;
ENV_CONFIG
.set(envy::from_env::<IdeaReactionEnv>().expect("Failed to load environment variables"))
.unwrap();

let mut client = create_discord_client(&ENV_CONFIG.get().unwrap().discord_api_token).await?;

load_config()?;

if let Err(why) = client.start().await {
println!("Failed run discord client: {:?}", why);
Expand Down

0 comments on commit b41c43d

Please sign in to comment.