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

feat: 引用機能の追加 #7

Merged
merged 8 commits into from
Aug 30, 2023
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
22 changes: 22 additions & 0 deletions Cargo.lock

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

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,11 @@ enable_sentry = []
anyhow = { version = "1.0" }
dotenvy = { version = "0.15" }
once_cell = { version = "1.18" }
regex = { version = "1.9" }
sentry = { version = "0.31" }
tracing = { version = "0.1" }
tracing-subscriber = { version = "0.3" }
typed-builder = { version = "0.16" }

[dependencies.serenity]
version = "0.11"
Expand Down
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@ A citation message Discord bot

### Todo

- [ ] 添付ファイルのサポート
- [ ] 添付ファイルのサポート ( [#5](https://github.com/m1sk9/babyrite/issues/5) )
- [ ] チャンネルリストのキャッシュ ( [#6](https://github.com/m1sk9/babyrite/issues/6) )

[babyrite v1.0.0 リリースのためのマイルストーンはこちら](https://github.com/m1sk9/babyrite2/milestone/1)

## Installation

Expand Down
73 changes: 73 additions & 0 deletions src/adapters/embed.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
use crate::model::embed::EmbedMessage;
use serenity::{builder::CreateEmbed, utils::Colour};

pub fn convert_embed(
EmbedMessage {
title,
author,
description,
fields,
footer,
color,
url,
thumbnail,
timestamp,
}: EmbedMessage,
) -> CreateEmbed {
let mut create_embed = CreateEmbed::default();

if let Some(title) = title {
create_embed.title(title);
}

if let Some(author) = author {
create_embed.author(|a| {
a.name(author.name);
if let Some(url) = author.url {
a.url(url);
}
if let Some(icon_url) = author.icon_url {
a.icon_url(icon_url);
};
a
});
}

if let Some(description) = description {
create_embed.description(description);
}

if let Some(fields) = fields {
fields.into_iter().for_each(|x| {
create_embed.field(x.name, x.value, x.inline.unwrap_or(false));
})
}

if let Some(footer) = footer {
create_embed.footer(|f| {
f.text(footer.text);
if let Some(icon_url) = footer.icon_url {
f.icon_url(icon_url);
};
f
});
}

if let Some(color) = color {
create_embed.color(Colour(color));
}

if let Some(url) = url {
create_embed.url(url);
}

if let Some(thumbnail) = thumbnail {
create_embed.thumbnail(thumbnail.url);
}

if let Some(timestamp) = timestamp {
create_embed.timestamp(timestamp);
}

create_embed
}
150 changes: 150 additions & 0 deletions src/adapters/message.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
use std::sync::Arc;

use anyhow::{Context, Error, Ok};
use serenity::{http::Http, model::channel::Message};

use crate::adapters::embed::convert_embed;
use crate::model::{
embed::{EmbedMessage, EmbedMessageAuthor, EmbedMessageFooter},
id::DiscordIds,
message::CitationMessage,
};

const PERSONAL_COLOR: u32 = 0xb586f7;
const WARN_COLOR: u32 = 0xfff700;
const ERROR_COLOR: u32 = 0xFF0012;

pub async fn send_citation_embed(
ids: DiscordIds,
http: &Arc<Http>,
target_message: &Message,
) -> anyhow::Result<()> {
let citation_message = get_citation_message(ids, &http).await?;

let embed_footer = EmbedMessageFooter::builder()
.text(citation_message.channel_name)
.build();
let embed_author = EmbedMessageAuthor::builder()
.name(citation_message.author_name)
.icon_url(citation_message.author_avatar_url)
.build();
let embed_object = EmbedMessage::builder()
.description(Some(citation_message.content))
.footer(Some(embed_footer))
.author(Some(embed_author))
.timestamp(Some(citation_message.create_at))
.color(Some(PERSONAL_COLOR))
.build();

target_message
.channel_id
.send_message(http, |m| {
m.reference_message(target_message);
m.allowed_mentions(|mention| {
mention.replied_user(true);
mention
});
m.set_embed(convert_embed(embed_object))
})
.await
.context("引用メッセージの送信に失敗しました")?;

Ok(())
}

async fn get_citation_message(
DiscordIds {
guild_id,
channel_id,
message_id,
}: DiscordIds,
http: &Arc<Http>,
) -> anyhow::Result<CitationMessage> {
let guild_channels = guild_id
.channels(&http)
.await
.context("チャンネルリストの取得に失敗しました")?;

match guild_channels.get(&channel_id) {
Some(channel) => {
if channel.is_nsfw() || !channel.is_text_based() {
return Err(anyhow::anyhow!("[ID: {}]のチャンネルはNSFWに指定されているか, テキストベースのチャンネルではありません", channel_id));
}

let message = channel
.message(http, message_id)
.await
.context("メッセージの取得に失敗しました")?;

let author = message.clone().author;
// アバター画像が存在していなくても埋め込み生成時に無視される
let author_icon_url = author.avatar_url();

Ok(CitationMessage::builder()
.content(message.content)
.author_name(author.name)
.author_avatar_url(author_icon_url)
.channel_name(channel.clone().name)
.create_at(message.timestamp)
.build())
}
None => Err(anyhow::anyhow!(
"[ID: {}]のチャンネルを見つけることが出来ませんでした",
channel_id
)),
}
}

pub async fn send_warn_embed(
http: &Arc<Http>,
message: &Message,
error_reason: &str,
) -> anyhow::Result<()> {
let embed_object = EmbedMessage::builder()
.title(Some("警告".to_string()))
.description(Some(format!("```\n{}\n```", error_reason)))
.color(Some(WARN_COLOR))
.build();

message
.channel_id
.send_message(http, |m| {
m.reference_message(message);
m.allowed_mentions(|mention| {
mention.replied_user(true);
mention
});
m.set_embed(convert_embed(embed_object))
})
.await
.context("警告メッセージの送信に失敗しました")?;

Ok(())
}

pub async fn send_error_embed(
http: &Arc<Http>,
message: &Message,
error_reason: &Error,
) -> anyhow::Result<()> {
let embed_object = EmbedMessage::builder()
.title(Some("エラー".to_string()))
.description(Some(format!("```\n{}\n```", error_reason)))
.color(Some(ERROR_COLOR))
.build();

message
.channel_id
.send_message(http, |m| {
m.reference_message(message);
m.allowed_mentions(|mention| {
mention.replied_user(true);
mention
});
m.set_embed(convert_embed(embed_object))
})
.await
.context("エラーメッセージの送信に失敗しました")?;

Ok(())
}
2 changes: 2 additions & 0 deletions src/adapters/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
pub mod embed;
pub mod message;
2 changes: 1 addition & 1 deletion src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use serenity::{prelude::GatewayIntents, Client};
use crate::event::EvHandler;

pub async fn discord_client(token: String) -> anyhow::Result<()> {
let intents = GatewayIntents::MESSAGE_CONTENT;
let intents = GatewayIntents::MESSAGE_CONTENT | GatewayIntents::GUILD_MESSAGES;

let mut client = Client::builder(token, intents)
.event_handler(EvHandler)
Expand Down
67 changes: 64 additions & 3 deletions src/event.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,51 @@
use crate::VERSION;
use crate::{
adapters::message::{send_citation_embed, send_error_embed, send_warn_embed},
model::id::DiscordIds,
VERSION,
};
use once_cell::sync::Lazy;
use regex::Regex;
use serenity::{
async_trait,
model::prelude::Ready,
model::prelude::{ChannelId, GuildId, Message, MessageId, Ready},
prelude::{Context, EventHandler},
};
use tracing::info;
use tracing::{error, info, warn};

pub struct EvHandler;

const MESSAGE_LINK_REGEX: Lazy<Regex> = Lazy::new(|| {
Regex::new(r"https://(?:ptb\.|canary\.)?discord\.com/channels/(\d+)/(\d+)/(\d+)").unwrap()
});
// 引用スキップ機能の正規表現
const SKIP_MESSAGE_LINK_REGEX: Lazy<Regex> = Lazy::new(|| {
Regex::new(r"<https://(?:ptb\.|canary\.)?discord\.com/channels/\d+/\d+/\d+>").unwrap()
});

#[async_trait]
impl EventHandler for EvHandler {
async fn message(&self, ctx: Context, message: Message) {
if message.is_private() || message.author.bot {
return;
}

let content = &message.content;
if !MESSAGE_LINK_REGEX.is_match(&content) || SKIP_MESSAGE_LINK_REGEX.is_match(&content) {
return;
}
let matched_str = MESSAGE_LINK_REGEX.find(content).unwrap().as_str();

if let Some(triple) = extract_ids_from_link(matched_str) {
if let Err(why) = send_citation_embed(triple, &ctx.http, &message).await {
let _ = send_error_embed(&ctx.http, &message, &why).await;
error!("{:?}", why)
}
} else {
let _ = send_warn_embed(&ctx.http, &message, "IDの取り出しに失敗しました").await;
warn!("IDの取り出しに失敗したため、引用をキャンセルしました")
}
}

async fn ready(&self, _: Context, bot: Ready) {
info!(
"Connected to {name}(ID:{id}). (Using babyrite v{version}).",
Expand All @@ -19,3 +55,28 @@ impl EventHandler for EvHandler {
)
}
}

fn extract_ids_from_link(message_link: &str) -> Option<DiscordIds> {
let captures = MESSAGE_LINK_REGEX.captures(message_link)?;

// GuildId
let first = captures
.get(1)
.and_then(|m| m.as_str().parse::<u64>().ok())?;
// ChannelId
let second = captures
.get(2)
.and_then(|m| m.as_str().parse::<u64>().ok())?;
// MessageId
let third = captures
.get(3)
.and_then(|m| m.as_str().parse::<u64>().ok())?;

Some(
DiscordIds::builder()
.guild_id(GuildId(first))
.channel_id(ChannelId(second))
.message_id(MessageId(third))
.build(),
)
}
2 changes: 2 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,11 @@ use crate::{
env::{env_var, load_dotenv},
};

mod adapters;
mod client;
mod env;
mod event;
mod model;

#[allow(dead_code)]
pub static DEFAULT_TIMEOUT_DURATION: Duration = Duration::from_secs(10);
Expand Down
Loading