Exemple #1
0
def main():
    parser = argparse.ArgumentParser(
        description="Send a message to RocketChat channels")
    parser.add_argument('channels',
                        metavar='str',
                        nargs='+',
                        help='Channels where the message to be sent')
    parser.add_argument('--settings',
                        default=os.environ.get('HOME') +
                        '/.config/rocketchat.api/settings.yaml',
                        help='Path to yaml file with rocketchat.api settings')
    parser.add_argument('-m',
                        '--message',
                        default=sys.stdin,
                        type=argparse.FileType('r'),
                        help='Path to the file with message text to be sent')

    args = parser.parse_args()

    with open(args.settings) as f:
        settings = yaml.safe_load(f)

    message = args.message.read()
    rocket = RocketChatAPI(settings=settings)
    for channel in args.channels:
        rocket.send_message(message, channel)
Exemple #2
0
    def __init__(self, name, domain, room, login, password):
        self.name = name
        self.login = login
        self.domain = domain
        self.password = password
        self.room = room
        self.room_id = ''
        self.api = None
        self.processed = []

        self.targets = {
            '192.168.1.1': {
                'comments': 'Router!',
                'services': {
                    '21': 'ftp',
                    '22': 'ssh',
                    '9989': 'http',
                }
            },
            '192.168.1.3': {
                'comments': '',
                'services': {
                    '80': 'http',
                }
            },
        }

        self.load_status()
        self.api = RocketChatAPI(settings={
            'username': self.login, 
            'password': self.password, 
            'domain': self.domain,
        })
        self.room_id = self.get_room_id('pentest-rdc')
Exemple #3
0
 def __init__(self, username, password, domain):
     # 设置队列,记录最近答复过的消息id,避免重复回答同一条消息,假定1分钟内@bot的人次不超过100
     self.replied_queue = deque([], maxlen=100)
     # 设置rocketchat的api参数
     self.api = RocketChatAPI(settings={'username': username, 
                                        'password': password,
                                        'domain': domain})
Exemple #4
0
def send_to_rocketchat(username,email):
    api = RocketChatAPI(settings={'username': RC_USERNAME, 'password': RC_PASSWORD,
                                  'domain': RC_DOMAIN})
    try:
        api.send_message(
            'Зарегистрирован новый пользователь:' + username + ' , e-mail:' + email,
            'users')
    except:
        print('Rocket chat not work!')
def sendMessage(server, username, password, room_id, message):
    try:
        api = RocketChatAPI(settings={
            'domain': server,
            'username': username,
            'password': password
        })
        api.send_message(message, room_id)
    except Exception as e:
        print(e)
Exemple #6
0
def RocketSendMessage(message, to=BOT_ROOT):
    api = RocketChatAPI(
        settings={
            'username': BOT_USER,
            'password': BOT_PW,
            'domain': 'https://chat.limak.ru'
        })
    #print (api.get_private_rooms())
    api.send_message(message, to)
    return True
Exemple #7
0
def ParsePacket(pkt):
    #
    bot = RocketChatAPI(
        settings={
            'username': '******',
            'password': '******',
            'domain': 'http://<Rocket Chat Server IP>:3000'
        })
    #
    if (pkt):
        #
        #pkt.show()
        #
        alert = ""
        #
        print("[*] DHCP Traffic Detected ")
        alert += " WLAN Association Detected \n"
        alert += " ------------------------------- \n"
        #
        source_addr = pkt['Ethernet'].src
        #
        raw_options = pkt['DHCP options'].options
        #
        time_stamp = time.ctime()
        #
        print("[*] Date/Time: %s " % time_stamp)
        alert += " Date/Time: %s \n" % time_stamp
        #
        host_name = raw_options[6][1]
        host_name = host_name.decode('utf-8')
        print("[*] Host name: %s " % host_name)
        alert += " Host name: %s \n" % host_name
        #
        print("[*] Source MAC Address: %s " % source_addr)
        alert += " Source MAC Address: %s \n" % source_addr
        #
        host_addr = raw_options[4][1]
        print("[*] Leased IP: %s " % host_addr)
        alert += " Leased IP: %s \n" % host_addr
        #
        try:
            #
            print("[*] Sending chat message...")
            #
            bot.send_message(alert, 'homelab.coord')
            #
        except Exception as e:
            #
            print("[!] Failed to send notification: %s " % e)
            #
        time.sleep(1)
        #
        os.system('clear')
        #
        return
