From 895f5f9373f3afde98c40c151d114e626344d203 Mon Sep 17 00:00:00 2001
From: Tobias Reisinger <tobias@msrg.cc>
Date: Mon, 3 Jun 2024 01:11:05 +0200
Subject: [PATCH 1/8] Fix some small issues

Don't crash without self_clid
Improve functions in main.rs
---
 Makefile                    |  4 +++-
 src/command_utils/events.rs | 19 ++++++++++++++++---
 src/main.rs                 | 30 +++++++++---------------------
 3 files changed, 28 insertions(+), 25 deletions(-)

diff --git a/Makefile b/Makefile
index a45ec9f..6383dc1 100644
--- a/Makefile
+++ b/Makefile
@@ -2,11 +2,13 @@
 
 INSTALL_DIR = $(HOME)/.local/bin
 
+export PATH := target/debug:$(PATH)
+
 build:
 	@cargo build
 
 run: build
-	@PATH=$(PWD)/target/debug:$(PATH) ./ts-control
+	./ts-control
 
 install:
 	mkdir -p "$(INSTALL_DIR)"
diff --git a/src/command_utils/events.rs b/src/command_utils/events.rs
index 6689a3f..9e6f35e 100644
--- a/src/command_utils/events.rs
+++ b/src/command_utils/events.rs
@@ -27,9 +27,19 @@ pub fn handle_event_response(connection: &mut Telnet, event: Event, known_client
     }
 }
 
