Ejemplo n.º 1
0
    def get_rocket_client(self, bot=False):
        """
        this will return a working ROCKETCHAT_API instance
        """
        if bot:
            if self.bot_user_id and self.bot_user_token:
                rocket = RocketChat(
                    auth_token=self.bot_user_token,
                    user_id=self.bot_user_id,
                    server_url=self.url,
                )
            else:
                rocket = RocketChat(
                    self.bot_user, self.bot_password, server_url=self.url
                )
        else:
            if self.admin_user_id and self.admin_user_token:
                rocket = RocketChat(
                    auth_token=self.admin_user_token,
                    user_id=self.admin_user_id,
                    server_url=self.url,
                )

            else:
                rocket = RocketChat(
                    self.admin_user, self.admin_password, server_url=self.url
                )

        return rocket
Ejemplo n.º 2
0
 def __init__(self, login, password):
     self.login = login
     self.rocket = RocketChat(login,
                              password,
                              server_url='http://178.70.22.151:3000/')
     self.connectMQTT()
     print('Bot initialized')
Ejemplo n.º 3
0
class TestChat(unittest.TestCase):
    def setUp(self):
        self.rocket = RocketChat()
        self.user = '******'
        self.password = '******'
        self.email = '*****@*****.**'
        self.rocket.users_register(email=self.email, name=self.user, password=self.password, username=self.user)
        self.rocket = RocketChat(self.user, self.password)

    def test_chat_post_update_delete_message(self):
        chat_post_message = self.rocket.chat_post_message("hello", channel='GENERAL').json()
        self.assertEqual(chat_post_message.get('channel'), 'GENERAL')
        self.assertEqual(chat_post_message.get('message').get('msg'), 'hello')
        self.assertTrue(chat_post_message.get('success'))

        chat_update = self.rocket.chat_update(room_id=chat_post_message.get('channel'),
                                              msg_id=chat_post_message.get('message').get('_id'),
                                              text='hello again').json()

        self.assertEqual(chat_update.get('message').get('msg'), 'hello again')
        self.assertTrue(chat_update.get('success'))

        chat_delete = self.rocket.chat_delete(room_id=chat_post_message.get('channel'),
                                              msg_id=chat_post_message.get('message').get('_id')).json()
        self.assertTrue(chat_delete.get('success'))
Ejemplo n.º 4
0
 def __init__(self, username="", password="", server_url="", ssl_verify=False):
     self.rocket = RocketChat(
         user=username,
         password=password,
         server_url=server_url,
         ssl_verify=ssl_verify,
     )
Ejemplo n.º 5
0
class Main:
    def __init__(self, chat_server: str):
        self.__rocket = RocketChat(settings.ROCKET_USERNAME,
                                   settings.ROCKET_PASSWORD,
                                   server_url=settings.ROCKET_URL)
        self.__connection = sqlite3.connect(settings.DB_PATH)
        self.__cursor = self.__connection.cursor()
        self.__db_api = DBApi(self.__connection, self.__cursor)
        self.__reader = RocketChatReader(chat_server, self.__get_channels())

    def start(self) -> None:
        self.__reader.connect()
        while True:
            request: Message = self.__reader.get_messages_queue().get()
            try:
                message = request.get_message().split(" ")
                if message[0] == "$bot_api":
                    message = [msg for msg in message if msg != ""]
                    response = self.__db_api.process(message)
                    self.__rocket.chat_post_message(
                        response,
                        room_id=request.get_channel_id(),
                        alias='BOT NOTIFICATION')
            except:
                self.__rocket.chat_post_message(
                    "Oops. Server error.",
                    room_id=request.get_channel_id(),
                    alias='BOT NOTIFICATION')

    def __get_channels(self) -> list:
        self.__cursor.execute("""SELECT name FROM channel""")
        return [channel[0] for channel in self.__cursor.fetchall()]
