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(wip): 読み上げ対象のチャネルの制限機能を追加 #37

Merged
merged 19 commits into from
Sep 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
6786151
feat(wip): 読み上げ対象のチャネルの制限機能を追加
raiga0310 Sep 12, 2023
c95ba54
fix(release): デプロイ用と開発用のcomposeファイルに分割
raiga0310 Sep 12, 2023
3b196ec
Merge pull request #36 from approvers/fix-release
raiga0310 Sep 12, 2023
a072d91
chore(main): release 0.1.7
github-actions[bot] Sep 12, 2023
c607d1d
Merge pull request #38 from approvers/release-please--branches--main-…
raiga0310 Sep 12, 2023
21eb4ea
feat: VC読み上げ対象の設定機能の実装
raiga0310 Sep 13, 2023
168f183
fix(reset): reset load environment
raiga0310 Sep 13, 2023
214bf72
refactor: チャネル追加・消去の操作の切り出し
raiga0310 Sep 13, 2023
9872bbc
feat(wip): 読み上げ対象のチャネルの制限機能を追加
raiga0310 Sep 12, 2023
0975600
feat: VC読み上げ対象の設定機能の実装
raiga0310 Sep 13, 2023
067e544
fix(reset): reset load environment
raiga0310 Sep 13, 2023
b9e062d
refactor: チャネル追加・消去の操作の切り出し
raiga0310 Sep 13, 2023
03c1f3d
Merge branch 'feat-subscribe' of https://github.com/approvers/yomiage…
raiga0310 Sep 13, 2023
41d49e5
fix: 正常に雪賊できていなかった問題を修正
raiga0310 Sep 13, 2023
124df98
fix(list): 読み上げ対象がない場合のメッセージを追加
raiga0310 Sep 14, 2023
2e866b2
fix: 参照まわりの修正
raiga0310 Sep 14, 2023
5a9a368
chore: 不要なgetの削除
raiga0310 Sep 14, 2023
a474d03
fix: Noneの場合のメッセージの追加
raiga0310 Sep 14, 2023
e11a05f
fix: `state` -> `app_state`
raiga0310 Sep 14, 2023
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
2 changes: 1 addition & 1 deletion .github/workflows/docker-image.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,4 @@ jobs:
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
gh release upload ${{ inputs.tag-name }} compose.yml --clobber
gh release upload ${{ inputs.tag-name }} ./deployment/compose.yml --clobber
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
# Changelog

## [0.1.7](https://github.com/approvers/yomiage-mon/compare/v0.1.6...v0.1.7) (2023-09-12)


### Bug Fixes

