]> git.somenet.org - pub/jan/mattermost-api-python.git/blob - mattermost/stdin2channel.py
README.md
[pub/jan/mattermost-api-python.git] / mattermost / stdin2channel.py
1 #!/usr/bin/env python3
2 """
3 Someone's Mattermost API v4 bindings.
4   Copyright (c) 2016-2021 by Someone <someone@somenet.org> (aka. Jan Vales <jan@jvales.net>)
5   published under MIT-License
6
7 post stdin to a channel.
8 """
9
10 import os
11 import sys
12
13 from inspect import cleandoc
14
15 import mattermost
16
17
18 def main():
19     show_usage = False
20     mm_api = None
21     chan_id = None
22
23     if "MM_APIURL" in os.environ:
24         mm_api = mattermost.MMApi(os.environ["MM_APIURL"])
25     else:
26         show_usage = True
27
28
29     if ("MM_USER" in os.environ and "MM_PASS" in os.environ) or ("MM_BEARER" in os.environ):
30         if "MM_BEARER" in os.environ:
31             mm_api.login(bearer=os.environ["MM_BEARER"])
32         else:
33             mm_api.login(os.environ["MM_USER"], os.environ["MM_PASS"])
34     else:
35         show_usage = True
36
37
38     if "MM_CHANID" in os.environ:
39         chan_id = os.environ["MM_CHANID"]
40     else:
41         show_usage = True
42
43
44     if len(sys.argv) < 1 or len(sys.argv) > 3:
45         show_usage = True
46
47
48     if show_usage:
49         print(cleandoc("""required ENV-parameters: MM_APIURL, MM_USER+MM_PASS or MM_BEARER, MM_CHANID.
50             arguments: [PREFIX] [SUFFIX]
51             """))
52         sys.exit(1)
53
54
55     prefix = suffix = ""
56     try:
57         prefix = sys.argv[1].replace("\\n", "\n")
58         suffix = sys.argv[2].replace("\\n", "\n")
59     except:
60         pass
61
62     print("Posting to channel:" +str(mm_api.create_post(chan_id, prefix+sys.stdin.read()+suffix, props={"from_webhook":"true"})))
63
64     mm_api.logout()
65
66
67 if __name__ == '__main__':
68     main()