Ejemplo n.º 1
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.º 2
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()]
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.º 4
0
class ChatManager(object):
    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,
        )

    def create_user(self, user, password):
        # Create the user's account on RocketChat
        if not self.rocket:
            return
        account = self.rocket.users_create(user.email, user.name, password,
                                           user.handle.replace(" ",
                                                               "_")).json()
        self.create_team(user.team, account)

    def create_team(self, team, account):
        # Create a private team group
        if options.teams:
            group = self.has_group(team)
            if not group:
                groups = self.rocket.groups_create(
                    team.name.replace(" ", "_").lower()).json()
                group = groups["group"]
            self.rocket.groups_invite(group["_id"], account["user"]["_id"])

    def has_group(self, team):
        if not team:
            return False
        privaterooms = self.rocket.groups_list().json()
        if "groups" in privaterooms:
            for group in privaterooms["groups"]:
                if group["name"] == team.name.replace(" ", "_").lower():
                    return group
        return False

    def post_message(self, message, channel=None):
        # Send a global message
        if not channel:
            default_channel = self.get_default_channel()
            if default_channel:
                channel = "#%s" % default_channel
        if channel:
            self.rocket.chat_post_message(channel=channel, text=message)

    def get_default_channel(self):
        # Get the default channel
        channels = self.rocket.channels_list().json()
        if "channels" in channels:
            for channel in channels["channels"]:
                if channel["default"]:
                    return channel["name"]
        return None
Ejemplo n.º 5
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.º 6
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.º 7
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.º 8
0
class TestIMs(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)
        # 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)

    def tearDown(self):
        pass

    def test_im_create(self):
        im_create = self.rocket.im_create(self.recipient_user).json()
        self.assertTrue(im_create.get('success'))

    def test_im_send(self):
        im_create = self.rocket.im_create(self.recipient_user).json()
        room_id = im_create.get('room').get('_id')
        im_send = self.rocket.chat_post_message(room_id=room_id,
                                                text='test').json()
        self.assertTrue(im_send.get('success'))
Ejemplo n.º 9
0
def home(request):
    rocket = RocketChat(settings.ROCKET_USERNAME,
                        settings.ROCKET_PASSWORD,
                        server_url=settings.SERVER_URL,
                        proxies=settings.PROXY_DICT)  # Login the system

    channels = []  # To record channels' info
    channel_list = rocket.channels_list().json()["channels"]
    for channel in channel_list:
        channels.append(
            (channel["name"], rocket.channels_history(
                room_id=channel["_id"]).json()["messages"][::-1]))

    messages_list = rocket.im_list().json()["ims"]
    messages_list = [i for i in messages_list if i["msgs"] > 0]
    message_contents = []
    for message in messages_list:
        message_contents.append(
            (message["usernames"][1], rocket.im_history(
                room_id=message["_id"]).json()["messages"][::-1]))

    me = rocket.me().json()  # Information about me like name, username, avatar

    context = {
        "messages_list": messages_list,
        "message_contents": message_contents,
        "channel_list": channel_list,
        "me": me,
        'channels': channels,
    }

    message = request.GET.get('message')  # receiving messages in the channels
    channel = request.GET.get("channel")
    if message and channel:
        rocket.chat_post_message(message, channel=channel)
        return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

    direct_message = request.GET.get(
        'direct')  # receiving messages in the direct chatting
    username = request.GET.get("username")
    if direct_message and username:
        print("burası çalıştı mı")
        rocket.chat_post_message(direct_message, channel=username)
        return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

    return render(request, 'home.html', context)
Ejemplo n.º 10
0
    def handle(self, *args, **kwargs):
        rocket = RocketChat(settings.ROCKET_USERNAME, settings.ROCKET_PASSWORD, server_url=settings.SERVER_URL, proxies=settings.PROXY_DICT)
        channel_names = ["random", "lessons", "python", "django", "react"]
        user_infos = [
            ("*****@*****.**", "Tom Rock", "Aa123456", "tom"), 
            ("*****@*****.**", "Harry Rock", "Aa123456", "harry"), 
            ("*****@*****.**", "Angelina Rock", "Aa123456", "angelina"), 
            ("*****@*****.**", "Jerry Rock", "Aa123456", "jerry"), 
            ]

        for channel in channel_names:
            rocket.channels_create(name = channel)
            rocket.chat_post_message("Hello World!", channel= channel)
        
        for user in user_infos:
            rocket.users_create(email= user[0], name = user[1], password = user[2], username = user[3])

        self.stdout.write(self.style.SUCCESS('5 channels, 5 messages and four users were created with success!'))
Ejemplo n.º 11
0
def post_rocketchat_message(config_file, msg):

    # get config from file
    r_cfg = get_config(config_file)

    # Authentification
    rocket = RocketChat(r_cfg['username'], r_cfg['password'], server_url=r_cfg['server_url'])

    # post message
    r = rocket.chat_post_message(msg, channel=r_cfg['channel'])
def post_rocketchat_message(config_file, msg):

    # get config from file
    r_cfg = get_config(config_file)

    # Authentification
    rocket = RocketChat(r_cfg['username'], r_cfg['password'], server_url=r_cfg['server_url'])

    # post message
    r = rocket.chat_post_message(msg, channel=r_cfg['channel'])
    logging.info("response status code: %s" % r.status_code)
