Initial commit

What works:
+ create_event command posts an event message to a channel
+ the event is also stored in a database

Todo:
+ Add event reminders to those who RSVP
+ Add permissions support
+ Add commands for editing/deleting events
master
Joey Hines 2020-04-22 22:28:51 -05:00
commit 3c710adf96
13 changed files with 2054 additions and 0 deletions

3
.gitignore vendored 100644
View File

@ -0,0 +1,3 @@
/target
**/*.rs.bk
.env

1747
Cargo.lock generated 100644

File diff suppressed because it is too large Load Diff

20
Cargo.toml 100644
View File

@ -0,0 +1,20 @@
[package]
name = "hype_bot"
version = "0.1.0"
authors = ["Joey Hines <joey@ahines.net>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
clap = "2.33.0"
serde = "1.0.106"
serde_derive = "1.0.104"
config = "0.9"
chrono = "0.4.11"
diesel = { version = "1.4.0", features = ["mysql", "chrono"] }
diesel_migrations = "1.4.0"
[dependencies.serenity]
version = "0.8.4"
features = ["framework", "standard_framework"]

22
README.md 100644
View File

@ -0,0 +1,22 @@
# HypeBot
A Discord bot for managing events. Uses [Serenity](https://github.com/serenity-rs/serenity) for the bot framework
and [Disel](http://diesel.rs/) as an ORM.
## Running
`./hype_bot -c config.toml`
##Config
```toml
# Database URL
db_url = "mysql://[user]:[password]@localhost/hypebot_db"
# Default image to show on the thumbnail
default_thumbnail_link = "https://i.imgur.com/wPdnvoE.png"
# Discord bot key
discord_key = ""
# Bot command prefix
prefix = "~"
# Channel ID to post to
event_channel = 0
# Permissions to use the bot
event_roles = 0
```

5
diesel.toml 100644
View File

@ -0,0 +1,5 @@
# For documentation on how to configure this file,
# see diesel.rs/guides/configuring-diesel-cli
[print_schema]
file = "src/database/schema.rs"

View File

View File

@ -0,0 +1,2 @@
-- This file should undo anything in `up.sql`
DROP TABLe events;

View File

@ -0,0 +1,9 @@
-- Your SQL goes here
CREATE TABLE events (
id INTEGER AUTO_INCREMENT PRIMARY KEY,
event_name VARCHAR(255) NOT NULL,
event_desc VARCHAR(255) NOT NULL,
event_time DATETIME NOT NULL,
message_id VARCHAR(255) NOT NULL,
thumbnail_link VARCHAR(255) NOT NULL
)

View File

@ -0,0 +1,33 @@
pub mod schema;
pub mod models;
use diesel::prelude::*;
use chrono::NaiveDateTime;
use models::{Event, NewEvent};
pub fn establish_connection(database_url: String) -> MysqlConnection {
MysqlConnection::establish(&database_url)
.expect(&format!("Error connecting to {}", database_url))
}
pub fn insert_event(databse_url: String, event_name: &str, event_desc: &str,
event_time: &NaiveDateTime, message_id: &str, thumbnail_link: &str) -> Event {
use schema::events::dsl::{id, events};
let new_event = NewEvent {
event_name,
event_desc,
event_time,
message_id,
thumbnail_link,
};
let connection = establish_connection(databse_url);
diesel::insert_into(events)
.values(&new_event)
.execute(&connection)
.expect("Error saving event");
events.order(id).first(&connection).unwrap()
}

View File

@ -0,0 +1,22 @@
use super::schema::events;
use chrono::{NaiveDateTime};
#[derive(Queryable)]
pub struct Event {
pub id: i32,
pub event_name: String,
pub event_desc: String,
pub event_time: NaiveDateTime,
pub message_id: String,
pub thumbnail_link: String,
}
#[derive(Insertable)]
#[table_name="events"]
pub struct NewEvent<'a> {
pub event_name: &'a str,
pub event_desc: &'a str,
pub event_time: &'a NaiveDateTime,
pub message_id: &'a str,
pub thumbnail_link: &'a str,
}

View File

@ -0,0 +1,10 @@
table! {
events (id) {
id -> Integer,
event_name -> Varchar,
event_desc -> Varchar,
event_time -> Datetime,
message_id -> Varchar,
thumbnail_link -> Varchar,
}
}

View File

@ -0,0 +1,25 @@
use config::{ConfigError, Config, File};
use serenity::prelude::TypeMapKey;
#[derive(Debug, Deserialize)]
pub struct HypeBotConfig {
pub db_url: String,
pub default_thumbnail_link: String,
pub discord_key: String,
pub prefix: String,
pub event_channel: u64,
pub event_roles: Vec<String>,
}
impl HypeBotConfig {
pub fn new(config_path: &str) -> Result<Self, ConfigError> {
let mut cfg = Config::new();
cfg.merge(File::with_name(config_path))?;
cfg.try_into()
}
}
impl TypeMapKey for HypeBotConfig {
type Value = HypeBotConfig;
}

156
src/main.rs 100644
View File

@ -0,0 +1,156 @@
#[macro_use]
extern crate diesel;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate diesel_migrations;
extern crate serde;
use serenity::client::Client;
use serenity::model::channel::Message;
use serenity::prelude::{EventHandler, Context};
use serenity::utils::{content_safe, ContentSafeOptions, Colour};
use serenity::model::gateway::Ready;
use serenity::framework::standard::StandardFramework;
use serenity::framework::standard::CommandResult;
use serenity::framework::standard::macros::{command, group,};
use serenity::framework::standard::Args;
use clap::{Arg, App};
use chrono::{DateTime, Utc};
use std::process::exit;
mod hypebot_config;
mod database;
use database::*;
use hypebot_config::HypeBotConfig;
/// Event commands group
#[group]
#[commands(create_event)]
struct EventCommands;
/// Handler for Discord events
struct Handler;
impl EventHandler for Handler {
/// On bot ready
fn ready(&self, _: Context, ready: Ready) {
println!("Connected as {}", ready.user.name);
}
}
embed_migrations!("migrations/");
fn main() {
// Initialize arg parser
let mut app = App::new("Hype Bot")
.about("Hype Bot: Hype Up Your Discord Events!").arg(Arg::with_name("config")
.index(1)
.short("c").
long("config")
.value_name("CONFIG_PATH")
.help("Config file path"));
// Get arg parser
let matches = app.clone().get_matches();
// Check if config is set
if let Some(config_path) = matches.value_of("config") {
// Load config
let cfg = match hypebot_config::HypeBotConfig::new(config_path) {
Ok(cfg) => cfg,
Err(err) => {
println!("Error opening config file: {}", err);
exit(-1);
}
};
// Run migrations
let connection = establish_connection(cfg.db_url.clone());
embedded_migrations::run(&connection).expect("Unable to run migrations");
// New client
let mut client = Client::new(cfg.discord_key.clone(), Handler)
.expect("Error creating client");
// Configure client
client.with_framework(StandardFramework::new()
.configure(|c| c.prefix(cfg.prefix.as_str().clone()))
.group(&EVENTCOMMANDS_GROUP));
// Copy config data to client data
{
let mut data = client.data.write();
data.insert::<HypeBotConfig>(cfg);
}
// Start bot
println!("Starting Hypebot!");
if let Err(why) = client.start() {
println!("An error occurred while running the client: {:?}", why);
}
}
else {
// Print help
app.print_help().unwrap();
}
}
#[command]
/// Creates an event and announce it
fn create_event (ctx: &mut Context, msg: &Message, mut args: Args) -> CommandResult {
// Open config
let data = ctx.data.read();
let config = data.get::<HypeBotConfig>().unwrap();
// Parse args
let event_name = args.single::<String>()?.replace("\"", "");
let date_string = args.single::<String>()?.replace("\"", "");
let description = args.single::<String>()?.replace("\"", "");
let thumbnail_link = match args.single::<String>() {
Ok(link) => link,
Err(_) => config.default_thumbnail_link.clone(),
};
// Parse date
let date = DateTime::parse_from_str(date_string.as_str(),
"%H:%M %z %Y-%m-%d").unwrap();
let date = DateTime::<Utc>::from(date);
// Clean channel, role, and everyone pings
let settings = ContentSafeOptions::default()
.clean_channel(true)
.clean_role(true)
.clean_everyone(true)
.display_as_member_from(msg.guild_id.unwrap());
let description = content_safe(&ctx.cache, description, &settings);
let channel = ctx.http.get_channel(config.event_channel)?;
// Send message
let msg = channel.id().send_message(&ctx, |m| {
m.embed(|e| {
e.title(event_name.as_str())
.color(Colour::PURPLE)
.description(format!("**{}**\n{}", date.format("%A, %B %d @ %I:%M %P %t %Z"), description))
.thumbnail(&thumbnail_link)
.footer(|f| { f.text("Local Event Time") })
.timestamp(date.to_rfc3339())
})
})?;
// Add reacts
msg.react(&ctx, "\u{2705}")?;
msg.react(&ctx, "\u{274C}")?;
// Insert event into the database
insert_event(config.db_url.clone(), event_name.as_str(),
description.as_str(), &date.naive_utc(),
format!("{}", msg.id.0).as_str(),
thumbnail_link.as_str());
Ok(())
}