forked from 8go/matrix-commander
-
Notifications
You must be signed in to change notification settings - Fork 1
/
matrix-commander.py
executable file
·4065 lines (3754 loc) · 161 KB
/
matrix-commander.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
r"""matrix-commander.py.
0123456789012345678901234567890123456789012345678901234567890123456789012345678
0000000000111111111122222222223333333333444444444455555555556666666666777777777
[![Built with matrix-nio](
https://img.shields.io/badge/built%20with-matrix--nio-brightgreen)](
https://github.com/poljar/matrix-nio)
![logo](logos/matrix-commander-logo.svg)
# matrix-commander
Simple but convenient CLI-based Matrix client app for sending, receiving,
creating rooms, inviting, verifying, and so much more.
- `matrix-commander` is a simple command-line [Matrix](https://matrix.org/)
client.
- It is a simple but convenient app to
- send Matrix text messages as well as text, image, audio, video or
other arbitrary files
- listen to and receive Matrix messages
- perform Matrix emoji verification
- create rooms
- invite to rooms
- It exclusively offers a command-line interface (CLI).
- Hence the word-play: matrix-command(lin)er
- There is no GUI and there are no windows (except for pop-up windows in
OS notification)
- It uses the [matrix-nio](https://github.com/poljar/matrix-nio/) SDK
- Both `matrix-nio` and `matrix-commander` are written in Python 3
# Summary
This program is a simple but convenient app to send and receive Matrix
messages from the CLI in various different ways.
Use cases for this program could be
- a bot or part of a bot,
- to send alerts,
- combine it with cron to publish periodic data,
- send yourself daily/weekly reminders via a cron job
- send yourself a daily song from your music collection
- a trivial way to fire off some instant messages from the command line
- to automate sending via programs and scripts
- a "blogger" who frequently sends messages and images to the same
room(s) could use it
- a person could write a diary or run a gratitutde journal by
sending messages to her/his own room
- as educational material that showcases the use of the `matrix-nio` SDK
# Give it a Star
If you like it, use it, fork it, make a Pull Request or contribute.
Please give it a :star: on Github right now so others find it more easily.
:heart:
# First Run, Set Up, Credentials File, End-to-end Encryption
This program on the first run creates a credentials.json file.
The credentials.json file stores: homeserver, user id,
access token, device id, and room id. On the first run
it asks some questions, creates the token and device id
and stores everything in the credentials.json file.
Since the credentials file holds an access token it
should be protected and secured. One can use different
credential files for different users or different rooms.
On creation the credentials file will always be created in the local
directory, so the users sees it right away. This is fine if you have
only one or a few credential files, but for better maintainability
it is suggested to place your credentials files into directory
$HOME/.config/matrix-commander/. When the program looks for
a credentials file it will first look in local directory and then
as secondary choice it will look in directory
$HOME/.config/matrix-commander/.
If you want to re-use an existing device id and an existing
access token, you can do so as well, just manually edit the
credentials file. However, for end-to-end encryption this will
NOT work.
End-to-end encryption (e2ee) is enabled by default. It cannot be turned off.
Wherever possible end-to-end encryption will be used. For e2ee to work
efficiently a `store` directory is needed to store e2ee data persistently.
The default location for the store directory is a local directory named
`store`. Alternatively, as a secondary choice the program looks for a store
directory in $HOME/.local/shared/matrix-commander/store/. The user can always
specify a different location via the --store argument. If needed the `store`
directory will be created on the first run.
From the second time the program is run, and on all
future runs it will use the homeserver, user id
and access token found in the credentials file to log
into the Matrix account. Now this program can be used
to easily send simple text messages, images, and so forth
to the preconfigured room.
# Sending
Messages to send can be provided
1) in the command line (-m or --message)
2) as input from the keyboard
3) through a pipe from stdin (|), i.e. piped in from another program.
For sending messages the program supports various text formats:
1) text: default
2) html: HTML formated text
3) markdown: MarkDown formatted text
4) code: used a block of fixed-sized font, ideal for ASCII art or
tables, bash outputs, etc.
5) notification
6) split: splits messages into multiple units at given pattern
Photos and images that can be sent. That includes files like
.jpg, .gif, .png or .svg.
Arbirtary files like .txt, .pdf, .doc, audio files like .mp3
or video files like .mp4 can also be sent.
# Listening, Receiving
One can listen to one or multiple rooms. Received messages will be displayed
on the screen. If desired, optionally, you can be notified of incoming
messages through the operating system standard notification system, usually a
small pop-up window.
Messages can be received or listened to various ways:
1) Forever: the program runs forever, listens forever, and prints all
messages as they arrive in real-time.
2) Once: the program prints all the messages that are waiting in the queue,
i.e. all messages that have been sent in, and after printing them the
program terminates.
3) Tail: prints the last N read or unread messages of one or multiple
specified rooms and after printing them the program terminates.
When listening to messages you can also choose to download and decrypt
media. Say, someone is sending a song. The mp3 file can be downloaded
and automatically decrypted for you.
# Verification
The program can accept verification request and verify other devices
via emojis. Do do so use the --verify option and the program will
await incoming verification request and act accordingly.
# Room Operations, Actions on Rooms
The program can create rooms, join, leave and forget rooms.
It can also send invitations to join rooms to
others (given that user has the appropriate permissions) as
well as ban, unban and kick other users from rooms.
# Summary, TLDR
This simple Matrix client written in Python allows you to send and
receive messages and verify other devices. End-to-end encryption is enabled
by default and cannot be turned off.
# Dependencies
- Python 3.8 or higher (3.7 will NOT work) installed
- libolm-dev must be installed as it is required by matrix-nio
- libolm-dev on Debian/Ubuntu, libolm-devel on Fedora, libolm on MacOS
- matrix-nio must be installed, see https://github.com/poljar/matrix-nio
- pip3 install --user --upgrade matrix-nio[e2e]
- python3 package markdown must be installed to support MarkDown format
- pip3 install --user --upgrade markdown
- python3 package python_magic must be installed to support image sending
- pip3 install --user --upgrade python_magic
- if (and only if) you want OS notification support, then the python3
package notify2 and dbus-python should be installed
- pip3 install --user --upgrade dbus-python # optional
- pip3 install --user --upgrade notify2 # optional
- python3 package urllib must be installed to support media download
- pip3 install --user --upgrade urllib
- the matrix-commander.py file must be installed, and should have
execution permissions
- chmod 755 matrix-commander.py
- for a full list or requirements look at the `requirements.txt` file
- run `pip install -r requirements.txt` to automatically install
all required Python packages
- if you e.g. run on a headless server and don't want dbus-python and
notify2, please remove the corresponding 2 lines from
the `requirements.txt` file
# Examples of calling `matrix-commander`
```
$ matrix-commander.py # first run; this will configure everything
$ # this created a credentials.json file, and a store directory
$ # optionally, if you want you can move credentials to app config directory
$ mkdir $HOME/.config/matrix-commander # optional
$ mv -i credentials.json $HOME/.config/matrix-commander/
$ # optionally, if you want you can move store to the app share directory
$ mkdir $HOME/.local/share/matrix-commander # optional
$ mv -i store $HOME/.local/share/matrix-commander/
$ # Now you are ready to run program for a second time
$ # Let us verify the device/room to where we want to send messages
$ # The other device will issue a "verify by emoji" request
$ matrix-commander.py --verify
$ # Now program is both configured and verified, let us send the first message
$ matrix-commander.py -m "First message!"
$ matrix-commander.py --debug # turn debugging on
$ matrix-commander.py --help # print help
$ matrix-commander.py # this will ask user for message to send
$ matrix-commander.py --message "Hello World!" # sends provided message
$ echo "Hello World" | matrix-commander.py # pipe input msg into program
$ matrix-commander.py -m msg1 -m msg2 # sends 2 messages
$ matrix-commander.py -m msg1 msg2 msg3 # sends 3 messages
$ df -h | matrix-commander.py --code # formatting for code/tables
$ matrix-commander.py -m "<b>BOLD</b> and <i>ITALIC</i>" --html
$ matrix-commander.py -m "- bullet1" --markdown
$ # take input from an RSS feed and split large RSS entries into multiple
$ # Matrix messages wherever the pattern "\n\n\n" is found
$ rssfeed | matrix-commander.py --split "\n\n\n"
$ matrix-commander.py --credentials usr1room2.json # select credentials file
$ matrix-commander.py --store /var/storage/ # select store directory
$ # Send to a specific room
$ matrix-commander.py -m "hi" --room '!YourRoomId:example.org'
$ # some shells require the ! of the room id to be escaped with \
$ matrix-commander.py -m "hi" --room "\!YourRoomId:example.org"
$ # Send to multiple rooms
$ matrix-commander.py -m "hi" -r '!r1:example.org' '!r2:example.org'
$ # Send to multiple rooms, another way
$ matrix-commander.py -m "hi" -r '!r1:example.org' -r '!r2:example.org'
$ # send 2 images and 1 text
$ matrix-commander.py -i photo1.jpg photo2.img -m "Do you like my 2 photos?"
$ # send 1 image and no text
$ matrix-commander.py -i photo1.jpg -m ""
$ # send 1 audio and 1 text to 2 rooms
$ matrix-commander.py -a song.mp3 -m "Do you like this song?" \
-r '!someroom1:example.com' '!someroom2:example.com'
$ # send a .pdf file and a video with a text
$ matrix-commander.py -f example.pdf video.mp4 -m "Here are the promised files"
$ # listen forever, get msgs in real-time and notify me via OS
$ matrix-commander.py --listen forever --os-notify
$ # listen forever, and show me also my own messages
$ matrix-commander.py --listen forever --listen-self
$ # listen once, get any new messages and quit
$ matrix-commander.py --listen once --listen-self
$ matrix-commander.py --listen once --listen-self | process-in-other-app
$ # listen to tail, get the last N messages and quit
$ matrix-commander.py --listen tail --tail 10 --listen-self
$ # listen to tail, another way of specifying it
$ matrix-commander.py --tail 10 --listen-self | process-in-other-app
$ # get the very last message
$ matrix-commander.py --tail 1 --listen-self
$ # listen to (get) all messages, old and new, and process them in another app
$ matrix-commander.py --listen all | process-in-other-app
$ # listen to (get) all messages, including own
$ matrix-commander.py --listen all --listen-self
$ # rename device-name, sometimes also called display-name
$ matrix-commander.py --rename-device "my new name"
$ # download and decrypt media files like images, audio, PDF, etc.
$ # and store downloaded files in directory "mymedia"
$ matrix-commander.py --listen forever --listen-self --download-media mymedia
$ # create rooms without name and topic, just with alias, use a simple alias
$ matrix-commander.py --room-create roomAlias1
$ # don't use a well formed alias like '#roomAlias1:example.com' as it will
$ # confuse the server!
$ # BAD: matrix-commander.py --room-create roomAlias1 '#roomAlias1:example.com'
$ matrix-commander.py --room-create roomAlias2
$ # create rooms with name and topic
$ matrix-commander.py --room-create roomAlias3 --name 'Fancy Room' \
--topic 'All about Matrix'
$ matrix-commander.py --room-create roomAlias4 roomAlias5 \
--name 'Fancy Room 4' -name 'Cute Room 5' \
--topic 'All about Matrix 4' 'All about Nio 5'
$ # join rooms
$ matrix-commander.py --room-join '!someroomId1:example.com' \
'!someroomId2:example.com' '#roomAlias1:example.com'
$ # leave rooms
$ matrix-commander.py --room-leave '#roomAlias1:example.com' \
'!someroomId2:example.com'
$ # forget rooms, you have to first leave a room before you forget it
$ matrix-commander.py --room-forget '#roomAlias1:example.com'
$ # invite users to rooms
$ matrix-commander.py --room-invite '#roomAlias1:example.com' \
--user '@user1:example.com' '@user2:example.com'
$ # ban users from rooms
$ matrix-commander.py --room-ban '!someroom1:example.com' \
'!someroom2:example.com' \
--user '@user1:example.com' '@user2:example.com'
$ # unban users from rooms, remember after unbanning you have to invite again
$ matrix-commander.py --room-unban '!someroom1:example.com' \
'!someroom2:example.com' \
--user '@user1:example.com' '@user2:example.com'
$ # kick users from rooms
$ matrix-commander.py --room-kick '!someroom1:example.com' \
'#roomAlias2:example.com' \
--user '@user1:example.com' '@user2:example.com'
$ # set log levels, INFO for matrix-commander and ERROR for modules below
$ matrix-commander.py -m "test" --log-level INFO ERROR
$ # example of how to quote text correctly, e.g. JSON text
$ matrix-commander -m '{title: "hello", message: "here it is"}'
$ matrix-commander -m "{title: \"hello\", message: \"here it is\"}"
$ matrix-commander -m "{title: \"${TITLE}\", message: \"${MSG}\"}"
$ matrix-commander -m "Don't do this"
$ matrix-commander -m 'He said "No" to me.'
```
# Usage
```
usage: matrix-commander.py [-h] [-d] [--log-level LOG_LEVEL [LOG_LEVEL ...]]
[-c CREDENTIALS] [-r ROOM [ROOM ...]]
[--room-create ROOM_CREATE [ROOM_CREATE ...]]
[--room-join ROOM_JOIN [ROOM_JOIN ...]]
[--room-leave ROOM_LEAVE [ROOM_LEAVE ...]]
[--room-forget ROOM_FORGET [ROOM_FORGET ...]]
[--room-invite ROOM_INVITE [ROOM_INVITE ...]]
[--room-ban ROOM_BAN [ROOM_BAN ...]]
[--room-unban ROOM_UNBAN [ROOM_UNBAN ...]]
[--room-kick ROOM_KICK [ROOM_KICK ...]]
[--user USER [USER ...]] [--name NAME [NAME ...]]
[--topic TOPIC [TOPIC ...]]
[-m MESSAGE [MESSAGE ...]] [-i IMAGE [IMAGE ...]]
[-a AUDIO [AUDIO ...]] [-f FILE [FILE ...]] [-w]
[-z] [-k] [-p SPLIT] [-j CONFIG] [--proxy PROXY]
[-n] [-e] [-s STORE] [-l [LISTEN]] [-t [TAIL]] [-y]
[--print-event-id] [-u [DOWNLOAD_MEDIA]] [-o]
[-v [VERIFY]] [-x RENAME_DEVICE] [--version]
Welcome to matrix-commander, a Matrix CLI client. ─── On first run this
program will configure itself. On further runs this program implements a
simple Matrix CLI client that can send messages, listen to messages, verify
devices, etc. It can send one or multiple message to one or multiple Matrix
rooms. The text messages can be of various formats such as "text", "html",
"markdown" or "code". Images, audio or arbitrary files can be sent as well.
For receiving there are three main options: listen forever, listen once and
quit, and get the last N messages and quit. Emoji verification is built-in
which can be used to verify devices. End-to-end encryption is enabled by
default and cannot be turned off. ─── See dependencies in source code or in
README.md on Github. For even more explications and examples also read the
documentation provided in the top portion of the source code and in the
GithubREADME.md file.
optional arguments:
-h, --help show this help message and exit
-d, --debug Print debug information. If used once, only the log
level of matrix-commander is set to DEBUG. If used
twice ("-d -d" or "-dd") then log levels of both
matrix-commander and underlying modules are set to
DEBUG. "-d" is a shortcut for "--log-level DEBUG". See
also --log-level. "-d" takes precedence over "--log-
level".
--log-level LOG_LEVEL [LOG_LEVEL ...]
Set the log level(s). Possible values are "DEBUG",
"INFO", "WARNING", "ERROR", and "CRITICAL". If
--log_level is used with one level argument, only the
log level of matrix-commander is set to the specified
value. If --log_level is used with two level argument
(e.g. "--log-level WARNING ERROR") then log levels of
both matrix-commander and underlying modules are set
to the specified values. See also --debug.
-c CREDENTIALS, --credentials CREDENTIALS
On first run, information about homeserver, user, room
id, etc. will be written to a credentials file. By
default, this file is "credentials.json". On further
runs the credentials file is read to permit logging
into the correct Matrix account and sending messages
to the preconfigured room. If this option is provided,
the provided file name will be used as credentials
file instead of the default one.
-r ROOM [ROOM ...], --room ROOM [ROOM ...]
Send to this room or these rooms. None, one or
multiple rooms can be specified. The default room is
provided in credentials file. If a room (or multiple
ones) is (or are) provided in the arguments, then it
(or they) will be used instead of the one from the
credentials file. The user must have access to the
specified room in order to send messages there.
Messages cannot be sent to arbitrary rooms. When
specifying the room id some shells require the
exclamation mark to be escaped with a backslash.
--room-create ROOM_CREATE [ROOM_CREATE ...]
Create this room or these rooms. One or multiple room
aliases can be specified. The room (or multiple ones)
provided in the arguments will be created. The user
must be permitted to create rooms.Combine --room-
create with --name and --topic to add names and topics
to the room(s) to be created.
--room-join ROOM_JOIN [ROOM_JOIN ...]
Join this room or these rooms. One or multiple room
aliases can be specified. The room (or multiple ones)
provided in the arguments will be joined. The user
must have permissions to join these rooms.
--room-leave ROOM_LEAVE [ROOM_LEAVE ...]
Leave this room or these rooms. One or multiple room
aliases can be specified. The room (or multiple ones)
provided in the arguments will be left.
--room-forget ROOM_FORGET [ROOM_FORGET ...]
After leaving a room you should (most likely) forget
the room. Forgetting a room removes the users' room
history. One or multiple room aliases can be
specified. The room (or multiple ones) provided in the
arguments will be forgotten. If all users forget a
room, the room can eventually be deleted on the
server.
--room-invite ROOM_INVITE [ROOM_INVITE ...]
Invite one ore more users to join one or more rooms.
Specify the user(s) as arguments to --user. Specify
the rooms as arguments to this option, i.e. as
arguments to --room-invite. The user must have
permissions to invite users.
--room-ban ROOM_BAN [ROOM_BAN ...]
Ban one ore more users from one or more rooms. Specify
the user(s) as arguments to --user. Specify the rooms
as arguments to this option, i.e. as arguments to
--room-ban. The user must have permissions to ban
users.
--room-unban ROOM_UNBAN [ROOM_UNBAN ...]
Unban one ore more users from one or more rooms.
Specify the user(s) as arguments to --user. Specify
the rooms as arguments to this option, i.e. as
arguments to --room-unban. The user must have
permissions to unban users.
--room-kick ROOM_KICK [ROOM_KICK ...]
Kick one ore more users from one or more rooms.
Specify the user(s) as arguments to --user. Specify
the rooms as arguments to this option, i.e. as
arguments to --room-kick. The user must have
permissions to kick users.
--user USER [USER ...]
Specify one or multiple users. This option is only
meaningful in combination with options like --room-
invite, --room-ban, --room-unban, --room-kick. This
option --user specifies the users to be used with
these other room commands (like invite, ban, etc.)
--name NAME [NAME ...]
Specify one or multiple names. This option is only
meaningful in combination with option --room-create.
This option --name specifies the names to be used with
the command --room-create.
--topic TOPIC [TOPIC ...]
Specify one or multiple topics. This option is only
meaningful in combination with option --room-create.
This option --topic specifies the topics to be used
with the command --room-create.
-m MESSAGE [MESSAGE ...], --message MESSAGE [MESSAGE ...]
Send this message. If not specified, and no input
piped in from stdin, then message will be read from
stdin, i.e. keyboard. This option can be used multiple
time to send multiple messages. If there is data is
piped into this program, then first data from the pipe
is published, then messages from this option are
published.
-i IMAGE [IMAGE ...], --image IMAGE [IMAGE ...]
Send this image. This option can be used multiple time
to send multiple images. First images are send, then
text messages are send.
-a AUDIO [AUDIO ...], --audio AUDIO [AUDIO ...]
Send this audio file. This option can be used multiple
time to send multiple audio files. First audios are
send, then text messages are send.
-f FILE [FILE ...], --file FILE [FILE ...]
Send this file (e.g. PDF, DOC, MP4). This option can
be used multiple time to send multiple files. First
files are send, then text messages are send.
-w, --html Send message as format "HTML". If not specified,
message will be sent as format "TEXT". E.g. that
allows some text to be bold, etc. Only a subset of
HTML tags are accepted by Matrix.
-z, --markdown Send message as format "MARKDOWN". If not specified,
message will be sent as format "TEXT". E.g. that
allows sending of text formated in MarkDown language.
-k, --code Send message as format "CODE". If not specified,
message will be sent as format "TEXT". If both --html
and --code are specified then --code takes priority.
This is useful for sending ASCII-art or tabbed output
like tables as a fixed-sized font will be used for
display.
-p SPLIT, --split SPLIT
If set, split the message(s) into multiple messages
wherever the string specified with --split occurs.
E.g. One pipes a stream of RSS articles into the
program and the articles are separated by three
newlines. Then with --split set to "\n\n\n" each
article will be printed in a separate message. By
default, i.e. if not set, no messages will be split.
-j CONFIG, --config CONFIG
Location of a config file. By default, no config file
is used. If this option is provided, the provided file
name will be used to read configuration from.
--proxy PROXY Optionally specify a proxy for connectivity. By
default, i.e. if this option is not set, no proxy is
used. If this option is used a proxy URL must be
provided. The provided proxy URL will be used for the
HTTP connection to the server. The proxy supports
SOCKS4(a), SOCKS5, and HTTP (tunneling). Examples of
valid URLs are "http://10.10.10.10:8118" or
"socks5://user:[email protected]:1080".
-n, --notice Send message as notice. If not specified, message will
be sent as text.
-e, --encrypted Send message end-to-end encrypted. Encryption is
always turned on and will always be used where
possible. It cannot be turned off. This flag does
nothing as encryption is turned on with or without
this argument.
-s STORE, --store STORE
Path to directory to be used as "store" for encrypted
messaging. By default, this directory is "./store/".
Since encryption is always enabled, a store is always
needed. If this option is provided, the provided
directory name will be used as persistent storage
directory instead of the default one. Preferably, for
multiple executions of this program use the same store
for the same device. The store directory can be shared
between multiple different devices and users.
-l [LISTEN], --listen [LISTEN]
The --listen option takes one argument. There are
several choices: "never", "once", "forever", "tail",
and "all". By default, --listen is set to "never". So,
by default no listening will be done. Set it to
"forever" to listen for and print incoming messages to
stdout. "--listen forever" will listen to all messages
on all rooms forever. To stop listening "forever", use
Control-C on the keyboard or send a signal to the
process or service. The PID for signaling can be found
in a PID file in directory "/home/user/.run". "--
listen once" will get all the messages from all rooms
that are currently queued up. So, with "once" the
program will start, print waiting messages (if any)
and then stop. The timeout for "once" is set to 10
seconds. So, be patient, it might take up to that
amount of time. "tail" reads and prints the last N
messages from the specified rooms, then quits. The
number N can be set with the --tail option. With
"tail" some messages read might be old, i.e. already
read before, some might be new, i.e. never read
before. It prints the messages and then the program
stops. Messages are sorted, last-first. Look at --tail
as that option is related to --listen tail. The option
"all" gets all messages available, old and new. Unlike
"once" and "forever" that listen in ALL rooms, "tail"
and "all" listen only to the room specified in the
credentials file or the --room options. Furthermore,
when listening to messages, no messages will be sent.
Hence, when listening, --message must not be used and
piped input will be ignored.
-t [TAIL], --tail [TAIL]
The --tail option reads and prints up to the last N
messages from the specified rooms, then quits. It
takes one argument, an integer, which we call N here.
If there are fewer than N messages in a room, it reads
and prints up to N messages. It gets the last N
messages in reverse order. It print the newest message
first, and the oldest message last. If --listen-self
is not set it will print less than N messages in many
cases because N messages are obtained, but some of
them are discarded by default if they are from the
user itself. Look at --listen as this option is
related to --tail.Furthermore, when tailing messages,
no messages will be sent. Hence, when tailing or
listening, --message must not be used and piped input
will be ignored.
-y, --listen-self If set and listening, then program will listen to and
print also the messages sent by its own user. By
default messages from oneself are not printed.
--print-event-id If set and listening, then program will print also the
event id foreach message or other event.
-u [DOWNLOAD_MEDIA], --download-media [DOWNLOAD_MEDIA]
If set and listening, then program will download
received media files (e.g. image, audio, video, text,
PDF files). media will be downloaded to local
directory. By default, media will be downloaded to is
"./media/". You can overwrite default with your
preferred directory. If media is encrypted it will be
decrypted and stored decrypted. By default media files
will not be downloaded.
-o, --os-notify If set and listening, then program will attempt to
visually notify of arriving messages through the
operating system. By default there is no notification
via OS.
-v [VERIFY], --verify [VERIFY]
Perform verification. By default, no verification is
performed. Possible values are: "emoji". If
verification is desired, run this program in the
foreground (not as a service) and without a pipe.
Verification questions will be printed on stdout and
the user has to respond via the keyboard to accept or
reject verification. Once verification is complete,
stop the program and run it as a service again. Don't
send messages or files when you verify.
-x RENAME_DEVICE, --rename-device RENAME_DEVICE
Rename the current device to the new device name
provided. No other operations like sending, listening,
or verifying are allowed when renaming the device.
--version Print version information. After printing version
information program will continue to run. This is
useful for having version number in the log files.
```
# Features
- CLI, Command Line Interface
- Python 3
- Uses nio-template
- End-to-end encryption
- Storage for End-to-end encryption
- Storage of credentials
- Supports access token instead of password
- Sending messages
- Sending notices
- Sending formatted messages
- Sending MarkDown messages
- Message splitting before sending
- Sending Code-formatted messages
- Sending to one room
- Sending to multiple rooms
- Sending image files (photos, etc.)
- Sending of media files (music, videos, etc.)
- Sending of arbitrary files (PDF, xls, doc, txt, etc.)
- Receiving messages forever
- Receiving messages once
- Receiving last messages
- Receiving or skipping its own messages
- Receiving and downloading media files
- including automatic decryption
- Creating new rooms
- Joining rooms
- Leaving rooms
- Forgetting rooms
- Inviting other users to rooms
- Banning from rooms
- Unbanning from rooms
- Kicking from rooms
- Supports renaming of device
- Supports notification via OS of received messages
- Supports periodic execution via crontab
- Supports room aliases
- Provides PID files
- Logging (at various levels)
- In-source documentation
- Can be run as a service
# For Developers
- Don't change tabbing, spacing, or formating as file is automatically
sorted, linted and formated.
- `pylama:format=pep8:linters=pep8`
- first `isort` import sorter
- then `flake8` linter/formater
- then `black` linter/formater
- linelength: 79
- isort matrix-commander.py
- flake8 matrix-commander.py
- python3 -m black --line-length 79 matrix-commander.py
# License
This program is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
When preparing to package `matrix-commander` for NIX the question
came up if `matrix-commander` is GPL3Only or GPL3Plus. GPL3PLus was
deemed to be better. As such the license was changed from GPL3Only
to GPL3Plus on May 25, 2021. Versions before this date are licensed
under GPL3. Versions on or after this date are GPL3Plus, i.e.
GPL3 or later.
See [GPL3 at FSF](https://www.fsf.org/licensing/).
# Things to do, Things missing
- see [Issues](https://github.com/8go/matrix-commander/issues) on Github
# Final Remarks
- Thanks to all of you who already have contributed! So appreciated!
- :heart: and :thumbsup: to @fyfe, @berlincount, @ezwen, @Scriptkiddi,
@pelzvieh, etc.
- Enjoy!
- Pull requests are welcome :heart:
"""
# automatically sorted by isort,
# then formatted by black --line-length 79
import argparse
import asyncio
import datetime
import getpass
import json
import logging
import os
import re # regular expression
import select
import sys
import tempfile
import textwrap
import traceback
import urllib.request
import uuid
from urllib.parse import urlparse
import aiofiles
import aiofiles.os
import magic
from aiohttp import ClientConnectorError
from markdown import markdown
from nio import (
AsyncClient,
AsyncClientConfig,
EnableEncryptionBuilder,
JoinError,
KeyVerificationCancel,
KeyVerificationEvent,
KeyVerificationKey,
KeyVerificationMac,
KeyVerificationStart,
LocalProtocolError,
LoginResponse,
MatrixRoom,
MessageDirection,
ProfileGetAvatarResponse,
RedactedEvent,
RedactionEvent,
RoomAliasEvent,
RoomBanError,
RoomCreateError,
RoomEncryptedAudio,
RoomEncryptedFile,
RoomEncryptedImage,
RoomEncryptedMedia,
RoomEncryptedVideo,
RoomEncryptionEvent,
RoomForgetError,
RoomInviteError,
RoomKickError,
RoomLeaveError,
RoomMemberEvent,
RoomMessage,
RoomMessageAudio,
RoomMessageEmote,
RoomMessageFile,
RoomMessageFormatted,
RoomMessageImage,
RoomMessageMedia,
RoomMessageNotice,
RoomMessagesError,
RoomMessageText,
RoomMessageUnknown,
RoomMessageVideo,
RoomNameEvent,
RoomReadMarkersError,
RoomResolveAliasError,
RoomUnbanError,
SyncError,
SyncResponse,
ToDeviceError,
UnknownEvent,
UpdateDeviceError,
UploadResponse,
crypto,
)
from PIL import Image
try:
import notify2
HAVE_NOTIFY = True
except ImportError:
HAVE_NOTIFY = False
# version number
VERSION = "2021-Jul-23"
# matrix-commander
PROG_WITHOUT_EXT = os.path.splitext(os.path.basename(__file__))[0]
# matrix-commander.py
PROG_WITH_EXT = os.path.basename(__file__)
# file to store credentials in case you want to run program multiple times
CREDENTIALS_FILE_DEFAULT = "credentials.json" # login credentials JSON file
# e.g. ~/.config/matrix-commander/
CREDENTIALS_DIR_LASTRESORT = (
os.path.expanduser("~/.config/")
+ os.path.splitext(os.path.basename(__file__))[0]
)
# directory to be used by end-to-end encrypted protocol for persistent storage
STORE_DIR_DEFAULT = "./store/"
# e.g. ~/.local/share/matrix-commander/
# the STORE_PATH_LASTRESORT will be concatenated with a directory name
# like store to result in a final path of
# e.g. ~/.local/share/matrix-commander/store/ as actual persistent store dir
STORE_PATH_LASTRESORT = os.path.normpath(
(
os.path.expanduser("~/.local/share/")
+ os.path.splitext(os.path.basename(__file__))[0]
)
)
# e.g. ~/.local/share/matrix-commander/store/
STORE_DIR_LASTRESORT = os.path.normpath(
(os.path.expanduser(STORE_PATH_LASTRESORT + "/" + STORE_DIR_DEFAULT))
)
# directory to be used for downloading media files
MEDIA_DIR_DEFAULT = "./media/"
# usually there are no permissions for using: /run/matrix-commander.pid
# so instead local files like ~/.run/matrix-commander.some-uuid-here.pid will
# be used for storing the PID(s) for sending signals.
# There might be more than 1 process running in parallel, so there might be
# more than 1 PID at a given point in time.
PID_DIR_DEFAULT = os.path.normpath(os.path.expanduser("~/.run/"))
PID_FILE_DEFAULT = os.path.normpath(
PID_DIR_DEFAULT + "/" + PROG_WITHOUT_EXT + "." + str(uuid.uuid4()) + ".pid"
)
EMOJI = "emoji" # verification type
ONCE = "once" # listening type
NEVER = "never" # listening type
FOREVER = "forever" # listening type
ALL = "all" # listening type
TAIL = "tail" # listening type
LISTEN_DEFAULT = NEVER
TAIL_UNUSED_DEFAULT = 0 # get 0 if --tail is not specified
TAIL_USED_DEFAULT = 10 # get the last 10 msgs by default with --tail
VERIFY_UNUSED_DEFAULT = None # use None if --verify is not specified
VERIFY_USED_DEFAULT = "emoji" # use emoji by default with --verify
RENAME_DEVICE_UNUSED_DEFAULT = None # use None if -m is not specified
def choose_available_filename(filename):
"""Return next available filename.
If filename (includes path) does not exist,
then it returns filename. If file already
exists it adds a counter at end, before
extension, and increases counter until it
finds a filename that does not yet exist.
This avoids overwritting files when sources
have same name.
"""
if os.path.exists(filename):
try:
start, ext = filename.rsplit(".", 1)
except ValueError:
start, ext = (filename, "")
i = 0
while os.path.exists(f"{start}_{i}.{ext}"):
i += 1
return f"{start}_{i}.{ext}"
else:
return filename
async def download_mxc(client: AsyncClient, url: str):
"""Download MXC resource."""
mxc = urlparse(url)
response = await client.download(mxc.netloc, mxc.path.strip("/"))
return response.body
class Callbacks(object):
"""Class to pass client to callback methods."""
def __init__(self, client):
"""Store AsyncClient."""
self.client = client
# according to pylama: function too complex: C901 # noqa: C901
async def message_callback(self, room: MatrixRoom, event): # noqa: C901
"""Handle all events of type RoomMessage.
Includes events like RoomMessageText, RoomMessageImage, etc.
"""
try:
logger.debug(
f"message_callback(): for room {room} received this "
f"event: type: {type(event)}, event_id: {event.event_id}, "
f"event: {event}"
)
if not pargs.listen_self:
if event.sender == self.client.user:
try:
logger.debug(
f"Skipping message sent by myself: {event.body}"
)
except AttributeError: # does not have .body
logger.debug(
f"Skipping message sent by myself: {event}"
)
return
# millisec since 1970
logger.debug(f"event.server_timestamp = {event.server_timestamp}")
timestamp = datetime.datetime.fromtimestamp(
int(event.server_timestamp / 1000)
) # sec since 1970
event_datetime = timestamp.strftime("%Y-%m-%d %H:%M:%S")
# e.g. 2020-08-06 17:30:18
logger.debug(f"event_datetime = {event_datetime}")
if isinstance(event, RoomMessageMedia): # for all media events
media_mxc = event.url
media_url = await self.client.mxc_to_http(media_mxc)
logger.debug(f"HTTP URL of media is : {media_url}")
msg_url = " [" + media_url + "]"
if pargs.download_media != "":
# download unencrypted media file
media_data = await download_mxc(self.client, media_mxc)
filename = choose_available_filename(
os.path.join(pargs.download_media, event.body)
)
async with aiofiles.open(filename, "wb") as f:
await f.write(media_data)
# Set atime and mtime of file to event timestamp
os.utime(
filename,
ns=((event.server_timestamp * 1000000,) * 2),
)
msg_url += f" [Downloaded media file to {filename}]"
if isinstance(event, RoomEncryptedMedia): # for all e2e media
media_mxc = event.url
media_url = await self.client.mxc_to_http(media_mxc)
logger.debug(f"HTTP URL of media is : {media_url}")
msg_url = " [" + media_url + "]"
if pargs.download_media != "":
# download encrypted media file
media_data = await download_mxc(self.client, media_mxc)
filename = choose_available_filename(
os.path.join(pargs.download_media, event.body)
)
async with aiofiles.open(filename, "wb") as f:
await f.write(
crypto.attachments.decrypt_attachment(
media_data,
event.source["content"]["file"]["key"]["k"],
event.source["content"]["file"]["hashes"][
"sha256"
],
event.source["content"]["file"]["iv"],
)
)
# Set atime and mtime of file to event timestamp
os.utime(
filename,
ns=((event.server_timestamp * 1000000,) * 2),
)
msg_url += (
f" [Downloaded and decrypted media file to {filename}]"
)
if isinstance(event, RoomMessageAudio):
msg = "Received audio: " + event.body + msg_url
elif isinstance(event, RoomMessageEmote):
msg = "Received emote: " + event.body
elif isinstance(event, RoomMessageFile):
msg = "Received file: " + event.body + msg_url
elif isinstance(event, RoomMessageFormatted):
msg = event.body
elif isinstance(event, RoomMessageImage):
# Usually body is something like "image.svg"
msg = "Received image: " + event.body + msg_url
elif isinstance(event, RoomMessageNotice):
msg = event.body # Extract the message text
elif isinstance(event, RoomMessageText):
msg = event.body # Extract the message text
elif isinstance(event, RoomMessageUnknown):
msg = "Received room message of unknown type: " + event.msgtype
elif isinstance(event, RoomMessageVideo):
msg = "Received video: " + event.body + msg_url
elif isinstance(event, RoomEncryptedAudio):
msg = "Received encrypted audio: " + event.body + msg_url
elif isinstance(event, RoomEncryptedFile):
msg = "Received encrypted file: " + event.body + msg_url
elif isinstance(event, RoomEncryptedImage):
# Usually body is something like "image.svg"
msg = "Received encrypted image: " + event.body + msg_url
elif isinstance(event, RoomEncryptedVideo):
msg = "Received encrypted video: " + event.body + msg_url
elif isinstance(event, RoomMessageMedia):
# this should never be reached, this is a base class
# it should be a audio, image, video, etc.
# Put here at the end as defensive programming
msg = "Received media: " + event.body + msg_url
elif isinstance(event, RoomEncryptedMedia):
# this should never be reached, this is a base class
# it should be a audio, image, video, etc.
# Put here at the end as defensive programming
msg = "Received encrypted media: " + event.body + msg_url
elif isinstance(event, RoomMemberEvent):
msg = (
"Received room-member event: "
f"sender: {event.sender}, operation: {event.membership}"
)
elif isinstance(event, RoomEncryptionEvent):
msg = (
"Received room-encryption event: "
f"sender: {event.sender}"
)
elif isinstance(event, RoomAliasEvent):
msg = (
"Received room-alias event: sender: "
f"{event.sender}, alias: {event.canonical_alias}"
)