Exemple #1
0
class Client:
    def __init__(self, user_session: UserSession):
        self.user_session = user_session
        self.driver = Driver({
            'login_id': self.user_session.username,
            'password': self.user_session.password,
            'verify': False,
            'scheme': os.getenv('MATTERMOST_SCHEME'),
            'url': os.getenv('MATTERMOST_URL_WITH_PORT')
        })
        self.driver.login()

    def get_channels(self) -> List[Dict]:
        teams_list = self.driver.api['teams'].get_teams()

        def channels_per_team(team: Dict) -> List[Dict]:
            team_id = team.get('id')
            channels_list = \
              self.driver.api['teams'].get_public_channels(team_id)

            def channel_transformer(channel: Dict) -> Dict:
                return {
                    'id': channel.get('id'),
                    'name': channel.get('display_name')
                }

            return _.map_(channels_list, channel_transformer)

        return _.flatten(_.map_(teams_list, channels_per_team))

    def get_channel_messages(self, channel_id: str) -> List[Dict]:
        channel_messages: Dict = \
          self.driver.api['posts'].get_posts_for_channel(channel_id)

        def message_transformer(post_id: str) -> Dict:
            return {
                'userid':
                channel_messages.get('posts', {}).get(post_id,
                                                      {}).get('user_id'),
                'content':
                channel_messages.get('posts', {}).get(post_id,
                                                      {}).get('message'),
                'timestamp':
                datetime.fromtimestamp(
                    float(
                        channel_messages.get('posts', {}).get(
                            post_id, {}).get('create_at')) / 1000)
            }

        return sorted(_.map_(_.reverse(channel_messages.get('order')),
                             message_transformer),
                      key=lambda message: message.get('timestamp'))

    def get_channels_messages(self) -> List[List[Dict]]:
        return _.map_(
            self.get_channels(),
            lambda channel: self.get_channel_messages(channel.get('id')))

    def get_username_by_id(self, id: str) -> str:
        return self.driver.api['users'].get_user(id).get('username')
Exemple #2
0
def mattermost(reportFile, issueList, target):
    accessToken = configs("mattermost")['accesstoken']
    reportFile = os.path.join(tempfile.gettempdir(), reportFile)
    issueList = '\n'.join('{}: {}'.format(*k) for k in enumerate(issueList, 1))
    mmost = Driver({
        'url': 'mattermost.viidakko.fi',
        'token': accessToken,
        'scheme': 'https',
        'port': 443,
        'basepath': '/api/v4',
        'verify': True,
        'timeout': 30,
        # 'mfa_token': 'TheMfaToken'
    })
    mmost.login()
    channel_id = mmost.api['channels'].get_channel_by_name_and_team_name(
        'development', 'burp-scan-reports')['id']
    file_id = mmost.api['files'].upload_file(
        channel_id=channel_id,
        files={'files': (reportFile, open(reportFile))})['file_infos'][0]['id']

    mmost.api['posts'].create_post(
        options={
            'channel_id': channel_id,
            'message': ':bell: **Scan result for ' + target + '**\n' +
            issueList,
            'file_ids': [file_id]
        })
    print(
        "\033[32m[+]\x1b[0m " +
        "Mattermost message sent, 'Burp Scan Report' channel, report file: \033[32m{}\x1b[0m"
        .format(reportFileName))
Exemple #3
0
def main():
    print("Creating Mattermost Driver...")
    driver_options = {
        'url': config.URL,
        'login_id': config.USERNAME,
        'password': config.PASSWORD,
        'port': config.PORT
    }
    driver = Driver(driver_options)

    print("Authenticating...")
    driver.login()
    driver.users.get_user('me')
    print("Successfully authenticated.")

    print("Retrieving Coffee Buddies participants...")
    team_name = config.TEAM_NAME
    channel_name = config.CHANNEL_NAME
    members = utils.get_channel_members(driver, team_name, channel_name)
    print("Successfully retrieved Coffee Buddies participants.")

    print("Preparing participants database...")
    utils.create_users(members)
    utils.create_pairs(members)
    print("Succesfully prepared participants database.")

    print("Pairing Coffee Buddies participants...")
    pairs = utils.get_pairs(members)
    print("Successfully paired Coffee Buddies participants.")

    print("Messaging paired Coffee Buddies participants...")
    utils.message_pairs(driver, pairs)
    print("Successfully messaged paired Coffee Buddies participants.")
Exemple #4
0
def connect(host: str, login_token: str = None, username: str = None, password: str = None) -> Driver:
    d = Driver({
        "url": host,
        "port": 443,
        "token": login_token,
        "username": username,
        "password": password
    })
    d.login()
    return d
Exemple #5
0
    def upload(src: str) -> None:
        driver = Driver({
            'scheme': 'https',
            'url': MattermostImport._getHost(),
            'token': MattermostImport._getToken(),
            'port': 443,
        })

        driver.login()
        print(driver.emoji.get_custom_emoji_by_name("doge"))
Exemple #6
0
def get_driver():
    my_driver = Driver({
        'url': params['MM_IP'],
        'token': params['PLOT_BOT_TOKEN'],
        'scheme': 'http',
        'port': 8065,
        'basepath': '/api/v4',
        'debug': False
    })
    my_driver.login()
    return my_driver
Exemple #7
0
 def mattermost_login(self):
     mm = Driver({
         'url': os.environ['MATTERMOST_ADDRESS'],
         'login_id': os.environ['MATTERMOST_LOGIN_ID'],
         'password': os.environ['MATTERMOST_PASSWORD'],
         'scheme': 'http',
         'port': int(os.environ['MATTERMOST_PORT']),
         'basepath': '/api/v3',
         'timeout': 30,
     })
     mm.login()
     return mm
Exemple #8
0
def get_standup_members(server_config: Dict) -> List[str]:
    d = Driver(server_config)

    d.login()

    channel_id = d.channels.get_channel_by_name_and_team_name(
        'team_name', 'channel')['id']

    channel_members = d.channels.get_channel_members(channel_id)

    d.logout()

    return channel_members
Exemple #9
0
def login(url, port, username, password, token):
    driver = Driver({
        'url': url,
        'port': int(port),
        'login_id': username,
        'password': password,
        'basepath': '/api/v4',
        'scheme': 'http',
        'token': token
    })

    driver.login()
    return driver
def post_mattermost(msg, hashtag="", data=None):
    """
    Post a message to a mattermost server.

    Optionally pass a dictionary to print as a table.

    All messages prefixed with #API

    :param msg: String message
    :param hashtag: e.g. #Oncore
    :param data: Dictionary
    :return:
    """
    try:
        driver = Driver(
            dict(url=MATTERMOST_URL,
                 login_id=MATTERMOST_USER,
                 password=MATTERMOST_PW,
                 scheme='https',
                 verify=False,
                 port=443))

        if data is not None:
            msg = f'| #API  {hashtag} | {msg} |\n' \
                  f'| :--- | :--- |\n'
            for k in data:
                v = data[k]
                if isinstance(v, str) and v is not "":
                    msg += f'| {k} | {v} |\n'
                elif isinstance(v, dict):
                    for inner_key in v:
                        inner_val = v[inner_key]
                        if isinstance(inner_val, str) and inner_val is not "":
                            msg += f'| {inner_key} | {v[inner_key]} |\n'
        else:
            msg = f'#API {hashtag} {msg}'

        driver.login()
        channel_id = driver.channels.get_channel_by_name_and_team_name(
            MATTERMOST_TEAM, MATTERMOST_CHANNEL)['id']
        driver.posts.create_post(options={
            'channel_id': channel_id,
            'message': msg
        })
        driver.logout()
    except Exception as e:
        logging.error("Error while posting to mattermost")
        logging.error(e)
Exemple #11
0
class Connection:
    """
	This class allows the user to connect to a Mattermost server and start the bot.
	
	There should be only one instance per program."""

    instance = None

    def __init__(self, settings):
        assert Connection.instance is None
        self.driver = Driver(settings)
        #self.driver.client.activate_verbose_logging()
        self.bot = Bot(convert_to_mmpy_bot(settings))
        Connection.instance = self

        # workaround for python versions < 3.7
        if sys.version_info.major < 3 or sys.version_info.minor < 7:
            api.load_driver_attributes()

    def __getattr__(self, name):
        return getattr(self.driver, name)

    def login(self):
        logger.info("login...")
        self.driver.login()
        api.me = api.User.by_id(self.driver.client.userid)
        logger.info(f"logged in as {api.me}")

    def start(self):
        # start bot at the end because the method will not return unless an exception occurs
        logger.info("start bot...")
        self.bot.run()
        logger.info("bot started")

    def stop(self):
        self.driver.logout()
        # TODO stop bot

    def __enter__(self):
        self.start()
        return self

    def __exit__(self, type, value, tb):
        self.stop()
Exemple #12
0
def main():
    print("Creating Mattermost Driver...")
    driver_options = {
        'url': config.URL,
        'login_id': config.USERNAME,
        'password': config.PASSWORD,
        'token': config.TOKEN,
        'port': config.PORT
    }
    driver = Driver(driver_options)

    print("Authenticating...")
    driver.login()
    driver.users.get_user('me')
    print("Successfully authenticated.")

    for team_name, channel_name in utils.get_channels(driver):

        print("Retrieving Coffee Buddies participants for {:s}/{:s}...".format(
            team_name, channel_name))
        utils.message_channel(driver, team_name, channel_name)
        members = utils.get_channel_members(driver, team_name, channel_name)
        print("Successfully retrieved Coffee Buddies participants.")

        print("Preparing participants database...")
        utils.create_users(members)
        utils.create_pairs(members)
        print("Successfully prepared participants database.")

        print("Pairing Coffee Buddies participants...")
        pairs, unmatched = utils.get_pairs(members)
        print("Successfully paired Coffee Buddies participants.")

        print("Messaging paired Coffee Buddies participants...")
        utils.message_pairs(driver, pairs, unmatched)
        print("Successfully messaged paired Coffee Buddies participants.")
