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
|
#!/usr/bin/env python3
import asyncio
import argparse
import getpass
import sys
from nio import (
AsyncClient,
MatrixRoom,
RoomMessageText,
LoginResponse,
RoomInfo,
responses,
RoomMessagesResponse,
RoomReadMarkersResponse
)
HOME = "matrix.org"
HOME_SERVER = f"https://{HOME}"
USERNAME = None
USER_ID = f"@{USERNAME}:{HOME}"
ROOM_IDS = []
EXCLUDE_ROOM_IDS = []
INCLUDE_ONLY_ROOM_IDS = []
ACCESS_TOKEN = None
USER_PASS = None
async def client_login(
hserv: str,
usr_id: str,
tk: str,
pw: str
)-> AsyncClient:
client = AsyncClient(HOME_SERVER, USER_ID)
if ACCESS_TOKEN:
client.access_token = ACCESS_TOKEN
return client
passwd = USER_PASS if USER_PASS else getpass.getpass()
if isinstance(await client.login(passwd), LoginResponse):
return client
return None
async def main() -> None:
client = None
try:
client = await client_login(HOME_SERVER, USER_ID, ACCESS_TOKEN, USER_PASS)
if not client:
print(f"Could not log on to {USERNAME} to {HOME}")
sys.exit(1)
sync_resp = await client.sync(
timeout=30000,
full_state=True
)
#print(f"Logged on as {USERNAME} to {HOME}")
tmp_rooms = await get_rooms(client, sync_resp)
rooms = []
for room in tmp_rooms:
if len(INCLUDE_ONLY_ROOM_IDS) > 0 and (len(EXCLUDE_ROOM_IDS) == 0):
if room["room_id"] in INCLUDE_ONLY_ROOM_IDS:
rooms.append(room)
elif len(INCLUDE_ONLY_ROOM_IDS) == 0 and (len(EXCLUDE_ROOM_IDS) > 0):
if room["room_id"] not in EXCLUDE_ROOM_IDS:
rooms.append(room)
else:
rooms.append(room)
if args.print_rooms:
for room in rooms:
print(f"{room['room_id']} | {room['display_name']} | Unread: {room['unread_count']}")
print(await sum_unread(client, rooms))
except Exception as e:
print(f"Error: {e}")
finally:
if client:
#print("logging out.")
await client.logout()
await client.close()
# SEE: room_context(), events.room_events.Event(), room_read_markers, and responses.RoomInfo() with unread_notifications
async def sum_unread(client: AsyncClient, rooms: list[dict]) -> int:
return sum(room["unread_count"] for room in rooms)
async def get_rooms(client: AsyncClient, sync_response) -> list[dict]:
rooms = []
for room_id, room in client.rooms.items():
# Skip if we have INCLUDE_ONLY_ROOM_IDS and this room isn't in it
if INCLUDE_ONLY_ROOM_IDS and room_id not in INCLUDE_ONLY_ROOM_IDS:
continue
# Skip if this room is in EXCLUDE_ROOM_IDS
if room_id in EXCLUDE_ROOM_IDS:
continue
unread = 0
if room_id in sync_response.rooms.join:
room_info = sync_response.rooms.join[room_id]
if hasattr(room_info, "unread_notifications"):
unread = room_info.unread_notifications.notification_count
rooms.append({
"room_id": room_id,
"display_name": room.display_name,
"unread_count": unread
})
return rooms
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="matrix-mcnt: Matrix Unread Message Count"
)
parser.add_argument(
"--username",
required=True,
help="eg. 'myusername' not '@myusername:matrix.org'"
# otherwise conflict arises if --homeserver is supplied
)
parser.add_argument(
"--access-token",
help="Supply an access token to prevent password prompting"
)
parser.add_argument(
"--passwd",
help="Supply a password to prevent prompting"
)
parser.add_argument(
"--homeserver",
default=HOME,
help="Supply homeserver domain (eg. 'matrix.org' or 'matrix.server.com')"
)
parser.add_argument(
"--rooms",
help="A list of Room(s) ID(s) to strictly include (eg. '!Abcdefghijklmnopqr' '!2Abcdefghijklmnopq')",
nargs="+",
default=[],
)
parser.add_argument(
"--exclude-rooms",
help="A list of Room(s) ID(s) to strictly exclude (eg. '!Abcdefghijklmnopqr' '!2Abcdefghijklmnopq')",
nargs="+",
default=[],
)
parser.add_argument(
"--print-rooms",
help="Print all available rooms",
action="store_true"
)
args = parser.parse_args()
HOME = args.homeserver
USERNAME = args.username
USER_ID = f"@{USERNAME}:{HOME}"
ROOM_IDS = args.rooms
EXCLUDE_ROOM_IDS = args.exclude_rooms
INCLUDE_ONLY_ROOM_IDS = args.rooms
ACCESS_TOKEN = args.access_token
USER_PASS = args.passwd
asyncio.run(main())
|