Skip to content

Commit

Permalink
Merge pull request ana-rchy#5 from ana-rchy/main
Browse files Browse the repository at this point in the history
shoulda done stuff on dev
  • Loading branch information
ana-rchy authored May 22, 2024
2 parents a70987a + 97acd17 commit 2f8bb29
Show file tree
Hide file tree
Showing 23 changed files with 427 additions and 95 deletions.
1 change: 1 addition & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
DISCORD_TOKEN=$(cat token.txt)
35 changes: 35 additions & 0 deletions .github/workflows/deploy-to-vps.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
name: Deploy main to Huey-Dewey-Louie

on:
push:
branches:
- main

jobs:
build-and-deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v2

- name: Setup SSH
uses: webfactory/[email protected]
with:
ssh-private-key: ${{ secrets.SSH_PRIVATE_KEY }}

- name: Build and Deploy with Docker Compose
run: |
ssh -o StrictHostKeyChecking=no ${{ secrets.USERNAME }}@${{ secrets.HOST }} << 'EOF'
cd /src/eveningbot
git reset --hard HEAD
git pull origin main
touch .env
chmod 644 .env
echo "DISCORD_TOKEN=${{secrets.BOT_TOKEN}}" > .env
docker compose up -d --build
docker image prune -f
EOF
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
target/
token.txt
assets/leaderboard.bin
29 changes: 29 additions & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ chrono-tz = "0.9.0"
poise = "0.6.1"
rand = "0.8.5"
reqwest = { version = "0.12.4", features = ["json"] }
rmp-serde = "1.3.0"
serde = "1.0.200"
time = { version = "0.3.36", features = ["serde", "parsing"] }
tokio = { version = "1.37.0", features = ["rt-multi-thread"] }
Expand Down
6 changes: 4 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,14 @@ copy Cargo.lock Cargo.lock
run cargo build --release

copy src/ src/
copy assets/ assets/
run cargo build --release

from debian:stable-slim as debug

run apt update && apt install -y libssl-dev

copy --from=builder /target/release/eveningbot /eveningbot
copy --from=builder /target/release/eveningbot /eveningbot/eveningbot
copy --from=builder /assets/ /eveningbot/assets/

cmd ["/eveningbot"]
cmd ["/eveningbot/eveningbot"]
Binary file added assets/fact_check/cat_state_false.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added assets/fact_check/dark_brandon.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added assets/fact_check/dark_maga.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added assets/fact_check/gabriel.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added assets/fact_check/gilded_dredgens.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added assets/fact_check/soyjak_party_coal.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added assets/fact_check/unsc_false.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added assets/fact_check/yakub.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
7 changes: 7 additions & 0 deletions docker-compose.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
version: '3.8'
services:
eveningbot:
env_file:
- ./.env
build: .
restart: on-failure:3
19 changes: 11 additions & 8 deletions src/commands.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
use crate::global::*;
use poise::{serenity_prelude::CreateAttachment, reply::CreateReply};
use tokio::fs::File;

type Data = ();
type Error = Box<dyn std::error::Error + Send + Sync>;
type Context<'a> = poise::Context<'a, Data, Error>;
type Context<'a> = poise::Context<'a, SharedData, Error>;

