
    Vh9Q                         d dl mZmZmZ eZdZdZd dlZd dl	m
Z
 d dlmZ d dlmZ dZd	Zd
ZdZdZdddZd Zd Zd Zd Zd Zd Zd Zedk(  r e        yy)    )absolute_importdivisionprint_functionai  
module: slack
short_description: Send Slack notifications
description:
  - The M(community.general.slack) module sends notifications to U(http://slack.com) using the Incoming WebHook integration.
author: "Ramon de la Fuente (@ramondelafuente)"
extends_documentation_fragment:
  - community.general.attributes
attributes:
  check_mode:
    support: full
  diff_mode:
    support: none
options:
  domain:
    type: str
    description:
      - Slack (sub)domain for your environment without protocol. (For example V(example.slack.com).) In Ansible 1.8 and beyond,
        this is deprecated and may be ignored. See token documentation for information.
  token:
    type: str
    description:
      - Slack integration token. This authenticates you to the slack service. Make sure to use the correct type of token,
        depending on what method you use.
      - 'Webhook token: Prior to Ansible 1.8, a token looked like V(3Ffe373sfhRE6y42Fg3rvf4GlK). In Ansible 1.8 and above,
        Ansible adapts to the new slack API where tokens look like V(G922VJP24/D921DW937/3Ffe373sfhRE6y42Fg3rvf4GlK). If tokens
        are in the new format then slack will ignore any value of domain. If the token is in the old format the domain is
        required. Ansible has no control of when slack will get rid of the old API. When slack does that the old format will
        stop working. ** Please keep in mind the tokens are not the API tokens but are the webhook tokens. In slack these
        are found in the webhook URL which are obtained under the apps and integrations. The incoming webhooks can be added
        in that area. In some cases this may be locked by your Slack admin and you must request access. It is there that the
        incoming webhooks can be added. The key is on the end of the URL given to you in that section.'
      - "WebAPI token: Slack WebAPI requires a personal, bot or work application token. These tokens start with V(xoxp-),
        V(xoxb-) or V(xoxa-), for example V(xoxb-1234-56789abcdefghijklmnop). WebAPI token is required if you intend to receive
        thread_id. See Slack's documentation (U(https://api.slack.com/docs/token-types)) for more information."
    required: true
  msg:
    type: str
    description:
      - Message to send. Note that the module does not handle escaping characters. Plain-text angle brackets and ampersands
        should be converted to HTML entities (for example C(&) to C(&amp;)) before sending. See Slack's documentation
        (U(https://api.slack.com/docs/message-formatting)) for more.
  channel:
    type: str
    description:
      - Channel to send the message to. If absent, the message goes to the channel selected for the O(token).
  thread_id:
    description:
      - Optional. Timestamp of parent message to thread this message, see U(https://api.slack.com/docs/message-threading).
    type: str
  message_id:
    description:
      - Optional. Message ID to edit, instead of posting a new message.
      - If supplied O(channel) must be in form of C(C0xxxxxxx). use C({{ slack_response.channel }}) to get RV(ignore:channel)
        from previous task run.
      - The token needs history scope to get information on the message to edit (C(channels:history,groups:history,mpim:history,im:history)).
      - Corresponds to C(ts) in the Slack API (U(https://api.slack.com/messaging/modifying)).
    type: str
    version_added: 1.2.0
  username:
    type: str
    description:
      - This is the sender of the message.
    default: "Ansible"
  icon_url:
    type: str
    description:
      - URL for the message sender's icon.
    default: https://docs.ansible.com/favicon.ico
  icon_emoji:
    type: str
    description:
      - Emoji for the message sender. See Slack documentation for options.
      - If O(icon_emoji) is set, O(icon_url) will not be used.
  link_names:
    type: int
    description:
      - Automatically create links for channels and usernames in O(msg).
    default: 1
    choices:
      - 1
      - 0
  parse:
    type: str
    description:
      - Setting for the message parser at Slack.
    choices:
      - 'full'
      - 'none'
  validate_certs:
    description:
      - If V(false), SSL certificates will not be validated. This should only be used on personally controlled sites using
        self-signed certificates.
    type: bool
    default: true
  color:
    type: str
    description:
      - Allow text to use default colors - use the default of V(normal) to not send a custom color bar at the start of the
        message.
      - Allowed values for color can be one of V(normal), V(good), V(warning), V(danger), any valid 3 digit or 6 digit hex
        color value.
    default: 'normal'
  attachments:
    type: list
    elements: dict
    description:
      - Define a list of attachments. This list mirrors the Slack JSON API.
      - For more information, see U(https://api.slack.com/docs/attachments).
  blocks:
    description:
      - Define a list of blocks. This list mirrors the Slack JSON API.
      - For more information, see U(https://api.slack.com/block-kit).
    type: list
    elements: dict
    version_added: 1.0.0
  prepend_hash:
    type: str
    description:
      - Setting for automatically prepending a V(#) symbol on the passed in O(channel).
      - The V(auto) method prepends a V(#) unless O(channel) starts with one of V(#), V(@), V(C0), V(GF), V(G0), V(CP). These
        prefixes only cover a small set of the prefixes that should not have a V(#) prepended. Since an exact condition which
        O(channel) values must not have the V(#) prefix is not known, the value V(auto) for this option will be deprecated
        in the future. It is best to explicitly set O(prepend_hash=always) or O(prepend_hash=never) to obtain the needed behavior.
      - The B(current default) is V(auto), which has been B(deprecated) since community.general 10.2.0. It will change to
        V(never) in community.general 12.0.0. To prevent deprecation warnings you can explicitly set O(prepend_hash) to the
        value you want. We suggest to only use V(always) or V(never), but not V(auto), when explicitly setting a value.
    choices:
      - 'always'
      - 'never'
      - 'auto'
    version_added: 6.1.0
a  
- name: Send notification message via Slack
  community.general.slack:
    token: thetoken/generatedby/slack
    msg: '{{ inventory_hostname }} completed'
  delegate_to: localhost

- name: Send notification message via Slack all options
  community.general.slack:
    token: thetoken/generatedby/slack
    msg: '{{ inventory_hostname }} completed'
    channel: '#ansible'
    thread_id: '1539917263.000100'
    username: 'Ansible on {{ inventory_hostname }}'
    icon_url: http://www.example.com/some-image-file.png
    link_names: 0
    parse: 'none'
  delegate_to: localhost

- name: Insert a color bar in front of the message for visibility purposes and use the default webhook icon and name configured
    in Slack
  community.general.slack:
    token: thetoken/generatedby/slack
    msg: '{{ inventory_hostname }} is alive!'
    color: good
    username: ''
    icon_url: ''

- name: Insert a color bar in front of the message with valid hex color value
  community.general.slack:
    token: thetoken/generatedby/slack
    msg: 'This message uses color in hex value'
    color: '#00aacc'
    username: ''
    icon_url: ''

- name: Use the attachments API
  community.general.slack:
    token: thetoken/generatedby/slack
    attachments:
      - text: Display my system load on host A and B
        color: '#ff00dd'
        title: System load
        fields:
          - title: System A
            value: "load average: 0,74, 0,66, 0,63"
            short: true
          - title: System B
            value: 'load average: 5,16, 4,64, 2,43'
            short: true

- name: Use the blocks API
  community.general.slack:
    token: thetoken/generatedby/slack
    blocks:
      - type: section
        text:
          type: mrkdwn
          text: |-
            *System load*
            Display my system load on host A and B
      - type: context
        elements:
          - type: mrkdwn
            text: |-
              *System A*
              load average: 0,74, 0,66, 0,63
          - type: mrkdwn
            text: |-
              *System B*
              load average: 5,16, 4,64, 2,43

- name: Send a message with a link using Slack markup
  community.general.slack:
    token: thetoken/generatedby/slack
    msg: We sent this message using <https://www.ansible.com|Ansible>!

- name: Send a message with angle brackets and ampersands
  community.general.slack:
    token: thetoken/generatedby/slack
    msg: This message has &lt;brackets&gt; &amp; ampersands in plain text.

- name: Initial Threaded Slack message
  community.general.slack:
    channel: '#ansible'
    token: xoxb-1234-56789abcdefghijklmnop
    msg: 'Starting a thread with my initial post.'
  register: slack_response
- name: Add more info to thread
  community.general.slack:
    channel: '#ansible'
    token: xoxb-1234-56789abcdefghijklmnop
    thread_id: "{{ slack_response['ts'] }}"
    color: good
    msg: 'And this is my threaded response!'

- name: Send a message to be edited later on
  community.general.slack:
    token: thetoken/generatedby/slack
    channel: '#ansible'
    msg: Deploying something...
  register: slack_response
- name: Edit message
  community.general.slack:
    token: thetoken/generatedby/slack
    # The 'channel' option does not accept the channel name. It must use the 'channel_id',
    # which can be retrieved for example from 'slack_response' from the previous task.
    channel: "{{ slack_response.channel }}"
    msg: Deployment complete!
    message_id: "{{ slack_response.ts }}"
N)AnsibleModule)	urlencode)	fetch_urlz3https://%s/services/hooks/incoming-webhook?token=%sz#https://hooks.slack.com/services/%sz&https://slack.com/api/chat.postMessagez!https://slack.com/api/chat.updatez+https://slack.com/api/conversations.history"')r	   r
   c                 2    t        j                  d|       ryy)Nz"^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$TF)rematch)color_choices    k/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/general/plugins/modules/slack.pyis_valid_hex_colorr     s    	xx5|D    c                 2    dj                  d | D              S )z!Backslash any quotes within text. c              3   H   K   | ]  }t         j                  ||        y w)N)escape_tableget).0cs     r   	<genexpr>z escape_quotes.<locals>.<genexpr>#  s     8a<##Aq)8s    ")jointexts    r   escape_quotesr   !  s    7784888r   c                 &   t        | t              rNi }| j                         D ]7  \  }}t        |t              r||v rt	        |      ||<   )t        ||      ||<   9 |S t        | t              r| D cg c]  }t        ||       }}|S | }|S c c}w )zGRecursively escape quotes inside supplied keys inside block kit objects)