Ejemplo n.º 13
0
def check_merged_requests_for_upvotes(channels_name: str, projects: dict):
    rocket = RocketChat(settings.ROCKET_USERNAME, settings.ROCKET_PASSWORD, server_url=settings.ROCKET_URL)
    request_params = {"private_token": settings.GITLAB_TOKEN, "state": "merged",
                      "created_after": datetime.date.today() - datetime.timedelta(days=1)}

    for project_id, approvers_number in projects.items():
        url = f"{settings.GITLAB_URL}projects/{project_id}/merge_requests"
        merge_requests = requests.get(url, params=request_params).json()

        channel_message = f"Unapproved MRs:\n"

        flag = False

        for merge_request in merge_requests:
            if merge_request.get('upvotes') < approvers_number:
                flag = True
                channel_message += merge_request.get('web_url') + '\n'

        if flag:
            rocket.chat_post_message(channel_message, channel=channels_name, alias='BOT NOTIFICATION')
        else:
            continue
Ejemplo n.º 14
0
class NotificationService:
    """
    An alerting service for unresolvable import or merge issues.
    """

    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")

    def send_message(self, message):
        """Send a message to the RocketChat channel"""
        response = self.service.chat_post_message(
            message, channel=self.channel, alias=self.alias
        )
        logging.debug(response.json())
Ejemplo n.º 15
0
class RocketChatNotificationService(BaseNotificationService):
    """Implement the notification service for Rocket.Chat."""
    def __init__(self, url, username, password, room):
        """Initialize the service."""

        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 == HTTPStatus.OK:
            if not resp.json()["success"]:
                _LOGGER.error("Unable to post Rocket.Chat message")
        else:
            _LOGGER.error("Incorrect status code when posting message: %d",
                          resp.status_code)
Ejemplo n.º 16
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.º 17
0
    elif "Mostly cloudy" in message:
        icon = ":white_sun_cloud: "
    elif "Mostly clear" in message:
        icon = ":white_sun_cloud:"
    elif "thunderstorms" in message:
        icon = ":cloud_lightning:"
    elif "showers" in message:
        icon = ":cloud_rain:"
    else:
        icon = ":sunny:"
    # Add the thunderstorm cloud to the message as well
    if "thunderstorms" in message:
        message = message + " " + ":cloud_lightning:"
    # Set the argument for the name to send rocket chat message or not
    if argument == "morning":
        timerun = ["Today", "Tonight"]
    elif argument == "afternoon":
        timerun = ["Tonight", "This Afternoon"]
    elif argument == "tonight":
        timerun = ["Tonight"]
    else:
        timerun = ""
    if name in timerun:
        # Send Rocket.chat Message.
        rocket.chat_post_message(message,
                                 channel='GENERAL',
                                 alias='%s' % name,
                                 emoji='%s' % icon).json()
    count = count + 1
sys.exit()
Ejemplo n.º 18
0
class RocketComm:
    rocket = None

    def __init__(self, config):
        self.user = config['user']
        self.password = config['pass']
        self.URL = config['type'] + '://' + config['host']

    def login(self):
        self.rocket = RocketChat(self.user, self.password, self.URL)

    def logout(self):
        self.rocket.logout()

    def _retrieve_msgs(self, settings, since=None):
        if since is None:
            hist = self.rocket.channels_history(settings['channel'],
                                                count=10000).json()
            msgs = hist['messages']
        else:
            old = dt.strftime(since, settings["parseDate"])
            hist = self.rocket.channels_history(settings['channel'],
                                                count=10000,
                                                oldest=old).json()
            msgs = hist['messages']

        return msgs

    def _retrieve_userlist(self):
        count = 0
        users = []

        stop = False
        while not stop:
            req = self.rocket.users_list(count=50, offset=count).json()
            count += 50
            stop = count > req['total']
            users.extend(req['users'])

        return users

    def get_name_from_id(self, id):
        users = self._retrieve_userlist()
        for user in users:
            if user['_id'] == _id:
                if 'username' in user:
                    return user['username']
                elif 'name' in user:
                    return user['name']
                else:
                    return user['_id']

        return ""

    def get_id_from_name(self, username):
        users = self._retrieve_userlist()
        for user in users:
            if 'username' in user:
                _username = user['username']
            elif 'name' in user:
                _username = user['name']
            else:
                _username = user['_id']

            if _username == username:
                return user['_id']
        return ""

    def get_active_users(self, settings, since, pic=False):
        users = []

        msgs = self._retrieve_msgs(settings, since)
        for msg in msgs:
            if not pic or (("attachments" in msg) and
                           (msg["attachments"] is not None) and
                           (len(msg["attachments"]) > 0) and
                           ("image_url" in msg["attachments"][0])):
                user = msg["u"]["username"]
                if user not in users:
                    users.append(user)

        return users

    def get_image_list(self, settings, since):
        imgs = []

        msgs = self._retrieve_msgs(settings, since)
        for msg in msgs:
            if (("attachments" in msg) and (msg["attachments"] is not None)
                    and (len(msg["attachments"]) > 0)
                    and ("image_url" in msg["attachments"][0])):
                user = msg["u"]["username"]
                url = msg["attachments"][0]["image_url"]
                date = dt.strptime(msg["ts"], settings["parseDate"])

                imgs.append(dict(user=user, url=url, date=date))

        return imgs

    def check_special_string(self, settings, since, string, name=""):
        dates = []

        msgs = self._retrieve_msgs(settings, since)
        for msg in msgs:
            if string in msg['msg'] and (name == ""
                                         or msg['u']['username'] == name):
                date = dt.strptime(msg["ts"], settings["parseDate"])

                dates.append(dict(fullstring=msg['msg'], date=date))

        return dates

    def get_raw_msgs(self, settings, since):
        rmsgs = []

        msgs = self._retrieve_msgs(settings, since)
        for msg in msgs:
            url = ""
            if (("attachments" in msg) and (msg["attachments"] is not None)
                    and (len(msg["attachments"]) > 0)
                    and ("image_url" in msg["attachments"][0])):
                url = msg["attachments"][0]["image_url"]
            date = dt.strptime(msg["ts"], settings["parseDate"])
            rmsg = msg['msg']
            user = msg['user']

            rmsgs.append(dict(user=user, date=date, msg=rmsg, url=url))

        return rmsgs

    def print_scores(self, settings, scores, to_chat=False):
        url = ""
        alias = ""

        print("avatar: " + url + "  alias: " + alias)
        pprint(scores)

        # Make the scoreboard and send it if required
        out = "Tableau des scores : \n"
        for name in scores:
            out += name + " a totalisé " + str(
                scores[name]['score']) + " points\n"
        print(out)
        if to_chat:
            self.rocket.chat_post_message(out,
                                          room_id=settings['channel'],
                                          avatar=url,
                                          alias=alias)