Exemple #13
0
def cli(ctx, host, token, port, config):

    if config:
        settings = configparser.ConfigParser()
        settings.read(config)
        if not host and 'host' in settings['Default']:
            host = settings['Default']['host']
        if not token and 'token' in settings['Default']:
            token = settings['Default']['token']
        if not port and 'port' in settings['Default']:
            port = int(settings['Default']['port'])

    if not host:
        click.echo('Missing parameter `--host/-h`.', err=True)
        click.echo(cli.get_help(ctx))
        sys.exit(1)
    if not port:
        click.echo('Missing parameter `--port/-p`.', err=True)
        click.echo(cli.get_help(ctx))
        sys.exit(1)
    if not token:
        click.echo('Missing parameter `--token/-t`.', err=True)
        click.echo(cli.get_help(ctx))
        sys.exit(1)

    connect = Driver({'url': host, 'token': token, 'port': port})
    try:
        connect.login()
    except exceptions.NoAccessTokenProvided:
        sys.exit('No or invalid Access Token.')
    ctx.obj = Config(connect)
    ctx.obj.set_config('host', host)
    ctx.obj.set_config('token', token)
    ctx.obj.set_config('port', port)
    if config:
        ctx.obj.set_config('settings', settings._sections)
Exemple #14
0
def init(channel, access_token, team_id = 'n1f7ge4biifutrbeq9wdx6sz6y') :
    global mm, channel_id
    # Tuning needed here to switch between GNA and DRW instance may be
    # static override with gna team id to post on gna channels
    # at current time get_team() doesnt return gna team id , only DRW one at index 0 - will need to chat to drw about this.
    # team_id = mm.api['teams'].get_teams()[0]['id']

    url = 'chat.drwholdings.com'
    mm = Driver({
        'url': url,
        'token': access_token,
        'scheme': 'https',
        'port': 443,
        'basepath': '/api/v4',
        'verify': True,
        'timeout': 20
    })
    r = mm.login()
    channel_id = mm.api['channels'].get_channel_by_name(team_id, channel)['id']    
    return r
Exemple #15
0
def post(markdown_file: Path, channel: str = 'APD'):
    mattermost = Driver({
        'url': 'chat.asf.alaska.edu',
        'token': os.environ.get('MATTERMOST_PAT'),
        'scheme': 'https',
        'port': 443
    })
    response = mattermost.login()
    logging.debug(response)

    channel_info = mattermost.channels.get_channel_by_name_and_team_name(
        'asf', channel)

    markdown = markdown_file.read_text()
    response = mattermost.posts.create_post(options={
        'channel_id': channel_info['id'],
        'message': markdown,
    })
    logging.debug(response)

    return response
Exemple #16
0
class ConnectorMattermost(Connector):
    """A connector for Mattermost."""
    def __init__(self, config, opsdroid=None):
        """Create the connector."""
        super().__init__(config, opsdroid=opsdroid)
        _LOGGER.debug(_("Starting Mattermost connector"))
        self.name = config.get("name", "mattermost")
        self.token = config["token"]
        self.url = config["url"]
        self.team_name = config["team-name"]
        self.scheme = config.get("scheme", "https")
        self.port = config.get("port", 8065)
        self.verify = config.get("ssl-verify", True)
        self.timeout = config.get("connect-timeout", 30)
        self.request_timeout = None
        self.mfa_token = None
        self.debug = False
        self.listening = True
        self.bot_id = None

        self.mm_driver = Driver({
            "url": self.url,
            "token": self.token,
            "scheme": self.scheme,
            "port": self.port,
            "verify": self.verify,
            "timeout": self.timeout,
            "request_timeout": self.request_timeout,
            "mfa_token": self.mfa_token,
            "debug": self.debug,
        })

    async def connect(self):
        """Connect to the chat service."""
        _LOGGER.info(_("Connecting to Mattermost"))

        login_response = self.mm_driver.login()

        _LOGGER.info(login_response)

        if "id" in login_response:
            self.bot_id = login_response["id"]
        if "username" in login_response:
            self.bot_name = login_response["username"]
            _LOGGER.info(_("Connected as %s"), self.bot_name)

        self.mm_driver.websocket = Websocket(self.mm_driver.options,
                                             self.mm_driver.client.token)

        _LOGGER.info(_("Connected successfully"))

    async def disconnect(self):
        """Disconnect from Mattermost."""
        self.listening = False
        self.mm_driver.logout()

    async def listen(self):
        """Listen for and parse new messages."""
        await self.mm_driver.websocket.connect(self.process_message)

    async def process_message(self, raw_message):
        """Process a raw message and pass it to the parser."""
        _LOGGER.info(raw_message)

        message = json.loads(raw_message)

        if "event" in message and message["event"] == "posted":
            data = message["data"]
            post = json.loads(data["post"])
            # if connected to Mattermost, don't parse our own messages
            # (https://github.com/opsdroid/opsdroid/issues/1775)
            if self.bot_id is None or self.bot_id != post["user_id"]:
                await self.opsdroid.parse(
                    Message(
                        text=post["message"],
                        user=data["sender_name"],
                        target=data["channel_name"],
                        connector=self,
                        raw_event=message,
                    ))

    @register_event(Message)
    async def send_message(self, message):
        """Respond with a message."""
        _LOGGER.debug(_("Responding with: '%s' in room  %s"), message.text,
                      message.target)
        channel_id = self.mm_driver.channels.get_channel_by_name_and_team_name(
            self.team_name, message.target)["id"]
        self.mm_driver.posts.create_post(options={
            "channel_id": channel_id,
            "message": message.text
        })
Exemple #17
0
class Patter(object):
    def __init__(self, message, format_as_code, user, channel, verbose):
        self.message = message
        self.format_as_code = format_as_code
        self.user = user
        self.channel = channel
        self.verbose = verbose

        self._check_env_vars()

        self.mm_client = Driver({
            "url": config_vars["MATTERMOST_URL"],
            "login_id": config_vars["MATTERMOST_USERNAME"],
            "password": config_vars["MATTERMOST_PASSWORD"],
            "scheme": "https",
            "port": int(config_vars["MATTERMOST_PORT"]),
            "basepath": "/api/v4",
            "verify": True,
            "timeout": 30,
            "debug": False,
        })
        self.team_name = config_vars["MATTERMOST_TEAM_NAME"]

        try:
            self.mm_client.login()
        except ConnectionError:
            print("Unable to connect to the configured Mattermost server.")
            raise

    def send_message(self):
        if self.format_as_code:
            self.message = "```\n{}```".format(self.message)
        self.message += "\n⁽ᵐᵉˢˢᵃᵍᵉ ᵇʳᵒᵘᵍʰᵗ ᵗᵒ ʸᵒᵘ ᵇʸ ᵖᵃᵗᵗᵉʳ⁾"

        if self.channel:
            self._send_message_to_channel()

        if self.user:
            self._send_message_to_user()

        return

    def _send_message_to_channel(self):
        try:
            channel_id = self._get_channel_id_by_name(self.channel)
        except HTTPError:
            raise MissingChannel("The channel \'{}\' does not exist.".format(
                self.channel, ))
        self.mm_client.posts.create_post(options={
            "channel_id": channel_id,
            "message": self.message,
        })

    def _send_message_to_user(self):
        try:
            recipient_user_id = self._get_user_id_by_name(self.user)
        except HTTPError:
            raise MissingUser("The user \'{}\' does not exist.".format(
                self.user, ))
        my_id = self.mm_client.users.get_user('me')['id']

        # The Mattermost API treats direct messages the same as regular channels,
        # so we need to first get a channel ID to send the direct message.
        user_channel_id = self.mm_client.channels.create_direct_message_channel(
            [recipient_user_id, my_id])['id']

        self.mm_client.posts.create_post(options={
            "channel_id": user_channel_id,
            "message": self.message,
        })

    def _get_channel_id_by_name(self, channel_name):
        """
        The Mattermost API expects a channel ID, not a channel name.
        Use this function to get an ID from a channel name.
        """
        channel = self.mm_client.channels.get_channel_by_name_and_team_name(
            team_name=self.team_name,
            channel_name=channel_name,
        )
        return channel["id"]

    def _get_user_id_by_name(self, user_name):
        """
        The Mattermost API expects a user ID, not a username.
        Use this function to get an ID from a username.
        """
        user = self.mm_client.users.get_user_by_username(username=user_name, )
        return user["id"]

    def _check_env_vars(self):
        """Check that all of the required environment variables are set. If not,
        print the ones that are missing.
        """
        missing_vars = list(k for k, v in config_vars.items() if v is None)
        if len(missing_vars) > 0:
            error_string = "\n\t".join(missing_vars)
            raise MissingEnvVars(
                "The following environment variables are required but not set:\n\t{}"
                .format(error_string))