isinstancedictitemsstrr   recursive_escape_quoteslist)objkeysescapedkvs        r   r#   r#   &  s    #tIIK 	>DAq!S!a4i*1-
4Q=
		> N	 
C	=@A*1d3AA N N Bs   3Bc                 @   i }|dk(  r| t        t        |             }n%| #t        t        t        |       |dg      g      }|=|dk(  r |j                  d      r||d<   n!d	|z   |d<   n|d
k(  r	d	|z   |d<   n
|dk(  r||d<   |||d<   |||d<   |||d<   n||d<   |||d<   |||d<   |||d<   |		d|vrg |d<   |	Hg d}|	D ]?  }|D ]  }||v st        ||         ||<    d|vr|d   |d<   |d   j                  |       A |
ddg}t	        |
|      |d<   |S )Nnormalr   r   )r   color	mrkdwn_in)attachmentsauto)#@C0GFG0CPchannelr0   alwaysnever	thread_tsusername
icon_emojiicon_url
link_namesparsetsr.   )titler   author_namepretextfallbackrC   alt_textblocks)r    r   
startswithappendr#   )r   r6   	thread_idr:   r<   r;   r=   r>   r,   r.   rE   
message_idprepend_hashpayloadattachment_keys_to_escape
attachmentkeyblock_keys_to_escapes                     r   build_payload_for_slackrP   6  s   GT-M$/0		DmD.A[aZb$c#de6!!!"DE%,	"%(7]	"X%!$wGIW$!(GI(&
 *&
 * "'%'GM"%
! & 	6J0 E*$&3JsO&DJsOE +)3F);
:&M"))*5	6  
 4F<PQNr   c                    ddd|z   d}t        ||ddd      }t        dz   |z   }t        | ||d	
      \  }}|d   dk7  r| j                  d       | j	                  |j                               }	|	j                  d      du r| j                  d|	z         t        |	d         dk  r| j                  d|z         t        |	d         dkD  r| j                  d|z         |	d   d   S )Napplication/json; charset=UTF-8application/jsonBearer )Content-TypeAcceptAuthorization   true)r6   r?   limit	inclusive?GET)moduleurlheadersmethodstatus   zfailed to get slack messagemsgokFzfailed to get slack message: %smessageszno messages matching ts: %sz#more than 1 message matching ts: %sr   )r   "SLACK_CONVERSATIONS_HISTORY_WEBAPIr   	fail_json	from_jsonreadr   len)