Ejemplo n.º 19
0
    def handle(self, *args, **options):

        proxyDict = {}

        rocket = RocketChat(
            settings.ROCKET_CHAT_LOGIN,
            settings.ROCKET_CHAT_PASSWORD,
            server_url=settings.ROCKET_CHAT_URL,
            proxies=proxyDict
        )

        template = textwrap.dedent(
            """
            Hello {name} :) !
            
            I would like to let you know, that you are added as a team-member to {project_plular} which {project_be} listed now on brand new [SteemProjects.com](https://SteemProjects.com/) :) List of all your known project user will be able to find on your profile page: {profile_page}
            
            What is a SteemProjects? If you are familiar with SteemTools, then think about it as better version of it :) Big difference is that SteemProjects is a community driven website. **You as a project member can add/modify information about your projects**.
            
            SteemProjects is now in pre-release stage. It is now time to make sure, that all your Steem-related projects are added to database and are in the good shape. Here is a list of all your project which I know about:
            """
        )

        accounts = []

        for account in Account.objects.filter(account_type__name='STEEM'):
            if not account.profile:
                accounts.append((account,))
            else:
                accounts.append(list(account.profile.account_set.all()))

        for accounts_tuple in accounts:

            membership = TeamMembership.objects.filter(account__in=accounts_tuple)
            if not membership.exists():
                continue

            steem_name = accounts_tuple[0].name if not accounts_tuple[0].profile else accounts_tuple[0].profile.steem_account.name

            chat_user_info = rocket.users_info(username=steem_name).json()

            if not chat_user_info['success']:
                print("User {} do not have account on steemit.chat".format(steem_name))
                continue
            else:
                print ("User {} - ok".format(steem_name))

            many_projects = membership.count() > 1

            message = template.format(
                name=steem_name,
                profile_page="{}/@{}".format(settings.SITE_URL, steem_name),
                project_plular="{} projects".format(membership.count()) if many_projects else "a project",
                project_be="are" if many_projects else "is",

            )

            for tm in membership:
                message += "  - [{}]({})\n".format(
                    tm.project.name,
                    "{}{}".format(settings.SITE_URL, tm.project.get_absolute_url())
                )

            message += textwrap.dedent("""
                Before editing a project or adding a new one, please read the instruction first: [{instruction_title}]({instruction_url}) - otherwise a result might be far from perfect.
                
                In case of any question, don't hesitate to ask me! :)
                """.format(
                    instruction_title='Tutorial: How to add/edit a project on SteemProjects.com',
                    instruction_url='https://steemit.com/utopian-io/@noisy/pre-release-tutorial-how-to-add-edit-a-project-on-steemprojects-com',
                )
            )

            print("-" * 60)
            print(message)
            print("-" * 60)

            ans = input('##### Send PM to @{}? [y/n/q]: '.format(steem_name))
            if ans.lower() == 'y':
                res = rocket.chat_post_message(text=message, channel="@{}".format(steem_name))
                print(str(res.json()))
            elif ans.lower() == 'q':
                return
Ejemplo n.º 20
0
from rocketchat_API.rocketchat import RocketChat

###VARIABLES THAT YOU NEED TO SET MANUALLY IF NOT ON HEROKU#####
try:
    SERVER_URL = os.environ['SERVER_URL']
    BOT_USERNAME = os.environ['BOT_USERNAME']
    BOT_PASS = os.environ['BOT_PASS']
    MESSAGE = os.environ['WELCOME_MESSAGE']
