summaryrefslogtreecommitdiff
path: root/crates/bot-client/src/lib.rs
blob: 851b8530b8e41c95d1241fa8c7550407e69b4f2e (plain)
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
use bot_config::Config;
use bot_error::Error;
use bot_http as http;

use std::sync::Arc;

use log::trace;
use serenity::prelude::{Client, GatewayIntents, TypeMapKey};

mod handler;

use handler::Handler;

/// Container for [`http::Client`]
struct SharedHttp;

impl TypeMapKey for SharedHttp {
	type Value = Arc<http::Client>;
}

/// Container for [`Config`]
struct SharedConfig;

impl TypeMapKey for SharedConfig {
	type Value = Arc<Config>;
}

/// Fetch our bot token
fn token() -> Result<String, Error> {
	let token = std::env::var("DISCORD_BOT_TOKEN")?;
	Ok(token)
}

/// Create our client
///
/// # Errors
///
/// Will return [`Err`] if a [`Client`] cannot be created or configuration
/// cannot be created from the environment.
///
/// # Panics
///
/// Will [`panic!`] if the bot token isn't found or the ctrl+c handler can't be made
pub async fn get() -> Result<Client, Error> {
	let token = token().expect("Couldn't find token in environment! Is DISCORD_BOT_TOKEN set?");

	let intents = GatewayIntents::default();
	trace!("Creating client");
	let client = Client::builder(token, intents)
		.event_handler(Handler)
		.await?;

	// add state stuff
	let http_client = <http::Client as http::ClientExt>::default();
	let config = Config::from_env()?;

	{
		let mut data = client.data.write().await;

		data.insert::<SharedHttp>(Arc::new(http_client));
		data.insert::<SharedConfig>(Arc::new(config.clone()));
	}

	let shard_manager = client.shard_manager.clone();

	// gracefully shutdown on ctrl+c
	tokio::spawn(async move {
		#[cfg(target_family = "unix")]
		tokio::signal::ctrl_c()
			.await
			.expect("Couldn't register ctrl+c handler!");
		shard_manager.shutdown_all().await;
	});

	// run our jobs
	bot_jobs::dispatch(config)?;

	Ok(client)
}