0%

slack介绍和机器人使用

经常用的 bearychat 凉了(估计受疫情影响), 还有国内的瀑布IM也凉了, 不得不选用一个新的企业协作工具.

那么在国内为什么不选用钉钉, 飞书, 企业微信? 哈哈哈你懂的. slack 是谁? 算是前面的标杆

1. 使用

1.1 机器人安装

注意先不要用官网最新的教程, 有坑!!!! 看这个 https://github.com/slackapi/hubot-slack/issues/584#issuecomment-611808704

  • Create a classic app from https://api.slack.com/apps?new_classic_app=1
  • Go to Features > OAuth & Permissions > Scopes
    • Click “Add an OAuth Scope”
    • Search “bot” and choose it
  • Go to Features > App Home
    • Click “Add Legacy Bot User”
    • Input “Display Name” and “Default username”
    • Click “Add”
  • Go to Settings > Install App
    • Click “Install App to Workspace”
    • Complete the OAuth flow

1.2 字段说明

2. 机器人发送信息

  • 不建议使用 web hookapi, 因为 channel 过多的时候会很累, 并且功能也少

  • 注意 token 是机器人的 token, 即Bot User OAuth Token

  • 注意需要把bot 拉入channel 里, /invite @BOT_NAME

2.1 golang 代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package main

import (
"fmt"

"github.com/slack-go/slack"
)

func main() {
api := slack.New("YOUR_TOKEN_HERE")

attachment := slack.Attachment{
Pretext: "some pretext",
Text: "some text",
// Uncomment the following part to send a field too
/*
Fields: []slack.AttachmentField{
slack.AttachmentField{
Title: "a",
Value: "no",
},
},
*/
}

channelID, timestamp, err := api.PostMessage(
"CHANNEL_ID",
slack.MsgOptionText("Some text", false),
slack.MsgOptionAttachments(attachment),
slack.MsgOptionAsUser(true), // Add this if you want that the bot would post message as a user, otherwise it will send response using the default slackbot
)
if err != nil {
fmt.Printf("%s\n", err)
return
}
fmt.Printf("Message successfully sent to channel %s at %s", channelID, timestamp)
}

2.2 python 代码

pip3 install slack_sdk

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import os
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError

client = WebClient(token=os.environ['SLACK_BOT_TOKEN'])

try:
response = client.chat_postMessage(channel='#random', text="Hello world!")
assert response["message"]["text"] == "Hello world!"
except SlackApiError as e:
# You will get a SlackApiError if "ok" is False
assert e.response["ok"] is False
assert e.response["error"] # str like 'invalid_auth', 'channel_not_found'
print(f"Got an error: {e.response['error']}")

3. app 使用

3.1 订阅github提交记录

image-20210228005233393

4. 参考资料

给作者打赏,可以加首页微信,咨询作者相关问题!