Ejemplo n.º 6
0
class TestPermissions(unittest.TestCase):
    def setUp(self):
        self.rocket = RocketChat()
        self.user = '******'
        self.password = '******'
        self.email = '*****@*****.**'
        self.rocket.users_register(email=self.email,
                                   name=self.user,
                                   password=self.password,
                                   username=self.user)
        self.rocket = RocketChat(self.user, self.password)

    def tearDown(self):
        pass

    def test_permissions_list_all(self):
        permissions_list_all = self.rocket.permissions_list_all().json()
        self.assertTrue(permissions_list_all.get('success'))
        self.assertIn('update', permissions_list_all)
        self.assertIn('remove', permissions_list_all)

    def test_permissions_list_all_with_updatedSince(self):
        permissions_list_all = self.rocket.permissions_list_all(
            updatedSince='2017-11-25T15:08:17.248Z').json()
        self.assertTrue(permissions_list_all.get('success'))
        self.assertIn('update', permissions_list_all)
        self.assertIn('remove', permissions_list_all)
Ejemplo n.º 7
0
 def setUp(self):
     self.rocket = RocketChat()
     self.user = '******'
     self.password = '******'
     self.email = '*****@*****.**'
     self.rocket.users_register(email=self.email, name=self.user, password=self.password, username=self.user)
     self.rocket = RocketChat(self.user, self.password)
Ejemplo n.º 8
0
class TestRooms(unittest.TestCase):
    def setUp(self):
        self.rocket = RocketChat()
        self.user = '******'
        self.password = '******'
        self.email = '*****@*****.**'
        self.rocket.users_register(email=self.email,
                                   name=self.user,
                                   password=self.password,
                                   username=self.user)
        self.rocket = RocketChat(self.user, self.password)

    def tearDown(self):
        pass

    def test_rooms_upload(self):
        # ToDo: Find a better way to test that this endpoint actually works fine (when using json and not data fails
        # silently)
        rooms_upload = self.rocket.rooms_upload(
            'GENERAL', file='tests/avatar.png',
            description='hey there').json()
        self.assertTrue(rooms_upload.get('success'))

    def test_rooms_get(self):
        rooms_get = self.rocket.rooms_get().json()
        self.assertTrue(rooms_get.get('success'))
Ejemplo n.º 9
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--server", required=True, type=str)
    parser.add_argument("--user", default="", type=str)
    parser.add_argument("--password", default="", type=str)
    parser.add_argument("--pass_file", default="", type=str)
    parser.add_argument("--emojipack", default="", type=str)

    args = parser.parse_args()

    username = input("Username: "******"Password: "******"Logging in...")
    rocket = RocketChat(username, password, server_url=args.server)

    authenticated_user = rocket.me().json()
    print("Authenticated as '{}'".format(authenticated_user["name"]))

    if args.emojipack:
        try:
            emojis = yaml.safe_load(get_file_or_url(args.emojipack))["emojis"]
        except:
            print("Could not load emoji pack: {}".format(args.emojipack))
            return
        do_create_all(emojis)
Ejemplo n.º 10
0
    def __init__(self,
                 addr,
                 username,
                 password,
                 create_test_user=True,
                 **kwargs):
        SplinterTestCase.__init__(self, addr, **kwargs)

        self.rocket = RocketChat(username, password, server_url=addr)

        self.schedule_pre_test_case('login')
        self.schedule_pre_test_case('test_check_version')

        if create_test_user:
            self.schedule_pre_test_case('create_user')

        self.username = username
        self.password = password
        self._rc_version = '0.70'

        self.test_username = '******'
        self.test_full_name = 'No Name'
        self.test_email = '*****@*****.**'
        self.test_password = '******'

        if create_test_user:
            self.schedule_test_case('remove_user')
Ejemplo n.º 11
0
class TestSettings(unittest.TestCase):
    def setUp(self):
        self.rocket = RocketChat()
        self.user = '******'
        self.password = '******'
        self.email = '*****@*****.**'
        self.rocket.users_register(email=self.email,
                                   name=self.user,
                                   password=self.password,
                                   username=self.user)
        self.rocket = RocketChat(self.user, self.password)

    def tearDown(self):
        pass

    def test_settings(self):
        settings = self.rocket.settings().json()
        self.assertTrue(settings.get('success'))
        settings_get = self.rocket.settings_get(
            _id='API_Allow_Infinite_Count').json()
        self.assertTrue(settings_get.get('success'))
        self.assertTrue(settings_get.get('value'))
        settings_update = self.rocket.settings_update(
            _id='API_Allow_Infinite_Count', value=True).json()
        self.assertTrue(settings_update.get('success'))
