Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Python Simulation to send Slack messages

2025-04-13 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)05/31 Report--

This article is to share with you about how to use Python simulation to send Slack messages, the editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.

There is a seemingly simple small demand, but it is still a bit difficult for a novice to start Python. Although others also have written code, they just don't want to move other people's code directly. They just don't want to move other people's code directly. When they don't know how to do it, they can't help it. They just want to toss about themselves, and others can write it, which means there must be relevant articles in some places, so don't be afraid to toss about.

1 some links related to Slack

Python slackclient

API Methods

Slack Token

2 how to code the function

Write code, as long as it is about the platform, first search the official website of the platform for relevant api documents and so on.

Secondly, search github to see if there are official open source modules or third-party modules.

Here's what you need, Google.

3 find out how to use 3.1 to simulate method requests in browsers

Here is a reference article

Poster download address of Firefox

3.2 write your own code

Use python to send a message to the channel specified by slack

From slackclient import SlackClientslack_token = os.environ ["SLACK_API_TOKEN"] sc = SlackClient (slack_token) sc.api_call ("chat.postMessage", channel= "C0XXXXXX", text= "Hello from Python!: tada:")

Api_call is a calling interface encapsulated in the module. The function of this interface is that you use a browser to simulate the execution of the post request. It encapsulates the dots that you want to implement the post request in the browser into a black box. Just fill in the parameters according to the format.

The method of sending messages by chat.postMessage

Channel specifies the channel to which the message is to be sent

Text what you want to send

Is it clear at a glance, for example, if I want to get a list of all the channel in workspace, what can I do?

Should we first find the method of getting the list in API Methods?

You can use the above code this time, and change the method of getting the channel list.

As to what the returned object is, you can check it through Type to facilitate the next step.

From slackclient import SlackClient# import requestsimport jsonslack_token= "# do not show you" sc= SlackClient (slack_token) resp = sc.api_call ("channels.list")

Learning is the method, the rest of you have to study hard, to gain something, to share a code written by yourself, although rubbish, but can still run, in the continuous growth, I think I will see what bug at a glance

#! / 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, Versionfrom exchangelib.protocol import BaseProtocol, NoVerifyHTTPAdapterfrom exchangelib import UTC_NOWimport reimport getopt, sysimport base64import requestsimport jsonimport datetimeimport timeimport urllib3import configparsertry: 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) # format of conversion time 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: message subject:% s"% item.subject data = {'as_user': "true" Channel: "# devops", "text": alertinfo,} latest_timestamp = timestamp (str (item.datetime_received) .replace ("+ 00:00" "") # read the last time the message was obtained if float (latest_timestamp) > float (beforce_timestamp): # write the last read time to the file 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'} # notice the modification of 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

The above functions are mainly to filter out the monitoring alarms sent to the outlook mailbox and send them to the channel of Slack.

Required version of python module requirements.txt

Slackclien==1.2.1exchangelib=1.10.7requests==2.18.4configparser==3.5.0

The format of the required configuration file is config.ini

[info] username = $EMAIL_ADDRESSpassword = $EMAIL_PASSWORDslack_channel = $CHANNELslackApp_postUser = @ Marionmail_server= $EMAIL_SERVER_ADDR

Timestamp file timestamp. The purpose of using this temporary file is to facilitate the migration of the script without missing it.

1524462419.03.3 script runs in container 3.3.1 DockerfileFROM python:3WORKDIR / usr/src/appCOPY requirements.txt. / COPY timestamp. / COPY config.ini. / COPY test2.py. / RUN pip install-- no-cache-dir-r requirements.txtCMD ["python" ". / test2.py"] 3.3.2 build an image root@ts:/home/xue.long/mailv1# lsconfig.ini Dockerfile iaasslack.yaml requirements.txt test1.py test2.py test.py timestamproot@ts:/home/xue.long/mailv1# docker build-t bluerdocker/alertnotify:v2-f. / Dockerfile .3.3.3 run the container docker run-d bluerdocker/alertnotify:v2 above is how to use Python simulation to send Slack messages The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report