Exemple #8
0
 def setUp(self):
     self.settings = {
         'username': '******',
         'password': '******',
         'domain': 'https://www.example.com'
     }
     self.api = RocketChatAPI(settings=self.settings)
Exemple #9
0
 def test_token_auth_params(self):
     settings = {
         'token': 'some_token',
         'user_id': 'some_id',
         'domain': 'https://www.example.com'
     }
     api = RocketChatAPI(settings=settings)
     base = RocketChatBase(settings=api.settings)
     self.assertEqual(base.headers['X-Auth-Token'], 'some_token')
     self.assertEqual(base.headers['X-User-Id'], 'some_id')
Exemple #10
0
def rocketchat_send_message(ctx, message, channels):
    """
    Send the message to the given RocketChat channels

    Before sending the message we read the config file
    from `~/.config/rocketchat.api/settings.yaml` which
    must include next records:

        username: '******'
        password: '******'
        domain: 'https://chat.suse.de'

    :param message:     plain text message content in the Rocket.Chat
                        messaging format
    :param channels:    a list of channels where to send the message,
                        the user private channel should be prefixed
                        with '@' symbol
    """
    try:
        from rocketchat.api import RocketChatAPI
    except Exception as e:
        log.warning(f'rocketchat: Failed to import rocketchat.api: {e}')
        return

    settings_path = \
        os.environ.get('HOME') + '/.config/rocketchat.api/settings.yaml'

    try:
        with open(settings_path) as f:
            settings = yaml.safe_load(f)
    except Exception as e:
        log.warning(
            f'rocketchat: Failed to load settings from {settings_path}: {e}')

    r = RocketChatAPI(settings=settings)
    for channel in channels:
        try:
            r.send_message(message, channel)
        except Exception as e:
            log.warning(
                f'rocketchat: Failed to send message to "{channel}" channel: {e}'
            )
def loop():
    """
    trigger loop
    """
    while True:
        """
        one infinite loop
        """
        conf = Configuration()
        for handle in conf.twitter_handles:
            hindex = conf.twitter_handles.index(handle)
            username, password = conf.get_account(hindex)
            url = conf.get_server(hindex)
            chat = RocketChatAPI(
                settings={
                    'username': username,
                    'password': password,
                    'domain': url
                    }
                )

            twits = TwitterAdapter(handle, 10)
            twit_feed = twits.dict
            for tweet in twit_feed:
                text = tweet['text']
                id = tweet['tweetId']

                jindex = JsonRemembers(handle)
                if not jindex.exists(id):
                    logger.info("id {} by {} sent".format(id, handle))
                    for channel in conf.get_rooms(hindex):
                        try:
                            text = transform(text)
                            chat.send_message(text, channel)
                        except json.decoder.JSONDecodeError:
                            logger.info("Could not read server response, bad server url?")
                    jindex.add(id)
                else:
                    logger.info("id {} by {} already sent".format(id, handle))

        logger.info("Sleeping {} seconds".format(conf.interval * 60))
        sleep(conf.interval * 60)
Exemple #12
0
def EstablishSession(username,password,server):
    #
    try:
        #
        chat_instance = RocketChatAPI(settings={
           'username':username,
           'password':password,
           'domain':server 
        })
        #
    except Exception as e:
        #
        print("[!] Error: %s " % e)
        #
        sys.exit(1)
        #
    return chat_instance
