]> git.somenet.org - pub/jan/mattermost-bot.git/blob - modules/CommandJoinAll.py
new file: modules/CommandFSOpen.py
[pub/jan/mattermost-bot.git] / modules / CommandJoinAll.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 import logging
10 logger = logging.getLogger(__name__)
11
12 # pylint: disable=wrong-import-position
13 from AbstractCommand import AbstractCommand
14 class CommandJoinAll(AbstractCommand):
15     TRIGGER = "join-all"
16     CONFIG = {"display_name": "somebot-command", "auto_complete": True,
17               "auto_complete_hint": "[<weeks; default=3>]"
18              }
19     USEINFO = CONFIG["auto_complete_desc"] = CONFIG["description"] = AbstractCommand.ICON_PRIVATE+"Join active public channels. considers channels with 7 posts+ in the last x weeks. default 3 weeks. There is no undo."
20
21
22     def __init__(self, team_id, skip_chann_ids):
23         super().__init__(team_id)
24
25         self.skip_chann_ids = skip_chann_ids
26         self.channel_index = None
27         self.channel_index_th = None
28
29
30     def on_register(self):
31         self._create_slash_command()
32         self.channel_index_th = threading.Timer(10.0, self._index_channels)
33         self.channel_index_th.setName("CommandJoinActive::_index_channels()")
34         self.channel_index_th.setDaemon(True)
35         self.channel_index_th.start()
36
37
38     def _index_channels(self):
39         if self.channel_index_th != threading.current_thread():
40             logger.warning("_index_channels(): thread mismatch")
41             return
42
43         logger.info("_index_channels(): started")
44         new_dict = {}
45         for chan in self.bot.api.get_team_channels(self.TEAM_ID):
46             if chan["id"] in self.skip_chann_ids:
47                 continue
48
49             posts = []
50             for post in self.bot.api.get_posts_for_channel(chan["id"]):
51                 if not post["type"].startswith("system_"):
52                     posts.append(post)
53
54                 if len(posts) == 7:
55                     break
56
57             if len(posts) > 0:
58                 new_dict[chan["id"]] = min([x["create_at"] for x in posts])
59
60         self.channel_index = new_dict
61         self.channel_index_th = threading.Timer(3600.0, self._index_channels)
62         self.channel_index_th.setName("CommandJoinActive::_index_channels()")
63         self.channel_index_th.setDaemon(True)
64         self.channel_index_th.start()
65         logger.info("_index_channels(): done")
66
67
68     def on_POST(self, request, data):
69         if self.channel_index is None:
70             request.respond_cmd_err("``/"+self.TRIGGER+"`` The channel indexer didnt finish yet. try again in a few minutes")
71             return
72
73         try:
74             td = datetime.timedelta(weeks=int(data["text"].strip()))
75         except:
76             td = datetime.timedelta(weeks=3)
77
78         timestamp = int((datetime.datetime.now()-td).timestamp())*1000
79
80         msg = ""
81         for chan in self.bot.api.get_team_channels(self.TEAM_ID):
82             #check against ban list and get the last 7 posts, if all of them are newer than min_timestamp: join
83             if chan["id"] in self.channel_index and chan["id"] not in self.skip_chann_ids and self.channel_index[chan["id"]] > timestamp:
84                 self.bot.api.add_user_to_channel(chan["id"], data["user_id"])
85                 msg += "\n + ~"+chan["name"]
86
87         request.respond_cmd_temp(cleandoc("""
88             ## :white_check_mark: Success! :)
89             By default it wont join you into channels that had less than 5 messages posted within the last 2 weeks.
90             If you want to be joined into less active channels give the command an integer number of weeks to to consider.
91             /join-active 8 will join you into channels that had less than 5 messages posted within the last 2 months.
92             Anyway: joined the following active public channels in the team (A reload might be needed to display the updated list of channels):
93             {}
94             """).format(msg))