Exemple #18
0
class MMostBot:
    def __init__(self,
                 mail,
                 pswd,
                 url,
                 welcome="hello",
                 tags=None,
                 debug=False):
        self.debug = debug
        self.config = {
            "url": url,
            "login_id": mail,
            "password": pswd,
            "scheme": "https",
            "port": 443,
            "verify": True,
            "debug": debug,
            "welcome": welcome
        }
        self.driver = Driver(self.config)
        self.tags = tags or []

    @property
    def user_id(self):
        return self.driver.users.get_user(user_id='me')["id"]

    def listen(self):
        self.driver.login()
        self.driver.init_websocket(self.event_handler)

    #def event_handler(self, event):
    async def event_handler(self, event):
        event = json.loads(event)
        event_type = event.get("event", "")
        if event_type == "hello":
            self.on_connect(event)
        elif event_type == "status_change":
            self.on_status_change(event)
        elif event_type == "typing":
            self.on_typing(event)
        elif event_type == "posted":
            self.on_message(event)
        elif event_type == "channel_viewed":
            self.on_viewed(event)
        elif event_type == "preferences_changed":
            self.on_preferences_changed(event)
        elif event_type == "post_deleted":
            self.on_post_deleted(event)
        elif event_type == "user_added":
            self.on_user_added(event)
        elif event_type == "user_removed":
            self.on_user_removed(event)
        else:
            LOG.debug(event)

    def on_connect(self, event):
        LOG.info("Connected")

    def on_status_change(self, event):
        user_id = event["data"]["user_id"]
        status = event["data"]["status"]

        user_data = self.driver.users.get_user(user_id=user_id)
        username = user_data["username"]
        email = user_data["email"]

        LOG.info(username + ":" + status)

    def on_typing(self, event):
        user_id = event["data"]["user_id"]
        channel_id = event["broadcast"]["channel_id"]

        channel_data = self.driver.channels.get_channel(channel_id)
        channel_name = channel_data["name"]

        user_data = self.driver.users.get_user(user_id=user_id)
        username = user_data["username"]

        if channel_name == self.user_id + "__" + user_id:
            LOG.info(username + " is typing a direct message")
        else:
            LOG.info(username + " is typing a message in channel: " +
                     channel_name)

    def on_message(self, event):
        post = event["data"]["post"]
        post = json.loads(post)
        sender = event["data"]["sender_name"]
        msg = post["message"]
        channel_id = post["channel_id"]
        user_id = post["user_id"]

        channel_data = self.driver.channels.get_channel(channel_id)
        channel_name = channel_data["name"]

        if channel_name == user_id + "__" + self.user_id:
            # direct_message
            if user_id != self.user_id:
                self.on_direct_message(event)
        else:
            if user_id != self.user_id:
                mention = False
                for tag in self.tags:
                    if tag in msg:
                        mention = True
                        break
                if mention:
                    self.on_mention(event)
                else:
                    LOG.info("New message at channel: " + channel_name)
                    LOG.info(sender + " said: " + msg)
                    msg = [sender, msg, channel_name]
                    #mycroft.send_msg(msg)
                    return msg

    def on_mention(self, event):
        post = event["data"]["post"]
        post = json.loads(post)
        sender = event["data"]["sender_name"]
        msg = post["message"]
        channel_id = post["channel_id"]
        user_id = post["user_id"]
        channel_data = self.driver.channels.get_channel(channel_id)
        channel_name = channel_data["name"]

        for tag in self.tags:
            msg = msg.replace(tag, "")

        LOG.info("New mention at channel: " + channel_name)
        LOG.info(sender + " said: " + msg)

        self.handle_mention(msg, sender, channel_id)

    def on_user_added(self, event):
        user_id = event["data"]["user_id"]
        channel_id = event["broadcast"]["channel_id"]

        if user_id != self.user_id:
            user_data = self.driver.users.get_user(user_id=user_id)
            username = user_data["username"]
            self.send_message(channel_id, "@" + user_id + " " + welcome)
        else:
            self.send_message(channel_id, "Blip Blop, I am a Bot!")

    def on_user_removed(self, event):
        user_id = event["broadcast"]["user_id"]
        #channel_id = event["data"]["channel_id"]
        #remover_id = event["data"]["remover_id"]

    def on_direct_message(self, event):
        post = event["data"]["post"]
        post = json.loads(post)
        sender = event["data"]["sender_name"]
        msg = post["message"]
        channel_id = post["channel_id"]

        LOG.info("Direct Message from: " + sender)
        LOG.info("Message: " + msg)
        # echo
        self.handle_direct_message(msg, sender, channel_id)

    def on_viewed(self, event):
        channel_id = event["data"]["channel_id"]
        user_id = event["broadcast"]["user_id"]

    def on_preferences_changed(self, event):
        preferences = json.loads(event["data"]["preferences"])
        for pref in preferences:
            user_id = pref["user_id"]
            category = pref["category"]
            value = pref["value"]
            LOG.debug(category + ":" + value)

    def on_post_deleted(self, event):
        msg = event["data"]["message"]

    def send_message(self, channel_id, message, file_paths=None):
        file_paths = file_paths or []
        file_ids = []
        # TODO not working
        #for f in file_paths:
        #    file_id = self.driver.files.upload_file(
        #        channel_id=channel_id,
        #        files = {'files': (f, open(f))}
        #    )['file_infos'][0]['id']
        #    file_ids.append(file_id)

        post = {'channel_id': channel_id, 'message': message}
        if len(file_ids):
            post["file_ids"] = file_ids

        self.driver.posts.create_post(options=post)

    # Relevant handlers
    def handle_direct_message(self, message, sender, channel_id):
        pass

    def handle_mention(self, message, sender, channel_id):
        pass
Exemple #19
0
class Mattermost(Forum):
    def __init__(self, **kwargs):
        """
        Initialize Mattermost class which extends Chat ABC
        Args:
            **kwargs: args to pass to Chat ABC
            team_channel : (String) required for posting to channel
            channel_name : (String) required for posting to channel
        """
        super().__init__(**kwargs)
        self.inst = Driver({
            'url': self.url,
            'verify': False,
            'token': self.api_key,
            'username': self.username,
            'port': kwargs.get('port', 8065)
        })
        self.team_name = kwargs.get("team_name", None)
        self.channel_name = kwargs.get("channel_name", None)
        self.filepath = kwargs.get("filepath", None)

    def _upload_files(self, file_location, channel_id):
        file_ids = []
        for root, dirs, files in walk(file_location):
            for filename in files:
                #TODO add optional parameters for adjusting size. Implement file splitting
                print(f"[...] Uploading {filename}")
                if stat(join_abs(root, filename)).st_size / 1024**2 > 49:
                    print(f"[!]\tFile {filename} is to big, ignoring for now")
                    continue
                else:
                    file_ids += [
                        self.inst.files.upload_file(
                            channel_id=channel_id,
                            files={
                                'files':
                                (filename, open(join_abs(root, filename),
                                                'rb'))
                            })['file_infos'][0]['id']
                    ]
                    if len(file_ids) >= 5:
                        self.inst.posts.create_post(
                            options={
                                'channel_id': channel_id,
                                'message':
                                f"Recon Data {datetime.datetime.now()}",
                                'file_ids': file_ids
                            })
                        file_ids = []
        if len(file_ids) > 0:
            self.inst.posts.create_post(
                options={
                    'channel_id': channel_id,
                    'message': f"Recon Data {datetime.datetime.now()}",
                    'file_ids': file_ids
                })

    def upload(self, **kwargs):
        """
        File upload

        Args:
            **kwargs:
                filepath: (String) optional filepath to check for files to upload
        Returns:

        """
        print("[*] doing post message")
        try:
            self.inst.login()

            team_id = self.inst.teams.get_team_by_name(self.team_name)['id']
            channel_id = self.inst.channels.get_channel_by_name(
                channel_name=self.channel_name, team_id=team_id)['id']
        except exceptions.NoAccessTokenProvided as er:
            print(f"[!] NoAccessTokenProvided {er}")
            logger.exception()
        except exceptions.InvalidOrMissingParameters as er:
            print(f"[!] InvalidOrMissingParameters {er}")
            logger.exception()

        try:
            if isfile(self.filepath):
                file_ids = [
                    self.inst.files.upload_file(
                        channel_id=channel_id,
                        files={
                            'files': (basename(self.filepath),
                                      open(join_abs(self.filepath), 'rb'))
                        })['file_infos'][0]['id']
                ]

                self.inst.posts.create_post(
                    options={
                        'channel_id': channel_id,
                        'message': f"Recon Data {datetime.datetime.now()}",
                        'file_ids': file_ids
                    })

            elif isdir(self.filepath):
                file_location = abspath(self.filepath)

                self._upload_files(file_location, channel_id)

        except exceptions.ContentTooLarge as er:
            print(f"[!] ContentTooLarge {er}")
            logger.exception()
        except exceptions.ResourceNotFound as er:
            print(f"[!] ResourceNotFound {er}")
            logger.exception()
        except OSError as er:
            print(f"[!] File not found {er}")
            logger.exception()
    print('blink')
    for x in range(10):
        GPIO.output(lights, GPIO.HIGH)
        sleep(0.5)
        GPIO.output(lights, GPIO.LOW)
        sleep(0.5)


mm = Driver({
    'url': mattermosturl,
    "token": personaltoken,
    'scheme': 'https',
    'port': 443
})

mm.login()


async def my_event_handler(e):
    message = json.loads(e)
    if 'event' in message:
        print('----------------------------------------------')
        print(message)
        if message['event'] == 'reaction_added':
            reaction = json.loads(message['data']['reaction'])
            post_id = reaction['post_id']
            post = mm.posts.get_post(post_id)
            emoji = reaction['emoji_name']
            if emoji == 'stop_sign':
                stop()
            if emoji == 'arrow_up':
Exemple #21
0
class MattermostClient:

    def __init__(self, mattermost_setting, username, mattermost_user_setting, selector: MattermostChannelSelect):
        self.driver = Driver({
            'url': mattermost_setting['url'],
            'token': mattermost_user_setting['token'],
            'scheme': mattermost_setting['scheme'],
            'port': mattermost_setting['port'],
            'basepath': mattermost_setting['basepath'],
            'timeout': mattermost_setting['timeout']
        })
        self.username = username
        team_name = mattermost_user_setting['team_name']
        self.driver.login()
        self.selector = selector
        self.team_id = self.driver.teams.get_team_by_name(team_name)['id']

    def post(self, mail: MailModel):
        try:
            channel_name = self.selector.select_channel(mail)
            self.__api_process(channel_name, mail)
        except Exception as e:
            LOGGER.error(e)
            try:
                self.__simple_post(mail, 'error', e)
            except Exception as e2:
                LOGGER.error(e2)

    def error_post(self, text):
        self.__simple_post(None, 'error', text)

    def __api_process(self, channel_name, mail):
        if channel_name == 'drops':
            self.__simple_post(mail, 'drops')
            return
        channel_id = self.__get_channel_id_if_create_channel(channel_name)
        file_ids = self.__check_if_upload_file(channel_id, mail)
        self.__create_message(channel_id, mail, file_ids)

    def __get_channel_id_if_create_channel(self, channel_name):
        try:
            channel = self.driver.channels.get_channel_by_name(self.team_id, channel_name)
            return channel['id']
        except ResourceNotFound:
            LOGGER.info('channel does not exist and create channel')
            user_id = self.driver.users.get_user_by_username(self.username)['id']
            channel = self.driver.channels.create_channel(options={
                'team_id': self.team_id,
                'name': channel_name,
                'display_name': channel_name,
                'type': 'O'
            })
            channel_id = channel['id']
            self.driver.channels.add_user(channel_id, options={
                'user_id': user_id
            })
            return channel_id

    def __create_message(self, channel_id, mail, file_ids):
        message = self.__format_message(mail)
        if len(message) >= MATTERMOST_POST_LIMIT_LENGTH:
            file_ids.append(self.__upload_file(channel_id, 'full_body.txt', message.encode('utf-8')))
            message = message[:MATTERMOST_POST_LIMIT_LENGTH]
        self.__execute_post(channel_id, message, file_ids)

    def __execute_post(self, channel_id, message, file_ids=[]):
        self.driver.posts.create_post(options={
            'channel_id': channel_id,
            'message': message,
            'file_ids': file_ids
        })

    def __format_message(self, mail):
        return dedent('''
        ```
        from: {}
        date: {}
        subject: {}
        uid: {}
        ```
        '''.format(mail.origin_from_, mail.date_, mail.subject_.strip(), mail.uid_)).strip() + '\n' + dedent(mail.body_)

    def __check_if_upload_file(self, channel_id, mail: MailModel):
        if len(mail.attachments_) <= 0:
            return []
        file_ids = []
        for attachment in mail.attachments_:
            file_ids.append(self.__upload_file(channel_id, attachment['name'], attachment['data']))
        return file_ids

    def __upload_file(self, channel_id, name, data):
        return self.driver.files.upload_file(channel_id, {'files': (name, data)})['file_infos'][0]['id']

    def __simple_post(self, mail, channel_name, error=None, plain_text=None):
        channel_id = self.__get_channel_id_if_create_channel(channel_name)
        if mail is None:
            self.__execute_post(channel_id, plain_text)
            return
        message = dedent('''
                ```
                from: {}
                date: {}
                subject: {}
                uid: {}
                ```
                '''.format(mail.origin_from_, mail.date_, mail.subject_.strip(), mail.uid_)).strip()
        if error is not None:
            message += '\n' + dedent(error)
        self.__execute_post(channel_id, message)
