-
Notifications
You must be signed in to change notification settings - Fork 1
/
bagel.py
101 lines (84 loc) · 2.98 KB
/
bagel.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
if __name__ == "__main__":
import datetime
import json
import os
import random
import dotenv
from mattermostdriver import Driver
from mattermostdriver import exceptions as me
# Load environment variables from .env as per 12-factor apps
dotenv.load_dotenv()
random.seed()
MATCHED_MSG = "Hello! This week you have been matched up as conversation partners! I hope you meet up and have a great time :)"
UNMATCHED_MSG = "Sorry! :( This week you haven't been matched with anyone. Better luck next week!"
bot_username = os.getenv("ROBONONA_MATTERMOST_USERNAME")
mattermost = Driver(
{
"url": os.getenv("ROBONONA_MATTERMOST_URL"),
"login_id": bot_username,
"password": os.getenv("ROBONONA_MATTERMOST_PASSWORD"),
"port": 443,
}
)
mattermost.login()
try:
mattermost_channel = mattermost.channels.get_channel_by_name_and_team_name(
os.getenv("ROBONONA_MATTERMOST_TEAM"),
os.getenv("ROBONONA_MATTERMOST_CHANNEL"),
)
channel_id = mattermost_channel['id']
team_id = mattermost_channel['team_id']
except me.ResourceNotFound:
print("ERROR: mattermost team or channel name cannot be found")
exit(1)
page = 0
users = []
response = mattermost.users.get_users(
params={
'active': True,
'in_channel': channel_id,
'per_page': 200,
'page': page,
}
)
users.extend(response)
while len(response) > 0:
page += 1
response = mattermost.users.get_users(
params={
'active': True,
'in_channel': channel_id,
'per_page': 200,
'page': page,
}
)
users.extend(response)
users = [ (u['id'], u['username']) for u in users if u['username'] != bot_username ]
random.shuffle(users)
unmatched_user = None;
if len(users) % 2 != 0:
unmatched_user = users.pop()
users = [users[i:i + 2] for i in range(0, len(users), 2)]
if not os.getenv("ROBONONA_DRY_RUN") or os.getenv("ROBONONA_DRY_RUN") == "0":
for pair in users:
channel_id = mattermost.channels.create_group_channel(
pair[0][0],
pair[1][0]
])['id']
mattermost.posts.create_post(options = {
'channel_id': channel_id,
'message': MATCHED_MSG
))
if unmatched_user:
channel_id = mattermost.channels.create_direct([user])['id']
mattermost.posts.create_post(options = {
'channel_id': channel_id,
'message': UNMATCHED_MSG
))
response = {
'date': datetime.datetime.now().isoformat(),
'dry_run': os.getenv("ROBONONA_DRY_RUN", False),
'matched': [ (u[0][1], u[1][1]) for u in users ],
'unmatched': unmatched_user,
}
print(json.dumps(response))