2017年4月21日 星期五

[python] 怎麼撰寫 slack bot


最重要的地方就是得到你的bot token


pip install slackclient

# coding=utf-8
import os
import subprocess
import shlex
import time
import socket

from subprocess import PIPE
from slackclient import SlackClient

def sent_msg(sc, channel='#general', msg=''):
    sc.api_call(
      "chat.postMessage",
      channel=channel,
      # text="Hello from Python! :tada:"
      text=msg
    )

# slack_token = os.environ["SLACK_API_TOKEN"]
slack_token = 'TOKEN'
cmd = 'df -h'
args = shlex.split(cmd)
p = subprocess.Popen(args, stdout=PIPE)
#print p
time.time()
hostname = socket.gethostname()
result = '\n=====\nGood Day Sir ~ ' + time.strftime("%y%m%d %H%M") + '\n'
result += hostname + ' disk usage\n'
result += p.communicate()[0]
sc = SlackClient(slack_token)
sent_msg(sc, channel='#general', msg=result)


How to Build Your First Slack Bot with Python - Full Stack Python
https://www.fullstackpython.com/blog/build-first-slack-bot-python.html

沒有留言:

張貼留言