except:
    SERVER_URL = 'Manually set SERVER_URL if youre not running through heroku or have not set vars in ENV'
    BOT_USERNAME = '******'
    BOT_PASS = '******'
    MESSAGE = 'Manually set the MESSAGE if youre not running through heroku or have not set vars in ENV'
###############################################################

rocket = RocketChat(BOT_USERNAME, BOT_PASS, server_url=SERVER_URL)
rocket.chat_post_message('good news everyone: I came to live!',
                         channel='GENERAL')
Ejemplo n.º 21
0
class RocketChatBot(OutputChannel):
    @classmethod
    def name(cls) -> Text:
        return "rocketchat"

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

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

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

    async def send_text_message(self, recipient_id: Text, text: Text,
                                **kwargs: Any) -> None:
        """Send message to output channel"""

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

    async def send_image_url(self, recipient_id: Text, image: Text,
                             **kwargs: Any) -> None:
        image_attachment = [{"image_url": image, "collapsed": False}]

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

    async def send_attachment(self, recipient_id: Text, attachment: Text,
                              **kwargs: Any) -> None:
        return self.rocket.chat_post_message(None,
                                             room_id=recipient_id,
                                             attachments=[attachment])

    async def send_text_with_buttons(
        self,
        recipient_id: Text,
        text: Text,
        buttons: List[Dict[Text, Any]],
        **kwargs: Any,
    ) -> None:
        # 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(text,
                                             room_id=recipient_id,
                                             attachments=button_attachment)

    async def send_elements(self, recipient_id: Text,
                            elements: Iterable[Dict[Text, Any]],
                            **kwargs: Any) -> None:
        return self.rocket.chat_post_message(None,
                                             room_id=recipient_id,
                                             attachments=elements)

    async def send_custom_json(self, recipient_id: Text,
                               json_message: Dict[Text,
                                                  Any], **kwargs: Any) -> None:
        text = json_message.pop("text")

        if json_message.get("channel"):
            if json_message.get("room_id"):
                logger.warning(
                    "Only one of `channel` or `room_id` can be passed to a RocketChat "
                    "message post. Defaulting to `channel`.")
                del json_message["room_id"]
            return self.rocket.chat_post_message(text, **json_message)
        else:
            json_message.setdefault("room_id", recipient_id)
            return self.rocket.chat_post_message(text, **json_message)
Ejemplo n.º 22
0
import win32com.client
import re
from rocketchat_API.rocketchat import RocketChat

rocket = RocketChat('botname',
                    'botpassword',
                    server_url="https://rockertchaturl.com")

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
folder = outlook.Folders("*****@*****.**")
inbox = folder.Folders("Inbox")

msg = inbox.Items
msg.sort("[ReceivedTime]", False)
msgs = msg.GetLast()

body = msgs.Body

links = re.findall(r'(https?://\S+)', body)

link = links[1]
link = link[:-1]

msg = "!parts \"" + link + "\""

rocket.chat_post_message(msg, channel="parts",
                         alias="INCOMING PARTS REQUEST").json()
def notify(title, message, url, username, password, room, retcode=None):

    rocket = RocketChat(username, password, server_url=url)

    msg = "**{}:** {}".format(title, message)
    rocket.chat_post_message(msg, channel=room)
Ejemplo n.º 24
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'))

        msg_id = chat_post_message.get('message').get('_id')
        chat_get_message = self.rocket.chat_get_message(msg_id=msg_id).json()
        self.assertEqual(chat_get_message.get('message').get('_id'), msg_id)

        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'))

    def test_chat_post_react(self):
        self.skipTest("Still not added but already documented endpoint")
        message_id = self.rocket.chat_post_message(
            "hello", channel='GENERAL').json().get('message').get('_id')
        chat_react = self.rocket.chat_react(msg_id=message_id).json()
        self.assertTrue(chat_react.get('success'))

    def test_post_pin_unpin(self):
        message_id = self.rocket.chat_post_message(
            "hello", channel='GENERAL').json().get('message').get('_id')
        chat_pin_message = self.rocket.chat_pin_message(message_id).json()
        self.assertTrue(chat_pin_message.get('success'))
        self.assertEqual(
            chat_pin_message.get('message').get('t'), 'message_pinned')

        chat_unpin_message = self.rocket.chat_unpin_message(message_id).json()
        self.assertTrue(chat_unpin_message.get('success'))

    def test_post_star_unstar(self):
        message_id = self.rocket.chat_post_message(
            "hello", channel='GENERAL').json().get('message').get('_id')
        chat_star_message = self.rocket.chat_star_message(message_id).json()
        self.assertTrue(chat_star_message.get('success'))

        chat_unstar_message = self.rocket.chat_unstar_message(
            message_id).json()
        self.assertTrue(chat_unstar_message.get('success'))
Ejemplo n.º 25
0
def sendMessage(mes,cha="integration_test"):
    rocket = RocketChat('aw5p', '@lexis1437', server_url='https://chat.newegg.org')
    pprint(rocket.me().json())
    pprint(rocket.channels_list().json())
    pprint(rocket.chat_post_message(mes, channel=cha, alias='AlertBot').json())