Exemple #13
0
class Bot():
    """
    创建一个聊天机器人
    :RoomsDictUpdate: 更新聊天室字典
    :SetRoom: 指定使用本聊天机器人的聊天室
    """
    def __init__(self, username, password, domain):
        # 设置队列,记录最近答复过的消息id,避免重复回答同一条消息,假定1分钟内@bot的人次不超过100
        self.replied_queue = deque([], maxlen=100)
        # 设置rocketchat的api参数
        self.api = RocketChatAPI(settings={'username': username, 
                                           'password': password,
                                           'domain': domain})
    
    
    def _RoomsDict(self, _class='private'):
        """
        获取聊天房间的字典,字典的key为聊天室名,value为聊天室id,聊天室不存在重名
        :_class: 聊天室类型
            - private: 私有聊天室
            - public: 公共聊天室
        """
        if _class == 'private':
            rooms = self.api.get_private_rooms()
        elif _class == 'public':
            rooms = self.api.get_public_rooms()
        else:
            raise ValueError('请指定正确的_class')
        fun = lambda d:tuple(d.values())
        rooms = {fun(d)[0]:fun(d)[1] for d in rooms}
        return rooms
    
    
    def RoomsDictUpdate(self):
        private_rooms = self._RoomsDict('private')
        public_rooms = self._RoomsDict('public')
        self.rooms_dict = dict(private_rooms, **public_rooms)
    
    def SetRoom(self, room_name):
        try:
            self.room_id = self.rooms_dict[room_name]
        except KeyError:
            raise KeyError('房间名<%s>不存在' % room_name)
    
       
    def History(self, oldest=None):
        """
        获取当前聊天室的历史聊天记录
        """
        history = self.api.get_private_room_history(self.room_id, oldest=oldest)
        if history['success']:
            history_msgs = history['messages']
        return history_msgs
  

    def NewMsgs(self):
        """
        获取指定聊天室最近60秒的历史消息
        """
        begin_CCT = datetime.now() + timedelta(seconds=-10)
        begin_UTC = begin_CCT.astimezone(pytz.timezone('UTC'))
        oldest = begin_UTC.strftime('%Y-%m-%dT%H:%M:%SZ')
        msgs = self.History(oldest=oldest)
        msgs.reverse() # 逆序排列
        return msgs
    
    
    def reply(self, ser):
        if ser['_id'] not in self.replied_queue:
            self.replied_queue.append(ser['_id'])
            text_out = BotApi(ser['msg'])
            text_out += ' @%s' % ser['name']
            self.api.send_message(text_out, room_id)
        
    
    def _Msgs2Bot(self, msgs: list):
        """
        解析获取到的聊天记录,筛选出@xbot的记录,保留'_id','name','msg'这三个字段
        """
        if len(msgs) > 0:
            df_msgs = pd.DataFrame(msgs)
            df_msgs['name'] = df_msgs['u'].map(lambda x:x['username'])
            df_msgs_select = df_msgs[['_id', 'name', 'msg']]
            self.msgs_at_bot = df_msgs_select[df_msgs_select['msg'].str.startswith('@xbot') | 
                                              df_msgs_select['msg'].str.endswith('@xbot')]
            self.msgs_at_bot.apply(self.reply, axis=1)


    def Msgs2Bot(self):
        self._Msgs2Bot(self.NewMsgs())
        
        
    def Run(self):
        while True:
            self.Msgs2Bot()
            time.sleep(0.5)
Exemple #14
0
if chat == '':
    print(
        'Укажите групповой чат (параметр -c=<Наименование группового чата> или конфигурационный параметр GROUP_CHAT = <Наименование группового чата>)'
    )
    sys.exit()

if chat_url == '':
    print(
        'Укажите URL-подключения Rocket.Chat (параметр -url=<URL-подключения к сервису> или конфигурационный параметр CHAT_URL = URL-подключения к сервису)'
    )
    sys.exit()

api = RocketChatAPI(settings={
    'username': user,
    'password': password,
    'domain': chat_url
})
room_id = ''
for room in api.get_private_rooms():
    if room['name'] == chat:
        room_id = room['id']

if room_id == '':
    print('Общий чат с таким именем не зарегистрирован')

if file_read == '':
    input_message = ''
    for line in sys.stdin:
        input_message = input_message + line
else:
Exemple #15
0
def send_to_rocketchat(username,email):
    api = RocketChatAPI(settings={'username': RC_USERNAME, 'password': RC_PASSWORD,
    try:                              'domain': RC_DOMAIN})
