class SaltTelegram(BotPlugin): # pylint: disable=too-many-ancestors """ Basic Telegram bot for remote shell commands execution using SaltStack """ @botcmd def minions(self, msg, args): """ Returns list of avaliable saltmaster minions """ configuration = self.bot_config api_response = MinionsRequest(configuration).request() client_response = MinionsResponse(api_response).response() self.send(msg.frm, client_response) @botcmd(split_args_with=ShlexArgParser()) def glob(self, msg, args): """ Executes command using glob target and returns its output """ configuration = self.bot_config api_response = GlobRequest(configuration).request(args) client_response = GlobResponse(api_response).response(args) self.send(msg.frm, client_response) @botcmd(split_args_with=ShlexArgParser()) def grain(self, msg, args): """ Executes command using grain target and returns its output """ configuration = self.bot_config api_response = GrainRequest(configuration).request(args) client_response = GrainResponse(api_response).response(args) self.send(msg.frm, client_response)
class ChatRoom(BotPlugin): connected = False def callback_connect(self): self.log.info('Callback_connect') if not self.connected: self.connected = True for room in self.bot_config.CHATROOM_PRESENCE: self.log.debug('Try to join room %s' % repr(room)) try: self._join_room(room) except Exception: # Ensure failure to join a room doesn't crash the plugin # as a whole. self.log.exception("Joining room %s failed", repr(room)) def _join_room(self, room): if isinstance(room, (tuple, list)): room_name = compat_str(room[0]) room_password = compat_str(room[1]) room, username, password = (room_name, self.bot_config.CHATROOM_FN, room_password) self.log.info( "Joining room {} with username {} and password".format( room, username)) else: room_name = compat_str(room) room, username, password = (room_name, self.bot_config.CHATROOM_FN, None) self.log.info("Joining room {} with username {}".format( room, username)) self.query_room(room).join(username=self.bot_config.CHATROOM_FN, password=password) def deactivate(self): self.connected = False super().deactivate() @botcmd(split_args_with=SeparatorArgParser()) def room_create(self, message, args): """ Create a chatroom. Usage: !room create <room> Examples (XMPP): !room create [email protected] Examples (IRC): !room create #example-room """ if len(args) < 1: return "Please tell me which chatroom to create." room = self.query_room(args[0]) room.create() return "Created the room {}".format(room) @botcmd() def room_join(self, message, args): """ Join (creating it first if needed) a chatroom. Usage: !room join <room> [<password>] Examples (XMPP): !room join [email protected] !room join [email protected] super-secret-password Examples (IRC): !room join #example-room !room join #example-room super-secret-password """ # We must account for password with whitespace before, after or in the middle args = args.split(' ', 1) arglen = len(args) if arglen < 1: return "Please tell me which chatroom to join." args[0].strip() room, password = (args[0], None) if arglen == 1 else (args[0], args[1]) self.query_room(room).join(username=self.bot_config.CHATROOM_FN, password=password) return "Joined the room {}".format(room) @botcmd(split_args_with=SeparatorArgParser()) def room_leave(self, message, args): """ Leave a chatroom. Usage: !room leave <room> Examples (XMPP): !room leave [email protected] Examples (IRC): !room leave #example-room """ if len(args) < 1: return "Please tell me which chatroom to leave." self.query_room(args[0]).leave() return "Left the room {}".format(args[0]) @botcmd(split_args_with=SeparatorArgParser()) def room_destroy(self, message, args): """ Destroy a chatroom. Usage: !room destroy <room> Examples (XMPP): !room destroy [email protected] Examples (IRC): !room destroy #example-room """ if len(args) < 1: return "Please tell me which chatroom to destroy." self.query_room(args[0]).destroy() return "Destroyed the room {}".format(args[0]) @botcmd(split_args_with=SeparatorArgParser()) def room_invite(self, message, args): """ Invite one or more people into a chatroom. Usage: !room invite <room> <identifier1> [<identifier2>, ..] Examples (XMPP): !room invite [email protected] [email protected] Examples (IRC): !room invite #example-room bob """ if len(args) < 2: return "Please tell me which person(s) to invite into which room." self.query_room(args[0]).invite(*args[1:]) return "Invited {} into the room {}".format(", ".join(args[1:]), args[0]) @botcmd def room_list(self, message, args): """ List chatrooms the bot has joined. Usage: !room list Examples: !room list """ rooms = [str(room) for room in self.rooms()] if len(rooms): return "I'm currently in these rooms:\n\t{}".format( "\n\t".join(rooms)) else: return "I'm not currently in any rooms." @botcmd(split_args_with=ShlexArgParser()) def room_occupants(self, message, args): """ List the occupants in a given chatroom. Usage: !room occupants <room 1> [<room 2> ..] Examples (XMPP): !room occupants [email protected] Examples (IRC): !room occupants #example-room #another-example-room """ if len(args) < 1: yield "Please supply a room to list the occupants of." return for room in args: try: occupants = [o.person for o in self.query_room(room).occupants] yield "Occupants in {}:\n\t{}".format(room, "\n\t".join(occupants)) except RoomNotJoinedError as e: yield "Cannot list occupants in {}: {}".format(room, e) @botcmd(split_args_with=ShlexArgParser()) def room_topic(self, message, args): """ Get or set the topic for a room. Usage: !room topic <room> [<new topic>] Examples (XMPP): !room topic [email protected] !room topic [email protected] "Err rocks!" Examples (IRC): !room topic #example-room !room topic #example-room "Err rocks!" """ arglen = len(args) if arglen < 1: return "Please tell me which chatroom you want to know the topic of." if arglen == 1: try: topic = self.query_room(args[0]).topic except RoomNotJoinedError as e: return "Cannot get the topic for {}: {}".format(args[0], e) if topic is None: return "No topic is set for {}".format(args[0]) else: return "Topic for {}: {}".format(args[0], topic) else: try: self.query_room(args[0]).topic = args[1] except RoomNotJoinedError as e: return "Cannot set the topic for {}: {}".format(args[0], e) return "Topic for {} set.".format(args[0]) def callback_message(self, mess): try: if mess.is_direct: username = mess.frm.person if username in self.bot_config.CHATROOM_RELAY: self.log.debug('Message to relay from %s.' % username) body = mess.body rooms = self.bot_config.CHATROOM_RELAY[username] for roomstr in rooms: room = self.room_join(roomstr) self.send(room, body) elif mess.is_group: fr = mess.frm chat_room = str(fr.room) if chat_room in self.bot_config.REVERSE_CHATROOM_RELAY: users_to_relay_to = self.bot_config.REVERSE_CHATROOM_RELAY[ chat_room] self.log.debug('Message to relay to %s.' % users_to_relay_to) body = '[%s] %s' % (fr.person, mess.body) for user in users_to_relay_to: self.send(user, body) except Exception as e: self.log.exception('crashed in callback_message %s' % e)
class ChatRoom(BotPlugin): connected = False def callback_connect(self): self.log.info('Connecting bot chatrooms') if not self.connected: self.connected = True for room in self.bot_config.CHATROOM_PRESENCE: self.log.debug('Try to join room %s', repr(room)) try: self._join_room(room) except Exception: # Ensure failure to join a room doesn't crash the plugin # as a whole. self.log.exception(f'Joining room {repr(room)} failed') def _join_room(self, room): username = self.bot_config.CHATROOM_FN password = None if isinstance(room, (tuple, list)): room, password = room # unpack self.log.info('Joining room %s with username %s and pass ***.', room, username) else: self.log.info('Joining room %s with username %s.', room, username) self.query_room(room).join(username=self.bot_config.CHATROOM_FN, password=password) def deactivate(self): self.connected = False super().deactivate() @botcmd(split_args_with=SeparatorArgParser()) def room_create(self, message, args): """ Create a chatroom. Usage: !room create <room> Examples (XMPP): !room create [email protected] Examples (IRC): !room create #example-room """ if len(args) < 1: return "Please tell me which chatroom to create." room = self.query_room(args[0]) room.create() return f'Created the room {room}.' @botcmd(split_args_with=ShlexArgParser()) def room_join(self, message, args): """ Join (creating it first if needed) a chatroom. Usage: !room join <room> [<password>] Examples (XMPP): !room join [email protected] !room join [email protected] super-secret-password Examples (IRC): !room join #example-room !room join #example-room super-secret-password !room join #example-room "password with spaces" """ arglen = len(args) if arglen < 1: return "Please tell me which chatroom to join." args[0].strip() room_name, password = (args[0], None) if arglen == 1 else (args[0], args[1]) room = self.query_room(room_name) if room is None: return f'Cannot find room {room_name}.' room.join(username=self.bot_config.CHATROOM_FN, password=password) return f'Joined the room {room_name}.' @botcmd(split_args_with=SeparatorArgParser()) def room_leave(self, message, args): """ Leave a chatroom. Usage: !room leave <room> Examples (XMPP): !room leave [email protected] Examples (IRC): !room leave #example-room """ if len(args) < 1: return 'Please tell me which chatroom to leave.' self.query_room(args[0]).leave() return f'Left the room {args[0]}.' @botcmd(split_args_with=SeparatorArgParser()) def room_destroy(self, message, args): """ Destroy a chatroom. Usage: !room destroy <room> Examples (XMPP): !room destroy [email protected] Examples (IRC): !room destroy #example-room """ if len(args) < 1: return "Please tell me which chatroom to destroy." self.query_room(args[0]).destroy() return f'Destroyed the room {args[0]}.' @botcmd(split_args_with=SeparatorArgParser()) def room_invite(self, message, args): """ Invite one or more people into a chatroom. Usage: !room invite <room> <identifier1> [<identifier2>, ..] Examples (XMPP): !room invite [email protected] [email protected] Examples (IRC): !room invite #example-room bob """ if len(args) < 2: return 'Please tell me which person(s) to invite into which room.' self.query_room(args[0]).invite(*args[1:]) return f'Invited {", ".join(args[1:])} into the room {args[0]}.' @botcmd def room_list(self, message, args): """ List chatrooms the bot has joined. Usage: !room list Examples: !room list """ rooms = [str(room) for room in self.rooms()] if len(rooms): rooms_str = '\n\t'.join(rooms) return f"I'm currently in these rooms:\n\t{rooms_str}" else: return "I'm not currently in any rooms." @botcmd(split_args_with=ShlexArgParser()) def room_occupants(self, message, args): """ List the occupants in a given chatroom. Usage: !room occupants <room 1> [<room 2> ..] Examples (XMPP): !room occupants [email protected] Examples (IRC): !room occupants #example-room #another-example-room """ if len(args) < 1: yield "Please supply a room to list the occupants of." return for room in args: try: occupants = [o.person for o in self.query_room(room).occupants] occupants_str = "\n\t".join(occupants) yield f'Occupants in {room}:\n\t{occupants_str}.' except RoomNotJoinedError as e: yield f'Cannot list occupants in {room}: {e}.' @botcmd(split_args_with=ShlexArgParser()) def room_topic(self, message, args): """ Get or set the topic for a room. Usage: !room topic <room> [<new topic>] Examples (XMPP): !room topic [email protected] !room topic [email protected] "Err rocks!" Examples (IRC): !room topic #example-room !room topic #example-room "Err rocks!" """ arglen = len(args) if arglen < 1: return "Please tell me which chatroom you want to know the topic of." if arglen == 1: try: topic = self.query_room(args[0]).topic except RoomNotJoinedError as e: return f'Cannot get the topic for {args[0]}: {e}.' if topic is None: return f'No topic is set for {args[0]}.' else: return f'Topic for {args[0]}: {topic}.' else: try: self.query_room(args[0]).topic = args[1] except RoomNotJoinedError as e: return f'Cannot set the topic for {args[0]}: {e}.' return f"Topic for {args[0]} set." def callback_message(self, msg): try: if msg.is_direct: username = msg.frm.person if username in self.bot_config.CHATROOM_RELAY: self.log.debug('Message to relay from %s.', username) body = msg.body rooms = self.bot_config.CHATROOM_RELAY[username] for roomstr in rooms: self.send(self.query_room(roomstr), body) elif msg.is_group: fr = msg.frm chat_room = str(fr.room) if chat_room in self.bot_config.REVERSE_CHATROOM_RELAY: users_to_relay_to = self.bot_config.REVERSE_CHATROOM_RELAY[chat_room] self.log.debug('Message to relay to %s.', users_to_relay_to) body = f'[{fr.person}] {msg.body}' for user in users_to_relay_to: self.send(user, body) except Exception as e: self.log.exception(f'crashed in callback_message {e}')
class ChatRoom(BotPlugin): min_err_version = VERSION # don't copy paste that for your plugin, it is just because it is a bundled plugin ! max_err_version = VERSION connected = False def callback_connect(self): log.info('Callback_connect') if not self.connected: self.connected = True for room in self.bot_config.CHATROOM_PRESENCE: if isinstance(room, basestring): room, username, password = (room, self.bot_config.CHATROOM_FN, None) else: room, username, password = (room[0], self.bot_config.CHATROOM_FN, room[1]) log.info("Joining room {} with username {}".format( room, username)) try: self.query_room(room).join( username=self.bot_config.CHATROOM_FN, password=password) except NotImplementedError: # Backward compatibility for backends which do not yet have a # query_room implementation and still have a join_room method. logging.warning( "query_room not implemented on this backend, using legacy join_room instead" ) self.join_room(room, username=username, password=password) def deactivate(self): self.connected = False super(ChatRoom, self).deactivate() @botcmd(split_args_with=SeparatorArgParser()) def room_create(self, message, args): """ Create a chatroom. Usage: !room create <room> Examples (XMPP): !room create [email protected] Examples (IRC): !room create #example-room Example (TOX): (no room name at creation) !room create """ if self.mode == 'tox': if len(args) != 0: return "You cannot specify a chatgroup name on TOX." room = self.query_room(None) else: if len(args) < 1: return "Please tell me which chatroom to create." room = self.query_room(args[0]) room.create() return "Created the room {}".format(room) @botcmd() def room_join(self, message, args): """ Join (creating it first if needed) a chatroom. Usage: !room join <room> [<password>] Examples (XMPP): !room join [email protected] !room join [email protected] super-secret-password Examples (IRC): !room join #example-room !room join #example-room super-secret-password """ # We must account for password with whitespace before, after or in the middle args = args.split(' ', 1) arglen = len(args) if arglen < 1: return "Please tell me which chatroom to join." args[0].strip() room, password = (args[0], None) if arglen == 1 else (args[0], args[1]) self.query_room(room).join(username=self.bot_config.CHATROOM_FN, password=password) return "Joined the room {}".format(room) @botcmd(split_args_with=SeparatorArgParser()) def room_leave(self, message, args): """ Leave a chatroom. Usage: !room leave <room> Examples (XMPP): !room leave [email protected] Examples (IRC): !room leave #example-room """ if len(args) < 1: return "Please tell me which chatroom to leave." self.query_room(args[0]).leave() return "Left the room {}".format(args[0]) @botcmd(split_args_with=SeparatorArgParser()) def room_destroy(self, message, args): """ Destroy a chatroom. Usage: !room destroy <room> Examples (XMPP): !room destroy [email protected] Examples (IRC): !room destroy #example-room """ if len(args) < 1: return "Please tell me which chatroom to destroy." self.query_room(args[0]).destroy() return "Destroyed the room {}".format(args[0]) @botcmd(split_args_with=SeparatorArgParser()) def room_invite(self, message, args): """ Invite one or more people into a chatroom. Usage: !room invite <room> <jid 1> [<jid2>, ..] Examples (XMPP): !room invite [email protected] [email protected] Examples (IRC): !room invite #example-room bob """ if len(args) < 2: return "Please tell me which person(s) to invite into which room." self.query_room(args[0]).invite(*args[1:]) return "Invited {} into the room {}".format(", ".join(args[1:]), args[0]) @botcmd def room_list(self, message, args): """ List chatrooms the bot has joined. Usage: !room list Examples: !room list """ rooms = [str(room) for room in self.rooms()] if len(rooms): return "I'm currently in these rooms:\n\t{}".format( "\n\t".join(rooms)) else: return "I'm not currently in any rooms." @botcmd(split_args_with=ShlexArgParser()) def room_occupants(self, message, args): """ List the occupants in a given chatroom. Usage: !room occupants <room 1> [<room 2> ..] Examples (XMPP): !room occupants [email protected] Examples (IRC): !room occupants #example-room #another-example-room """ if len(args) < 1: yield "Please supply a room to list the occupants of." return for room in args: try: occupants = [str(o) for o in self.query_room(room).occupants] yield "Occupants in {}:\n\t{}".format(room, "\n\t".join(occupants)) except RoomNotJoinedError as e: yield "Cannot list occupants in {}: {}".format(room, e) @botcmd(split_args_with=ShlexArgParser()) def room_topic(self, message, args): """ Get or set the topic for a room. Usage: !room topic <room> [<new topic>] Examples (XMPP): !room topic [email protected] !room topic [email protected] "Err rocks!" Examples (IRC): !room topic #example-room !room topic #example-room "Err rocks!" """ arglen = len(args) if arglen < 1: return "Please tell me which chatroom you want to know the topic of." if arglen == 1: try: topic = self.query_room(args[0]).topic except RoomNotJoinedError as e: return "Cannot get the topic for {}: {}".format(args[0], e) if topic is None: return "No topic is set for {}".format(args[0]) else: return "Topic for {}: {}".format(args[0], topic) else: try: self.query_room(args[0]).topic = args[1] except RoomNotJoinedError as e: return "Cannot set the topic for {}: {}".format(args[0], e) return "Topic for {} set.".format(args[0]) @botcmd def gtalk_room_create(self, mess, args): """ Create an adhoc chatroom for Google talk and invite the listed persons. If no person is listed, only the requestor is invited. Examples: !root create !root create [email protected] [email protected] """ room_name = "*****@*****.**" % uuid4() self.join_room(room_name) to_invite = (mess.frm.stripped, ) if not args else ( jid.strip() for jid in args.split()) self.invite_in_room(room_name, to_invite) return "Room created (%s)" % room_name def callback_message(self, mess): if bot.mode != 'campfire': # no relay support in campfire try: mess_type = mess.type if mess_type == 'chat': username = mess.frm.node if username in self.bot_config.CHATROOM_RELAY: log.debug('Message to relay from %s.' % username) body = mess.body rooms = self.bot_config.CHATROOM_RELAY[username] for room in rooms: self.send(room, body, message_type='groupchat') elif mess_type == 'groupchat': fr = mess.frm chat_room = fr.node + '@' + fr.domain if fr.domain else fr.node if chat_room in self.bot_config.REVERSE_CHATROOM_RELAY: users_to_relay_to = self.bot_config.REVERSE_CHATROOM_RELAY[ chat_room] log.debug('Message to relay to %s.' % users_to_relay_to) body = '[%s] %s' % (fr.resource, mess.body) for user in users_to_relay_to: self.send(user, body) except Exception as e: log.exception('crashed in callback_message %s' % e)
class Salt(BotPlugin): """Plugin to run salt commands on hosts""" def get_configuration_template(self): """ configuration entries """ config = { 'paste_api_url': None, 'api_url': None, 'api_user': None, 'api_pass': None, 'api_auth': None, } return config def pastebin(self, data): ''' Post the output to pastebin ''' clean_data = data url = requests.post( self.config['paste_api_url'], data={ 'content': clean_data, }, ) log.debug('url: {}'.format(url)) return url.text.strip('"') @botcmd def salt(self, msg, args): ''' executes a salt command on systems example: !salt log*.local cmd.run 'cat /etc/hosts' !salt log*.local test.ping ''' parser = OptionParser() (options, args) = parser.parse_args(shlex.split(args)) if len(args) < 2: response = '2 parameters required. see !help salt' self.send(msg.frm, response, message_type=msg.type, in_reply_to=msg, groupchat_nick_reply=True) return targets = args.pop(0) action = args.pop(0) api = pepper.Pepper(self.config['api_url'], debug_http=False) auth = api.login(self.config['api_user'], self.config['api_pass'], self.config['api_auth']) ret = api.local(targets, action, arg=args, kwarg=None, expr_form='pcre') results = json.dumps(ret, sort_keys=True, indent=4) self.send(msg.frm, self.pastebin(results), message_type=msg.type, in_reply_to=msg, groupchat_nick_reply=True) @botcmd(split_args_with=ShlexArgParser()) def salt_grains(self, msg, args): ''' executes a salt command on systems example: !salt grains 'os:Centos' cmd.run 'cat /etc/hosts' ''' if len(args) < 2: response = '2 parameters required. see !help salt' self.send(msg.frm, response, message_type=msg.type, in_reply_to=msg, groupchat_nick_reply=True) return targets = args.pop(0) action = args.pop(0) api = pepper.Pepper(self.config['api_url'], debug_http=False) auth = api.login(self.config['api_user'], self.config['api_pass'], self.config['api_auth']) ret = api.local(targets, action, arg=args, kwarg=None, expr_form='grain') results = json.dumps(ret, sort_keys=True, indent=4) self.send(msg.frm, self.pastebin(results), message_type=msg.type, in_reply_to=msg, groupchat_nick_reply=True)