Ejemplo n.º 26
0
            fields.append({"short": True, "title": "Pixiv ID", "value": image['pixiv_id']})
        if image['tag_string_general'] != "":
            fields.append({"short": False, "title": "Tags", "value": image['tag_string_general']})

        print("Posting image #{} to channel {}".format(image['id'], CONFIG['rocketchat_channel']))

        source_url = None
        if source_url is None and image["pixiv_id"] not in ["", '""', "null", None]:
            source_url = PIXIV_POST_URL.format(id=image['pixiv_id'])
        if source_url is None and ("http://" in image["source"] or "https://" in image["source"]):
            source_url = image["source"]
        if source_url is None:
            source_url = DANBOORU_POST_URL.format(id=image['id'])

        rating = " ".join(filter(lambda x: "rating:" in x, CONFIG['tags']))
        if not rating:
            rating = "rating:{}".format(get_image_rating(image["rating"]))
        res = rocketchat.chat_post_message(text=None, channel=CONFIG['rocketchat_channel'], attachments=[
            {
                "title": "Danbooru #{} - {}".format(image['id'], rating),
                "title_link": source_url,
                "image_url": image_url,
                "fields": fields
            }
        ])
        if res.status_code != 200:
            print("Posting failed! Error {}".format(res.status_code))
            print(res.json())
        else:
            print("Done!")
