Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf: メッセージ取得部分の改善 #218

Merged
merged 5 commits into from
Oct 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 14 additions & 33 deletions Cargo.lock

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

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@ envy = { version = "0.4.2" }
once_cell = { version = "1.19.0" }
regex = { version = "1.10.4" }
tracing = { version = "0.1.40" }
typed-builder = { version = "0.20.0" }
serde_yaml = { version = "0.9.33" }
thiserror = { version = "1.0.64" }
url = { version = "2.5.2" }

[dependencies.serenity]
version = "0.12.1"
Expand Down
2 changes: 1 addition & 1 deletion src/model/config.rs → src/config.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use serde::Deserialize;

use crate::env::babyrite_envs;
use crate::babyrite_envs;

#[derive(Debug, Deserialize)]
pub struct BabyriteConfig {
Expand Down
17 changes: 0 additions & 17 deletions src/env.rs

This file was deleted.

144 changes: 28 additions & 116 deletions src/handler.rs
Original file line number Diff line number Diff line change
@@ -1,149 +1,61 @@
use crate::model::cache::get_channel_list_cache;
use crate::model::config::BABYRITE_CONFIG;
use crate::model::ids::BabyriteIDs;
use crate::model::message::{
CitationMessage, CitationMessageAuthor, MESSAGE_LINK_REGEX, SKIP_MESSAGE_LINK_REGEX,
};
use serenity::all::{Context, CreateAllowedMentions, CreateMessage, Message, Ready};
use crate::preview::{MessagePreviewIDs, MESSAGE_LINK_REGEX, SKIP_LINK_REGEX};
use serenity::all::{Context, CreateAllowedMentions, Message, Ready};
use serenity::builder::CreateMessage;
use serenity::client::EventHandler;
use serenity::gateway::ActivityData;
use tracing::{debug, info};

pub struct BabyriteHandler;

#[serenity::async_trait]
impl EventHandler for BabyriteHandler {
async fn message(&self, ctx: Context, message: Message) {
let config = BABYRITE_CONFIG.get().unwrap();
if message.author.bot {
return;
}
let config = crate::config::BabyriteConfig::get();

let content = &message.content;
if !MESSAGE_LINK_REGEX.is_match(content) || SKIP_MESSAGE_LINK_REGEX.is_match(content) {
if message.author.bot {
return;
}
let captures = MESSAGE_LINK_REGEX
.captures(MESSAGE_LINK_REGEX.find(content).unwrap().as_str())
.unwrap();
let ids = BabyriteIDs::new(captures).unwrap();

if !config.bypass_guilds && message.guild_id != Some(ids.guild) {
if !MESSAGE_LINK_REGEX.is_match(&message.content)
|| SKIP_LINK_REGEX.is_match(&message.content)
{
return;
}

tracing::info!(
"* Request from {}: Start processing...",
message.author.tag(),
);

let target_channel = match get_channel_list_cache(&ctx, ids.guild, ids.channel).await {
Ok(channel) => {
tracing::info!(
"{} - Message retrieved: {}({})",
message.author.tag(),
channel.name,
channel.id
);
channel
}
let ids = match MessagePreviewIDs::find_from_str(&message.content) {
Ok(ids) => ids,
Err(e) => {
tracing::error!(
"Failed to retrieve channel. It does not exist or the cache is invalid: {:?}",
e
);
debug!(name: "babyrite Message", "Failed to parse message: {:?}", e);
return;
}
};
debug!(name: "babyrite Message", "Found ids: {:?}", ids);

if target_channel.nsfw {
tracing::warn!(
"{} - Cancel message citation: Target channel was NSFW.",
message.author.tag()
);
return;
}

let target_message = match target_channel.message(&ctx.http, ids.message).await {
Ok(target) => {
tracing::info!(
"{} - Channel retrieved: {}",
message.author.tag(),
target.id
);
target
}
let preview = match ids.get_preview(&ctx).await {
Ok(preview) => preview,
Err(e) => {
tracing::error!("Failed to retrieve message: {:?}", e);
debug!(name: "babyrite Message", "Failed to get preview: {:?}", e);
return;
}
};

if !target_message.embeds.is_empty() && target_message.content.is_empty() {
if target_channel.nsfw {
tracing::warn!(
"{} - Cancel message citation: Message with embedding.",
message.author.tag()
);
return;
}
return;
}

let source_message = CitationMessage::builder()
.content(target_message.content.clone())
.author(
CitationMessageAuthor::builder()
.name(target_message.author.name.clone())
.icon_url(Some(target_message.author.avatar_url().unwrap_or(
"https://cdn.discordapp.com/embed/avatars/0.png".to_string(),
)))
.build(),
)
.channel_name(target_channel.name.clone())
.create_at(target_message.timestamp)
.attachment_image_url(target_message.attachments.first().map(|a| a.url.clone()))
.build();

let embed = source_message.to_embed();

tracing::debug!(
"Target: {:?}({:?}), Embed: {:?}",
&target_message,
&target_channel,
&embed
);
if let Err(why) = message
.channel_id
.send_message(&ctx.http, {
CreateMessage::default()
.embed(embed)
.allowed_mentions(
CreateAllowedMentions::default().replied_user(config.citation_mention),
)
.reference_message(&message.clone())
})
.await
{
tracing::error!("Failed to send message: {:?}", why);
debug!(name: "babyrite Message", "Found preview: {:?}", preview);

let embed = MessagePreviewIDs::generate_preview(preview);
let reply = CreateMessage::default()
.embed(embed)
.reference_message(&message)
.allowed_mentions(CreateAllowedMentions::new().replied_user(config.citation_mention));
if let Err(why) = message.channel_id.send_message(&ctx.http, reply).await {
debug!(name: "babyrite Message", "Failed to send message: {:?}", why);
}

tracing::info!(
"* Request from {}: Successful citation.",
message.author.tag()
);
}

async fn ready(&self, ctx: Context, client: Ready) {
tracing::info!(
"Connected as {}, id: {}",
&client.user.name,
&client.user.id
);
info!(name: "babyrite Initialize Ready", "babyrite is ready! Connected as {}, id: {}", &client.user.name, &client.user.id);
debug!(name: "babyrite Initialize Ready", "client: {:?}", client);
ctx.set_activity(Some(ActivityData::playing(format!(
"babyrite v{}",
"v{}",
env!("CARGO_PKG_VERSION")
))));
tracing::debug!("client: {:?}", client);
tracing::info!("babyrite is ready!");
}
}
31 changes: 22 additions & 9 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,35 @@
use crate::model::config::BabyriteConfig;
use model::config::LoggerFormat;
#[deny(unused_imports)]
#![deny(unused_imports)]

use config::BabyriteConfig;
use config::LoggerFormat;
use serenity::prelude::GatewayIntents;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};

mod env;
mod handler;
mod model;
pub mod config;
pub mod handler;
pub mod preview;

#[derive(serde::Deserialize)]
pub struct BabyriteEnv {
pub config_file_path: String,
pub discord_api_token: String,
}

pub fn babyrite_envs() -> &'static BabyriteEnv {
static BABYRITE_ENV: std::sync::OnceLock<BabyriteEnv> = std::sync::OnceLock::new();
BABYRITE_ENV.get_or_init(|| {
envy::from_env()
.expect("Failed to read environment variables. Do you set the environment variables?")
})
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
tracing::info!("Starting babyrite at v{}", env!("CARGO_PKG_VERSION"));

dotenvy::dotenv().ok();

BabyriteConfig::init();
let config = BabyriteConfig::get();
let envs = env::babyrite_envs();
let envs = babyrite_envs();

match config.logger_format {
LoggerFormat::Compact => {
Expand Down
4 changes: 0 additions & 4 deletions src/model.rs

This file was deleted.

Loading