-
Notifications
You must be signed in to change notification settings - Fork 11
/
matrixto.py
executable file
·206 lines (161 loc) · 6.14 KB
/
matrixto.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
#!/usr/bin/env python3
# SPDX-FileCopyrightText: © 2023 Georg Sauthoff <[email protected]>
# SPDX-License-Identifier: GPL-3.0-or-later
import argparse
import asyncio
import configparser
import logging
import nio
import os
import sys
log = logging.getLogger(__name__)
def parse_args(*a):
p = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description='Send a message via Matrix',
epilog='''
Examples:
Send a direct message (to an existing private room):
matrixto -u @juser:matrix.example.de -m "Host $(hostname) is back at it since $(date -Is)!"
Send a message to some room:
fortune | matrixto --room '!deadcafe:matrix.example.org'
Send multiple messages:
dstat -cdngy 60 10 | matrixto --line -u @juser:matrix.example.de
Initial Setup:
mkdir ~/.config/matrixto
cd !$
cat > config.ini
[user]
server = https://matrix.myhomeserver.example.net
user = @juser:myhandle.example.net
password = sehr-geheim
2021, Georg Sauthoff <[email protected]>, GPLv3+
''')
p.add_argument('--message', '-m',
help='message to send instead of reading it from stdin')
p.add_argument('--room', '-r', help='room ID to message')
p.add_argument('--user', '-u', help='user ID to message to (i.e. looks for a direct messaging room the user is part of')
p.add_argument('--profile', '-p', default='user',
help='profile name to lookup homeserver, password, etc. (default: %(default)s)')
p.add_argument('--config', '-c', metavar='CONFIG_FILENAME', help='configuration file')
p.add_argument('--state', dest='state_filename',
help='state file where access token etc. is stored')
p.add_argument('--no-state', action='store_false', default=True, dest='store_state',
help="don't store access token etc. in state file after successful login")
p.add_argument('--line', action='store_true', help='read and send stdin line by line')
args = p.parse_args(*a)
if not args.config:
args.config = os.getenv('HOME') + '/.config/matrixto/config.ini'
cp = configparser.ConfigParser()
cp.read(args.config)
if args.profile not in cp:
raise RuntimeError(f"Couldn't find any profile '{args.profile}' in {args.config}")
args.config = cp[args.profile]
default_state_filename = os.getenv('HOME') + '/.config/matrixto/state.ini'
if not args.state_filename:
fn = default_state_filename
if os.path.exists(fn):
args.state_filename = fn
if args.state_filename:
cp = configparser.ConfigParser()
cp.read(args.state_filename)
if args.profile in cp:
args.state = cp[args.profile]
else:
log.warning(f"Couldn't find any profile '{args.profile}' in {args.state_filename}")
args.state = None
else:
args.state = None
args.state_filename = default_state_filename
return args
class Response_Error(RuntimeError):
def __init__(self, msg, resp):
super().__init__(msg)
self.resp = resp
def raise_for_response(r, prefix=''):
if r.transport_response.status != 200:
raise Response_Error(f'{prefix}{r.message}', r)
def is_private_room(my_id, friend_id, joined_members):
if len(joined_members) != 2:
return False
xs = [ a.user_id for a in joined_members ]
if my_id not in xs:
return False
if friend_id not in xs:
return False
return True
async def private_room(client, friend_id):
rs = await client.joined_rooms()
raise_for_response(rs)
for room in rs.rooms:
ms = await client.joined_members(room)
raise_for_response(ms)
if is_private_room(client.user_id, friend_id, ms.members):
return room
return
async def send_message(client, room, msg):
r = await client.room_send(room_id=room, message_type='m.room.message',
content={ 'msgtype': 'm.text', 'body': msg })
raise_for_response(r)
async def do_with_relogin(client, args, f, *xs, **kws):
try:
x = await f(*xs, **kws)
except Response_Error as e:
if e.resp.transport_response.status == 401:
r = await client.login(args.config['password'])
raise_for_response(r)
if args.store_state:
update_state(client, args.state_filename, args.profile)
x = await f(*xs, **kws)
else:
raise
return x
def update_state(client, filename, profile):
cp = configparser.ConfigParser()
if os.path.exists(filename):
cp.read(filename)
if profile not in cp:
cp[profile] = {}
h = cp[profile]
h['access_token'] = client.access_token
h['user_id'] = client.user_id
h['device_id'] = client.device_id
with open(filename, 'w') as f:
cp.write(f)
async def run(args):
profile = args.config
client = nio.AsyncClient(profile['server'], profile['user'])
if args.state:
state = args.state
client.access_token = state['access_token']
client.user_id = state['user_id']
client.device_id = state['device_id']
else:
r = await client.login(profile['password'])
raise_for_response(r)
if args.store_state:
update_state(client, args.state_filename, args.profile)
if args.user:
room = await do_with_relogin(client, args, private_room, client, args.user)
if not room:
raise RuntimeError(f'Could not find private direct message room user {args.user}')
else:
room = args.room
if args.line:
return await send_line_by_line(client, args, room)
if args.message:
msg = args.message
else:
msg = sys.stdin.read()
await do_with_relogin(client, args, send_message, client, room, msg)
await client.close()
async def send_line_by_line(client, args, room):
for line in sys.stdin:
await do_with_relogin(client, args, send_message, client, room, line)
await client.close()
def main():
args = parse_args()
logging.basicConfig(level=logging.WARN)
asyncio.run(run(args))
if __name__ == '__main__':
sys.exit(main())