Exemple #16
0
            if line.count('=') > 0:
                password = line.split('=')[1].strip().replace('"', '')

        if line.startswith('CLEAN_HISTORY_GROUP_CHAT'):
            if line.count('=') > 0:
                chats = line.split('=')[1].strip().replace('"', '')

        if line.startswith('CHAT_URL'):
            if line.count('=') > 0:
                chat_url = line.split('=')[1].strip().replace('"', '')

    conf_file.close()

api = RocketChatAPI(settings={
    'username': user,
    'password': password,
    'domain': chat_url
})
room_id = ''

for chat in chats.split(','):
    for room in api.get_private_rooms():
        if room['name'] == chat.strip():
            room_id = room['id']
            count = 0
            for message in api.get_private_room_history(
                    room_id, oldest='2016-05-30T13:42:25.304Z',
                    count=2000)['messages']:
                count = count + 1
                message_ts = parser.parse(message['ts'])
                utc = pytz.UTC
from typing import List

SITE_URL = os.getenv("SHAMAN_SITEURL", "")
BOTNAME = os.getenv("SHAMAN_NAME", "shaman")
BOTPASSWORD = os.getenv("SHAMAN_PASSWORD", "shaman")
BOTNAME_NOCASE = re.compile(re.escape(BOTNAME), re.IGNORECASE)

if SITE_URL == "":
    print("Set SHAMAN_SITEURL")
    sys.exit(1)
if BOTPASSWORD == "":
    print("Set SHAMAN_PASSWORD")
    sys.exit(1)

print("Connecting to.. {}".format(SITE_URL))
RC = RocketChatAPI(settings={'username': BOTNAME, 'password': BOTPASSWORD,
                             'domain': 'https://' + SITE_URL})

ROOMS = {r['name']: r['id'] for r in RC.get_public_rooms()}

ws = None # global rocket chat websocket connection object

# websockets rocket chat login handshake
def wslogin():
    # get an auth token from the rest api
    auth_token = GetMe(RC.settings).auth_token
    url = "wss://" + SITE_URL + "/websocket"

    trace = uuid.uuid4().hex[:5]
    global ws
    ws = create_connection(url)
    # must ping first
Exemple #18
0
    def jenkins(self, request):
        """
         {
         'number': '2',
         'job_name': 'fett-master-none-dev-ubuntu16.04-linux-sv01-ci01-execute_cmd',
         'timestamp': '1508516240981',
         'builtOn': 'dev-ubuntu16.04-linux-sv01-ci01',
         'event': 'jenkins.job.started',
         'userId': 'prusse',
         'url': 'job/fett-master-none-dev-ubuntu16.04-linux-sv01-ci01-execute_cmd/2/',
         }
        :param request:
        :return:
        """
        from rocketchat.api import RocketChatAPI

        rocket_api = RocketChatAPI(
            settings={
                'username': self.config['ROCKETCHAT_USER'],
                'password': self.config['ROCKETCHAT_PASSWORD'],
                'domain': self.config['ROCKETCHAT_DOMAIN'],
            }
        )
        self.log.debug('Jenkins: received request: {}'.format(pformat(dict(request.params))))
        info = dict(request.params)

        settings = self.load_user_settings(info['userId'])

        # move this job info to the first position
        infos = settings['jobs']
        for index, existing_info in enumerate(infos):
            if existing_info['job_name'] == info['job_name']:
                del infos[index]
        infos.insert(0, info)

        # limit number of jobs
        infos = infos[:15]
        settings['jobs'] = infos

        if info['event'] == 'jenkins.job.started':
            template = JOB_STARTED_MSG
            status = ':pray:'
            fmt_kwargs = {'comment': get_job_state_comment('STARTED')}
        else:
            template = JOB_COMPLETED_MSG
            status = ":white_check_mark:" if info['result'] == 'SUCCESS' else ":x:"
            comment = get_job_state_comment(info['result'])
            info['test_failures'] = self._get_build_test_errors(info['job_name'], info['number'])
            if info['test_failures']:
                max_show = 10
                failures_items = ['**{} failed tests**'.format(len(info['test_failures']))]
                failures_items += ['`{}`'.format(x['name']) for x in info['test_failures'][:max_show]]
                if len(info['test_failures']) > max_show:
                    failures_items.append('... and {} more'.format(len(info['test_failures']) - max_show))
                failures_msg = '\n'.join(failures_items)
            else:
                failures_msg = ''

            fmt_kwargs = {
                'test_failures_msg': failures_msg,
                'comment': comment,
            }

        info['status'] = status
        self.save_user_settings(info['userId'], settings)

        fmt_kwargs['jenkins_url'] = self.config['JENKINS_URL']
        fmt_kwargs.update(info)
        rocket_api.send_message(template.format(**fmt_kwargs).strip(), '@{}'.format(info['userId']))
        return 'OK'