def main():
    args = parse_arguments()
    config = yaml.load(open(args.config))

    with sessions.Session() as session:
        rocket = RocketChat(
            user_id=config["user_id"],
            auth_token=config["auth_token"],
            server_url=config["server"],
            session=session,
        )

        channel_dump = pd.read_csv(args.channel_dump)

        with open(args.input) as f:
            destination_channels = [channel.strip() for channel in f]
            destination_channels = [
                channel for channel in destination_channels if channel != ""
            ]

        nonexistent_channels = set(destination_channels) - set(
            channel_dump["name"])
        assert len(
            nonexistent_channels
        ) == 0, "Some channels not found: " + str(nonexistent_channels)

        channel_ids = channel_dump[channel_dump["name"].isin(
            destination_channels)]["_id"]

        for channel_name, channel in zip(destination_channels, channel_ids):
            if not args.test:
                rocket.channels_add_all(channel)
            print('Added all users to channel "{}"'.format(channel_name))
Ejemplo n.º 13
0
    def test_create_necessary_rooms(self):
        groups = ['hr', 'leave-coordination']

        rocket = RocketChat(self.username, self.password, server_url=self.addr)

        for name in groups:
            rocket.groups_create(name, members=['meeseeks'])
Ejemplo n.º 14
0
def find_articles(
        rss_url,
        rc_url,
        rc_user,
        rc_password,
        rc_channel,
        rc_alias='yagizo',
        rc_icon=':new:',
        database='./feed.db',
        enable_post=True
        ):
    con = sqlite3.connect(database)
    cur = con.cursor()
    cur.execute('CREATE TABLE IF NOT EXISTS entries (published, link, tiltle)')

    rocket = RocketChat(rc_user, rc_password, server_url=rc_url)

    feeds = feedparser.parse(rss_url)
    for entry in feeds.entries:
        d = parse(entry.published).astimezone(timezone('Asia/Tokyo'))
        cur.execute('SELECT count(*) FROM entries WHERE link = ?', (entry.link, ))
        cnt = cur.fetchone()[0]
        if cnt == 0:
            print('[{}]{} ({})'.format(d.strftime("%Y/%m/%d"), entry.title, entry.link))
            cur.execute('INSERT INTO entries VALUES (?, ?, ?)', (d, entry.link, entry.title,))
            msg = '*{}* {}\n{}'.format(d.strftime("%Y/%m/%d"), entry.title, entry.link)
            if enable_post:
                rocket.chat_post_message(msg, channel=rc_channel, alias=rc_alias, emoji=rc_icon)

    con.commit()
    con.close()
Ejemplo n.º 15
0
class TestSubscriptions(unittest.TestCase):
    def setUp(self):
        self.rocket = RocketChat()
        self.user = '******'
        self.password = '******'
        self.email = '*****@*****.**'
        self.rocket.users_register(email=self.email,
                                   name=self.user,
                                   password=self.password,
                                   username=self.user)
        self.rocket = RocketChat(self.user, self.password)

    def tearDown(self):
        pass

    def test_subscriptions_get(self):
        subscriptions_get = self.rocket.subscriptions_get().json()
        self.assertTrue(subscriptions_get.get('success'))
        self.assertIn('update', subscriptions_get)

    def test_subscriptions_get_one(self):
        subscriptions_get_one = self.rocket.subscriptions_get_one(
            room_id='GENERAL').json()
        self.assertTrue(subscriptions_get_one.get('success'))
        self.assertIn('subscription', subscriptions_get_one)

    def test_subscriptions_unread(self):
        subscriptions_unread = self.rocket.subscriptions_unread(
            room_id='GENERAL').json()
        self.assertTrue(subscriptions_unread.get('success'),
                        'Call did not succeed')