Ejemplo n.º 27
0
class RocketChatBot(object):
    USE_BUTTONS = False

    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.unknown_command = [
            'command not found',
        ]
        self.handle_unknown = None
        self.lastts = {}
        self.command_character = command_character

        self.conversations = {}
        self.button_variants = {}

        self.personal_ids: set = set()

    def echo(self, message: Message):
        self.send_message('@' + message.user.username + ' : ' + message.text,
                          message.chat.id)

    def get_status(self, auser):
        return self.api.users_get_presence(username=auser)

    def send_photo(self, chat_id, file, *args, **kwargs):
        self.api.rooms_upload(rid=chat_id, file=file, *args, **kwargs)

    def send_chat_action(self, *args, **kwargs):
        # No such methods in Rocket.Chat
        pass

    def post_new_message(self, obj):
        response = self.api.call_api_post("chat.postMessage", **obj)
        print(response)

    def send_message(self, channel_id, msg, reply_markup=None):
        attachments, msg = self.get_attachments(reply_markup, channel_id, msg)
        # pprint(attachments)
        response = self.api.chat_post_message(channel=channel_id,
                                              text=msg,
                                              attachments=attachments)
        if response.status_code // 100 > 2:
            logging.error(response.json().get(
                "error", "Error in sending message: {}".format(response.text)))

    def get_attachments(self, reply_markup, user_id, msg):
        if reply_markup is None:
            return None, msg
        if self.USE_BUTTONS:
            return reply_markup.to_json(), msg
        else:
            msg += reply_markup.get_text()
            self.button_variants.update({user_id: reply_markup.get_variants()})
            return None, msg

    def reply_to(self, message: Message, *args, **kwargs):
        return self.send_message(message.chat.id, *args, **kwargs)

    def register_next_step_handler(self, message: Message, f: Callable, *args,
                                   **kwargs):
        self.conversations.update({message.from_user.id: (f, args, kwargs)})

    def get_user(self, username: str):
        return self.api.users_info(username=username)

    def add_dm_handler(self, command, action):
        self.commands.append((command, action))

    def add_auto_answer(self, triggers, answers):
        self.auto_answers.append((triggers, answers))

    def add_direct_answer(self, triggers, answers):
        self.direct_answers.append((triggers, answers))

    def set_unknown_handler(self, action):
        self.handle_unknown = action

    def handle_command_character_message(self, message, channel_id):
        msg = message['msg'].lstrip(self.command_character)

        command = msg.split()[0].lower()
        arguments = " ".join(msg.split()[1:])
        user = message['u']['username']
        attachments = message['attachments']
        pass_message = Message(message_id=message["_id"],
                               text=msg,
                               chat=Chat(chat_id=channel_id),
                               user=User.from_message(message),
                               attachments=attachments,
                               json=message)
        for cmd_list in self.commands:
            if command.lower() in cmd_list[0]:
                cmd_list[1](pass_message)
                return

        if not self.handle_auto_answer(message, self.direct_answers,
                                       channel_id):
            self.send_message('@' + user + ' :' + choice(self.unknown_command),
                              channel_id)

    def handle_direct_message(self, message, channel_id):
        msg = message['msg'].partition('@' + self.botname)[2].strip() if message["msg"].startswith('@' + self.botname) \
            else message["msg"].strip()
        if len(msg) > 0:
            command = msg.split()[0].lower()
            # arguments = " ".join(msg.split()[1:])
            user = User.from_message(message)
            attachments = message['attachments']
            pass_message = Message(message_id=message["_id"],
                                   text=msg,
                                   chat=Chat(chat_id=channel_id),
                                   user=user,
                                   attachments=attachments,
                                   json=message)

            conversation = self.conversations.get(user.id)
            variants = self.button_variants.get(channel_id)
            pass_message.text = variants.get(
                pass_message.text,
                pass_message.text) if variants else pass_message.text
            if conversation is not None:
                # Зарегистрирован следующий шаг
                f, args, kwargs = conversation
                self.conversations.pop(user.id)
                f(pass_message, *args, **kwargs)
            else:
                # Следующий шаг не найден, обработка как обычно
                for cmd_list in self.commands:
                    if command.lower() in cmd_list[0]:
                        cmd_list[1](pass_message)
                        return

                if not self.handle_auto_answer(message, self.direct_answers,
                                               channel_id):
                    if self.handle_unknown is not None:
                        self.handle_unknown(pass_message)
                    else:
                        self.send_message(
                            '@' + user.username + ' :' +
                            choice(self.unknown_command), channel_id)
        else:
            user = User.from_message(message)
            attachments = message['attachments']
            pass_message = Message(message_id=message["_id"],
                                   text=msg,
                                   chat=Chat(chat_id=channel_id),
                                   user=user,
                                   attachments=attachments,
                                   json=message)
            self.handle_unknown(pass_message)

    def handle_auto_answer(self, message, answers, channel_id):
        for kind in answers:
            for k in kind[0]:
                if k in message['msg'].lower():
                    self.send_message(
                        choice(kind[1]) + ' @' + message['u']['username'],
                        channel_id)
                    return True
        return False

    def handle_messages(self, messages, channel_id):
        for message in messages['messages']:
            if message['u']['username'] != self.botname:
                pprint(message)
                pprint(channel_id)
                if message['u']['username'] == 'rocket.cat':
                    pass
                    # continue
                Thread(target=self.handle_direct_message,
                       args=(message, channel_id)).start()
                # if message['msg'].startswith('@' + self.botname) or channel_id in self.personal_ids:
                #     Thread(target=self.handle_direct_message, args=(message, channel_id)).start()
                # elif self.command_character is not None and message['msg'].startswith(self.command_character):
                #     Thread(target=self.handle_command_character_message, args=(message, channel_id)).start()
                # elif 'mentions' not in message or message.get('mentions') == []:
                #     Thread(target=self.handle_auto_answer, args=(message, self.auto_answers, channel_id)).start()

    def load_ts(self, channel_id, messages):
        if len(messages) > 0:
            self.lastts[channel_id] = messages[0]['ts']
        else:
            self.lastts[channel_id] = ''

    def load_channel_ts(self, channel_id):
        self.load_ts(channel_id,
                     self.api.channels_history(channel_id).json()['messages'])

    def load_group_ts(self, channel_id):
        self.load_ts(channel_id,
                     self.api.groups_history(channel_id).json()['messages'])

    def load_im_ts(self, channel_id):
        response = self.api.im_history(channel_id).json()
        if response.get('success'):
            self.load_ts(channel_id,
                         self.api.im_history(channel_id).json()['messages'])

    def process_messages(self, messages, channel_id):
        try:
            if "success" in messages:
                if messages['success'] == False:
                    raise RuntimeError(messages['error'])
            if len(messages['messages']) > 0:
                self.lastts[channel_id] = messages['messages'][0]['ts']
            self.handle_messages(messages, channel_id)
        except Exception as e:
            pprint(e)

    def process_channel(self, channel_id):
        if channel_id not in self.lastts:
            self.lastts[channel_id] = ''

        self.process_messages(
            self.api.channels_history(channel_id,
                                      oldest=self.lastts[channel_id]).json(),
            channel_id)

    def process_group(self, channel_id):
        if channel_id not in self.lastts:
            self.lastts[channel_id] = ''

        self.process_messages(
            self.api.groups_history(channel_id,
                                    oldest=self.lastts[channel_id]).json(),
            channel_id)

    def process_im(self, channel_id):
        if channel_id not in self.lastts:
            self.lastts[channel_id] = ''

        self.process_messages(
            self.api.im_history(channel_id,
                                oldest=self.lastts[channel_id]).json(),
            channel_id)

    def run(self):
        for channel in self.api.channels_list_joined().json().get('channels'):
            self.load_channel_ts(channel.get('_id'))

        for group in self.api.groups_list().json().get('groups'):
            self.load_group_ts(group.get('_id'))

        for im in self.api.im_list().json().get('ims'):
            self.load_im_ts(im.get('_id'))

        while 1:
            for channel in self.api.channels_list_joined().json().get(
                    'channels'):
                Thread(target=self.process_channel,
                       args=(channel.get('_id'), )).start()

            for group in self.api.groups_list().json().get('groups'):
                Thread(target=self.process_group,
                       args=(group.get('_id'), )).start()

            for im in self.api.im_list().json().get('ims'):
                if self.botname in im.get("usernames"):
                    self.personal_ids.add(im.get('_id'))
                Thread(target=self.process_im, args=(im.get('_id'), )).start()

            sleep(1)