#!/usr/bin/python
'''
rocketchat bot script, sends messagetext to any channel you specify using rocketchat API.
By jreiners
'''

from rocketchat.api import RocketChatAPI
import os
import sys

messagetext = 'I just grabbed *"{}"* from the *"{}"* category. I acquired it from the *"{}"* newsgroup'
# unless DEFAULT room is used, this needs to be the room code from
roomname = 'GENERAL_or_RoomID from above'
api = RocketChatAPI(settings={'username': '******', 'password': '******', 'domain': 'http://url:3000'})

api.send_message( messagetext.format(sys.argv[3], sys.argv[5], sys.argv[6]) , roomname)
print("sent notification to #quickbox chatroom.")

sys.exit(0)
from rocketchat.api import RocketChatAPI
import os
import sys

api = RocketChatAPI(
    settings={
        'username': '******',
        'password': '******',
        'domain': 'http://rc-url.com:3000'
    })


def getPrivates():
    print("Private rooms:")
    rooms2 = api.get_private_rooms()
    for x in rooms2:
        print("Name: {}, ID: {}".format(x['name'], x['id']))


def getPublic():
    print("Public rooms")
    rooms = api.get_public_rooms()
    for x in rooms:
        print("Name: {}, ID: {}".format(x['name'], x['id']))


getPublic()
getPrivates()
# For env vars
import os

ghAccessToken = os.environ.get('GITHUB_ACCESS_TOKEN')
rocketChatBotUsername = os.environ.get('ROCKET_USERNAME')
rocketChatBotPassword = os.environ.get('ROCKET_PASSWORD')
rocketChatDomain = os.environ.get('ROCKET_DOMAIN')
rocketChatChannel = os.environ.get('ROCKET_CHANNEL')
webhookSecret = os.environ.get('WEBHOOK_SECRET')
webhookPort = os.environ.get('WEBHOOOK_PORT')

g = Github(ghAccessToken)

rocketAPI = RocketChatAPI(
    settings={
        'username': rocketChatBotUsername,
        'password': rocketChatBotPassword,
        'domain': rocketChatDomain
    })

app = Flask(__name__)
webhook = Webhook(app, secret=webhookSecret)


def notifyInboundSolutionFocusTicket(data):
    app.logger.info('Checking if event is suitible...')
    # Check we really want to notift about this post
    if data['action'] != 'created':
        app.logger.info('Action is not type created, ignoring')
        return
    app.logger.info('Generating message')
    sender = data['sender']['login']
Exemple #22
0
from rocketchat.api import RocketChatAPI
from pprint import pprint

api = RocketChatAPI(settings={
    'username': '******',
    'password': '******',
    'domain': 'http://localhost:3000'
})