class MattermostBackend(ErrBot):
	def __init__(self, config):
		super().__init__(config)
		identity = config.BOT_IDENTITY
		self._login = identity.get('login', None)
		self._password = identity.get('password', None)
		self._personal_access_token = identity.get('token', None)
		self._mfa_token = identity.get('mfa_token', None)
		self.team = identity.get('team')
		self._scheme = identity.get('scheme', 'https')
		self._port = identity.get('port', 8065)
		self.cards_hook = identity.get('cards_hook', None)
		self.url = identity.get('server').rstrip('/')
		self.insecure = identity.get('insecure', False)
		self.timeout = identity.get('timeout', DEFAULT_TIMEOUT)
		self.teamid = ''
		self.token = ''
		self.bot_identifier = None
		self.driver = None
		self.md = md()

	@property
	def userid(self):
		return "{}".format(self.bot_identifier.userid)

	@property
	def mode(self):
		return 'mattermost'

	def username_to_userid(self, name):
		"""Converts a name prefixed with @ to the userid"""
		name = name.lstrip('@')
		user = self.driver.users.get_user_by_username(username=name)
		if user is None:
			raise UserDoesNotExistError("Cannot find user {}".format(name))
		return user['id']

	@asyncio.coroutine
	def mattermost_event_handler(self, payload):
		if not payload:
			return

		payload = json.loads(payload)
		if 'event' not in payload:
			log.debug("Message contains no event: {}".format(payload))
			return

		event_handlers = {
			'posted': self._message_event_handler,
			'status_change': self._status_change_event_handler,
			'hello': self._hello_event_handler,
			'user_added': self._room_joined_event_handler,
			'user_removed': self._room_left_event_handler,
		}

		event = payload['event']
		event_handler = event_handlers.get(event)

		if event_handler is None:
			log.debug("No event handler available for {}, ignoring.".format(event))
			return
		# noinspection PyBroadException
		try:
			event_handler(payload)
		except Exception:
			log.exception("{} event handler raised an exception".format(event))

	def _room_joined_event_handler(self, message):
		log.debug('User added to channel')
		if message['data']['user_id'] == self.userid:
			self.callback_room_joined(self)

	def _room_left_event_handler(self, message):
		log.debug('User removed from channel')
		if message['broadcast']['user_id'] == self.userid:
			self.callback_room_left(self)

	def _message_event_handler(self, message):
		log.debug(message)
		data = message['data']

		# In some cases (direct messages) team_id is an empty string
		if data['team_id'] != '' and self.teamid != data['team_id']:
			log.info("Message came from another team ({}), ignoring...".format(data['team_id']))
			return

		broadcast = message['broadcast']

		if 'channel_id' in data:
			channelid = data['channel_id']
		elif 'channel_id' in broadcast:
			channelid = broadcast['channel_id']
		else:
			log.error("Couldn't find a channelid for event {}".format(message))
			return

		channel_type = data['channel_type']

		if channel_type != 'D':
			channel = data['channel_name']
		else:
			channel = channelid

		text = ''
		post_id = ''
		file_ids = None
		userid = None

		if 'post' in data:
			post = json.loads(data['post'])
			text = post['message']
			userid = post['user_id']
			if 'file_ids' in post:
				file_ids = post['file_ids']
			post_id = post['id']
			if 'type' in post and post['type'] == 'system_add_remove':
				log.info("Ignoring message from System")
				return

		if 'user_id' in data:
			userid = data['user_id']

		if not userid:
			log.error('No userid in event {}'.format(message))
			return

		mentions = []
		if 'mentions' in data:
			# TODO: Only user, not channel mentions are in here at the moment
			mentions = self.mentions_build_identifier(json.loads(data['mentions']))

		# Thread root post id
		root_id = post.get('root_id')
		if root_id is '':
			root_id = post_id

		msg = Message(
			text,
			extras={
				'id': post_id,
				'root_id': root_id,
				'mattermost_event': message,
				'url': '{scheme:s}://{domain:s}:{port:s}/{teamname:s}/pl/{postid:s}'.format(
					scheme=self.driver.options['scheme'],
					domain=self.driver.options['url'],
					port=str(self.driver.options['port']),
					teamname=self.team,
					postid=post_id
				)
			}
		)
		if file_ids:
			msg.extras['attachments'] = file_ids

		# TODO: Slack handles bots here, but I am not sure if bot users is a concept in mattermost
		if channel_type == 'D':
			msg.frm = MattermostPerson(self.driver, userid=userid, channelid=channelid, teamid=self.teamid)
			msg.to = MattermostPerson(
				self.driver, userid=self.bot_identifier.userid, channelid=channelid, teamid=self.teamid)
		elif channel_type == 'O' or channel_type == 'P':
			msg.frm = MattermostRoomOccupant(self.driver, userid=userid, channelid=channelid, teamid=self.teamid, bot=self)
			msg.to = MattermostRoom(channel, teamid=self.teamid, bot=self)
		else:
			log.warning('Unknown channel type \'{}\'! Unable to handle {}.'.format(
				channel_type,
				channel
			))
			return

		self.callback_message(msg)

		if mentions:
			self.callback_mention(msg, mentions)

	def _status_change_event_handler(self, message):
		"""Event handler for the 'presence_change' event"""
		idd = MattermostPerson(self.driver, message['data']['user_id'])
		status = message['data']['status']
		if status == 'online':
			status = ONLINE
		elif status == 'away':
			status = AWAY
		else:
			log.error(
				"It appears the Mattermost API changed, I received an unknown status type %s" % status
			)
			status = ONLINE
		self.callback_presence(Presence(identifier=idd, status=status))

	def _hello_event_handler(self, message):
		"""Event handler for the 'hello' event"""
		self.connect_callback()
		self.callback_presence(Presence(identifier=self.bot_identifier, status=ONLINE))

	@lru_cache(1024)
	def get_direct_channel(self, userid, other_user_id):
		"""
		Get the direct channel to another user.
		If it does not exist, it will be created.
		"""
		try:
			return self.driver.channels.create_direct_message_channel(options=[userid, other_user_id])
		except (InvalidOrMissingParameters, NotEnoughPermissions):
			raise RoomDoesNotExistError("Could not find Direct Channel for users with ID {} and {}".format(
				userid, other_user_id
			))

	def build_identifier(self, txtrep):
		"""
		Convert a textual representation into a :class:`~MattermostPerson` or :class:`~MattermostRoom`

		Supports strings with the following formats::

			@username
			~channelname
			channelid
		"""
		txtrep = txtrep.strip()
		if txtrep.startswith('~'):
			# Channel
			channelid = self.channelname_to_channelid(txtrep[1:])
			if channelid is not None:
				return MattermostRoom(channelid=channelid, teamid=self.teamid, bot=self)
		else:
			# Assuming either a channelid or a username
			if txtrep.startswith('@'):
				# Username
				userid = self.username_to_userid(txtrep[1:])
			else:
				# Channelid
				userid = txtrep

			if userid is not None:
				return MattermostPerson(
					self.driver,
					userid=userid,
					channelid=self.get_direct_channel(self.userid, userid)['id'],
					teamid=self.teamid
				)
		raise Exception(
			'Invalid or unsupported Mattermost identifier: %s' % txtrep
		)

	def mentions_build_identifier(self, mentions):
		identifier = []
		for mention in mentions:
			if mention != self.bot_identifier.userid:
				identifier.append(
					self.build_identifier(mention)
				)
		return identifier

	def serve_once(self):
		self.driver = Driver({
			'scheme': self._scheme,
			'url': self.url,
			'port': self._port,
			'verify': not self.insecure,
			'timeout': self.timeout,
			'login_id': self._login,
			'password': self._password,
			'token': self._personal_access_token,
			'mfa_token': self._mfa_token
		})
		self.driver.login()

		self.teamid = self.driver.teams.get_team_by_name(name=self.team)['id']
		userid = self.driver.users.get_user(user_id='me')['id']

		self.token = self.driver.client.token

		self.bot_identifier = MattermostPerson(self.driver, userid=userid, teamid=self.teamid)

		# noinspection PyBroadException
		try:
			loop = self.driver.init_websocket(event_handler=self.mattermost_event_handler)
			self.reset_reconnection_count()
			loop.run_forever()
		except KeyboardInterrupt:
			log.info("Interrupt received, shutting down..")
			return True
		except Exception:
			log.exception("Error reading from RTM stream:")
		finally:
			log.debug("Triggering disconnect callback")
			self.disconnect_callback()

	def _prepare_message(self, message):
		to_name = "<unknown>"
		if message.is_group:
			to_channel_id = message.to.id
			if message.to.name:
				to_name = message.to.name
			else:
				self.channelid_to_channelname(channelid=to_channel_id)
		else:
			to_name = message.to.username

			if isinstance(message.to, RoomOccupant):  # private to a room occupant -> this is a divert to private !
				log.debug("This is a divert to private message, sending it directly to the user.")
				channel = self.get_direct_channel(self.userid, self.username_to_userid(to_name))
				to_channel_id = channel['id']
			else:
				to_channel_id = message.to.channelid
		return to_name, to_channel_id

	def send_message(self, message):
		super().send_message(message)
		try:
			to_name, to_channel_id = self._prepare_message(message)

			message_type = "direct" if message.is_direct else "channel"
			log.debug('Sending %s message to %s (%s)' % (message_type, to_name, to_channel_id))

			body = self.md.convert(message.body)
			log.debug('Message size: %d' % len(body))

			limit = min(self.bot_config.MESSAGE_SIZE_LIMIT, MATTERMOST_MESSAGE_LIMIT)
			parts = self.prepare_message_body(body, limit)

			root_id = None
			if message.parent is not None:
				root_id = message.parent.extras.get('root_id')

			for part in parts:
				self.driver.posts.create_post(options={
					'channel_id': to_channel_id,
					'message': part,
					'root_id': root_id,
				})
		except (InvalidOrMissingParameters, NotEnoughPermissions):
			log.exception(
				"An exception occurred while trying to send the following message "
				"to %s: %s" % (to_name, message.body)
			)

	def send_card(self, card: Card):
		if isinstance(card.to, RoomOccupant):
			card.to = card.to.room

		to_humanreadable, to_channel_id = self._prepare_message(card)

		attachment = {}
		if card.summary:
			attachment['pretext'] = card.summary
		if card.title:
			attachment['title'] = card.title
		if card.link:
			attachment['title_link'] = card.link
		if card.image:
			attachment['image_url'] = card.image
		if card.thumbnail:
			attachment['thumb_url'] = card.thumbnail
		attachment['text'] = card.body

		if card.color:
			attachment['color'] = COLORS[card.color] if card.color in COLORS else card.color

		if card.fields:
			attachment['fields'] = [{'title': key, 'value': value, 'short': True} for key, value in card.fields]

		data = {
			'attachments': [attachment]
		}

		if card.to:
			if isinstance(card.to, MattermostRoom):
				data['channel'] = card.to.name

		try:
			log.debug('Sending data:\n%s', data)
			# We need to send a webhook - mattermost has no api endpoint for attachments/cards
			# For this reason, we need to build our own url, since we need /hooks and not /api/v4
			# Todo: Reminder to check if this is still the case
			self.driver.webhooks.call_webhook(self.cards_hook, options=data)
		except (
					InvalidOrMissingParameters,
					NotEnoughPermissions,
					ContentTooLarge,
					FeatureDisabled,
					NoAccessTokenProvided
				):
			log.exception(
				"An exception occurred while trying to send a card to %s.[%s]" % (to_humanreadable, card)
			)

	def prepare_message_body(self, body, size_limit):
		"""
		Returns the parts of a message chunked and ready for sending.
		This is a staticmethod for easier testing.
		Args:
			body (str)
			size_limit (int): chunk the body into sizes capped at this maximum
		Returns:
			[str]
		"""
		fixed_format = body.startswith('```')  # hack to fix the formatting
		parts = list(split_string_after(body, size_limit))

		if len(parts) == 1:
			# If we've got an open fixed block, close it out
			if parts[0].count('```') % 2 != 0:
				parts[0] += '\n```\n'
		else:
			for i, part in enumerate(parts):
				starts_with_code = part.startswith('```')

				# If we're continuing a fixed block from the last part
				if fixed_format and not starts_with_code:
					parts[i] = '```\n' + part

				# If we've got an open fixed block, close it out
				if parts[i].count('```') % 2 != 0:
					parts[i] += '\n```\n'

		return parts

	def change_presence(self, status: str=ONLINE, message: str=''):
		pass  # Mattermost does not have a request/websocket event to change the presence

	def is_from_self(self, message: Message):
		return self.bot_identifier.userid == message.frm.userid

	def shutdown(self):
		self.driver.logout()
		super().shutdown()

	def query_room(self, room):
		""" Room can either be a name or a channelid """
		return MattermostRoom(room, teamid=self.teamid, bot=self)

	def prefix_groupchat_reply(self, message: Message, identifier):
		super().prefix_groupchat_reply(message, identifier)
		message.body = '@{0}: {1}'.format(identifier.nick, message.body)

	def build_reply(self, message, text=None, private=False, threaded=False):
		response = self.build_message(text)
		response.frm = self.bot_identifier
		if private:
			response.to = message.frm
		else:
			response.to = message.frm.room if isinstance(message.frm, RoomOccupant) else message.frm

		if threaded:
			response.extras['root_id'] = message.extras.get('root_id')
			self.driver.posts.get_post(message.extras.get('root_id'))
			response.parent = message

		return response

	def get_public_channels(self):
		channels = []
		page = 0
		channel_page_limit = 200
		while True:
			channel_list = self.driver.channels.get_public_channels(
				team_id=self.teamid,
				params={'page': page, 'per_page': channel_page_limit}
			)
			if len(channel_list) == 0:
				break
			else:
				channels.extend(channel_list)
			page += 1
		return channels

	def channels(self, joined_only=False):
		channels = []
		channels.extend(self.driver.channels.get_channels_for_user(user_id=self.userid, team_id=self.teamid))
		if not joined_only:
			public_channels = self.get_public_channels()
			for channel in public_channels:
				if channel not in channels:
					channels.append(channel)
		return channels

	def rooms(self):
		"""Return public and private channels, but no direct channels"""
		rooms = self.channels(joined_only=True)
		channels = [channel for channel in rooms if channel['type'] != 'D']
		return [MattermostRoom(channelid=channel['id'], teamid=channel['team_id'], bot=self) for channel in channels]

	def channelid_to_channelname(self, channelid):
		"""Convert the channelid in the current team to the channel name"""
		channel = self.driver.channels.get_channel(channel_id=channelid)
		if 'name' not in channel:
			raise RoomDoesNotExistError("No channel with ID {} exists in team with ID {}".format(
				id, self.teamid
			))
		return channel['name']

	def channelname_to_channelid(self, name):
		"""Convert the channelname in the current team to the channel id"""
		channel = self.driver.channels.get_channel_by_name(team_id=self.teamid, channel_name=name)
		if 'id' not in channel:
			raise RoomDoesNotExistError("No channel with name {} exists in team with ID {}".format(
				name, self.teamid
			))
		return channel['id']

	def __hash__(self):
		return 0  # This is a singleton anyway
