Commit 8418ff595e

8418ff595e9f53bd91d700a0a4e01137e4676212

parent: 851de84e68

Unsigned

Darafei Praliaskouski <me@komzpa.net> · 2026-07-27 18:02 UTC
committer: <strk@kbt.io>

feat: add Matrix reply command

Layout: unified · split

src/commands/mod.rs +4
@@ -23,6 +23,7 @@ mod nick;
2323mod page_up;
2424mod part;
2525mod redact;
26mod reply;
2627mod topic;
2728mod upload;
2829mod verification;
@@ -43,6 +44,7 @@ use nick::NickCommand;
4344use page_up::PageUpCommand;
4445use part::PartCommand;
4546use redact::RedactCommand;
47use reply::ReplyCommand;
4648use topic::TopicCommand;
4749use upload::UploadCommand;
4850
@@ -56,6 +58,7 @@ pub struct Commands {
5658 _kick: Command,
5759 _page_up: CommandRun,
5860 _redact: Command,
61 _reply: Command,
5962 _topic: Command,
6063 _verification: Command,
6164 _buffer_clear: CommandRun,
@@ -84,6 +87,7 @@ impl Commands {
8487 _keys: KeysCommand::create(servers)?,
8588 _page_up: PageUpCommand::create(servers)?,
8689 _redact: RedactCommand::create(servers)?,
90 _reply: ReplyCommand::create(servers)?,
8791 _topic: TopicCommand::create(servers)?,
8892 _verification: VerificationCommand::create(servers)?,
8993 _buffer_clear: BufferClearCommand::create(servers)?,
src/commands/reply.rs added +201
@@ -0,0 +1,201 @@
1use clap::{App as Argparse, AppSettings as ArgParseSettings, Arg};
2use matrix_sdk::ruma::{
3 events::{
4 relation::InReplyTo,
5 room::message::{Relation, RoomMessageEventContent},
6 },
7 EventId, OwnedEventId,
8};
9use weechat::{
10 buffer::Buffer,
11 hooks::{Command, CommandCallback, CommandSettings},
12 Args, Prefix, Weechat,
13};
14
15use super::parse_and_run;
16use crate::Servers;
17
18const EVENT_ID_TAG_PREFIX: &str = "matrix_id_";
19
20pub struct ReplyCommand {
21 servers: Servers,
22}
23
24impl ReplyCommand {
25 pub fn create(servers: &Servers) -> Result<Command, ()> {
26 let settings = CommandSettings::new("reply")
27 .description("Reply to a Matrix event in the current room.")
28 .add_argument("[event-id|index] <message>")
29 .arguments_description(
30 "event-id: The Matrix event ID to reply to.
31 index: 1-based recent event index. 1, 0, or -1 select the latest event; \
32 2 or -2 select the event before that.
33 message: Reply message text. If no event ID or index is given, all text is \
34 sent as a reply to the latest Matrix event in the buffer.",
35 );
36
37 Command::new(
38 settings,
39 ReplyCommand {
40 servers: servers.clone(),
41 },
42 )
43 }
44
45 fn latest_event_id(buffer: &Buffer) -> Option<OwnedEventId> {
46 Self::event_id_at_index(buffer, 1)
47 }
48
49 fn event_id_at_index(
50 buffer: &Buffer,
51 index: usize,
52 ) -> Option<OwnedEventId> {
53 buffer
54 .lines()
55 .rev()
56 .filter_map(|line| {
57 let tags = line.tags();
58
59 if tags.iter().any(|tag| tag.as_ref() == "matrix_redacted") {
60 return None;
61 }
62
63 tags.iter()
64 .find_map(|tag| {
65 tag.as_ref().strip_prefix(EVENT_ID_TAG_PREFIX)
66 })
67 .and_then(|event_id| EventId::parse(event_id).ok())
68 })
69 .nth(index.saturating_sub(1))
70 }
71
72 fn parse_index(argument: &str) -> Option<usize> {
73 let index = argument.parse::<isize>().ok()?;
74
75 match index {
76 0 | -1 => Some(1),
77 n if n > 0 => Some(n as usize),
78 n => n.checked_abs().map(|n| n as usize),
79 }
80 }
81
82 fn parse_arguments(
83 buffer: &Buffer,
84 arguments: Option<Vec<&str>>,
85 ) -> Result<(OwnedEventId, String), String> {
86 let Some(arguments) =
87 arguments.filter(|arguments| !arguments.is_empty())
88 else {
89 return Err("Usage: /reply [event-id|index] <message>".to_owned());
90 };
91
92 let (event_id, message) =
93 if let Some((first, rest)) = arguments.split_first() {
94 if first.starts_with('$') && EventId::parse(*first).is_err() {
95 return Err(format!("Invalid Matrix event ID: {}", first));
96 }
97
98 if let Ok(event_id) = EventId::parse(*first) {
99 (event_id, rest.join(" "))
100 } else if let Some(index) = Self::parse_index(first) {
101 let event_id = Self::event_id_at_index(buffer, index)
102 .ok_or_else(|| {
103 format!(
104 "No Matrix event found at reply index {}.",
105 first
106 )
107 })?;
108
109 (event_id, rest.join(" "))
110 } else {
111 let event_id =
112 Self::latest_event_id(buffer).ok_or_else(|| {
113 "No Matrix event found to reply to.".to_owned()
114 })?;
115
116 (event_id, arguments.join(" "))
117 }
118 } else {
119 unreachable!("empty arguments were filtered above");
120 };
121
122 if message.is_empty() {
123 Err("Reply message cannot be empty.".to_owned())
124 } else {
125 Ok((event_id, message))
126 }
127 }
128
129 fn reply(&self, buffer: &Buffer, event_id: OwnedEventId, message: String) {
130 if let Some(room) = self.servers.find_room(buffer) {
131 Weechat::spawn(async move {
132 room.send_message(reply_content(event_id, message)).await
133 })
134 .detach();
135 } else {
136 Weechat::print(
137 "The /reply command needs to be run in a Matrix room buffer.",
138 );
139 }
140 }
141}
142
143impl CommandCallback for ReplyCommand {
144 fn callback(&mut self, _: &Weechat, buffer: &Buffer, arguments: Args) {
145 let argparse = Argparse::new("reply")
146 .setting(ArgParseSettings::NoBinaryName)
147 .arg(Arg::with_name("arguments").multiple(true));
148
149 parse_and_run(argparse, arguments, |args| match Self::parse_arguments(
150 buffer,
151 args.values_of("arguments").map(|v| v.collect()),
152 ) {
153 Ok((event_id, message)) => self.reply(buffer, event_id, message),
154 Err(error) => buffer.print(&format!(
155 "{}matrix: {}",
156 Weechat::prefix(Prefix::Error),
157 error
158 )),
159 });
160 }
161}
162
163fn reply_content(
164 event_id: OwnedEventId,
165 message: String,
166) -> RoomMessageEventContent {
167 let mut content = RoomMessageEventContent::text_plain(message);
168 content.relates_to = Some(Relation::Reply {
169 in_reply_to: InReplyTo::new(event_id),
170 });
171 content
172}
173
174#[cfg(test)]
175mod tests {
176 use matrix_sdk::ruma::{events::room::message::Relation, owned_event_id};
177
178 use super::{reply_content, ReplyCommand};
179
180 #[test]
181 fn reply_index_accepts_recent_event_forms() {
182 assert_eq!(Some(1), ReplyCommand::parse_index("1"));
183 assert_eq!(Some(1), ReplyCommand::parse_index("0"));
184 assert_eq!(Some(1), ReplyCommand::parse_index("-1"));
185 assert_eq!(Some(2), ReplyCommand::parse_index("2"));
186 assert_eq!(Some(2), ReplyCommand::parse_index("-2"));
187 assert_eq!(None, ReplyCommand::parse_index("abc"));
188 }
189
190 #[test]
191 fn reply_content_sets_reply_relation() {
192 let event_id = owned_event_id!("$replyevent:example.org");
193 let content = reply_content(event_id.clone(), "Thanks".to_owned());
194
195 let Some(Relation::Reply { in_reply_to }) = content.relates_to else {
196 panic!("reply command must create a Matrix reply relation");
197 };
198
199 assert_eq!(event_id, in_reply_to.event_id);
200 }
201}