Completed
Pull Request — master (#472)
by Arma
02:19
created

PostMessageAction   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 36
Duplicated Lines 0 %
Metric Value
wmc 7
dl 0
loc 36
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
C run() 0 35 7
1
import json
2
import httplib
3
4
try:
5
    from six.moves.urllib.parse import urlencode
6
except ImportError:
7
    from urllib import urlencode
8
9
import requests
10
11
from st2actions.runners.pythonrunner import Action
12
13
__all__ = [
14
    'PostMessageAction'
15
]
16
17
18
class PostMessageAction(Action):
19
    def run(self, message, username=None, icon_emoji=None, channel=None,
20
            disable_formatting=False):
21
        config = self.config['post_message_action']
22
        username = username if username else config['username']
23
        icon_emoji = icon_emoji if icon_emoji else config.get('icon_emoji', None)
24
        channel = channel if channel else config.get('channel', None)
25
26
        headers = {}
27
        headers['Content-Type'] = 'application/x-www-form-urlencoded'
28
        body = {
29
            'username': username,
30
            'icon_emoji': icon_emoji,
31
            'text': message
32
        }
33
34
        if channel:
35
            body['channel'] = channel
36
37
        if disable_formatting:
38
            body['parse'] = 'none'
39
40
        data = {'payload': json.dumps(body)}
41
        data = urlencode(data)
42
        response = requests.post(url=config['webhook_url'],
43
                                 headers=headers, data=data)
44
45
        if response.status_code == httplib.OK:
46
            self.logger.info('Message successfully posted')
47
        else:
48
            failure_reason = ('Failed to post message: %s (status code: %s)' %
49
                              (response.text, response.status_code))
50
            self.logger.exception(failure_reason)
51
            raise Exception(failure_reason)
52
53
        return True
54