-pub fn loop_response_reader(connection: &mut Telnet, self_clid: i32) {
+fn try_get_self_clid(connection: &mut Telnet) -> Option<i32> {
+    wrappers::get_self_clid(connection)
+        .unwrap_or_default()
+        .parse()
+        .map(Some)
+        .unwrap_or(None)
+}
+
+pub fn loop_response_reader(connection: &mut Telnet) {
     let mut known_clients = wrappers::get_clients(connection).unwrap_or_else(|_| Vec::new());
-    
+
+    let mut self_clid: Option<i32> = try_get_self_clid(connection);
+
     loop {
         match commands::read_response(connection, true, String::new()) {
             Ok(response) => {
@@ -37,7 +47,10 @@ pub fn loop_response_reader(connection: &mut Telnet, self_clid: i32) {
                     let event = Event::new(connection, event_type, params, &known_clients);
 
                     if let Some(client) = &event.client {
-                        if client.clid == self_clid {
+                        if self_clid.is_none() {
+                            self_clid = try_get_self_clid(connection);
+                        }
+                        if Some(client.clid) == self_clid {
                             continue;
                         }
                     }
diff --git a/src/main.rs b/src/main.rs
index 5ada48b..ac3fdf4 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,11 +1,8 @@
 use std::io::{Error, ErrorKind};
-use std::num::ParseIntError;
 
 use telnet::Telnet;
 
 use crate::cli::Commands;
-use crate::models::Channel;
-use crate::models::Client;
 
 mod wrappers;
 mod commands;
@@ -16,14 +13,10 @@ mod models;
 mod response;
 mod command_utils;
 
-fn channel_or_error(channel_res: Result<Option<Channel>, String>) -> Result<Channel, Error> {
-    channel_res.map_err(|err| make_action_error("find channel", err))?
-        .ok_or_else(|| make_action_error("find channel", String::from("Not Found.")))
-}
-
-fn client_or_error(client_res: Result<Option<Client>, String>) -> Result<Client, Error> {
-    client_res.map_err(|err| make_action_error("find client", err))?
-        .ok_or_else(|| make_action_error("find client", String::from("Not Found.")))
+fn result_or_error<T>(res: Result<Option<T>, String>, result_type: &str) -> Result<T, Error> {
+    let error_action = format!("find {}", result_type);
+    res.map_err(|err| make_action_error(&error_action, err))?
+        .ok_or_else(|| make_action_error(&error_action, String::from("Not Found.")))
 }
 
 fn connect() -> Result<Telnet, Error> {
@@ -89,7 +82,7 @@ fn main() -> Result<(), Error> {
             }
 
             if args.want_client() {
-                let client = client_or_error(args.client(&mut connection))?;
+                let client = result_or_error(args.client(&mut connection), "client")?;
 
                 match wrappers::fetch_client(&mut connection, &[client]) {
                     Ok(_) => println!("Successfully fetched client."),
@@ -100,7 +93,7 @@ fn main() -> Result<(), Error> {
             }
 
             if args.want_channel() {
-                let channel = channel_or_error(args.channel(&mut connection))?;
+                let channel = result_or_error(args.channel(&mut connection), "channel")?;
 
                 match wrappers::fetch_channel(&mut connection, channel) {
                     Ok(_) => println!("Successfully fetched channel."),
@@ -124,8 +117,8 @@ fn main() -> Result<(), Error> {
         }
 
         Commands::Move(args) => {
-            let channel = channel_or_error(args.channel(&mut connection))?;
-            let client = client_or_error(args.client(&mut connection))?;
+            let channel = result_or_error(args.channel(&mut connection), "channel")?;
+            let client = result_or_error(args.client(&mut connection), "client")?;
 
             match wrappers::move_client(&mut connection, &channel, &[client]) {
                 Ok(resp) => println!("Successfully moved client: {}", resp),
@@ -149,12 +142,7 @@ fn main() -> Result<(), Error> {
                 command_utils::events::register_events(&mut connection, args.event.clone())
                     .map_err(to_other_error)?;
 
-                let self_clid: i32 = wrappers::get_self_clid(&mut connection)
-                    .map_err(|msg| make_action_error("get self clid", msg))?
-                    .parse()
-                    .map_err(|err: ParseIntError| make_action_error("parse clid", err.to_string()))?;
-
-                command_utils::events::loop_response_reader(&mut connection, self_clid);
+                command_utils::events::loop_response_reader(&mut connection);
 
                 // loop_response_reader failed. Let's try to reconnect after 1 second.
                 std::thread::sleep(std::time::Duration::from_secs(1));

From 915c2ccbbfa8bf7c3561fc1a50752630720fb66b Mon Sep 17 00:00:00 2001
From: Tobias Reisinger <tobias@msrg.cc>
Date: Mon, 3 Jun 2024 01:39:37 +0200
Subject: [PATCH 2/8] Add Events filter

---
 src/cli.rs                  | 11 ++++++++++-
 src/command_utils/events.rs | 15 +++++++--------
 src/main.rs                 |  5 +++--
 src/models/event.rs         | 18 ++++++++++++++++++
 ts-control                  |  2 +-
 5 files changed, 39 insertions(+), 12 deletions(-)

diff --git a/src/cli.rs b/src/cli.rs
index 9cfdb0d..62898e9 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -1,4 +1,4 @@
-use clap::{Args, Parser, Subcommand};
+use clap::{Args, Parser, Subcommand, ValueEnum};
 use telnet::Telnet;
 
 use crate::parameter::ParameterList;
@@ -79,9 +79,18 @@ pub struct UpdateArgs {
     speakers: Option<bool>,
 }
 
+#[derive(Clone, ValueEnum)]
+pub enum EventArgsFilter {
+    All,
+    Mine,
+    Others,
+}
+
 #[derive(Args)]
 pub struct EventArgs {
     pub event: Vec<EventType>,
+    #[arg(long, short)]
+    pub filter: Option<EventArgsFilter>,
 }
 
 impl FetchArgs {
diff --git a/src/command_utils/events.rs b/src/command_utils/events.rs
index 9e6f35e..34881fd 100644
--- a/src/command_utils/events.rs
+++ b/src/command_utils/events.rs
@@ -1,6 +1,7 @@
 use telnet::Telnet;
 
 use crate::{commands, wrappers};
+use crate::cli::EventArgsFilter;
 use crate::models::{Client, Event, EventType};
 use crate::response::Response;
 
@@ -35,7 +36,7 @@ fn try_get_self_clid(connection: &mut Telnet) -> Option<i32> {
         .unwrap_or(None)
 }
 
-pub fn loop_response_reader(connection: &mut Telnet) {
+pub fn loop_response_reader(connection: &mut Telnet, filter: &EventArgsFilter) {
     let mut known_clients = wrappers::get_clients(connection).unwrap_or_else(|_| Vec::new());
 
     let mut self_clid: Option<i32> = try_get_self_clid(connection);
@@ -46,13 +47,11 @@ pub fn loop_response_reader(connection: &mut Telnet) {
                 if let Response::Event(event_type, params) = response {
                     let event = Event::new(connection, event_type, params, &known_clients);
 
-                    if let Some(client) = &event.client {
-                        if self_clid.is_none() {
-                            self_clid = try_get_self_clid(connection);
-                        }
-                        if Some(client.clid) == self_clid {
-                            continue;
-                        }
+                    if self_clid.is_none() {
+                        self_clid = try_get_self_clid(connection);
+                    }
+                    if !event.should_handle(filter, self_clid) {
+                        continue;
                     }
 
                     handle_event_response(connection, event, &mut known_clients);
diff --git a/src/main.rs b/src/main.rs
index ac3fdf4..d82e91b 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -2,7 +2,7 @@ use std::io::{Error, ErrorKind};
 
 use telnet::Telnet;
 
-use crate::cli::Commands;
+use crate::cli::{Commands, EventArgsFilter};
 
 mod wrappers;
 mod commands;
@@ -138,11 +138,12 @@ fn main() -> Result<(), Error> {
         }
 
         Commands::Events(args) => {
+            let filter = args.filter.unwrap_or(EventArgsFilter::All);
             loop {
                 command_utils::events::register_events(&mut connection, args.event.clone())
                     .map_err(to_other_error)?;
 
-                command_utils::events::loop_response_reader(&mut connection);
+                command_utils::events::loop_response_reader(&mut connection, &filter);
 
                 // loop_response_reader failed. Let's try to reconnect after 1 second.
                 std::thread::sleep(std::time::Duration::from_secs(1));
diff --git a/src/models/event.rs b/src/models/event.rs
index 50360bd..fbc8b6d 100644
--- a/src/models/event.rs
+++ b/src/models/event.rs
@@ -4,6 +4,7 @@ use std::str::FromStr;
 use serde::{Deserialize, Serialize, Serializer};
 use serde::ser::SerializeStruct;
 use telnet::Telnet;
+use crate::cli::EventArgsFilter;
 
 use crate::models::{Channel, Client};
 use crate::parameter::{parameter_find, ParameterList};
@@ -265,6 +266,23 @@ impl Event {
             _ => String::from(""),
         }
     }
+    
+    pub fn is_mine(&self, self_clid: Option<i32>) -> bool {
+        if let Some(self_clid) = self_clid {
+            if let Some(client) = &self.client {
+                return client.clid == self_clid;
+            }
+        }
+        false
+    }
+    
+    pub fn should_handle(&self, filter: &EventArgsFilter, self_clid: Option<i32>) -> bool {
+        match filter {
+            EventArgsFilter::All => true,
+            EventArgsFilter::Mine => self.is_mine(self_clid),
+            EventArgsFilter::Others => !self.is_mine(self_clid),
+        }
+    }
 }
 
 impl Serialize for Event {
diff --git a/ts-control b/ts-control
index 31adc4e..61cced6 100755
--- a/ts-control
+++ b/ts-control
@@ -99,7 +99,7 @@ case $action in
 		teamspeak-query-lib message --strict-client --client "$user" "$message"
 		;;
 	"events")
-		teamspeak-query-lib events NotifyClientMoved NotifyClientEnterView NotifyClientLeftView NotifyTextMessage NotifyClientPoke \
+		teamspeak-query-lib events --filter=others NotifyClientMoved NotifyClientEnterView NotifyClientLeftView NotifyTextMessage NotifyClientPoke \
 			| jq -r --unbuffered '.message' \
 			| tee >(xargs -I{} notify-send "TS3 Event" "{}")
 esac

From b827471e6de1a1e6c0b3018e42eca08e9ba04ba0 Mon Sep 17 00:00:00 2001
From: Tobias Reisinger <tobias@msrg.cc>
Date: Fri, 27 Sep 2024 16:16:21 +0200
Subject: [PATCH 3/8] Add ntfy-events

---
 src/models/event.rs |  1 +
 ts-control          | 43 ++++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 43 insertions(+), 1 deletion(-)

diff --git a/src/models/event.rs b/src/models/event.rs
index fbc8b6d..281ada7 100644
--- a/src/models/event.rs
+++ b/src/models/event.rs
@@ -294,6 +294,7 @@ impl Serialize for Event {
         x.serialize_field("type", &self.event_type)?;
         x.serialize_field("channel", &self.channel)?;
         x.serialize_field("client", &self.client)?;
+        x.serialize_field("params", &self.params)?;
         x.serialize_field("message", &self.get_message())?;
         x.end()
     }
diff --git a/ts-control b/ts-control
index 61cced6..601bb90 100755
--- a/ts-control
+++ b/ts-control
@@ -9,7 +9,8 @@ not away
 back
 message
 message-user
-events"
+events
+ntfy-events"
 
 _ts_control_get_entity() {
 	entity=$(_ts_control_single_or_dmenu "$(teamspeak-query-lib "$1s")" "$2")
@@ -54,6 +55,41 @@ _ts_control_single_or_dmenu() {
 	fi
 }
 
+handle_ntfy_events() {
+  while read -r data; do
+    msg=$(echo "$data" | jq -r --unbuffered '.message')
+    type=$(echo "$data" | jq -r --unbuffered '.type')
+    mode=$(echo "$data" | jq -r --unbuffered '.params.targetmode')
+    
+    echo "$data"
+
+    if [ "$type" = "NotifyTextMessage" ] && [ "$mode" != "1" ]; then
+      continue # Skip all messages that are not direct messages
+    fi
+    
+    friendly_type="Event"
+    case $type in
+      "NotifyClientPoke")
+        friendly_type="Poke"
+        ;;
+      "NotifyTextMessage")
+        friendly_type="Message"
+        ;;
+    esac
+    
+    echo "($friendly_type) $target: $msg"
+    
+    curl -sSL \
+  		-H "Authorization: Bearer $TS3_NTFY_TOKEN" \
+  		-d "{
+     		\"topic\": \"$TS3_NTFY_TOPIC\",
+    			\"message\": \"$msg\",
+    			\"title\": \"TS3 $friendly_type\"
+  			}" \
+  		"$TS3_NTFY_HOST"
+  done
+}
+
 # Add '$' to $1 to add 'End of line' to the regex for grep
 action=$(_ts_control_single_or_dmenu "$actions" "$1$")
 
@@ -102,4 +138,9 @@ case $action in
 		teamspeak-query-lib events --filter=others NotifyClientMoved NotifyClientEnterView NotifyClientLeftView NotifyTextMessage NotifyClientPoke \
 			| jq -r --unbuffered '.message' \
 			| tee >(xargs -I{} notify-send "TS3 Event" "{}")
+		;;
+	"ntfy-events")
+		teamspeak-query-lib events --filter=others NotifyClientPoke NotifyTextMessage \
+      | handle_ntfy_events
+  	;;
 esac

From fb1e41ddc4efeea462652f584c1abf6117fced31 Mon Sep 17 00:00:00 2001
From: Tobias Reisinger <tobias@msrg.cc>
Date: Tue, 1 Oct 2024 00:20:08 +0200
Subject: [PATCH 4/8] Fix some issues

---
 .forgejo/workflows/build.yaml | 10 +---------
 Cargo.lock                    |  2 +-
 Cargo.toml                    |  2 +-
 ts-control                    | 11 +++++++----
 4 files changed, 10 insertions(+), 15 deletions(-)

diff --git a/.forgejo/workflows/build.yaml b/.forgejo/workflows/build.yaml
index db7e32c..9a70b4a 100644
--- a/.forgejo/workflows/build.yaml
+++ b/.forgejo/workflows/build.yaml
@@ -16,17 +16,9 @@ jobs:
           source "$HOME/.cargo/env"
           cargo build --release
         shell: bash
-      - uses: https://code.forgejo.org/actions/upload-artifact@v3
-        with:
-          name: teamspeak-query-lib
-          path: ${{ github.workspace }}/target/release/teamspeak-query-lib
-      - uses: https://code.forgejo.org/actions/download-artifact@v3
-        with:
-          name: teamspeak-query-lib
-          path: /tmp/artifacts
-        shell: bash
       - id: copy-ts-control-artificat
         run: |
+          cp ${{ github.workspace }}/target/release/teamspeak-query-lib /tmp/artifacts
           cp ${{ github.workspace }}/ts-control /tmp/artifacts
         shell: bash
       - uses: https://code.forgejo.org/actions/forgejo-release@v1
diff --git a/Cargo.lock b/Cargo.lock
index c541dfd..0d9a85b 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -182,7 +182,7 @@ dependencies = [
 
 [[package]]
 name = "teamspeak-query-lib"
-version = "0.1.5"
+version = "0.1.6"
 dependencies = [
  "clap",
  "serde",
diff --git a/Cargo.toml b/Cargo.toml
index 78a7388..dfad335 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "teamspeak-query-lib"
-version = "0.1.5"
+version = "0.1.6"
 edition = "2021"
 
 [dependencies]
diff --git a/ts-control b/ts-control
index 601bb90..4c89323 100755
--- a/ts-control
+++ b/ts-control
@@ -46,12 +46,16 @@ _ts_control_fetch() {
 }
 
 _ts_control_single_or_dmenu() {
-	options=$(echo "$1" | grep "$2")
+	filter="$2"
+	if [ "$filter" == "^$" ]; then
+		filter=""
+	fi
+	options=$(echo "$1" | grep "$filter")
 	count=$(echo "$options" | wc -l)
 	if [ "$count" -eq 1 ]; then
 		echo "$options"
 	else
-		echo "$options" | $DMENU
+		echo "$1" | $DMENU
 	fi
 }
 
@@ -90,8 +94,7 @@ handle_ntfy_events() {
   done
 }
 
-# Add '$' to $1 to add 'End of line' to the regex for grep
-action=$(_ts_control_single_or_dmenu "$actions" "$1$")
+action=$(_ts_control_single_or_dmenu "$actions" "^$1$")
 
 case $action in
 	"quick")

From 3463907670d4bac7bab76b79e8399edef27cc0d8 Mon Sep 17 00:00:00 2001
From: Tobias Reisinger <tobias@msrg.cc>
Date: Sun, 27 Oct 2024 18:55:08 +0100
Subject: [PATCH 5/8] Add response option to ntfy

---
 ts-control | 33 ++++++++++++++++++++++++---------
 1 file changed, 24 insertions(+), 9 deletions(-)

diff --git a/ts-control b/ts-control
index 4c89323..d872875 100755
--- a/ts-control
+++ b/ts-control
@@ -64,6 +64,7 @@ handle_ntfy_events() {
     msg=$(echo "$data" | jq -r --unbuffered '.message')
     type=$(echo "$data" | jq -r --unbuffered '.type')
     mode=$(echo "$data" | jq -r --unbuffered '.params.targetmode')
+    client_nickname=$(echo "$data" | jq -r --unbuffered '.client.client_nickname')
     
     echo "$data"
 
@@ -71,25 +72,39 @@ handle_ntfy_events() {
       continue # Skip all messages that are not direct messages
     fi
     
-    friendly_type="Event"
+    title="TS3 Event"
     case $type in
       "NotifyClientPoke")
-        friendly_type="Poke"
+        title="TS3 Poke"
         ;;
       "NotifyTextMessage")
-        friendly_type="Message"
+        title="TS3 Message"
         ;;
     esac
     
-    echo "($friendly_type) $target: $msg"
+    echo "($title) $target: $msg"
+
+    payload=$(jq -n \
+  		--arg topic "$TS3_NTFY_TOPIC" \
+  		--arg webhook "$TS3_NTFY_WEBHOOK&client=$client_nickname" \
+  		--arg msg "$msg" \
+  		--arg type "$title" \
+  		'{
+    		topic: $topic,
+    		message: $msg,
+    		title: $type,
+    		actions: [{
+        	action: "http",
+        	label: "TS response",
+        	method: "POST",
+        	url: $webhook,
+        	clear: true
+      	}]
+  		}')
     
     curl -sSL \
   		-H "Authorization: Bearer $TS3_NTFY_TOKEN" \
-  		-d "{
-     		\"topic\": \"$TS3_NTFY_TOPIC\",
-    			\"message\": \"$msg\",
-    			\"title\": \"TS3 $friendly_type\"
-  			}" \
+  		-d "$payload" \
   		"$TS3_NTFY_HOST"
   done
 }

From 21c1e3fbb3a97239e5c96fa68daa292f8426f6de Mon Sep 17 00:00:00 2001
From: Tobias Reisinger <tobias@msrg.cc>
Date: Thu, 9 Jan 2025 18:10:58 +0100
Subject: [PATCH 6/8] Add "migrate" command

---
 src/cli.rs  |  1 +
 src/main.rs | 20 ++++++++++++++++++++
 ts-control  | 11 +++++++++++
 3 files changed, 32 insertions(+)

diff --git a/src/cli.rs b/src/cli.rs
index 62898e9..4c72d25 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -17,6 +17,7 @@ struct Cli {
 
 #[derive(Subcommand)]
 pub enum Commands {
+    Info,
     Channels(ChannelsArgs),
     Clients,
     Fetch(FetchArgs),
diff --git a/src/main.rs b/src/main.rs
index d82e91b..1451eb4 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -47,6 +47,26 @@ fn main() -> Result<(), Error> {
     // You can check for the existence of subcommands, and if found use their
     // matches just as you would the top level cmd
     match cli {
+        Commands::Info => {
+            let client = match wrappers::find_self(&mut connection) {
+                Ok(client) => client,
+                Err(msg) => return Err(make_action_error("find self", msg))
+            };
+            
+            let channel_name: String = match wrappers::find_channel(&mut connection, "cid", &client.cid.to_string(), true) {
+                Ok(channel) => match channel {
+                    Some(channel) => channel.channel_name,
+                    None => return Err(to_other_error("Channel not found.".to_string()))
+                },
+                Err(msg) => return Err(make_action_error("find self", msg))
+            };
+            
+            println!("Client: {}", client.client_nickname);
+            println!("Channel: {}", channel_name);
+            println!("Channel ID: {}", client.cid);
+            println!("Client ID: {}", client.clid);
+        }
+        
         Commands::Channels(args) => {
             match wrappers::get_channels(&mut connection, args.spacers) {
                 Ok(channels) => {
diff --git a/ts-control b/ts-control
index d872875..f791e83 100755
--- a/ts-control
+++ b/ts-control
@@ -4,6 +4,7 @@ actions="quick
 move
 fetch-client
 fetch-channel
+migrate
 away
 not away
 back
@@ -45,6 +46,13 @@ _ts_control_fetch() {
 	teamspeak-query-lib fetch "--strict-$1" "--$1" "$target"
 }
 
+_ts_control_migrate() {
+	target=$(_ts_control_get_entity "channel" "$2")
+  current_channel=$(teamspeak-query-lib info | grep "Channel: " | sed 's/Channel: //')
+  _ts_control_move_self "$target"
+	teamspeak-query-lib fetch "--strict-channel" "--channel" "$current_channel"
+}
+
 _ts_control_single_or_dmenu() {
 	filter="$2"
 	if [ "$filter" == "^$" ]; then
@@ -128,6 +136,9 @@ case $action in
 	"fetch-channel")
 		_ts_control_fetch channel "$2"
 		;;
+  "migrate")
+    _ts_control_migrate "$2"
+    ;;
 	"not away")
 		teamspeak-query-lib move "Not Away From Keyboard"
 		teamspeak-query-lib update --microphone=false --speakers=false

From 93ebbbd5d2e098aac4fb0145b151a1c3a31ce4d2 Mon Sep 17 00:00:00 2001
From: Tobias Reisinger <tobias@msrg.cc>
Date: Tue, 24 Jun 2025 20:42:23 +0200
Subject: [PATCH 7/8] Fix wrong parameter for migrate command

---
 ts-control | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/ts-control b/ts-control
index f791e83..120eabb 100755
--- a/ts-control
+++ b/ts-control
@@ -47,7 +47,7 @@ _ts_control_fetch() {
 }
 
 _ts_control_migrate() {
-	target=$(_ts_control_get_entity "channel" "$2")
+	target=$(_ts_control_get_entity "channel" "$1")
   current_channel=$(teamspeak-query-lib info | grep "Channel: " | sed 's/Channel: //')
   _ts_control_move_self "$target"
 	teamspeak-query-lib fetch "--strict-channel" "--channel" "$current_channel"

From 7694bf365cc001dbeb92d508234032c8db96ddce Mon Sep 17 00:00:00 2001
From: Tobias Reisinger <tobias@msrg.cc>
Date: Tue, 8 Jul 2025 13:05:36 +0200
Subject: [PATCH 8/8] Refactor ts-control with bashly

---
 .envrc                                |   1 +
 .gitignore                            |   1 +
 bashly-settings.yml                   |   1 +
 control_src/ask_command.sh            |  20 +++
 control_src/away_command.sh           |   4 +
 control_src/back_command.sh           |   3 +
 control_src/bashly.yml                |  59 +++++++++
 control_src/events_command.sh         |   5 +
 control_src/events_ntfy_command.sh    |  52 ++++++++
 control_src/fetch_channel_command.sh  |   1 +
 control_src/fetch_client_command.sh   |   1 +
 control_src/lib/ntfy.sh               |   0
 control_src/lib/simple.sh             |  46 +++++++
 control_src/message_client_command.sh |   3 +
 control_src/message_command.sh        |   2 +
 control_src/migrate_command.sh        |   4 +
 control_src/move_command.sh           |   1 +
 control_src/not_away_command.sh       |   2 +
 control_src/quick_command.sh          |   5 +
 shell.nix                             |   6 +
 ts-control                            | 175 --------------------------
 21 files changed, 217 insertions(+), 175 deletions(-)
 create mode 100644 .envrc
 create mode 100644 bashly-settings.yml
 create mode 100644 control_src/ask_command.sh
 create mode 100644 control_src/away_command.sh
 create mode 100644 control_src/back_command.sh
 create mode 100644 control_src/bashly.yml
 create mode 100644 control_src/events_command.sh
 create mode 100644 control_src/events_ntfy_command.sh
 create mode 100644 control_src/fetch_channel_command.sh
 create mode 100644 control_src/fetch_client_command.sh
 create mode 100644 control_src/lib/ntfy.sh
 create mode 100644 control_src/lib/simple.sh
 create mode 100644 control_src/message_client_command.sh
 create mode 100644 control_src/message_command.sh
 create mode 100644 control_src/migrate_command.sh
 create mode 100644 control_src/move_command.sh
 create mode 100644 control_src/not_away_command.sh
 create mode 100644 control_src/quick_command.sh
 create mode 100644 shell.nix
 delete mode 100755 ts-control

diff --git a/.envrc b/.envrc
new file mode 100644
index 0000000..1d953f4
--- /dev/null
+++ b/.envrc
@@ -0,0 +1 @@
+use nix
diff --git a/.gitignore b/.gitignore
index ea8c4bf..d3aa771 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1 +1,2 @@
 /target
+ts-control
diff --git a/bashly-settings.yml b/bashly-settings.yml
new file mode 100644
index 0000000..7b737a7
--- /dev/null
+++ b/bashly-settings.yml
@@ -0,0 +1 @@
+source_dir: control_src
diff --git a/control_src/ask_command.sh b/control_src/ask_command.sh
new file mode 100644
index 0000000..e855e88
--- /dev/null
+++ b/control_src/ask_command.sh
@@ -0,0 +1,20 @@
+actions=(
+  "quick"
+  "move"
+  "fetch-client"
+  "fetch-channel"
+  "migrate"
+  "away"
+  "not-away"
+  "back"
+  "message"
+  "message-client"
+  "events"
+  "events-ntfy"
+)
+
+action=$(echo "${actions[@]}" | tr ' ' '\n' | $DMENU)
+
+if [ -n "$action" ]; then
+  $0 "$action"
+fi
diff --git a/control_src/away_command.sh b/control_src/away_command.sh
new file mode 100644
index 0000000..9a4bbe0
--- /dev/null
+++ b/control_src/away_command.sh
@@ -0,0 +1,4 @@
+message=$(_ts_control_get_message "${args[channel]}")
+teamspeak-query-lib move "Away From Keyboard"
+teamspeak-query-lib update --away "$message"
+teamspeak-query-lib update --microphone=false --speakers=false --away "$message"
diff --git a/control_src/back_command.sh b/control_src/back_command.sh
new file mode 100644
index 0000000..f930b9b
--- /dev/null
+++ b/control_src/back_command.sh
@@ -0,0 +1,3 @@
+teamspeak-query-lib update --back
+_ts_control_move_self "${args[channel]}"
+teamspeak-query-lib update --microphone=true --speakers=true
diff --git a/control_src/bashly.yml b/control_src/bashly.yml
new file mode 100644
index 0000000..b04f3e6
--- /dev/null
+++ b/control_src/bashly.yml
@@ -0,0 +1,59 @@
+name: ts-control
+help: Teamspeak query lib utility script
+version: 0.1.0
+
+environment_variables:
+  - name: ts3_client_api_key
+    help: Set your API key
+    required: true
+
+commands:
+  - name: ask
+    default: force
+  - name: quick
+  - name: move
+    args:
+      - name: channel
+        required: false
+  - name: fetch-client
+    args:
+      - name: client
+        required: false
+  - name: fetch-channel
+    args:
+      - name: channel
+        required: false
+  - name: migrate
+    args:
+      - name: channel
+        required: false
+  - name: not-away
+  - name: away
+    args:
+      - name: message
+        required: false
+  - name: back
+    args:
+      - name: channel
+        required: false
+  - name: message
+    args:
+      - name: message
+        required: false
+  - name: message-client
+    args:
+      - name: client
+        required: false
+      - name: message
+        required: false
+  - name: events
+  - name: events-ntfy
+    environment_variables:
+      - name: ts3_ntfy_host
+        required: true
+      - name: ts3_ntfy_token
+        required: true
+      - name: ts3_ntfy_topic
+        required: true
+      - name: ts3_ntfy_webhook
+        required: true
diff --git a/control_src/events_command.sh b/control_src/events_command.sh
new file mode 100644
index 0000000..b1fbaa1
--- /dev/null
+++ b/control_src/events_command.sh
@@ -0,0 +1,5 @@
+teamspeak-query-lib events --filter=others \
+  NotifyClientMoved NotifyClientEnterView NotifyClientLeftView \
+  NotifyTextMessage NotifyClientPoke \
+	| jq -r --unbuffered '.message' \
+	| tee >(xargs -I{} notify-send "TS3 Event" "{}")
diff --git a/control_src/events_ntfy_command.sh b/control_src/events_ntfy_command.sh
new file mode 100644
index 0000000..22506c3
--- /dev/null
+++ b/control_src/events_ntfy_command.sh
@@ -0,0 +1,52 @@
+handle_ntfy_events() {
+  while read -r data; do
+    msg=$(echo "$data" | jq -r --unbuffered '.message')
+    type=$(echo "$data" | jq -r --unbuffered '.type')
+    mode=$(echo "$data" | jq -r --unbuffered '.params.targetmode')
+    client_nickname=$(echo "$data" | jq -r --unbuffered '.client.client_nickname')
+    
+    echo "$data"
+
+    if [ "$type" = "NotifyTextMessage" ] && [ "$mode" != "1" ]; then
+      continue # Skip all messages that are not direct messages
+    fi
+    
+    title="TS3 Event"
+    case $type in
+      "NotifyClientPoke")
+        title="TS3 Poke"
+        ;;
+      "NotifyTextMessage")
+        title="TS3 Message"
+        ;;
+    esac
+    
+    echo "($title) $target: $msg"
+
+    payload=$(jq -n \
+  		--arg topic "$TS3_NTFY_TOPIC" \
+  		--arg webhook "$TS3_NTFY_WEBHOOK&client=$client_nickname" \
+  		--arg msg "$msg" \
+  		--arg type "$title" \
+  		'{
+    		topic: $topic,
+    		message: $msg,
+    		title: $type,
+    		actions: [{
+        	action: "http",
+        	label: "TS response",
+        	method: "POST",
+        	url: $webhook,
+        	clear: true
+      	}]
+  		}')
+    
+    curl -sSL \
+  		-H "Authorization: Bearer $TS3_NTFY_TOKEN" \
+  		-d "$payload" \
+  		"$TS3_NTFY_HOST"
+  done
+}
+
+teamspeak-query-lib events --filter=others NotifyClientPoke NotifyTextMessage \
+  | handle_ntfy_events
diff --git a/control_src/fetch_channel_command.sh b/control_src/fetch_channel_command.sh
new file mode 100644
index 0000000..ddefcd7
--- /dev/null
+++ b/control_src/fetch_channel_command.sh
@@ -0,0 +1 @@
+_ts_control_fetch channel "${args[channel]}"
diff --git a/control_src/fetch_client_command.sh b/control_src/fetch_client_command.sh
new file mode 100644
index 0000000..ff432fe
--- /dev/null
+++ b/control_src/fetch_client_command.sh
@@ -0,0 +1 @@
+_ts_control_fetch client "${args[client]}"
diff --git a/control_src/lib/ntfy.sh b/control_src/lib/ntfy.sh
new file mode 100644
index 0000000..e69de29
diff --git a/control_src/lib/simple.sh b/control_src/lib/simple.sh
new file mode 100644
index 0000000..2108a0a
--- /dev/null
+++ b/control_src/lib/simple.sh
@@ -0,0 +1,46 @@
+_ts_control_get_entity() {
+	entity=$(_ts_control_single_or_dmenu "$(teamspeak-query-lib "$1s")" "$2")
+	if [ -z "$entity" ]; then
+		exit 1
+	fi
+	echo "$entity"
+}
+
+_ts_control_get_message() {
+	if [ -n "$1" ];
+	then
+		message="$1"
+	else
+		message=$(printf "\n" | $DMENU -p "message")
+	fi
+
+	if [ -z "$message" ]; then
+		exit 1
+	fi
+
+	echo "$message"
+}
+
+_ts_control_move_self() {
+	channel=$(_ts_control_get_entity channel "$1" "$2")
+	teamspeak-query-lib move --strict-channel "$channel"
+}
+
+_ts_control_fetch() {
+	target=$(_ts_control_get_entity "$1" "$2")
+	teamspeak-query-lib fetch "--strict-$1" "--$1" "$target"
+}
+
+_ts_control_single_or_dmenu() {
+	filter="$2"
+	if [ "$filter" == "^$" ]; then
+		filter=""
+	fi
+	options=$(echo "$1" | grep "$filter")
+	count=$(echo "$options" | wc -l)
+	if [ "$count" -eq 1 ]; then
+		echo "$options"
+	else
+		echo "$1" | $DMENU
+	fi
+}
diff --git a/control_src/message_client_command.sh b/control_src/message_client_command.sh
new file mode 100644
index 0000000..17746f6
--- /dev/null
+++ b/control_src/message_client_command.sh
@@ -0,0 +1,3 @@
+client=$(_ts_control_get_entity client "${args[client]}")
+message=$(_ts_control_get_message "${args[message]}")
+teamspeak-query-lib message --strict-client --client "$client" "$message"
diff --git a/control_src/message_command.sh b/control_src/message_command.sh
new file mode 100644
index 0000000..f4a5ddf
--- /dev/null
+++ b/control_src/message_command.sh
@@ -0,0 +1,2 @@
+message=$(_ts_control_get_message "${args[message]}")
+teamspeak-query-lib message "$message"
diff --git a/control_src/migrate_command.sh b/control_src/migrate_command.sh
new file mode 100644
index 0000000..345d13e
--- /dev/null
+++ b/control_src/migrate_command.sh
@@ -0,0 +1,4 @@
+target=$(_ts_control_get_entity "channel" "$1")
+current_channel=$(teamspeak-query-lib info | grep "Channel: " | sed 's/Channel: //')
+_ts_control_move_self "$target"
+teamspeak-query-lib fetch "--strict-channel" "--channel" "$current_channel"
diff --git a/control_src/move_command.sh b/control_src/move_command.sh
new file mode 100644
index 0000000..bc60cba
--- /dev/null
+++ b/control_src/move_command.sh
@@ -0,0 +1 @@
+_ts_control_move_self "${args[channel]}"
diff --git a/control_src/not_away_command.sh b/control_src/not_away_command.sh
new file mode 100644
index 0000000..e090b5b
--- /dev/null
+++ b/control_src/not_away_command.sh
@@ -0,0 +1,2 @@
+teamspeak-query-lib move "Not Away From Keyboard"
+teamspeak-query-lib update --microphone=false --speakers=false
diff --git a/control_src/quick_command.sh b/control_src/quick_command.sh
new file mode 100644
index 0000000..ead1c38
--- /dev/null
+++ b/control_src/quick_command.sh
@@ -0,0 +1,5 @@
+action=$($DMENU < "$XDG_CONFIG_HOME/ts-control-quick")
+if [ -z "$action" ]; then
+	exit 1
+fi
+eval "$0 $action"
diff --git a/shell.nix b/shell.nix
new file mode 100644
index 0000000..121edf5
--- /dev/null
+++ b/shell.nix
@@ -0,0 +1,6 @@
+with import <nixpkgs> {};
+mkShell {
+	nativeBuildInputs = [
+		bashly
+	];
+}
diff --git a/ts-control b/ts-control
deleted file mode 100755
index 120eabb..0000000
--- a/ts-control
+++ /dev/null
@@ -1,175 +0,0 @@
-#!/usr/bin/env bash
-
-actions="quick
-move
-fetch-client
-fetch-channel
-migrate
-away
-not away
-back
-message
-message-user
-events
-ntfy-events"
-
-_ts_control_get_entity() {
-	entity=$(_ts_control_single_or_dmenu "$(teamspeak-query-lib "$1s")" "$2")
-	if [ -z "$entity" ]; then
-		exit 1
-	fi
-	echo "$entity"
-}
-
-_ts_control_get_message() {
-	if [ -n "$1" ];
-	then
-		message="$1"
-	else
-		message=$(printf "\n" | $DMENU -p "message")
-	fi
-
-	if [ -z "$message" ]; then
-		exit 1
-	fi
-
-	echo "$message"
-}
-
-_ts_control_move_self() {
-	channel=$(_ts_control_get_entity channel "$1" "$2")
-	teamspeak-query-lib move --strict-channel "$channel"
-}
-
-_ts_control_fetch() {
-	target=$(_ts_control_get_entity "$1" "$2")
-	teamspeak-query-lib fetch "--strict-$1" "--$1" "$target"
-}
-
-_ts_control_migrate() {
-	target=$(_ts_control_get_entity "channel" "$1")
-  current_channel=$(teamspeak-query-lib info | grep "Channel: " | sed 's/Channel: //')
-  _ts_control_move_self "$target"
-	teamspeak-query-lib fetch "--strict-channel" "--channel" "$current_channel"
-}
-
-_ts_control_single_or_dmenu() {
-	filter="$2"
-	if [ "$filter" == "^$" ]; then
-		filter=""
-	fi
-	options=$(echo "$1" | grep "$filter")
-	count=$(echo "$options" | wc -l)
-	if [ "$count" -eq 1 ]; then
-		echo "$options"
-	else
-		echo "$1" | $DMENU
-	fi
-}
-
-handle_ntfy_events() {
-  while read -r data; do
-    msg=$(echo "$data" | jq -r --unbuffered '.message')
-    type=$(echo "$data" | jq -r --unbuffered '.type')
-    mode=$(echo "$data" | jq -r --unbuffered '.params.targetmode')
-    client_nickname=$(echo "$data" | jq -r --unbuffered '.client.client_nickname')
-    
-    echo "$data"
-
-    if [ "$type" = "NotifyTextMessage" ] && [ "$mode" != "1" ]; then
-      continue # Skip all messages that are not direct messages
-    fi
-    
-    title="TS3 Event"
-    case $type in
-      "NotifyClientPoke")
-        title="TS3 Poke"
-        ;;
-      "NotifyTextMessage")
-        title="TS3 Message"
-        ;;
-    esac
-    
-    echo "($title) $target: $msg"
-
-    payload=$(jq -n \
-  		--arg topic "$TS3_NTFY_TOPIC" \
-  		--arg webhook "$TS3_NTFY_WEBHOOK&client=$client_nickname" \
-  		--arg msg "$msg" \
-  		--arg type "$title" \
-  		'{
-    		topic: $topic,
-    		message: $msg,
-    		title: $type,
-    		actions: [{
-        	action: "http",
-        	label: "TS response",
-        	method: "POST",
-        	url: $webhook,
-        	clear: true
-      	}]
-  		}')
-    
-    curl -sSL \
-  		-H "Authorization: Bearer $TS3_NTFY_TOKEN" \
-  		-d "$payload" \
-  		"$TS3_NTFY_HOST"
-  done
-}
-
-action=$(_ts_control_single_or_dmenu "$actions" "^$1$")
-
-case $action in
-	"quick")
-		action=$($DMENU < "$XDG_CONFIG_HOME/ts-control-quick")
-		if [ -z "$action" ]; then
-			exit 1
-		fi
-		eval "$0 $action"
-		;;
-	"move")
-		_ts_control_move_self "$2"
-		;;
-	"fetch-client")
-		_ts_control_fetch client "$2"
-		;;
-	"fetch-channel")
-		_ts_control_fetch channel "$2"
-		;;
-  "migrate")
-    _ts_control_migrate "$2"
-    ;;
-	"not away")
-		teamspeak-query-lib move "Not Away From Keyboard"
-		teamspeak-query-lib update --microphone=false --speakers=false
-		;;
-	"away")
-		message=$(_ts_control_get_message)
-		teamspeak-query-lib move "Away From Keyboard"
-		teamspeak-query-lib update --away "$message"
-		teamspeak-query-lib update --microphone=false --speakers=false --away "$message"
-		;;
-	"back")
-		teamspeak-query-lib update --back
-		_ts_control_move_self "$2"
-		teamspeak-query-lib update --microphone=true --speakers=true
-		;;
-	"message")
-		message=$(_ts_control_get_message "$2")
-		teamspeak-query-lib message "$message"
-		;;
-	"message-user")
-		user=$(_ts_control_get_entity client "$2")
-		message=$(_ts_control_get_message "$3")
-		teamspeak-query-lib message --strict-client --client "$user" "$message"
-		;;
-	"events")
-		teamspeak-query-lib events --filter=others NotifyClientMoved NotifyClientEnterView NotifyClientLeftView NotifyTextMessage NotifyClientPoke \
-			| jq -r --unbuffered '.message' \
-			| tee >(xargs -I{} notify-send "TS3 Event" "{}")
-		;;
-	"ntfy-events")
-		teamspeak-query-lib events --filter=others NotifyClientPoke NotifyTextMessage \
-      | handle_ntfy_events
-  	;;
-esac