Exemple #23
0
class SubscriptionBot:
    """ A mattermost bot implementing a publish/subscribe mechanism. """

    SUBSCRIBED_MESSAGE = "Hi there - thx for joining!"
    UNSUBSCRIBED_MESSAGE = "Bye then, couch potato!"
    NOT_SUBSCRIBED_MESSAGE = "Are you also trying to cancel your gym membership before even registering?"
    UNKNOWN_COMMAND_TEXT = "I don't get it, want to join? Try 'subscribe' instead. 'help' may also be your friend."
    HELP_TEXT = """
|Command|Description|
|:------|:----------|
|subscribe|Join the growing list of subscribers now!|
|unsubscribe|Go back to your boring office-chair-only life.|
|help|I'm quite sure, you know what this one does.|        
"""

    def __init__(self, username, password, scheme='https', debug=False):
        self.subscriptions = set()

        self.username = username
        self.debug = debug

        self.driver = Driver({
            'url': "192.168.122.254",
            'login_id': username,
            'password': password,
            'scheme': scheme,
            'debug': debug,
        })
        self.driver.login()

        # get userid for username since it is not automatically set to driver.client.userid ... for reasons
        res = self.driver.users.get_user_by_username('bot')
        self.userid = res['id']

    def start_listening(self):
        worker = threading.Thread(
            target=SubscriptionBot._start_listening_in_thread, args=(self, ))
        worker.daemon = True
        worker.start()

        print("Initialized bot.")

    def _start_listening_in_thread(self):
        # Setting event loop for thread
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)

        self.driver.init_websocket(self.websocket_handler)

    @asyncio.coroutine
    def websocket_handler(self, event_json):
        event = json.loads(event_json)

        if self.debug:
            print("websocket_handler:" + json.dumps(event, indent=4))

        if 'event' in event and event['event'] == 'posted':
            # mentions is automatically set in direct messages
            mentions = json.loads(event['data']['mentions']
                                  ) if 'mentions' in event['data'] else []

            post = json.loads(event['data']['post'])
            post_id = post['id']
            message = post['message']
            channel_id = post['channel_id']
            sender_id = post['user_id']

            if self.userid in mentions:
                self.handle_bot_message(channel_id, post_id, sender_id,
                                        message)

    def handle_bot_message(self, channel_id, post_id, sender_id, message):
        if re.match(r'(@' + self.username + ')?\s*help\s*', message):
            self._show_help(channel_id, post_id)
        elif re.match(r'(@' + self.username + ')?\s*subscribe\s*', message):
            self._handle_subscription(sender_id, channel_id, post_id)
        elif re.match(r'(@' + self.username + ')?\s*unsubscribe\s*', message):
            self._handle_unsubscription(channel_id, post_id, sender_id)
        else:
            self._handle_unknown_command(channel_id, post_id)

    def _show_help(self, channel_id, post_id):
        self.driver.posts.create_post({
            'channel_id': channel_id,
            'message': self.HELP_TEXT,
            'root_id': post_id,
        })

    def _handle_subscription(self, sender_id, channel_id, post_id):
        self.subscriptions.add(sender_id)
        if self.debug:
            print(sender_id + " subscribed.")

        self.driver.posts.create_post({
            'channel_id': channel_id,
            'message': self.SUBSCRIBED_MESSAGE,
            'root_id': post_id,
        })

    def _handle_unsubscription(self, channel_id, post_id, sender_id):
        if sender_id in self.subscriptions:
            self.subscriptions.discard(sender_id)
            if self.debug:
                print(sender_id + " unsubscribed.")

            self.driver.posts.create_post({
                'channel_id': channel_id,
                'message': self.UNSUBSCRIBED_MESSAGE,
                'root_id': post_id,
            })
        else:
            self.driver.posts.create_post({
                'channel_id': channel_id,
                'message': self.UNSUBSCRIBED_MESSAGE,
                'root_id': post_id,
            })

    def _handle_unknown_command(self, channel_id, post_id):
        self.driver.posts.create_post({
            'channel_id': channel_id,
            'message': self.UNKNOWN_COMMAND_TEXT,
            'root_id': post_id,
        })

    def send_messages_to_subscribers(self, message):
        for subscriber in self.subscriptions:
            self._send_direct_message(subscriber, message)

    def _send_direct_message(self, user_id, message, root_id=None):
        res = self.driver.channels.create_direct_message_channel(
            [self.userid, user_id])
        channel_id = res['id']

        post_options = {
            'channel_id': channel_id,
            'message': message,
        }
        if root_id:
            post_options['root_id'] = root_id

        self.driver.posts.create_post(post_options)