def main():
    args = parse_arguments()
    config = yaml.load(open(args.config), Loader=yaml.SafeLoader)

    with sessions.Session() as session:
        rocket = RocketChat(
            user_id=config["user_id"],
            auth_token=config["auth_token"],
            server_url=config["server"],
            session=session,
        )
        channels_params = get_params(args.filter_featured, args.regexp)

        count = 50  # number of channels per page (default 50)
        channels_list: List[Dict] = []
        channels_json = rocket.channels_list(count=count, **channels_params).json()
        channels_list.extend(channels_json["channels"])

        total = channels_json["total"]
        print(f"Found {total} channels")

        for offset in tqdm(range(count, total, count)):
            channels_json = rocket.channels_list(
                offset=offset, count=count, **channels_params
            ).json()
            channels_list.extend(channels_json["channels"])

        channels_df = postprocess(pd.DataFrame(channels_list))

        if args.add_owners:
            print("Adding owners")
            channels_df = add_owners(channels_df, rocket)
        channels_df.to_csv(args.output_file, index=False)
Ejemplo n.º 17
0
    def send(start, stop):
        """send expiring access chat remninders."""
        if current_app.config['ROCKET_ENABLED'] != 1:
            print("rocket sending is disabled %s" %
                  current_app.config['ROCKET_ENABLED'])
            return

        print("start: %s stop: %s" % (start, stop))

        access = Access.query.filter(
            func.datetime(Access.stop) > start,
            func.datetime(Access.stop) < stop).all()

        rocket = RocketChat(current_app.config['ROCKET_USER'],
                            current_app.config['ROCKET_PASS'],
                            server_url=current_app.config['ROCKET_URL'])

        for a in access:
            stopdate = a.stop.strftime("%Y-%m-%d")
            msg = f'''Access for: @{a.user.username} \
                    to: {a.role.name} \
                    expires at: {stopdate} \
                    mgr: @{a.role.service.manager.username} \
                    please act on this as needed'''

            pprint(
                rocket.chat_post_message(
                    msg, channel=current_app.config['ROCKET_CHANNEL']).json())
            time.sleep(1)
def rocketchat_send_message(test_result, config, exitstatus):
    timeout = config.option.rocket_timeout
    report_link = config.option.rocket_report_link
    rocket_domain = config.option.rocket_domain
    channel = config.option.rocket_channel
    ssl_verify = config.option.ssl_verify
    message_prefix = config.option.rocket_message_prefix
    rocket_username = (
        config.option.rocket_username
        if config.option.rocket_username
        else "Regression testing results"
    )
    rocket_pass = config.option.rocket_password
    if int(exitstatus) == 0:
        color = "#56a64f"
        emoji = config.option.rocket_success_emoji
    else:
        color = "#ff0000"
        emoji = config.option.rocket_failed_emoji
    final_results = "Passed=%s Failed=%s Skipped=%s Error=%s XFailed=%s XPassed=%s" % (
        test_result.passed,
        test_result.failed,
        test_result.skipped,
        test_result.error,
        test_result.xfailed,
        test_result.xpassed,
    )
    if report_link:
        final_results = "<%s|%s>" % (report_link, final_results)
    if message_prefix:
        final_results = "%s: %s" % (message_prefix, final_results)

    # # uncomment after fix 3.11.1 rocket issue
    # # https://github.com/RocketChat/Rocket.Chat/issues/20556
    #
    # results_pattern = {
    #     "color": color,
    #     "text": final_results,
    #     "mrkdwn_in": [
    #         "text",
    #         "pretext",
    #     ]
    # }

    rocket_client = RocketChat(
        user=rocket_username,
        password=rocket_pass,
        server_url=rocket_domain,
        ssl_verify=ssl_verify,
    )

    rocket_client.chat_post_message(
        # attachments=[results_pattern],  # uncomment after fix3.11.1 rocket
        channel=channel,
        alias=rocket_username,
        emoji=emoji,
        text=final_results,
        timeout=timeout,
    )
