use reqwest::{Client, StatusCode};
use std::env;
use serde_json::{json, Value};
use prettytable::{Table, row};
fn pretty_print_bot_details (bot: &DiscordBot) -> () {
let mut table = Table::new();
table.add_row(row!["BOT_ATTRIBUTES"]);
table.add_row(row!["IDENTIFIER", bot.identifier]);
table.add_row(row!["CHANNEL ID", bot.channel_id]);
table.printstd();
}
#[derive(Clone)]
pub struct DiscordBot {
identifier: String,
token: String,
channel_id: String,
api_base_url: String,
client: Client,
}
impl DiscordBot {
pub fn new(identifier: &str, channel_id: &str) -> Self {
dotenv::dotenv().ok();
let token = env::var("DISCORD_TOKEN")
.expect("DISCORD_TOKEN must be set in the environment or .env file");
let bot = DiscordBot {
identifier: identifier.to_string(),
token,
channel_id: channel_id.to_string(),
api_base_url: "https://discord.com/api/v9".to_string(),
client: Client::new(),
};
pretty_print_bot_details(&bot);
bot
}
pub fn new_with_base_url(identifier: &str, channel_id: &str, base_url: &str) -> Self {
dotenv::dotenv().ok();
let token = env::var("DISCORD_TOKEN")
.expect("DISCORD_TOKEN must be set in the environment or .env file");
DiscordBot {
identifier: identifier.to_string(),
token,
channel_id: channel_id.to_string(),
api_base_url: base_url.to_string(),
client: Client::new(),
}
}
pub async fn send_notification(&self, message: &str) -> Result<(), reqwest::Error> {
let url = format!("{}/channels/{}/messages", self.api_base_url, self.channel_id);
let body = json!({
"embeds": [{
"title": self.identifier.clone(),
"description": message,
"color": 3447003
}]
});
self.client
.post(&url)
.header("Authorization", format!("Bot {}", self.token))
.json(&body)
.send()
.await?
.error_for_status()?; Ok(())
}
pub async fn send_advanced_notification(
&self,
title: &str,
description: &str,
color: u32,
image_url: Option<&str>,
) -> Result<Value, reqwest::Error> {
let url = format!("{}/channels/{}/messages", self.api_base_url, self.channel_id);
let mut embed = json!({
"title": title,
"description": description,
"color": color
});
if let Some(image) = image_url {
embed["image"] = json!({"url": image});
}
let body = json!({
"embeds": [embed]
});
let response = self.client
.post(&url)
.header("Authorization", format!("Bot {}", self.token))
.json(&body)
.send()
.await?
.error_for_status()?
.json::<Value>()
.await?;
Ok(response)
}
}