Exemple #24
0
class Patter(object):
    def __init__(self, message, filename, format_as_code, user, channel,
                 verbose):
        self.message = self._format_message(message, format_as_code)
        self.filename = filename
        self.user = user
        self.channel = channel
        self.verbose = verbose

        self._check_env_vars()

        self.mm_client = Driver({
            "url": config_vars["MATTERMOST_URL"],
            "login_id": config_vars["MATTERMOST_USERNAME"],
            "password": config_vars["MATTERMOST_PASSWORD"],
            "scheme": "https",
            "port": int(config_vars["MATTERMOST_PORT"]),
            "basepath": "/api/v4",
            "verify": True,
            "timeout": 30,
            "debug": False,
        })
        self.team_name = config_vars["MATTERMOST_TEAM_NAME"]

        try:
            self.mm_client.login()
        except ConnectionError:
            print("Unable to connect to the configured Mattermost server.")
            raise

    def send_message(self):
        """Send the message."""
        channel_id = self._get_message_channel_id()

        attached_file_id = None
        if self.filename:
            attached_file_id = self._attach_file(self.filename, channel_id)

        options = {
            "channel_id": channel_id,
            "message": self.message,
        }
        if attached_file_id:
            options["file_ids"] = [attached_file_id]

        self.mm_client.posts.create_post(options)

    def _format_message(self, message, format_as_code):
        """Adds formatting to the given message.

        :param message: Message for format
        :param format_as_code: Boolen if message should be formatted as code.

        :returns: Formatted message.

        """
        formatted_message = message
        if format_as_code:
            formatted_message = "```\n{}```".format(message)
        formatted_message += "\n⁽ᵐᵉˢˢᵃᵍᵉ ᵇʳᵒᵘᵍʰᵗ ᵗᵒ ʸᵒᵘ ᵇʸ ᵖᵃᵗᵗᵉʳ⁾"
        return formatted_message

    def _get_message_channel_id(self):
        """Get the channel to send the message to.

        :returns: Channel id string.

        """

        if self.channel:
            try:
                return self._get_channel_id_by_name(self.channel)
            except HTTPError:
                raise MissingChannel(
                    "The channel \'{}\' does not exist.".format(
                        self.channel, ))

        if self.user:
            return self._get_channel_id_for_user(self.user)

    def _get_channel_id_by_name(self, channel_name):
        """Use this function to get an ID from a channel name.

        :param channel_name: Name of channel
        :returns: Channel id string.

        """
        channel = self.mm_client.channels.get_channel_by_name_and_team_name(
            team_name=self.team_name,
            channel_name=channel_name,
        )
        return channel["id"]

    def _get_channel_id_for_user(self, user_name):
        """Get the channel id for a direct message with the target user.

        :returns: Channel id string.

        """
        try:
            recipient_user_id = self._get_user_id_by_name(user_name)
        except HTTPError:
            raise MissingUser("The user \'{}\' does not exist.".format(
                user_name, ))
        my_id = self.mm_client.users.get_user("me")["id"]

        # The Mattermost API treats direct messages the same as regular
        # channels so we need to first get a channel ID to send the direct
        # message.
        user_channel = self.mm_client.channels.create_direct_message_channel(
            [recipient_user_id, my_id])
        return user_channel["id"]

    def _get_user_id_by_name(self, user_name):
        """The Mattermost API expects a user ID, not a username.

        Use this function to get an ID from a username.

        :param user_name: Name of user to get user id for.

        :returns: User id string.

        """
        user = self.mm_client.users.get_user_by_username(username=user_name, )
        return user["id"]

    def _check_env_vars(self):
        """Check that all of the required environment variables are set.

        If not, raise exception noting the ones that are missing.

        :raises: MissingEnvVars.
        """
        missing_vars = list(k for k, v in config_vars.items() if v is None)
        if len(missing_vars) > 0:
            error_string = "\n\t".join(missing_vars)
            raise MissingEnvVars(
                "The following environment variables are required but not set:\n\t{}"
                .format(error_string))

    def _attach_file(self, filename, channel_id):
        """Attach the given filename into the given channel.

        :param filename: Name of file to attach.
        :param channel_id: Id string of channel to attach file to.

        :returns; Id string of file attachment.

        """
        response = self.mm_client.files.upload_file(
            channel_id=channel_id, files={"files": (filename, open(filename))})
        try:
            file_id = response["file_infos"][0]["id"]
        except (KeyError, IndexError):
            raise FileUploadException(
                "Unable to upload file '{}'".format(filename))
        return file_id
Exemple #25
0

# on parcoure un set de messages et on les supprime s'ils sont à nous
# ici ce qui est degueu (entre autre) c'est que la ref à myUserID
# est déclarée en dehors de la fonction
def delete_posts(handler, msg_list):
    for msg_id in msg_list:
        msg = foo.posts.get_post(msg_id)
        if (msg['user_id'] == myUserID):
            #         print(msg['message'])
            print("Pouet ==> Pan ==> -=RIP=-")

            foo.posts.delete_post(msg_id)


foo.login()
myuser = foo.users.get_user_by_username(myLogin)
myUserID = myuser['id']
myTeam = foo.teams.get_user_teams(myUserID)
myTeamID = myTeam[0]['id']
myChannelsList = foo.channels.get_channels_for_user(myUserID, myTeamID)
for myChannel in myChannelsList:  #parcours de mes chans
    myChannelID = myChannel['id']
    page = 0
    myChannelMessageLength = 1
    # tant qu'il reste des messages dans le set de msg de la page
    while (myChannelMessageLength != 0):
        # provient de l'API V4, et permet d'accéder
        # à des options supplémentaires
        options = {'page': page, 'per_page': PER_PAGE}