Ejemplo n.º 19
0
def create_session(user=None, password=None, server_url=None):
    global rocket_api_session

    if not rocket_api_session:
        rocket_api_session = RocketChat(user, password, server_url)

    pprint(rocket_api_session.me().json())
    return rocket_api_session
Ejemplo n.º 20
0
 def __init__(self):
     """A RocketChat channel"""
     self.user = os.environ.get("ROCKETCHAT_USER")
     self.password = os.environ.get("ROCKETCHAT_PASS")
     self.url = os.environ.get("ROCKETCHAT_URL")
     self.service = RocketChat(self.user, self.password, server_url=self.url)
     self.channel = os.environ.get("ROCKETCHAT_CHANNEL", "hatchbuck")
     self.alias = os.environ.get("ROCKETCHAT_ALIAS", "carddav2hatchbuck")
Ejemplo n.º 21
0
 def __init__(self, chat_server: str):
     self.__rocket = RocketChat(settings.ROCKET_USERNAME,
                                settings.ROCKET_PASSWORD,
                                server_url=settings.ROCKET_URL)
     self.__connection = sqlite3.connect(settings.DB_PATH)
     self.__cursor = self.__connection.cursor()
     self.__db_api = DBApi(self.__connection, self.__cursor)
     self.__reader = RocketChatReader(chat_server, self.__get_channels())
Ejemplo n.º 22
0
 def loginUser(self, user_name, user_pass):
     rocket = RocketChat('Admin', 'chat.service', server_url=self.chat_ip_port, proxies=None)
     print(user_name + " " + user_pass)
     data = rocket.login(user_name, user_pass).json()
     status = data["status"]
     authToken = data["data"]["authToken"]
     print(status + " " + authToken)
     return (status, authToken)
Ejemplo n.º 23
0
 def __init__(self, botname, passwd, server):
     self.botname = botname
     self.api = RocketChat(botname, passwd, server, ssl_verify=True)
     self.commands = [(['echo', ], self.echo), (['ping', ], self.ping)]
     self.auto_answers = []
     self.direct_answers = []
     self.unknow_command = ['command not found', ]
     self.lastts = {}
Ejemplo n.º 24
0
 def setUp(self):
     self.rocket = RocketChat()
     self.user = '******'
     self.password = '******'
     self.email = '*****@*****.**'
     self.rocket.users_register(email=self.email, name=self.user, password=self.password, username=self.user)
     self.rocket.channels_add_owner('GENERAL', username=self.user)
     self.rocket = RocketChat(self.user, self.password)
     self.testuser = self.rocket.users_create('*****@*****.**', 'user0', 'password', 'user0').json()
Ejemplo n.º 25
0
 def __init__(self, channel_names: List[str]):
     threading.Thread.__init__(self, daemon=True)
     self.__rocket = RocketChat(settings.ROCKET_USERNAME,
                                settings.ROCKET_PASSWORD,
                                server_url=settings.ROCKET_URL)
     self.__ws = websocket.WebSocket()
     self.__messages_queue = queue.Queue()
     self.__channel_ids = list()
     self.__get_channel_ids(channel_names)
Ejemplo n.º 26
0
 def setUp(self):
     self.rocket = RocketChat()
     self.user = '******'
     self.password = '******'
     self.email = '*****@*****.**'
     self.rocket.users_register(email=self.email, name=self.user, password=self.password, username=self.user)
     self.rocket = RocketChat(self.user, self.password)
     self.testuser = self.rocket.users_create('*****@*****.**', 'user0', 'password', 'user0').json()
     self.test_group_id = self.rocket.groups_create(str(uuid.uuid1())).json().get('group').get('_id')
Ejemplo n.º 27
0
def user_api_rocket_chat(auth_token, user_id):
    """
    Returns an ApirocketChat instance using the given auth_token and user_id
    """
    url_service = get_rocket_chat_settings().get('private_url_service', None)
    user_api_rocket_chat = ApiRocketChat(server_url=url_service)  # pylint: disable=redefined-outer-name
    user_api_rocket_chat.headers['X-Auth-Token'] = auth_token
    user_api_rocket_chat.headers['X-User-Id'] = user_id
    return user_api_rocket_chat