r^   tokenr6   r?   r`   qsr_   responseinfodatas
             r   get_slack_messagerr   w  s   9$"U*G
 
	 
B -s
2R
7Cf#wuUNHdH~:;HMMO,Dxx~>EF
4
q :R?@
4
q BRGH
Ar   c           	         d}|j                  d      dk\  r
t        |z  }nHt        j                  d|      rd|v rt        nt
        }d}n|s| j                  d       t        ||fz  }d	d
d}|rd|z   |d<   | j                  |      }t        | ||d|      \  }}	|	d   dk7  r,|r|}
n	t        dz  }
| j                  d|d|
d|	d          |r| j                  |j                               S ddiS )NF/   z^xox[abp]-\S+$r?   TzkSlack has updated its webhook API.  You need to specify a token of the form XXXX/YYYY/ZZZZ in your playbookrd   rR   rS   )rU   rV   rT   rW   POST)r^   r_   r`   ra   rq   rb   rc   z
[obscured]z failed to send z to z: re   webhookrf   )countSLACK_INCOMING_WEBHOOKr   r   SLACK_UPDATEMESSAGE_WEBAPISLACK_POSTMESSAGE_WEBAPIri   OLD_SLACK_INCOMING_WEBHOOKjsonifyr   rj   rk   )r^   domainrm   rK   
use_webapi	slack_urir`   rq   ro   rp   obscured_incoming_webhooks              r   do_notify_slackr     s   J{{31*U2		#U	+26'/.G_	
 "C D.&%@	 :$G #,u#4 >>'"Df)WU[bfgNHdH~(1%(>(M%tE^`dej`klm 004  r   c                  b   t        t        d:i dt        d      dt        ddd      dt        d      dt        d      d	t        d      d
t        dd      dt        dd      dt        d      dt        ddddg      dt        dddg      dt        dd      dt        dd      dt        dd !      d"t        dd !      d#t        d      d$t        dg d%      d&      } | j                  d   }| j                  d   }| j                  d   }| j                  d   }| j                  d	   }| j                  d
   }| j                  d   }| j                  d   }| j                  d   }	| j                  d   }
| j                  d   }| j                  d   }| j                  d"   }| j                  d#   }| j                  d$   }|| j                  d'd(d)*       d+}g d,}||vr t	        |      s| j                  d-|z  .       d}|qd/}t        | |||      }d0D ]3  }|j                  |      | j                  j                  |      k7  s1d} n | j                  s|s9| j                  ||d1   |d   2       n| j                  r| j                  |3       t        |||||||	|
|||||      }t        | |||      }d4|v rJ|d4   r.| j                  |      }| j                  ||d1   |d   ||5       y | j                  d6|d7   8       y | j                  d9.       y );Nr~   r"   )typerm   T)r   requiredno_logre   r6   rH   r:   Ansible)r   defaultr<   z$https://docs.ansible.com/favicon.icor;   r=   intrX   r   )r   r   choicesr>   nonefull)r   r   validate_certsbool)r   r   r,   r+   r.   r$   r    )r   elementsrE   rI   rJ   )r7   r8   r/   )argument_specsupports_check_modezThe default value 'auto' for 'prepend_hash' is deprecated and will change to 'never' in community.general 12.0.0. You can explicitly set 'prepend_hash' in your task to avoid this deprecation warningz12.0.0zcommunity.general)versioncollection_namer/   )r+   goodwarningdangerz[Color value specified should be either one of %r or any valid hex value with length 3 or 6.rd   F)r<   r;   r=   r,   r.   rE   r?   )changedr?   r6   )r   rf   )r   r?   r6   apirK   zSlack API errorerror)re   r   OK )r   r    params	deprecater   ri   rr   r   
check_mode	exit_jsonrP   r   r}   )r^   r~   rm   r   r6   rH   r:   r<   r;   r=   r>   r,   r.   rE   rI   rJ   color_choicesr   re   rN   rK   slack_responsepayload_jsons                          r   mainr     s    
U#
ED>
 % 
 e$	

 &
 ui8
 u.TU
 '
 Aq6B
 EFF+;<
  6:
 E84
 &6:
 Vf5
 '
  52MN!
$ !'F, ]]8$FMM'"E==DmmI&Gk*I}}Z(H}}Z(H|,J|,JMM'"EMM'"E--.K]]8$F|,J==0Ld/	 	 	
 ;MM!*<U*C JLYZ 	[ G w
C] 	Cwws|v}}0055	 GWTC	NS			)%dGY(T^`j&+UKUacG$VVUGDN~$!>>'2LW1E~^gOh!/  G !2.:QR 	T"r   __main__)
__future__r   r   r   r   __metaclass__DOCUMENTATIONEXAMPLESr   ansible.module_utils.basicr   +ansible.module_utils.six.moves.urllib.parser   ansible.module_utils.urlsr   r|   ry   r{   rz   rh   r   r   r   r#   rP   rr   r   r   __name__r   r   r   <module>r      s    A @DLn` 
 4 A /R > C @ %R "
 
	9
 >B4#!LV#r zF r   