class MattermostBackend(ErrBot):
    def __init__(self, config):
        super().__init__(config)
        identity = config.BOT_IDENTITY
        self._login = identity.get("login", None)
        self._password = identity.get("password", None)
        self._personal_access_token = identity.get("token", None)
        self._mfa_token = identity.get("mfa_token", None)
        self.team = identity.get("team")
        self._scheme = identity.get("scheme", "https")
        self._port = identity.get("port", 8065)
        self.cards_hook = identity.get("cards_hook", None)
        self.url = identity.get("server").rstrip("/")
        self.insecure = identity.get("insecure", False)
        self.timeout = identity.get("timeout", DEFAULT_TIMEOUT)
        self.teamid = ""
        self.token = ""
        self.bot_identifier = None
        self.driver = None
        self.md = md()
        self.event_handlers = {
            "posted": [self._message_event_handler],
            "status_change": [self._status_change_event_handler],
            "hello": [self._hello_event_handler],
            "user_added": [self._room_joined_event_handler],
            "user_removed": [self._room_left_event_handler],
        }

    def set_message_size_limit(self, limit=16377, hard_limit=16383):
        """
        Mattermost message limit is 16383 chars, need to leave some space for
        backticks when messages are split
        """
        super().set_message_size_limit(limit, hard_limit)

    @property
    def userid(self):
        return "{}".format(self.bot_identifier.userid)

    @property
    def mode(self):
        return "mattermost"

    def username_to_userid(self, name):
        """Converts a name prefixed with @ to the userid"""
        name = name.lstrip("@")
        user = self.driver.users.get_user_by_username(username=name)
        if user is None:
            raise UserDoesNotExistError("Cannot find user {}".format(name))
        return user["id"]

    def register_handler(self, event, handler):
        if event not in self.event_handlers:
            self.event_handlers[event] = []
        self.event_handlers[event].append(handler)

    @asyncio.coroutine
    def mattermost_event_handler(self, payload):
        if not payload:
            return

        payload = json.loads(payload)
        if "event" not in payload:
            log.debug("Message contains no event: {}".format(payload))
            return

        event = payload["event"]
        event_handlers = self.event_handlers.get(event)

        if event_handlers is None:
            log.debug(
                "No event handlers available for {}, ignoring.".format(event))
            return
        # noinspection PyBroadException
        for event_handler in event_handlers:
            try:
                event_handler(payload)
            except Exception:
                log.exception(
                    "{} event handler raised an exception".format(event))

    def _room_joined_event_handler(self, message):
        log.debug("User added to channel")
        if message["data"]["user_id"] == self.userid:
            self.callback_room_joined(self)

    def _room_left_event_handler(self, message):
        log.debug("User removed from channel")
        if message["broadcast"]["user_id"] == self.userid:
            self.callback_room_left(self)

    def _message_event_handler(self, message):
        log.debug(message)
        data = message["data"]

        # In some cases (direct messages) team_id is an empty string
        if data["team_id"] != "" and self.teamid != data["team_id"]:
            log.info("Message came from another team ({}), ignoring...".format(
                data["team_id"]))
            return

        broadcast = message["broadcast"]

        if "channel_id" in data:
            channelid = data["channel_id"]
        elif "channel_id" in broadcast:
            channelid = broadcast["channel_id"]
        else:
            log.error("Couldn't find a channelid for event {}".format(message))
            return

        channel_type = data["channel_type"]

        if channel_type != "D":
            channel = data["channel_name"]
        else:
            channel = channelid

        text = ""
        post_id = ""
        file_ids = None
        userid = None

        if "post" in data:
            post = json.loads(data["post"])
            text = post["message"]
            userid = post["user_id"]
            if "file_ids" in post:
                file_ids = post["file_ids"]
            post_id = post["id"]
            if "type" in post and post["type"] == "system_add_remove":
                log.info("Ignoring message from System")
                return

        if "user_id" in data:
            userid = data["user_id"]

        if not userid:
            log.error("No userid in event {}".format(message))
            return

        mentions = []
        if "mentions" in data:
            # TODO: Only user, not channel mentions are in here at the moment
            mentions = self.mentions_build_identifier(
                json.loads(data["mentions"]))

        # Thread root post id
        root_id = post.get("root_id", "")
        if root_id == "":
            root_id = post_id

        msg = Message(
            text,
            extras={
                "id":
                post_id,
                "root_id":
                root_id,
                "mattermost_event":
                message,
                "url":
                "{scheme:s}://{domain:s}:{port:s}/{teamname:s}/pl/{postid:s}".
                format(
                    scheme=self.driver.options["scheme"],
                    domain=self.driver.options["url"],
                    port=str(self.driver.options["port"]),
                    teamname=self.team,
                    postid=post_id,
                ),
            },
        )
        if file_ids:
            msg.extras["attachments"] = file_ids

        # TODO: Slack handles bots here, but I am not sure if bot users is a concept in mattermost
        if channel_type == "D":
            msg.frm = MattermostPerson(self.driver,
                                       userid=userid,
                                       channelid=channelid,
                                       teamid=self.teamid)
            msg.to = MattermostPerson(
                self.driver,
                userid=self.bot_identifier.userid,
                channelid=channelid,
                teamid=self.teamid,
            )
        elif channel_type == "O" or channel_type == "P":
            msg.frm = MattermostRoomOccupant(
                self.driver,
                userid=userid,
                channelid=channelid,
                teamid=self.teamid,
                bot=self,
            )
            msg.to = MattermostRoom(channel, teamid=self.teamid, bot=self)
        else:
            log.warning(
                "Unknown channel type '{}'! Unable to handle {}.".format(
                    channel_type, channel))
            return

        self.callback_message(msg)

        if mentions:
            self.callback_mention(msg, mentions)

    def _status_change_event_handler(self, message):
        """Event handler for the 'presence_change' event"""
        idd = MattermostPerson(self.driver, message["data"]["user_id"])
        status = message["data"]["status"]
        if status == "online":
            status = ONLINE
        elif status == "away":
            status = AWAY
        else:
            log.error(
                "It appears the Mattermost API changed, I received an unknown status type %s"
                % status)
            status = ONLINE
        self.callback_presence(Presence(identifier=idd, status=status))

    def _hello_event_handler(self, message):
        """Event handler for the 'hello' event"""
        self.connect_callback()
        self.callback_presence(
            Presence(identifier=self.bot_identifier, status=ONLINE))

    @lru_cache(1024)
    def get_direct_channel(self, userid, other_user_id):
        """
        Get the direct channel to another user.
        If it does not exist, it will be created.
        """
        try:
            return self.driver.channels.create_direct_message_channel(
                options=[userid, other_user_id])
        except (InvalidOrMissingParameters, NotEnoughPermissions):
            raise RoomDoesNotExistError(
                "Could not find Direct Channel for users with ID {} and {}".
                format(userid, other_user_id))

    def build_identifier(self, txtrep):
        """
        Convert a textual representation into a :class:`~MattermostPerson` or :class:`~MattermostRoom`

        Supports strings with the following formats::

                @username
                ~channelname
                channelid
        """
        txtrep = txtrep.strip()
        if txtrep.startswith("~"):
            # Channel
            channelid = self.channelname_to_channelid(txtrep[1:])
            if channelid is not None:
                return MattermostRoom(channelid=channelid,
                                      teamid=self.teamid,
                                      bot=self)
        else:
            # Assuming either a channelid or a username
            if txtrep.startswith("@"):
                # Username
                userid = self.username_to_userid(txtrep[1:])
            else:
                # Channelid
                userid = txtrep

            if userid is not None:
                return MattermostPerson(
                    self.driver,
                    userid=userid,
                    channelid=self.get_direct_channel(self.userid,
                                                      userid)["id"],
                    teamid=self.teamid,
                )
        raise Exception("Invalid or unsupported Mattermost identifier: %s" %
                        txtrep)

    def mentions_build_identifier(self, mentions):
        identifier = []
        for mention in mentions:
            if mention != self.bot_identifier.userid:
                identifier.append(self.build_identifier(mention))
        return identifier

    def serve_once(self):
        self.driver = Driver({
            "scheme": self._scheme,
            "url": self.url,
            "port": self._port,
            "verify": not self.insecure,
            "timeout": self.timeout,
            "login_id": self._login,
            "password": self._password,
            "token": self._personal_access_token,
            "mfa_token": self._mfa_token,
        })
        self.driver.login()

        self.teamid = self.driver.teams.get_team_by_name(name=self.team)["id"]
        userid = self.driver.users.get_user(user_id="me")["id"]

        self.token = self.driver.client.token

        self.bot_identifier = MattermostPerson(self.driver,
                                               userid=userid,
                                               teamid=self.teamid)

        # noinspection PyBroadException
        try:
            loop = self.driver.init_websocket(
                event_handler=self.mattermost_event_handler)
            self.reset_reconnection_count()
            loop.run_forever()
        except KeyboardInterrupt:
            log.info("Interrupt received, shutting down..")
            return True
        except Exception:
            log.exception("Error reading from RTM stream:")
        finally:
            log.debug("Triggering disconnect callback")
            self.disconnect_callback()

    def _prepare_message(self, message):
        to_name = "<unknown>"
        if message.is_group:
            to_channel_id = message.to.id
            if message.to.name:
                to_name = message.to.name
            else:
                self.channelid_to_channelname(channelid=to_channel_id)
        else:
            to_name = message.to.username

            if isinstance(
                    message.to, RoomOccupant
            ):  # private to a room occupant -> this is a divert to private !
                log.debug(
                    "This is a divert to private message, sending it directly to the user."
                )
                channel = self.get_direct_channel(
                    self.userid, self.username_to_userid(to_name))
                to_channel_id = channel["id"]
            else:
                to_channel_id = message.to.channelid
        return to_name, to_channel_id

    def send_message(self, message):
        super().send_message(message)
        try:
            to_name, to_channel_id = self._prepare_message(message)

            message_type = "direct" if message.is_direct else "channel"
            log.debug("Sending %s message to %s (%s)" %
                      (message_type, to_name, to_channel_id))

            body = self.md.convert(message.body)
            log.debug("Message size: %d" % len(body))

            parts = self.prepare_message_body(body, self.message_size_limit)

            root_id = None
            if message.parent is not None:
                root_id = message.parent.extras.get("root_id")

            for part in parts:
                self.driver.posts.create_post(
                    options={
                        "channel_id": to_channel_id,
                        "message": part,
                        "root_id": root_id,
                    })
        except (InvalidOrMissingParameters, NotEnoughPermissions):
            log.exception(
                "An exception occurred while trying to send the following message "
                "to %s: %s" % (to_name, message.body))

    def send_card(self, card: Card):
        if isinstance(card.to, RoomOccupant):
            card.to = card.to.room

        to_humanreadable, to_channel_id = self._prepare_message(card)

        attachment = {}
        if card.summary:
            attachment["pretext"] = card.summary
        if card.title:
            attachment["title"] = card.title
        if card.link:
            attachment["title_link"] = card.link
        if card.image:
            attachment["image_url"] = card.image
        if card.thumbnail:
            attachment["thumb_url"] = card.thumbnail
        attachment["text"] = card.body

        if card.color:
            attachment["color"] = (COLORS[card.color]
                                   if card.color in COLORS else card.color)

        if card.fields:
            attachment["fields"] = [{
                "title": key,
                "value": value,
                "short": True
            } for key, value in card.fields]

        data = {"attachments": [attachment]}

        if card.to:
            if isinstance(card.to, MattermostRoom):
                data["channel"] = card.to.name

        try:
            log.debug("Sending data:\n%s", data)
            # We need to send a webhook - mattermost has no api endpoint for attachments/cards
            # For this reason, we need to build our own url, since we need /hooks and not /api/v4
            # Todo: Reminder to check if this is still the case
            self.driver.webhooks.call_webhook(self.cards_hook, options=data)
        except (
                InvalidOrMissingParameters,
                NotEnoughPermissions,
                ContentTooLarge,
                FeatureDisabled,
                NoAccessTokenProvided,
        ):
            log.exception(
                "An exception occurred while trying to send a card to %s.[%s]"
                % (to_humanreadable, card))

    def prepare_message_body(self, body, size_limit):
        """
        Returns the parts of a message chunked and ready for sending.
        This is a staticmethod for easier testing.
        Args:
                body (str)
                size_limit (int): chunk the body into sizes capped at this maximum
        Returns:
                [str]
        """
        fixed_format = body.startswith("```")  # hack to fix the formatting
        parts = list(split_string_after(body, size_limit))

        if len(parts) == 1:
            # If we've got an open fixed block, close it out
            if parts[0].count("```") % 2 != 0:
                parts[0] += "\n```\n"
        else:
            for i, part in enumerate(parts):
                starts_with_code = part.startswith("```")

                # If we're continuing a fixed block from the last part
                if fixed_format and not starts_with_code:
                    parts[i] = "```\n" + part

                # If we've got an open fixed block, close it out
                if parts[i].count("```") % 2 != 0:
                    parts[i] += "\n```\n"

        return parts

    def change_presence(self, status: str = ONLINE, message: str = ""):
        pass  # Mattermost does not have a request/websocket event to change the presence

    def is_from_self(self, message: Message):
        return self.bot_identifier.userid == message.frm.userid

    def shutdown(self):
        self.driver.logout()
        super().shutdown()

    def query_room(self, room):
        """Room can either be a name or a channelid"""
        return MattermostRoom(room, teamid=self.teamid, bot=self)

    def prefix_groupchat_reply(self, message: Message, identifier):
        super().prefix_groupchat_reply(message, identifier)
        message.body = "@{0}: {1}".format(identifier.nick, message.body)

    def build_reply(self, message, text=None, private=False, threaded=False):
        response = self.build_message(text)
        response.frm = self.bot_identifier
        if private:
            response.to = message.frm
        else:
            response.to = (message.frm.room if isinstance(
                message.frm, RoomOccupant) else message.frm)

        if threaded:
            response.extras["root_id"] = message.extras.get("root_id")
            self.driver.posts.get_post(message.extras.get("root_id"))
            response.parent = message

        return response

    def get_public_channels(self):
        channels = []
        page = 0
        channel_page_limit = 200
        while True:
            channel_list = self.driver.channels.get_public_channels(
                team_id=self.teamid,
                params={
                    "page": page,
                    "per_page": channel_page_limit
                },
            )
            if len(channel_list) == 0:
                break
            else:
                channels.extend(channel_list)
            page += 1
        return channels

    def channels(self, joined_only=False):
        channels = []
        channels.extend(
            self.driver.channels.get_channels_for_user(user_id=self.userid,
                                                       team_id=self.teamid))
        if not joined_only:
            public_channels = self.get_public_channels()
            for channel in public_channels:
                if channel not in channels:
                    channels.append(channel)
        return channels

    def rooms(self):
        """Return public and private channels, but no direct channels"""
        rooms = self.channels(joined_only=True)
        channels = [channel for channel in rooms if channel["type"] != "D"]
        return [
            MattermostRoom(channelid=channel["id"],
                           teamid=channel["team_id"],
                           bot=self) for channel in channels
        ]

    def channelid_to_channelname(self, channelid):
        """Convert the channelid in the current team to the channel name"""
        channel = self.driver.channels.get_channel(channel_id=channelid)
        if "name" not in channel:
            raise RoomDoesNotExistError(
                "No channel with ID {} exists in team with ID {}".format(
                    id, self.teamid))
        return channel["name"]

    def channelname_to_channelid(self, name):
        """Convert the channelname in the current team to the channel id"""
        channel = self.driver.channels.get_channel_by_name(team_id=self.teamid,
                                                           channel_name=name)
        if "id" not in channel:
            raise RoomDoesNotExistError(
                "No channel with name {} exists in team with ID {}".format(
                    name, self.teamid))
        return channel["id"]

    def __hash__(self):
        return 0  # This is a singleton anyway