Ejemplo n.º 28
0
 def getUserInfo(self, userID, user_name):
     rocket = RocketChat('Admin', 'chat.service', server_url='http://www.chat.service', proxies=None)
     data = rocket.users_info(userID, user_name).json()
     status = data["success"]
     uId = data['user']['_id']
     email = data['user']['emails'][0]['address']
     userName = data['user']['name']
     userNick = data['user']['username']
     return (status, uId, email, userName, userNick)
Ejemplo n.º 29
0
 def __init__(self, botname, passwd, server, command_character=None):
     self.botname = botname
     self.api = RocketChat(user=botname, password=passwd, server_url=server)
     self.commands = [(['echo', ], self.echo)]
     self.auto_answers = []
     self.direct_answers = []
     self.unknow_command = ['command not found', ]
     self.lastts = {}
     self.command_character = command_character
Ejemplo n.º 30
0
 def registerUser(self, param):
     email = param['email']
     username = param['username']
     password = param['password']
     rocket = RocketChat('Admin', 'chat.service', server_url=self.chat_ip_port, proxies=None)
     data = rocket.users_register(email, username, password, username).json()
     status = data['success']
     uId = data['user']['_id']
     return (status, uId)
Ejemplo n.º 31
0
class RocketChatBot(OutputChannel):
    @classmethod
    def name(cls):
        return "rocketchat"

    def __init__(self, user, password, server_url):
        from rocketchat_API.rocketchat import RocketChat

        self.rocket = RocketChat(user, password, server_url=server_url)

    def send_text_message(self, recipient_id, message):
        """Messages handler."""

        for message_part in message.split("\n\n"):
            self.rocket.chat_post_message(message_part,
                                          roomId=recipient_id)

    def send_image_url(self, recipient_id, image_url):
        image_attachment = [{
            "image_url": image_url,
            "collapsed": False,
        }]

        return self.rocket.chat_post_message(None,
                                             roomId=recipient_id,
                                             attachments=image_attachment)

    def send_attachment(self, recipient_id, attachment, message=""):
        return self.rocket.chat_post_message(None,
                                             roomId=recipient_id,
                                             attachments=[attachment])

    @staticmethod
    def _convert_to_rocket_buttons(buttons):
        return [{"text": b['title'],
                 "msg": b['payload'],
                 "type": "button",
                 "msg_in_chat_window": True}
                for b in buttons]

    def send_text_with_buttons(self, recipient_id, message, buttons, **kwargs):
        # implementation is based on
        # https://github.com/RocketChat/Rocket.Chat/pull/11473
        # should work in rocket chat >= 0.69.0
        button_attachment = [
            {"actions": self._convert_to_rocket_buttons(buttons)}]

        return self.rocket.chat_post_message(message,
                                             roomId=recipient_id,
                                             attachments=button_attachment)
Ejemplo n.º 32
0
class RocketChatNotificationService(BaseNotificationService):
    """Implement the notification service for Rocket.Chat."""

    def __init__(self, url, username, password, room):
        """Initialize the service."""
        from rocketchat_API.rocketchat import RocketChat
        self._room = room
        self._server = RocketChat(username, password, server_url=url)

    def send_message(self, message="", **kwargs):
        """Send a message to Rocket.Chat."""
        data = kwargs.get(ATTR_DATA) or {}
        resp = self._server.chat_post_message(
            message, channel=self._room, **data)
        if resp.status_code == 200:
            success = resp.json()["success"]
            if not success:
                _LOGGER.error("Unable to post Rocket.Chat message")
        else:
            _LOGGER.error("Incorrect status code when posting message: %d",
                          resp.status_code)
Ejemplo n.º 33
0
 def __init__(self, url, username, password, room):
     """Initialize the service."""
     from rocketchat_API.rocketchat import RocketChat
     self._room = room
     self._server = RocketChat(username, password, server_url=url)
Ejemplo n.º 34
0
    def __init__(self, user, password, server_url):
        from rocketchat_API.rocketchat import RocketChat

        self.rocket = RocketChat(user, password, server_url=server_url)