summaryrefslogtreecommitdiffstats
path: root/ansible_collections/community/general/plugins/modules/nexmo.py
blob: 39f127f98c0766f27d44f95a75be182d14974d65 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
#!/usr/bin/python
# -*- coding: utf-8 -*-

# Copyright (c) 2014, Matt Martz <matt@sivel.net>
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later

from __future__ import absolute_import, division, print_function
__metaclass__ = type


DOCUMENTATION = '''
module: nexmo
short_description: Send a SMS via nexmo
description:
    - Send a SMS message via nexmo
author: "Matt Martz (@sivel)"
attributes:
  check_mode:
    support: none
  diff_mode:
    support: none
options:
  api_key:
    type: str
    description:
      - Nexmo API Key
    required: true
  api_secret:
    type: str
    description:
      - Nexmo API Secret
    required: true
  src:
    type: int
    description:
       - Nexmo Number to send from
    required: true
  dest:
    type: list
    elements: int
    description:
      - Phone number(s) to send SMS message to
    required: true
  msg:
    type: str
    description:
      - Message to text to send. Messages longer than 160 characters will be
        split into multiple messages
    required: true
  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
extends_documentation_fragment:
  - ansible.builtin.url
  - community.general.attributes
'''

EXAMPLES = """
- name: Send notification message via Nexmo
  community.general.nexmo:
    api_key: 640c8a53
    api_secret: 0ce239a6
    src: 12345678901
    dest:
      - 10987654321
      - 16789012345
    msg: '{{ inventory_hostname }} completed'
  delegate_to: localhost
"""
import json

from ansible.module_utils.six.moves.urllib.parse import urlencode
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.urls import fetch_url, url_argument_spec


NEXMO_API = 'https://rest.nexmo.com/sms/json'


def send_msg(module):
    failed = list()
    responses = dict()
    msg = {
        'api_key': module.params.get('api_key'),
        'api_secret': module.params.get('api_secret'),
        'from': module.params.get('src'),
        'text': module.params.get('msg')
    }
    for number in module.params.get('dest'):
        msg['to'] = number
        url = "%s?%s" % (NEXMO_API, urlencode(msg))

        headers = dict(Accept='application/json')
        response, info = fetch_url(module, url, headers=headers)
        if info['status'] != 200:
            failed.append(number)
            responses[number] = dict(failed=True)

        try:
            responses[number] = json.load(response)
        except Exception:
            failed.append(number)
            responses[number] = dict(failed=True)
        else:
            for message in responses[number]['messages']:
                if int(message['status']) != 0:
                    failed.append(number)
                    responses[number] = dict(failed=True, **responses[number])

        if failed:
            msg = 'One or messages failed to send'
        else:
            msg = ''

        module.exit_json(failed=bool(failed), msg=msg, changed=False,
                         responses=responses)


def main():
    argument_spec = url_argument_spec()
    argument_spec.update(
        dict(
            api_key=dict(required=True, no_log=True),
            api_secret=dict(required=True, no_log=True),
            src=dict(required=True, type='int'),
            dest=dict(required=True, type='list', elements='int'),
            msg=dict(required=True),
        ),
    )

    module = AnsibleModule(
        argument_spec=argument_spec
    )

    send_msg(module)


if __name__ == '__main__':
    main()