使用python利用slack bot发送消息

这篇博客详细介绍了如何使用Python通过Slack Bot发送文本消息和图片等附件。首先,你需要安装相关库,然后在Slack上创建APP并赋予Bot权限。获取Token后,将Bot加入到指定channel。代码部分展示了发送文本消息和附件的实现,如果Bot被移除,可以通过重新安装和更新密钥来重新加入channel。
部署运行你感兴趣的模型镜像

用到的库

地址

安装: pip install slack_sdk

在slack创建APP

  1. 进入 https://api.slack.com/apps , create a new app
  2. OAuth & Permissions 菜单, 给bot加入权限:
  3. Click the “Allow” button.
  4. https://api.slack.com/apps/xxx/app-home 设置app的名字
  5. 然后可以在 OAuth Tokens for Your Team 看到 Token

加入channel

创建完app后, 在slack里, Add xxx to a channel

代码

发送文本消息代码
import os
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError

client = WebClient(token='xxxx')

try:
    response = client.chat_postMessage(channel='xxx', text="Hello world22!")
    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']}")
发送图片或者其他文本附件
import os
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError

client = WebClient(token='xxx')

try:
    filepath="./tmp.txt"
    response = client.files_upload(channels='#random', file=filepath)
    assert response["file"]  # the uploaded file
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']}")
		

被从channel移除后,重新加入:

  1. 重新reinstall在这里插入图片描述
    在这里插入图片描述

  2. 在slack客户端add apps在这里插入图片描述

  3. 进入app,加入channel
    在这里插入图片描述

  4. 更新代码内的密钥
    client = WebClient(token='xoxb-878537608886-16834xxxxxx')

您可能感兴趣的与本文相关的镜像

Python3.10

Python3.10

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值