Ejemplo n.º 28
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'))

        with self.assertRaises(RocketMissingParamException):
            self.rocket.chat_post_message(text='text')

        msg_id = chat_post_message.get('message').get('_id')
        chat_get_message = self.rocket.chat_get_message(msg_id=msg_id).json()
        self.assertEqual(chat_get_message.get('message').get('_id'), msg_id)

        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'))

    def test_chat_post_react(self):
        message_id = self.rocket.chat_post_message(
            "hello", channel='GENERAL').json().get('message').get('_id')
        chat_react = self.rocket.chat_react(msg_id=message_id).json()
        self.assertTrue(chat_react.get('success'))

    def test_post_pin_unpin(self):
        message_id = self.rocket.chat_post_message(
            "hello", channel='GENERAL').json().get('message').get('_id')
        chat_pin_message = self.rocket.chat_pin_message(message_id).json()
        self.assertTrue(chat_pin_message.get('success'))
        self.assertEqual(
            chat_pin_message.get('message').get('t'), 'message_pinned')

        chat_unpin_message = self.rocket.chat_unpin_message(message_id).json()
        self.assertTrue(chat_unpin_message.get('success'))

    def test_post_star_unstar(self):
        message_id = self.rocket.chat_post_message(
            "hello", channel='GENERAL').json().get('message').get('_id')
        chat_star_message = self.rocket.chat_star_message(message_id).json()
        self.assertTrue(chat_star_message.get('success'))

        chat_unstar_message = self.rocket.chat_unstar_message(
            message_id).json()
        self.assertTrue(chat_unstar_message.get('success'))

    def test_chat_search(self):
        chat_search = self.rocket.chat_search(room_id='GENERAL',
                                              search_text='hello').json()
        self.assertTrue(chat_search.get('success'))

    def test_chat_get_message_read_receipts(self):
        message_id = self.rocket.chat_post_message(
            "hello", channel='GENERAL').json().get('message').get('_id')
        chat_get_message_read_receipts = self.rocket.chat_get_message_read_receipts(
            message_id=message_id).json()
        self.assertTrue(chat_get_message_read_receipts.get('success'))
        self.assertIn('receipts', chat_get_message_read_receipts)
Ejemplo n.º 29
0
from requests import sessions
from pprint import pprint
import requests
from rocketchat_API.rocketchat import RocketChat

rocket = RocketChat('username', 'password', server_url='rocket.chat:port')
url = 'https://icanhazdadjoke.com/slack'
headers = {'user-agent': 'My Library (Link to your github here)'}
response = requests.get(url, headers=headers)
results = response.json()
rocket.chat_post_message(results['attachments'][0]['text'],
                         channel='GENERAL',
                         alias='DAD JOKES!',
                         emoji=':joy:').json()
Ejemplo n.º 30
0
class TestIMs(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)
        # 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)

    def tearDown(self):
        pass

    def test_im_create(self):
        im_create = self.rocket.im_create(self.recipient_user).json()
        self.assertTrue(im_create.get('success'))

    def test_im_send(self):
        im_create = self.rocket.im_create(self.recipient_user).json()
        room_id = im_create.get('room').get('_id')
        im_send = self.rocket.chat_post_message(room_id=room_id,
                                                text='test').json()
        self.assertTrue(im_send.get('success'))

    def test_im_list(self):
        self.rocket.im_create(self.recipient_user)
        im_list = self.rocket.im_list().json()
        self.assertTrue(im_list.get('success'))

    def test_im_close_open(self):
        im_create = self.rocket.im_create(self.recipient_user).json()
        room_id = im_create.get('room').get('_id')
        im_close = self.rocket.im_close(room_id).json()
        self.assertTrue(im_close.get('success'))
        im_open = self.rocket.im_open(room_id).json()
        self.assertTrue(im_open.get('success'))

    def test_im_set_topic(self):
        topic = 'this is my new topic'
        im_create = self.rocket.im_create(self.recipient_user).json()
        room_id = im_create.get('room').get('_id')
        im_set_topic = self.rocket.im_set_topic(room_id, topic).json()
        self.assertTrue(im_set_topic.get('success'))
        self.assertEqual(im_set_topic.get('topic'), topic,
                         'Topic set does not match topic returned')

    def test_im_list_everyone(self):
        im_list_everyone = self.rocket.im_list_everyone().json()
        self.assertTrue(im_list_everyone.get('success'))

    def test_im_history(self):
        im_create = self.rocket.im_create(self.recipient_user).json()
        room_id = im_create.get('room').get('_id')
        im_history = self.rocket.im_history(room_id).json()
        self.assertTrue(im_history.get('success'))

    def test_im_messages_others(self):
        # ToDo: Try changing the access configuration so endpoint can be successfully tested
        im_create = self.rocket.im_create(self.recipient_user).json()
        room_id = im_create.get('room').get('_id')
        im_messages_others = self.rocket.im_messages_others(room_id).json()
        self.assertFalse(im_messages_others.get('success'))

    def test_im_files(self):
        im_create = self.rocket.im_create(self.recipient_user).json()
        self.assertTrue(im_create.get('success'))

        im_files = self.rocket.im_files(
            room_id=im_create.get('room').get('_id')).json()
        self.assertTrue(im_files.get('success'))

        im_files = self.rocket.im_files(user_name=self.recipient_user).json()
        self.assertTrue(im_files.get('success'))

        with self.assertRaises(RocketMissingParamException):
            self.rocket.im_files()

    def test_im_counters(self):
        im_create = self.rocket.im_create(self.recipient_user).json()
        self.assertTrue(im_create.get('success'))

        im_counters = self.rocket.im_counters(
            room_id=im_create.get('room').get('_id')).json()
        self.assertTrue(im_counters.get('success'))

        im_counters = self.rocket.im_counters(
            user_name=self.rocket.me().json().get('_id')).json()
        self.assertTrue(im_counters.get('success'))

        with self.assertRaises(RocketMissingParamException):
            self.rocket.im_counters()
