]> git.somenet.org - pub/jan/mattermost-bot.git/blob - modules/CommandJoinActive.py
modules/CommandInskription.py
[pub/jan/mattermost-bot.git] / modules / CommandJoinActive.py
1 # Mattermost Bot module.
2 #  Copyright (c) 2016-2022 by Someone <someone@somenet.org> (aka. Jan Vales <jan@jvales.net>)
3 #  published under MIT-License
4
5 import datetime
6 import threading
7 from inspect import cleandoc
8
9 # pylint: disable=wrong-import-position
10 from AbstractCommand import AbstractCommand
11 class CommandJoinActive(AbstractCommand):
12     TRIGGER = "join-active"
13     CONFIG = {"display_name": "somebot-command", "auto_complete": True,
14               "auto_complete_hint": "[<weeks; default=2>]"
15              }
16     USEINFO = CONFIG["auto_complete_desc"] = CONFIG["description"] = "Join active public channels. active = '10 posts+ in the last x months'. There is no undo."
17
18
19     def __init__(self, team_id, skip_chann_ids):
20         super().__init__(team_id)
21
22         self.skip_chann_ids = skip_chann_ids
23         self.channel_index = None
24         self.channel_index_th = None
25
26
27     def on_register(self):
28         self._create_slash_command()
29         self.channel_index_th = threading.Timer(15.0, self._index_channels)
30         self.channel_index_th.setName("CommandJoinActive::_index_channels()")
31         self.channel_index_th.setDaemon(True)
32         self.channel_index_th.start()
33
34
35     def _index_channels(self):
36         if self.channel_index_th != threading.current_thread():
37             print("_index_channels(): thread mismatch")
38             return
39
40         print("_index_channels(): started")
41         new_dict = dict()
42         for c in self.bot.api.get_team_channels(self.TEAM_ID):
43             if c["id"] in self.skip_chann_ids:
44                 continue
45
46             posts = []
47             for p in self.bot.api.get_posts_for_channel(c["id"]):
48                 if p["type"] in ["", "slack_attachement"]:
49                     posts.append(p)
50
51                 if len(posts) == 5:
52                     break
53
54             new_dict[c["id"]] = min([x["create_at"] for x in posts])
55
56         self.channel_index = new_dict
57         self.channel_index_th = threading.Timer(3600.0, self._index_channels)
58         self.channel_index_th.setName("CommandJoinActive::_index_channels()")
59         self.channel_index_th.setDaemon(True)
60         self.channel_index_th.start()
61         print("_index_channels(): done")
62
63
64     def on_POST(self, request, data):
65         if self.channel_index is None:
66             request.cmd_respond_text_temp("### ``Failed`` :(\nThe channel indexer didnt finish yet. try again in a few minutes")
67             return
68
69         try:
70             td = datetime.timedelta(weeks=int(data["text"].strip()))
71         except:
72             td = datetime.timedelta(weeks=2)
73
74         timestamp = int((datetime.datetime.now()-td).timestamp())*1000
75
76         msg = ""
77         for c in self.bot.api.get_team_channels(self.TEAM_ID):
78             #check against ban list and get the last 10 posts, if all of them are newer than min_timestamp: join
79             if not c["id"] in self.skip_chann_ids and self.channel_index[c["id"]] > timestamp:
80                 self.bot.api.add_user_to_channel(c["id"], data["user_id"])
81                 msg += "\n + ~"+c["name"]
82
83         request.cmd_respond_text_temp(cleandoc("""
84             ### ``Done`` :)
85             By default it wont join you into channels that had less than 5 messages posted within the last 2 weeks.
86             If you want to be joined into less active channels give the command an integer number of weeks to to consider.
87             /join-active 8 will join you into channels that had less than 5 messages posted within the last 2 months.
88             Anyway: joined the following active public channels in the team (A reload might be needed to display the updated list of channels):
89             {}
90             """).format(msg))