#[poise::command(prefix_command, slash_command)]
pub async fn fact_check(ctx: Context<'_>) -> Result<(), Error> {
let image = get_fact_check_image().await;
let (image, filename) = get_fact_check_image(ctx.data()).await;
let attachment = CreateAttachment
::file(&image, "fact_check.png").await.unwrap();
::file(&image, filename).await.unwrap();

let reply = CreateReply {
attachments: vec![attachment],
Expand All @@ -22,15 +22,18 @@ pub async fn fact_check(ctx: Context<'_>) -> Result<(), Error> {
}


async fn get_fact_check_image() -> File {
let paths = std::fs::read_dir("assets/fact_check/").unwrap();
async fn get_fact_check_image(shared_data: &SharedData) -> (File, String) {
let root_folder = &shared_data.root_path;

let paths = std::fs::read_dir(format!("{}/assets/fact_check/", root_folder)).unwrap();
let mut images: Vec<String> = vec![];

for path in paths {
images.push(path.unwrap().path().display().to_string());
images.push(format!("{}", path.unwrap().path().display().to_string()));
}

let rand_index = rand::random::<usize>() % images.len();
let image = &images[rand_index];

File::open(image).await.unwrap()
(File::open(image).await.unwrap(), image.to_string())
}
83 changes: 83 additions & 0 deletions src/event.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
use crate::global::*;
use std::sync::atomic::Ordering;
use poise::serenity_prelude::{self as serenity, CreateMessage, EmojiId, GuildRef, ReactionType};
use time::*;

type Error = Box<dyn std::error::Error + Send + Sync>;

pub async fn event_handler(
ctx: &serenity::Context,
event: &serenity::FullEvent,
_framework: poise::FrameworkContext<'_, SharedData, Error>,
shared_data: &SharedData
) -> std::prelude::v1::Result<(), Error> {
match event {
serenity::FullEvent::GuildMemberRemoval { guild_id, user, .. } => {
const USERS_REMOVED_CHANNEL_ID: u64 = 1240091460217344100;
let channel = serenity::ChannelId::new(USERS_REMOVED_CHANNEL_ID);

let member_count = {
let guild: GuildRef = ctx.cache.guild(guild_id).unwrap();
guild.member_count
};

let message = CreateMessage::new()
.content(
format!("<@{}> left, now {} server members",
user.id,
member_count)
);

let _ = channel.send_message(&ctx.http, message).await;
}

serenity::FullEvent::Message { new_message } => {
// early returns
const BOT_ID: u64 = 1235086289255137404;
#[allow(dead_code)]
const TESTING_CHANNEL_ID: u64 = 1235087573421133824;
const GENERAL_CHANNEL_ID: u64 = 1215048710074011692;

let sunset_time = *shared_data.sunset_time.lock().unwrap();
let current_time = OffsetDateTime::now_utc().to_offset(sunset_time.offset());

if !(current_time > sunset_time && current_time.hour() < 24)
|| !(new_message.channel_id == GENERAL_CHANNEL_ID || new_message.channel_id == TESTING_CHANNEL_ID)
|| new_message.author.id == BOT_ID
|| !GOOD_EVENINGS.iter().any(|a| new_message.content.to_lowercase().contains(a))
{
return Ok(());
}


// react to good evenings
let reaction = ReactionType::Custom {
animated: false,
id: EmojiId::new(1241916769648775238),
name: Some("eepy".to_string()),
};

new_message.react(&ctx.http, reaction).await.unwrap();


// handle leaderboard if its the first GE of the day
if shared_data.first_ge_sent.load(Ordering::SeqCst) {
return Ok(());
}

shared_data.first_ge_sent.store(true, Ordering::SeqCst);

let user_id = u64::from(new_message.author.id);
let mut leaderboard = shared_data.evening_leaderboard.lock().await;

leaderboard.entry(user_id).and_modify(|e| *e += 1).or_insert(1);

let leaderboard_bytes = rmp_serde::encode::to_vec(&*leaderboard).expect("couldnt serialize leaderboard");
_ = std::fs::write(format!("{}/assets/leaderboard.bin", shared_data.root_path), leaderboard_bytes);
}

_ => {}
}

Ok(())
}
104 changes: 104 additions & 0 deletions src/global.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
use crate::web;
use std::collections::HashMap;
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, Mutex};
use tokio::sync as tsync;


pub struct SharedData {
pub sunset_time: Arc<Mutex<time::OffsetDateTime>>,
pub root_path: String,
pub evening_leaderboard: Arc<tsync::Mutex<HashMap<u64, u16>>>,
pub first_ge_sent: Arc<AtomicBool>
}

impl SharedData {
pub async fn new() -> Self {
let mut exec_path = std::env::current_exe().expect("couldnt get current executable path");
exec_path.pop();
if cfg!(debug_assertions) {
exec_path.pop(); exec_path.pop();
}
let assets_path = exec_path.to_string_lossy().to_string();

let leaderboard: HashMap<u64, u16> = {
let path_string = format!("{}/assets/leaderboard.bin", assets_path);
let path = std::path::Path::new(&path_string);

if !path.try_exists().expect("file checking error") {
HashMap::new()
} else {
let bytes = std::fs::read(format!("{}/assets/leaderboard.bin", assets_path)).expect("couldnt read leaderboard file");
rmp_serde::decode::from_slice(&bytes).expect("couldnt deserialize leaderboard")
}
};

SharedData {
sunset_time: Arc::new(Mutex::new(web::get_sunset_time().await.unwrap())),
root_path: assets_path,
evening_leaderboard: Arc::new(tsync::Mutex::new(leaderboard)),
first_ge_sent: Arc::new(AtomicBool::new(false))
}
}
}

pub static EVENING_MOTD: &[&str] = &[
"evening good?",
"yawn.",
"boo",
"WHATEVER YOU DO, DO NOT LOOK AT THE MOON",
"the sun will rise once again.",
"DAY AND NIGHT, DAY AND NIGHT",
"jkhgkdfhgskjldahfgkljsdfhgjklsdhfgjk",
"mun pona",
"toki a!",
];

pub static NIGHT_MOTD: &[&str] = &[
"the voices are coming.",
"how many eepers does it change to take a log by bolb? none, their to busy ???? their body pillow",
"who up shlombing rn",
":goofyskull:",
"why are you up? disgusting.",
"gay sex",
"i hope mom doesnt find me playing on my ds",
"estrogen injection hours",
"you should totally knock on the walls your neighbours will appreciate it",
"meow",
"lets cant sleep together :3",
"comrade, we must go hunt for business students",
"yooyokokkokokoiyoykoyoyitoyitoykoyoykoykoyyoyoyoyokokokoykykyoyoyoyoykyoyyyyy",
"THE LONELY STONER FREES HIS MIND AT NIGHT, MIND AT NIGHT",
"THE MOON LOOKS BEAUTIFUL TONIGHT. YOU SHOULD GO LOOK.",
"tenpo pimeja 🌃",
"where are my programming socks",
];

pub static GOOD_EVENINGS: &[&str] = &[
"good evening",
"dobry wieczor",
"dobry wieczór",
"tenpo pimeja pona",
"pimeja pona",
"buenas noches",
"bonsoir",
"こんばんは",
"こんばん",
"konbanwa",
"konbanha",
"konban",
"晚上好",
"晚安",
"wan3 shang4 hao3",
"wan shang hao",
"wan4 an1",
"wan an",
"guten abend",
"tráthnóna maith",
"tráthnona maith",
"trathnóna maith",
"trathnona maith",
"goejûn",
"goejun",
"gott kveld",
];
Loading

0 comments on commit 2f8bb29

Please sign in to comment.