Ejemplo n.º 31
0
class RocketChatBot(object):
    def __init__(self, botname, passwd, server):
        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 = {}

    def echo(self, msg, user, channel_id):
        self.send_message('@' + user + ' : ' + msg, channel_id)

    def get_status(self, auser):
        return self.api.users_get_presence(username=auser)

    def send_message(self, msg, channel_id):
        self.api.chat_post_message(channel=channel_id, text=msg)

    def add_dm_handler(self, command, action):
        self.commands.append((command, action))

    def add_auto_answer(self, triggers, answers):
        self.auto_answers.append((triggers, answers))

    def add_direct_answer(self, triggers, answers):
        self.direct_answers.append((triggers, answers))

    def handle_direct_message(self, message, channel_id):
        msg = message['msg'].lstrip('@' + self.botname).strip()
        if len(msg) > 0:
            command = msg.split()[0].lower()
            arguments = " ".join(msg.split()[1:])
            user = message['u']['username']
            for cmd_list in self.commands:
                if command.lower() in cmd_list[0]:
                    cmd_list[1](arguments, user, channel_id)
                    return

            if not self.handle_auto_answer(message, self.direct_answers,
                                           channel_id):
                self.send_message(
                    '@' + user + ' :' + choice(self.unknow_command),
                    channel_id)
        else:
            self.send_message('Here I am', channel_id)

    def handle_auto_answer(self, message, answers, channel_id):
        for kind in answers:
            for k in kind[0]:
                if k in message['msg'].lower():
                    self.send_message(
                        choice(kind[1]) + ' @' + message['u']['username'],
                        channel_id)
                    return True
        return False

    def handle_messages(self, messages, channel_id):
        for message in messages['messages']:
            if message['u']['username'] != self.botname:
                pprint(message)
                if message['u']['username'] == 'rocket.cat':
                    continue
                if message['msg'].startswith('@' + self.botname):
                    Thread(target=self.handle_direct_message,
                           args=(message, channel_id)).start()
                elif 'mentions' not in message or message.get(
                        'mentions') == []:
                    Thread(target=self.handle_auto_answer,
                           args=(message, self.auto_answers,
                                 channel_id)).start()

    def load_ts(self, channel_id, messages):
        if len(messages) > 0:
            self.lastts[channel_id] = messages[0]['ts']
        else:
            self.lastts[channel_id] = ''

    def load_channel_ts(self, channel_id):
        self.load_ts(channel_id,
                     self.api.channels_history(channel_id).json()['messages'])

    def load_group_ts(self, channel_id):
        self.load_ts(channel_id,
                     self.api.groups_history(channel_id).json()['messages'])

    def load_im_ts(self, channel_id):
        response = self.api.im_history(channel_id).json()
        if response.get('success'):
            self.load_ts(channel_id,
                         self.api.im_history(channel_id).json()['messages'])

    def process_messages(self, messages, channel_id):
        try:
            if "success" in messages:
                if messages['success'] == False:
                    raise RuntimeError(messages['error'])
            if len(messages['messages']) > 0:
                self.lastts[channel_id] = messages['messages'][0]['ts']
            self.handle_messages(messages, channel_id)
        except Exception as e:
            pprint(e)

    def process_channel(self, channel_id):
        if channel_id not in self.lastts:
            self.lastts[channel_id] = ''

        self.process_messages(
            self.api.channels_history(channel_id,
                                      oldest=self.lastts[channel_id]).json(),
            channel_id)

    def process_group(self, channel_id):
        if channel_id not in self.lastts:
            self.lastts[channel_id] = ''

        self.process_messages(
            self.api.groups_history(channel_id,
                                    oldest=self.lastts[channel_id]).json(),
            channel_id)

    def process_im(self, channel_id):
        if channel_id not in self.lastts:
            self.lastts[channel_id] = ''

        self.process_messages(
            self.api.im_history(channel_id,
                                oldest=self.lastts[channel_id]).json(),
            channel_id)

    def run(self):
        for channel in self.api.channels_list_joined().json().get('channels'):
            self.load_channel_ts(channel.get('_id'))

        for group in self.api.groups_list().json().get('groups'):
            self.load_group_ts(group.get('_id'))

        for im in self.api.im_list().json().get('ims'):
            self.load_im_ts(im.get('_id'))

        while 1:
            for channel in self.api.channels_list_joined().json().get(
                    'channels'):
                Thread(target=self.process_channel,
                       args=(channel.get('_id'), )).start()

            for group in self.api.groups_list().json().get('groups'):
                Thread(target=self.process_group,
                       args=(group.get('_id'), )).start()

            for im in self.api.im_list().json().get('ims'):
                Thread(target=self.process_im, args=(im.get('_id'), )).start()

            sleep(1)