* **release:** デプロイ用と開発用のcomposeファイルに分割 ([c95ba54](https://github.com/approvers/yomiage-mon/commit/c95ba54e32818bad6ecdd6be776ebfdb6e4d3b74))

## [0.1.6](https://github.com/approvers/yomiage-mon/compare/v0.1.5...v0.1.6) (2023-09-12)


Expand Down
2 changes: 1 addition & 1 deletion Cargo.lock

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

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "yomiagemon"
version = "0.1.6"
version = "0.1.7"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
Expand Down
4 changes: 3 additions & 1 deletion compose.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
services:
app:
image: ghcr.io/approvers/yomiage-mon:latest
build:
context: .
dockerfile: Dockerfile
env_file:
- .env
init: true
Expand Down
18 changes: 18 additions & 0 deletions deployment/compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
services:
app:
image: ghcr.io/approvers/yomiage-mon:latest
env_file:
- .env
init: true
depends_on:
- voicevox
restart: unless-stopped
secrets:
- discord_token
voicevox:
image: voicevox/voicevox_engine:cpu-ubuntu20.04-0.14.4
restart: unless-stopped

secrets:
discord_token:
file: .secret
45 changes: 37 additions & 8 deletions src/app_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,15 @@ use serenity::{
},
prelude::TypeMapKey,
};
use std::sync::Arc;
use std::{collections::HashMap, sync::Arc};
use tokio::sync::RwLock;

use crate::voice::voicevox::VoiceVoxClient;

pub struct AppState {
pub voicevox_client: VoiceVoxClient,
pub connected_guild_state: DashMap<GuildId, ConnectedGuildState>,
pub subscribe_channels: HashMap<GuildId, Vec<ChannelId>>,
}

pub struct ConnectedGuildState {
Expand All @@ -22,20 +25,46 @@ pub struct ConnectedGuildState {
}

impl TypeMapKey for AppState {
type Value = Arc<AppState>;
type Value = Arc<RwLock<AppState>>;
}

pub async fn initialize(client: &Client, state: AppState) {
let mut data = client.data.write().await;
data.insert::<AppState>(Arc::new(state));
data.insert::<AppState>(Arc::new(RwLock::new(state)));
}

pub async fn get(ctx: &Context) -> Result<Arc<AppState>> {
pub async fn get(ctx: &Context) -> Result<Arc<RwLock<AppState>>> {
use anyhow::Context as _;
let data = ctx.data.read().await;

let state_ref = data
let state = data
.get::<AppState>()
.ok_or_else(|| anyhow::anyhow!("AppState is not initialized"))?;
.context("AppState is not initialized. Please call app_state::initialize() first.")?;
Ok(state.clone())
}

pub async fn add_channels(ctx: &Context, guild_id: GuildId, channels: &[ChannelId]) -> Result<()> {
let state = get(ctx).await?;
let mut state = state.write().await;
state
.subscribe_channels
.entry(guild_id)
.or_default()
.extend(channels);
Ok(())
}

pub async fn remove_channel(ctx: &Context, guild_id: GuildId, channel: ChannelId) -> Result<()> {
let state = get(ctx).await?;
let mut state = state.write().await;
state.subscribe_channels.entry(guild_id).and_modify(|c| {
c.retain(|c| *c != channel);
});
Ok(())
}

Ok(state_ref.clone())
pub async fn remove_all_channels(ctx: &Context, guild_id: GuildId) -> Result<()> {
let state = get(ctx).await?;
let mut state = state.write().await;
state.subscribe_channels.remove(&guild_id);
Ok(())
}
153 changes: 143 additions & 10 deletions src/commands/zunda.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ use serenity::model::prelude::*;
use serenity::prelude::*;
use serenity::Result;

use crate::app_state::{self, add_channels, remove_all_channels, remove_channel};

#[command]
#[description = "Zunda!"]
async fn zunda(ctx: &Context, msg: &Message) -> CommandResult {
Expand All @@ -21,6 +23,8 @@ async fn zunda(ctx: &Context, msg: &Message) -> CommandResult {
#[description = "コマンドを送った人がいるVCに入るのだ! VCに入っていないと使えないのだ!"]
#[only_in(guilds)]
async fn vc(ctx: &Context, msg: &Message) -> CommandResult {
let app_state = app_state::get(ctx).await.unwrap();

let guild = msg.guild(&ctx.cache).unwrap();
let guild_id = guild.id;

Expand All @@ -32,6 +36,25 @@ async fn vc(ctx: &Context, msg: &Message) -> CommandResult {
let connect_to = match channel_id {
Some(channel) => {
println!("VC connected.");
let _ = add_channels(ctx, guild_id, &[channel, msg.channel_id]).await;
let state = app_state.read().await;
check_msg(
msg.reply(
ctx,
format!(
"VCに入ったのだ! 読み上げ対象は\n {} \nなのだ!",
state
.subscribe_channels
.get(&msg.guild_id.unwrap())
.unwrap_or(&vec![])
.iter()
.map(|c| format!(" <#{}> ", c))
.collect::<Vec<String>>()
.join("\n")
),
)
.await,
);
channel
}
None => {
Expand All @@ -46,7 +69,20 @@ async fn vc(ctx: &Context, msg: &Message) -> CommandResult {
.expect("Songbird Voice client placed in at initialisation.")
.clone();

let _handler = manager.join(guild_id, connect_to).await;
let handler = manager.join(guild_id, connect_to).await;
match handler.1 {
Ok(_) => {
println!("Joined VC");
}
Err(why) => {
println!("Failed to join VC: {:?}", why);
check_msg(
msg.channel_id
.say(&ctx.http, format!("Error joining the channel: {:?}", why))
.await,
);
}
}

Ok(())
}
Expand All @@ -57,12 +93,11 @@ async fn vc(ctx: &Context, msg: &Message) -> CommandResult {
async fn leave(ctx: &Context, msg: &Message) -> CommandResult {
let guild = msg.guild(&ctx.cache).unwrap();
let guild_id = guild.id;

let has_handler = has_handler(ctx, guild_id).await;
let manager = songbird::get(ctx)
.await
.expect("Songbird Voice client placed in at initialisation.")
.clone();
let has_handler = manager.get(guild_id).is_some();

if has_handler {
if let Err(e) = manager.remove(guild_id).await {
Expand All @@ -73,21 +108,119 @@ async fn leave(ctx: &Context, msg: &Message) -> CommandResult {
);
}

if let Err(e) = remove_all_channels(ctx, guild_id).await {
check_msg(
msg.channel_id
.say(&ctx.http, format!("Failed: {:?}", e))
.await,
);
} else {
check_msg(
msg.channel_id
.say(
&ctx.http,
"サヨナラなのだ!また必要になったら`vc`で呼ぶのだ!",
)
.await,
);
}
} else {
check_msg(msg.reply(ctx, "Not in a voice channel").await);
}

Ok(())
}

#[command]
#[aliases("add")]
#[description = "読み上げ対象のチャンネルを追加するのだ!"]
#[only_in(guilds)]
async fn listen(ctx: &Context, msg: &Message) -> CommandResult {
let guild = msg.guild(&ctx.cache).unwrap();
let guild_id = guild.id;

if has_handler(ctx, guild_id).await {
if let Err(e) = add_channels(ctx, guild_id, &[msg.channel_id]).await {
check_msg(
msg.channel_id
.say(&ctx.http, format!("Failed: {:?}", e))
.await,
);
} else {
check_msg(msg.reply(ctx, "VCの読み上げ対象に追加したのだ!").await);
}
}

Ok(())
}

#[command]
#[description = "読み上げ対象のチャンネルを確認するのだ!"]
#[only_in(guilds)]
async fn list(ctx: &Context, msg: &Message) -> CommandResult {
let app_state = app_state::get(ctx).await.unwrap();
let subscribe_channels = app_state.read().await.subscribe_channels.clone();

let guild = msg.guild(&ctx.cache).unwrap();
let guild_id = guild.id;

if let Some(channels) = subscribe_channels.get(&guild_id) {
if channels.is_empty() {
check_msg(msg.reply(ctx, "読み上げ対象はないのだ!").await);
return Ok(());
}

check_msg(
msg.channel_id
.say(
&ctx.http,
"サヨナラなのだ!また必要になったら`vc`で呼ぶのだ!",
)
.await,
msg.reply(
ctx,
format!(
"読み上げ対象は\n {} \nなのだ!",
channels
.iter()
.map(|c| format!(" <#{}> ", c))
.collect::<Vec<String>>()
.join("\n")
),
)
.await,
);
} else {
check_msg(msg.reply(ctx, "Not in a voice channel").await);
check_msg(msg.reply(ctx, "読み上げ対象はないのだ!").await);
}

Ok(())
}

#[command]
#[aliases("remove")]
#[description = "読み上げ対象のチャンネルを削除するのだ!"]
#[only_in(guilds)]
async fn listen_remove(ctx: &Context, msg: &Message) -> CommandResult {
let guild = msg.guild(&ctx.cache).unwrap();
let guild_id = guild.id;

if has_handler(ctx, guild_id).await {
if let Err(e) = remove_channel(ctx, guild_id, msg.channel_id).await {
check_msg(
msg.channel_id
.say(&ctx.http, format!("Failed: {:?}", e))
.await,
);
} else {
check_msg(msg.reply(ctx, "VCの読み上げ対象から削除したのだ!").await);
}
}

Ok(())
}

async fn has_handler(ctx: &Context, guild_id: GuildId) -> bool {
let manager = songbird::get(ctx)
.await
.expect("Songbird Voice client placed in at initialisation.");
manager.get(guild_id).is_some()
}

fn check_msg(result: Result<Message>) {
if let Err(why) = result {
println!("Error sending message: {:?}", why);
Expand Down
27 changes: 22 additions & 5 deletions src/event_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,15 @@ impl EventHandler for Handler {
}

async fn message(&self, ctx: Context, msg: Message) {
let app_state = app_state::get(&ctx).await.unwrap();
let listen_channels = app_state
.read()
.await
.subscribe_channels
.clone()
.get(&msg.guild_id.unwrap())
.unwrap_or(&vec![])
.clone();
let guild_id = msg.guild_id.unwrap();
let guild = guild_id.to_guild_cached(&ctx.cache).unwrap();

Expand All @@ -33,6 +42,10 @@ impl EventHandler for Handler {
return;
}

if !listen_channels.contains(&msg.channel_id) {
return;
}

let voice_state = guild.voice_states.get(&msg.author.id).unwrap();
let is_mute = voice_state.self_mute;
if !is_mute {
Expand All @@ -47,11 +60,9 @@ impl EventHandler for Handler {
if is_head_symbol(&msg.content) {
return;
}

let state = app_state::get(&ctx).await.unwrap();

let voicevox_client = &app_state.read().await.voicevox_client;
let eoncoded_audio = make_speech(
&state.voicevox_client,
voicevox_client,
SpeechRequest {
text: msg.clone().content,
},
Expand Down Expand Up @@ -80,7 +91,13 @@ impl EventHandler for Handler {
.expect("Songbird Voice client placed in at initialisation.")
.clone();
let channel_id_bot_joined = get_channel_id(guild.clone(), ctx.cache.current_user_id());
let is_members_in_vc = !get_members_in_vc(guild, channel_id_bot_joined.unwrap()).is_empty();
let is_members_in_vc = !get_members_in_vc(
guild,
channel_id_bot_joined.unwrap_or_else(|| {
panic!("Bot is not in VC. Bot is in {:?}", channel_id_bot_joined)
}),
)
.is_empty();
if !is_members_in_vc {
let _ = manager.remove(guild_id).await;
}
Expand Down
Loading
Loading