-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcow.py
80 lines (57 loc) · 2.22 KB
/
cow.py
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
"""Utility functions for cowsay/slack integration.
"""
import json
import random
from cowpy import cow
import requests
import settings
COW_OPTIONS = set(cow.cow_options())
def say(text, name='default'):
"""Return some cowsayed text."""
cowacter = cow.get_cow(name)()
return cowacter.milk(text)
def parse_cowacter(text):
"""Parse out the name from the start only if it's a valid cow name at
the start of the string with double dashes. Returns (name, text).
"""
name = 'default'
text = text.strip()
# parse out the name from the start only if it's a valid cow name
# at the start of the string with double dashes
if text.startswith('--'):
split = text.split(None, 1)
if len(split) > 1:
name_part, text_part = split
name_part = name_part.strip('-')
if name_part in COW_OPTIONS:
name = name_part
text = text_part
elif name_part == 'random':
name = random.choice(list(COW_OPTIONS))
text = text_part
return name, text
def post(text, url=settings.WEBHOOK_URL, channel=None, username=None):
"""Post the proper request to a url to integrate with slack."""
# if it starts with --help, have slackbot return a help message
# (and don't post anything to room)
if text.strip().startswith('--help'):
return help_text()
# use webhook to post message to room and return empty string
# so that slackbot doesn't say anything
else:
# parse optional cow name from text
cowacter, text = parse_cowacter(text)
payload = {
'text': '```%s\n\n```' % say(text, name=cowacter),
'icon_emoji': ':cow:',
}
if channel is not None:
payload['channel'] = channel
if username is not None:
payload['username'] = username
requests.post(url, data={'payload': json.dumps(payload)})
return ''
def help_text():
return """Moo. I am a cow that says things.
To choose your cowacter, start your message with --{cowacter} where {cowacter} is something from: %s
Or, if you are feeling adventurous, use --random to choose a random cowacter.""" % list(sorted(COW_OPTIONS))