api.send_message('message', 'bot')
Exemple #23
0
class SecBot:

    def __init__(self, name, domain, room, login, password):
        self.name = name
        self.login = login
        self.domain = domain
        self.password = password
        self.room = room
        self.room_id = ''
        self.api = None
        self.processed = []

        self.targets = {
            '192.168.1.1': {
                'comments': 'Router!',
                'services': {
                    '21': 'ftp',
                    '22': 'ssh',
                    '9989': 'http',
                }
            },
            '192.168.1.3': {
                'comments': '',
                'services': {
                    '80': 'http',
                }
            },
        }

        self.load_status()
        self.api = RocketChatAPI(settings={
            'username': self.login, 
            'password': self.password, 
            'domain': self.domain,
        })
        self.room_id = self.get_room_id('pentest-rdc')
    
    def read_messages(self):
        res = self.api.get_private_room_history(self.room_id)
        for r in res['messages']:
            yield r

    def post(self, message):
        self.api.send_message(message, self.room)

    def process_message(self, message):
        # {
        #     '_id': '9ota4D4ewkJpEmFBT', 
        #     'rid': 'TJf4aSR5Bo765XZk8', 
        #     'msg': 'Is Bob there?', 
        #     'ts': '2018-12-02T14:08:21.850Z', 
        #     'u': {
        #         '_id': 'Nd3f8bzCzSmWrLc32', 
        #         'username': '******', 
        #         'name': 'Tiao'
        #     }, 
        #     '_updatedAt': '2018-12-02T14:08:21.863Z', 
        #     'editedBy': None, 
        #     'editedAt': None, 
        #     'emoji': None, 
        #     'avatar': None, 
        #     'alias': None, 
        #     'customFields': None, 
        #     'groupable': None, 
        #     'attachments': None, 
        #     'reactions': None, 
        #     'mentions': [], 
        #     'channels': []
        # }


        # TODO: Process zenmap output
        # TODO: Allow users to book one IP for investigation
        # TODO: List non-investigated IPs
        # TODO: List ports for one IP
        # TODO: Propose tools commands to execute

        if message['_id'] not in self.processed and message['u']['username'] != self.login:
            print('Processing', message)


            if 'Bob' in message['msg']:
                s = message['u']['username']
                self.post('@%s, who is Bob?' % s)

            if '@secbot' in message['msg']:
                s = message['u']['username']

                if 'targets' in message['msg']:
                    print('listing targets')
                    msg = ''
                    ts = self.targets
                    for i in ts:
                        msg += i + ' ' + ts[i]['comments'] + '\n'
                        print('test')
                    self.post(msg)

        





            self.processed.append(message['_id'])








    def get_room_id(self, room):
        rooms = self.api.get_private_rooms()
        print(rooms)
        for r in rooms:
            if r['name'] == room:
                return r['id']
        return ''

    def load_status(self):
        with open('status.json', 'r') as f:
            data = json.load(f)
            self.processed = data['processed']
            print('Processed', self.processed)

    def save_status(self):
        data = {}
        data['processed'] = self.processed
        with open('status.json', 'w') as f:
            json.dump(data, f)

    def start(self):
        while 1:
            for m in self.read_messages():
                self.process_message(m)
            time.sleep(0.5)
from pprint import pprint
from rocketchat.api import RocketChatAPI
from rocketchat_API.rocketchat import RocketChat

api = RocketChatAPI(settings={'username': '******', 'password': '******',
                              'domain': 'https://chat.rgwit.be'})
#get information
api.get_my_info()

#send message to room
api.send_message('test', 'GENERAL')

#send dm
api.send_message('test', '@yongchin')

#
Exemple #25
0
from flask import request, jsonify
from plugins.db import db
from rocketchat.api import RocketChatAPI
import datetime

# make sure we read the .env file
load_dotenv(verbose=True)
ROCKET_CHAT_DOMAIN = os.getenv("ROCKET_CHAT_DOMAIN")
ROCKET_CHAT_USERNAME = os.getenv("ROCKET_CHAT_USERNAME")
ROCKET_CHAT_PASSWORD = os.getenv("ROCKET_CHAT_PASSWORD")
WEBHOOK_TOKEN = os.getenv("WEBHOOK_TOKEN")

# establish API link
api = RocketChatAPI(
    settings={
        'username': ROCKET_CHAT_USERNAME,
        'password': ROCKET_CHAT_PASSWORD,
        'domain': ROCKET_CHAT_DOMAIN
    })

app = Flask(__name__)


@app.route("/")
def hello():
    return "Hello!"


@app.route("/falcon/api/message", methods=['POST'])
def process_request():
    req = {
        'who': request.json['user_name'],