千家信息网

如何用Python模拟发送Slack消息

发表于:2026-11-04 作者:千家信息网编辑
千家信息网最后更新 2026年11月04日,本篇文章给大家分享的是有关如何用Python模拟发送Slack消息,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。有一个看似很简单的小需求
千家信息网最后更新 2026年11月04日如何用Python模拟发送Slack消息

本篇文章给大家分享的是有关如何用Python模拟发送Slack消息,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

有一个看似很简单的小需求,但是对于一个Python入门的新手来讲还是有些难度的,虽然人家也有写好的代码,但是自己就是不想直接去搬人家的代码,在不懂得时候还装的那么高大上,没办法,就是想自己折腾折腾,别人能写的出来,就说明在某些地方肯定有相关的文章,所以不要怕折腾…

1 一些Slack相关的链接

  • Python slackclient

  • API Methods

  • Slack Token

2 如何能码出功能

  1. 写代码,只要是有关平台的,首先在平台的官网上搜搜有没有相关的api文档之类的

  2. 其次在github上搜搜,有没有官方的开源模块或者第三方模块

  3. 在这就是Google你的需求了

3 找到方法如何运用

3.1 在浏览器中模拟方法请求

这里有一个参考的文章

  • 火狐的poster下载地址

3.2 自己写代码

用python发送一条消息到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是模块中封装的一个调用接口,这个接口的作用就是相当于你使用浏览器模拟post请求的执行过程,他把你在浏览器中要实现post请求所要执行的点点点封装成一个黑箱子,只要按格式填写参数就可以了

  • chat.postMessage 发送消息的方法

  • channel 要指定消息要发送到的channel

  • text 你所要发送的内容

这样是不是一目了然了,再比如说我想获取workspace中所有的channel列表,怎么做?

  1. 是不是首先要在API Methods中找到获取列表方法

  2. 可以在次使用上面的代码,换一个获取channel列表的方法就可以了

  3. 至于返回的对象是什么,可以通过Type查看,方便下一步处理

from slackclient import SlackClient# import requestsimport jsonslack_token="#不给你看"sc= SlackClient(slack_token)resp =sc.api_call(    "channels.list")

学习的是方法,剩下的要自己努力专研,要有所收获,分享一个自己写的代码,虽然垃圾,但是还能跑,在不断成长后,我觉得会一眼看出其中的什么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, 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)# 转换时间的格式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", ""))            # 读取最后一次获得邮件的时间            if float(latest_timestamp) > float(beforce_timestamp):                # 把最后一次读取邮件的时间写入文件                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

以上的功能主要是把发送到outlook邮箱里面的监控告警过滤出来,发送到Slack的channel中

需要的python module的版本requirements.txt

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

需要的配置文件的格式为config.ini

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

时间戳文件timestamp,用这个临时文件的目的是为了方便迁移脚本后也能不漏读

1524462419.0

3.3 脚本运行在容器中

3.3.1 Dockerfile
FROM 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 构建镜像
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 运行容器
docker run -d bluerdocker/alertnotify:v2

以上就是如何用Python模拟发送Slack消息,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注行业资讯频道。

代码 方法 消息 就是 文件 时间 文章 格式 模块 浏览器 邮件 浏览 功能 容器 平台 接口 更多 知识 篇文章 脚本 数据库的安全要保护哪些东西 数据库安全各自的含义是什么 生产安全数据库录入 数据库的安全性及管理 数据库安全策略包含哪些 海淀数据库安全审计系统 建立农村房屋安全信息数据库 易用的数据库客户端支持安全管理 连接数据库失败ssl安全错误 数据库的锁怎样保障安全 小米移动互联网科技园 广州淘业互联网络科技 互联网和科技技术 奇酷互联网科技 远信互联网科技 互联网科技公司官网 互联网 视角下的科技创新 一五八零互联网科技 互联网养老 桔豆科技 互联网科技股午盘股票涨跌 滨湖区互联网智能科技产品供应 深圳市运趣互联网科技有限公司 新华互联网科技2019 互联网公司科技股 燊美集互联网科技有限公司 河南住房之家互联网科技 广州新华互联网科技学校电竞方面 每天都有哪些好的互联网科技 长沙易易互联网科技有限公司 河南商务圈互联网科技有限公司 互联网和科技创新 齐家互联网科技 苏州互联网科技贷款公司 居家互联网科技有限公司 美国互联网前沿科技 现代互联网科技股 武汉健翔互联网络科技有限公司 中国航天科技大学国际工业互联网 济南有互联网科技公司吗 滨湖区互联网智能科技产品有哪些
0