本篇文章給大家分享的是有關(guān)如何用Python模擬發(fā)送Slack消息,小編覺(jué)得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話(huà)不多說(shuō),跟著小編一起來(lái)看看吧。

成都創(chuàng)新互聯(lián)主要從事網(wǎng)站設(shè)計(jì)、做網(wǎng)站、網(wǎng)頁(yè)設(shè)計(jì)、企業(yè)做網(wǎng)站、公司建網(wǎng)站等業(yè)務(wù)。立足成都服務(wù)蓮湖,10年網(wǎng)站建設(shè)經(jīng)驗(yàn),價(jià)格優(yōu)惠、服務(wù)專(zhuān)業(yè),歡迎來(lái)電咨詢(xún)建站服務(wù):18980820575
有一個(gè)看似很簡(jiǎn)單的小需求,但是對(duì)于一個(gè)Python入門(mén)的新手來(lái)講還是有些難度的,雖然人家也有寫(xiě)好的代碼,但是自己就是不想直接去搬人家的代碼,在不懂得時(shí)候還裝的那么高大上,沒(méi)辦法,就是想自己折騰折騰,別人能寫(xiě)的出來(lái),就說(shuō)明在某些地方肯定有相關(guān)的文章,所以不要怕折騰…
Python slackclient
API Methods
Slack Token
寫(xiě)代碼,只要是有關(guān)平臺(tái)的,首先在平臺(tái)的官網(wǎng)上搜搜有沒(méi)有相關(guān)的api文檔之類(lèi)的
其次在github上搜搜,有沒(méi)有官方的開(kāi)源模塊或者第三方模塊
在這就是Google你的需求了
這里有一個(gè)參考的文章
火狐的poster下載地址
用python發(fā)送一條消息到slack指定的頻道中
from slackclient import SlackClient slack_token = os.environ["SLACK_API_TOKEN"] sc = SlackClient(slack_token) sc.api_call( "chat.postMessage", channel="C0XXXXXX", text="Hello from Python! :tada:" )
api_call是模塊中封裝的一個(gè)調(diào)用接口,這個(gè)接口的作用就是相當(dāng)于你使用瀏覽器模擬post請(qǐng)求的執(zhí)行過(guò)程,他把你在瀏覽器中要實(shí)現(xiàn)post請(qǐng)求所要執(zhí)行的點(diǎn)點(diǎn)點(diǎn)封裝成一個(gè)黑箱子,只要按格式填寫(xiě)參數(shù)就可以了
chat.postMessage 發(fā)送消息的方法
channel 要指定消息要發(fā)送到的channel
text 你所要發(fā)送的內(nèi)容
這樣是不是一目了然了,再比如說(shuō)我想獲取workspace中所有的channel列表,怎么做?
是不是首先要在API Methods中找到獲取列表方法
可以在次使用上面的代碼,換一個(gè)獲取channel列表的方法就可以了
至于返回的對(duì)象是什么,可以通過(guò)Type查看,方便下一步處理
from slackclient import SlackClient # import requests import json slack_token="#不給你看" sc= SlackClient(slack_token) resp =sc.api_call( "channels.list" )
學(xué)習(xí)的是方法,剩下的要自己努力專(zhuān)研,要有所收獲,分享一個(gè)自己寫(xiě)的代碼,雖然垃圾,但是還能跑,在不斷成長(zhǎng)后,我覺(jué)得會(huì)一眼看出其中的什么bug吧
#!/usr/bin/env python3.5
###############################
# function: send zabbix/cacti/ops alert to slack.
#
###############################
from exchangelib import DELEGATE, IMPERSONATION, Account, Credentials, ServiceAccount, \
EWSDateTime, EWSTimeZone, Configuration, NTLM, CalendarItem, Message, \
Mailbox, Attendee, Q, ExtendedProperty, FileAttachment, ItemAttachment, \
HTMLBody, Build, Version
from exchangelib.protocol import BaseProtocol, NoVerifyHTTPAdapter
from exchangelib import UTC_NOW
import re
import getopt, sys
import base64
import requests
import json
import datetime
import time
import urllib3
import configparser
try:
configcfg = configparser.ConfigParser()
configcfg.read("config.ini")
slackApp_postUser=configcfg["info"]["slackApp_postUser"]
username=configcfg["info"]["username"]
# password=str(base64.b64decode(configcfg["info"]["password"]),"utf-8")
password=configcfg["info"]["password"]
slack_channel = configcfg["info"]["slack_channel"]
mail_server = configcfg["info"]["mail_server"]
# print(username,password,slack_channel,slackApp_postUser)
# slackAPP_postMessageAPI = config.get("info", "slackAPP_postMessageAPI")
# slackApp_postUser = config.get("info", "slackApp_postUser")
except:
print("ERR : no configuration \n")
print("please create configuration file\n")
print("configuration must be renamed config.ini\n")
print("the script will be exit in 5 second\n")
time.sleep(5)
# 轉(zhuǎn)換時(shí)間的格式
def timestamp(timestr):
time_array = time.strptime(timestr, "%Y-%m-%d %H:%M:%S")
return time.mktime(time_array)
cred = Credentials(username, password)
config = Configuration(server=mail_server, credentials=cred, auth_type=NTLM)
account = Account(primary_smtp_address=username, config=config,autodiscover=False,access_type=DELEGATE)
email_address = ["1451032707@qq.com"]
with open("timestamp", "r") as f:
beforce_timestamp = float(f.read())
while True:
time.sleep(5)
try:
for item in account.inbox.all().order_by('-datetime_received')[:20]:
alertinfo = ":slack:郵件主題: %s" % item.subject
data = {
'as_user': "true",
"channel": "#devops",
"text": alertinfo,
}
latest_timestamp = timestamp(str(item.datetime_received).replace("+00:00", ""))
# 讀取最后一次獲得郵件的時(shí)間
if float(latest_timestamp) > float(beforce_timestamp):
# 把最后一次讀取郵件的時(shí)間寫(xiě)入文件
with open("timestamp", "w") as f:
f.write(str(latest_timestamp))
beforce_timestamp = latest_timestamp
if item.sender not in email_address:
header = {'Content-Type': 'application/json',
'Authorization': '$slack_token'} #注意修改這里的Token
netRequest = requests.post(url="https://slack.com/api/chat.postMessage", headers=header,
data=json.dumps(data), timeout=(10, 30))
else:
continue
except urllib3.exceptions:
break
except requests.exceptions:
break以上的功能主要是把發(fā)送到outlook郵箱里面的監(jiān)控告警過(guò)濾出來(lái),發(fā)送到Slack的channel中
需要的python module的版本requirements.txt
slackclien==1.2.1 exchangelib=1.10.7 requests==2.18.4 configparser==3.5.0
需要的配置文件的格式為config.ini
[info] username = $EMAIL_ADDRESS password = $EMAIL_PASSWORD slack_channel = $CHANNEL slackApp_postUser = @Marion mail_server= $EMAIL_SERVER_ADDR
時(shí)間戳文件timestamp,用這個(gè)臨時(shí)文件的目的是為了方便遷移腳本后也能不漏讀
1524462419.0
FROM python:3 WORKDIR /usr/src/app COPY requirements.txt ./ COPY timestamp ./ COPY config.ini ./ COPY test2.py ./ RUN pip install --no-cache-dir -r requirements.txt CMD [ "python", "./test2.py" ]
root@ts:/home/xue.long/mailv1# ls config.ini Dockerfile iaasslack.yaml requirements.txt test1.py test2.py test.py timestamp root@ts:/home/xue.long/mailv1# docker build -t bluerdocker/alertnotify:v2 -f ./Dockerfile .
docker run -d bluerdocker/alertnotify:v2
以上就是如何用Python模擬發(fā)送Slack消息,小編相信有部分知識(shí)點(diǎn)可能是我們?nèi)粘9ぷ鲿?huì)見(jiàn)到或用到的。希望你能通過(guò)這篇文章學(xué)到更多知識(shí)。更多詳情敬請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
網(wǎng)站欄目:如何用Python模擬發(fā)送Slack消息
新聞來(lái)源:http://chinadenli.net/article4/ipdgie.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供電子商務(wù)、移動(dòng)網(wǎng)站建設(shè)、品牌網(wǎng)站設(shè)計(jì)、做網(wǎng)站、品牌網(wǎng)站制作、網(wǎng)頁(yè)設(shè)計(jì)公司
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話(huà):028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)