Exemple #27
0
class MattermostBackend():
    def __init__(self):
        self.url = 'mattermost.example.com'
        self._login = '******'
        self._scheme = 'https'
        self._port = 443
        self.insecure = False
        self.timeout = DEFAULT_TIMEOUT
        self.teamid = ''
        self.token = ''
        self.driver = None

        # Get password from Gnome keyring, matching the stored Chromium password
        self._password = Secret.password_lookup_sync(
            SECRET_SCHEMA, {
                'username_value': self._login,
                'action_url': 'https://mattermost.example.com/login'
            }, None)

    @asyncio.coroutine
    def mattermost_event_handler(self, payload):
        if not payload:
            return

        payload = json.loads(payload)
        if 'event' not in payload:
            log.debug('Message contains no event: {}'.format(payload))
            return

        event_handlers = {
            'posted': self._message_event_handler,
        }

        event = payload['event']
        event_handler = event_handlers.get(event)

        if event_handler is None:
            log.debug(
                'No event handler available for {}, ignoring.'.format(event))
            return

        try:
            event_handler(payload)
        except Exception:
            log.exception(
                '{} event handler raised an exception. Exiting.'.format(event))
            sys.exit(1)

    def _message_event_handler(self, message):
        log.debug(message)
        data = message['data']

        broadcast = message['broadcast']

        if 'channel_id' in data:
            channelid = data['channel_id']
        elif 'channel_id' in broadcast:
            channelid = broadcast['channel_id']
        else:
            log.error("Couldn't find a channelid for event {}".format(message))
            return

        channel_type = data['channel_type']

        if channel_type != 'D':
            channel = data['channel_name']
            if 'team_id' in data:
                teamid = data['team_id']
                if teamid:
                    team = self.driver.api['teams'].get_team(team_id=teamid)
                    teamname = team['display_name']
        else:
            channel = channelid
            teamname = None

        text = ''
        userid = None

        if 'post' in data:
            post = json.loads(data['post'])
            text = post['message']
            userid = post['user_id']
            if 'type' in post and post['type'] == 'system_add_remove':
                log.info('Ignoring message from System')
                return

        if 'user_id' in data:
            userid = data['user_id']

        if not userid:
            log.error('No userid in event {}'.format(message))
            return

        mentions = []
        if 'mentions' in data:
            mentions = json.loads(data['mentions'])

        if mentions:
            username = self.driver.api['users'].get_user(
                user_id=userid)['username']

            print('mentioned: ', teamname, '"', mentions, '"', username, text)
            if self.userid in mentions:
                if teamname:
                    self.notify(
                        '{} in {}/{}'.format(username, teamname, channel),
                        text)
                else:
                    self.notify('{} in DM'.format(username), text)
            log.info('"posted" event from {}: {}'.format(
                self.driver.api['users'].get_user(user_id=userid)['username'],
                text))

    def notify(self, summary, desc=''):
        self._notification = Notification(summary, desc)

    def serve_once(self):
        self.driver = Driver({
            'scheme': self._scheme,
            'url': self.url,
            'port': self._port,
            'verify': not self.insecure,
            'timeout': self.timeout,
            'login_id': self._login,
            'password': self._password
        })
        self.driver.login()

        self.userid = self.driver.api['users'].get_user(user_id='me')['id']

        self.token = self.driver.client.token

        try:
            loop = self.driver.init_websocket(
                event_handler=self.mattermost_event_handler)
            loop.run_forever()
            # loop.stop()
        except KeyboardInterrupt:
            log.info("Interrupt received, shutting down..")
            Notify.uninit()
            self.driver.logout()
            return True
        except Exception:
            log.exception("Error reading from RTM stream:")
        finally:
            log.debug("Triggering disconnect callback")
from bot import Bot
from mattermostdriver import Driver
import asyncio
import json
import os

driver = Driver({
    'url': os.getenv('MATTERMOST_URL') or 'chat.openshift.io',
    'port': os.getenv('MATTERMOST_PORT') or 443,
    'login_id': os.getenv('MATTERMOST_LOGIN_ID'),
    'password': os.getenv('MATTERMOST_PASSWORD'),
    'debug': False
})

# login to mattermost server
driver.login()
bot = Bot()


class MatterMostOutputChannel(OutputChannel):
    """Interact with the mattemost."""
    @classmethod
    def name(cls):
        """Every channel needs a name to identify it."""
        return "mattermost_output"

    def send_text_message(self, recipient_id, message):
        """Post message to user."""
        driver.posts.create_post({
            'channel_id': recipient_id,
            'message': message
Exemple #29
0
class EmojiReconciler:
    """Maintain state of custom emojis in Mattermost"""
    def __init__(self, emoji_names, user):
        self.user = user
        self.emoji_names = emoji_names
        self.mattermost = None
        self.authenticate()

    def authenticate(self):
        """Authenticate against the Mattermost server"""
        url = urlparse(API_URL)
        settings = {
            "scheme": url.scheme,
            "url": url.hostname,
            "port": url.port,
            "basepath": url.path,
            "login_id": USERS[self.user]["email"],
            "password": USERS[self.user]["password"],
        }

        self.mattermost = Mattermost(settings)
        self.mattermost.login()

    def create(self, name):
        """Create emojis using a specific user"""
        with open(EMOJIS[name], "rb") as image:
            return self.mattermost.emoji.create_custom_emoji(
                name, {"image": image})

    def delete(self, emoji):
        """Delete emojis using a specific user"""
        self.mattermost.emoji.delete_custom_emoji(emoji["id"])

    def get_actual(self):
        """Get list of existing custom emojis on Mattermost"""
        emojis = []
        count, previous_count = 0, 0
        params = {"page": 0, "per_page": 200}
        while True:
            emojis += self.mattermost.emoji.get_emoji_list(params=params)
            count = len(emojis)
            if count - previous_count < 200:
                break
            params["page"] += 1
            previous_count = count
        return emojis

    def get_expected(self):
        """Return list of desired emojis"""
        return self.emoji_names

    def reconcile(self):
        """Make the expected emojis match the actual emojis in Mattermost"""
        actual_emojis = self.get_actual()
        expected_emojis = self.get_expected()
        emojis = []
        for emoji in actual_emojis:
            if emoji["name"] not in expected_emojis:
                self.delete(emoji)
            else:
                emojis.append(emoji)
        for name in expected_emojis:
            if name not in [e["name"] for e in actual_emojis]:
                emojis.append(self.create(name))
        return emojis

    def destroy(self):
        """Destroy all emojis on Mattermost"""
        for emoji in self.get_actual():
            self.delete(emoji)
        return True

    if event == "channel_viewed":
        mark_channel_viewed(cur, conn, channel_id)
    elif event == "posted":
        if isinstance(message["data"]["post"], str):
            message["data"]["post"] = json.loads(message["data"]["post"])
        sender_id = message["data"]["post"]["user_id"]
        if sender_id == user_id:
            mark_channel_viewed(cur, conn, channel_id)
        else:
            mentions = message.get("data", {}).get("mentions", []) or []
            omitted_users = message.get("broadcast", {}).get("omit_users",
                                                             []) or []
            if user_id in mentions and user_id not in omitted_users:
                increment_channel_mention_count(cur, conn, channel_id)
    conn.close()


with open(stdout_loc, "w+") as stdout:

    with open(stderr_loc, "w+") as stderr:

        with daemon.DaemonContext(stdout=stdout, stderr=stderr):

            d = Driver(options=options)

            d.login()

            d.init_websocket(my_event_handler, websocket_cls=CustomWebsocket)