From f9d8b0d33ad0ec39545ef1a66d4af42897b52c1d Mon Sep 17 00:00:00 2001 From: Ryan Hayes Date: Tue, 28 Nov 2023 21:55:05 -0500 Subject: [PATCH 1/4] Adds .env file, parsing, and displaying of the server name based on the configured server ID. --- .env.sample | 2 ++ .gitignore | 5 ++++- src/main.rs | 44 +++++++++++++++++++++++++++++++++++++++++--- 3 files changed, 47 insertions(+), 4 deletions(-) create mode 100644 .env.sample diff --git a/.env.sample b/.env.sample new file mode 100644 index 0000000..349c6d4 --- /dev/null +++ b/.env.sample @@ -0,0 +1,2 @@ +BOT_TOKEN= +SERVER_ID= \ No newline at end of file diff --git a/.gitignore b/.gitignore index 9f97022..603e19d 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,4 @@ -target/ \ No newline at end of file +target/ +.env + +.idea/ \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index 08df917..216fa4b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,9 @@ use discord::Discord; use clap::Parser; +use discord::model::ServerId; use dotenv::dotenv; +use std::str::FromStr; +use std::u64; extern crate discord; @@ -13,7 +16,17 @@ const BOT_TOKEN_LENGTH: usize = 72; pub struct Config { /// Your bot token you got from Discord Developer portal. #[arg(short, long, env("BOT_TOKEN"))] - pub bot_token: String + pub bot_token: String, + + /// Your Discord Server ID that you want to interact with + /// TODO: This will probably change if/when this bot becomes more generic. + #[arg(short, long, env("SERVER_ID"))] + pub server_id: String, + // + // /// Your Discord App's Public Key + // /// TODO: Is this needed? + // #[arg(short = "k", long, env("DISCORD_PUBLIC_KEY"))] + // pub discord_public_key: String, } impl Config { @@ -21,6 +34,14 @@ impl Config { dotenv().ok(); Self::parse() } + + /// Creates a new `Config` instance with default values. + pub fn new(bot_token: String, server_id: String) -> Self { + Self { + bot_token, + server_id, + } + } } fn get_discord(bot_token: &str) -> Discord { @@ -28,20 +49,30 @@ fn get_discord(bot_token: &str) -> Discord { panic!("invalid bot token"); } + return match Discord::from_bot_token(bot_token) { Ok(discord) => discord, Err(err) => panic!("error happened: {}", err) - } + }; +} + +/// Extracts the server id from the config +fn get_server_id(config: Config) -> u64 { + let num = u64::from_str(config.server_id.as_str()).unwrap(); + return num; } fn main() { let cfg = Config::from_env_and_args(); let discord = get_discord(cfg.bot_token.as_str()); + let server_id = ServerId(self::get_server_id(cfg)); + let server = discord.get_server(server_id).unwrap(); + println!("{}", server.name); } #[cfg(test)] mod tests { - use crate::get_discord; + use crate::{Config, get_discord, get_server_id}; #[test] #[should_panic] @@ -54,4 +85,11 @@ mod tests { // Our only validation rule right now is length get_discord("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); } + + #[test] + fn test_get_server_id() { + let config = Config::new("123".to_string(), "456".to_string()); + let expected_result = 456; + assert_eq!(expected_result, get_server_id(config)); + } } From 4d5ce4c0e60ff76021acdacfacbc3ea61b4dbee3 Mon Sep 17 00:00:00 2001 From: Ryan Hayes Date: Tue, 28 Nov 2023 21:58:48 -0500 Subject: [PATCH 2/4] Cleanup --- src/main.rs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/main.rs b/src/main.rs index 216fa4b..4e75fa6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -22,11 +22,6 @@ pub struct Config { /// TODO: This will probably change if/when this bot becomes more generic. #[arg(short, long, env("SERVER_ID"))] pub server_id: String, - // - // /// Your Discord App's Public Key - // /// TODO: Is this needed? - // #[arg(short = "k", long, env("DISCORD_PUBLIC_KEY"))] - // pub discord_public_key: String, } impl Config { From 9fa093b34d58f55f22602be8d5ffab63def4a8ca Mon Sep 17 00:00:00 2001 From: Ryan Hayes Date: Tue, 28 Nov 2023 22:22:30 -0500 Subject: [PATCH 3/4] Starts up a chatbot loop! --- src/main.rs | 41 ++++++++++++++++++++++++++++++++++------- 1 file changed, 34 insertions(+), 7 deletions(-) diff --git a/src/main.rs b/src/main.rs index 4e75fa6..6c931bb 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,9 +1,9 @@ use discord::Discord; use clap::Parser; -use discord::model::ServerId; +use discord::model::{Event, ServerId}; use dotenv::dotenv; use std::str::FromStr; -use std::u64; +use std::{u64}; extern crate discord; @@ -44,11 +44,37 @@ fn get_discord(bot_token: &str) -> Discord { panic!("invalid bot token"); } + return Discord::from_bot_token(bot_token).expect("Expected token"); +} + +fn bot_loop(discord: Discord) { + let (mut connection, _) = discord.connect().expect("connect failed"); + println!("Ready."); - return match Discord::from_bot_token(bot_token) { - Ok(discord) => discord, - Err(err) => panic!("error happened: {}", err) - }; + loop { + match connection.recv_event() { + Ok(Event::MessageCreate(message)) => { + println!("{} says: {}", message.author.name, message.content); + if message.content == "!test" { + let _ = discord.send_message( + message.channel_id, + "This is a reply to the test.", + "", + false, + ); + } else if message.content == "!quit" { + println!("Quitting."); + break; + } + } + Ok(_) => {} + Err(discord::Error::Closed(code, body)) => { + println!("Gateway closed on us with code {:?}: {}", code, body); + break; + } + Err(err) => println!("Receive error: {:?}", err), + } + } } /// Extracts the server id from the config @@ -62,7 +88,8 @@ fn main() { let discord = get_discord(cfg.bot_token.as_str()); let server_id = ServerId(self::get_server_id(cfg)); let server = discord.get_server(server_id).unwrap(); - println!("{}", server.name); + println!("Connected to {}!", server.name); + bot_loop(discord); } #[cfg(test)] From 71139425d6be94558f0d646018170a5074ee956f Mon Sep 17 00:00:00 2001 From: Ryan Hayes Date: Tue, 28 Nov 2023 22:35:44 -0500 Subject: [PATCH 4/4] Adds some docs about the .env file --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index b72b810..f7c23c1 100644 --- a/README.md +++ b/README.md @@ -15,5 +15,7 @@ A Discord bot for the best Discord community out there, TriDev. Vertex comes jam 3. Create a new bot user 4. Generate the invite link. 5. Add the bot to your server with the link. -6. Use the bot token as an environment variable `BOT_TOKEN` to start the app +6. Use the bot token as an environment variable `BOT_TOKEN` to start the app. + * Create a copy of `.env.sample` and name it `.env`. In this file, you can set `BOT_TOKEN` or other + environment variables you may want to set. 7. Start the bot, profit!