Ejemplo n.º 1
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.º 2
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.º 3
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.º 4
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.º 5
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)
     user2_exists = self.rocket.users_info(
         username='******').json().get('success')
     if user2_exists:
         user_id = self.rocket.users_info(
             username='******').json().get('user').get('_id')
         self.rocket.users_delete(user_id)
Ejemplo n.º 6
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)
     # Register DM recipient
     self.recipient_user = '******'
     self.recipient_password = '******'
     self.recipient_email = '*****@*****.**'
     self.rocket.users_register(
         email=self.recipient_email, name=self.recipient_user,
         password=self.recipient_password, username=self.recipient_user)
     self.rocket = RocketChat(self.user, self.password)
Ejemplo n.º 7
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.º 8
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)
Ejemplo n.º 9
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')
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.º 11
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.º 12
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.º 13
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)
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.º 15
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'])
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,
        )

        fields = get_rocketchat_fields(args)

        fields_string = json.dumps(fields)

        print(fields_string)
        users = get_all_users(rocket, fields_string)

        if args.add_roles:
            add_roles(users, rocket)

        df = pd.DataFrame(users)

        if "emails" in df:
            df["email"] = df["emails"].apply(join_emails)
        if "email" not in df and not args.no_email:
            print("WARN: emails not retrieved; do you have permission?")
        if "lastLogin" not in df and not args.no_lastlogin:
            print("WARN: last login not retrieved; do you have permission?")

        df.to_csv("rocketchat-user-details.csv", index=False)
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.º 18
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.º 19
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.º 20
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.º 21
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.º 22
0
 def __new__(cls, *args, **kwargs):
     if cls._instance is None:
         cls.rocket = RocketChat(
             user_id=os.environ['ROCKET_CHAT_USER_ID'],
             auth_token=os.environ['ROCKET_CHAT_AUTH_TOKEN'],
             server_url=ROCKET_CHAT_URL)
         cls._instance = object.__new__(cls)
     return cls._instance
Ejemplo n.º 23
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)
def connect_rocket_API(config, session):
    rocket = RocketChat(
        user_id=config["user_id"],
        auth_token=config["auth_token"],
        server_url=config["server"],
        session=session,
    )
    return rocket
Ejemplo n.º 25
0
def create_user():
    user = type('test', (object,), {})()
    user.name = "rocket"
    user.password = "******"
    user.email = "*****@*****.**"

    RocketChat().users_register(
        email=user.email,
        name=user.name,
        password=user.password,
        username=user.name
    )
    rocket_chat = RocketChat(user_id=user.name, password=user.password)
    login = rocket_chat.login(user.name, user.password).json()
    response = rocket_chat.users_create_token(user_id=login.get("data").get("userId"))
    os.environ['ROCKET_CHAT_AUTH_TOKEN'] = response.json()['data']['authToken']
    os.environ['ROCKET_CHAT_USER_ID'] = response.json()['data']['userId']
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.channels_add_owner('GENERAL', username=self.user)
        self.rocket = RocketChat(self.user, self.password)

        testuser = self.rocket.users_info(username='******').json()
        if not testuser.get('success'):
            testuser = self.rocket.users_create(
                '*****@*****.**', 'testuser1', 'password', 'testuser1').json()
            if not testuser.get('success'):
                self.fail("can't create test user")

        self.testuser_id = testuser.get('user').get('_id')
Ejemplo n.º 27
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.º 28
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.º 29
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.º 30
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