![](/img/trans.png)
[英]How to send application/x-www-form-urlencoded to slack via python slackclient?
[英]How to send Image to Slack as slack bot via slackclient?
我正在构建一个简单的机器人来定期生成图表作为图像并通过 python slackclient包发布到 slack。
我已经设法使用以下代码发送机器人消息:
def post_message_to_channel(self, channel_id, message=DEFAULT_TEST_MESSAGE):
sc = SlackClient(TOKEN)
sc.api_call(
"chat.postMessage",
channel=channel_id,
username='mybot',
text='test text message'
)
但是当我尝试对文件上传做同样的事情时,图像被正确发送,但它显示了我的名字,而不是指定的机器人名称:
def post_image_to_channel(self, channel_name, filepath, tile='Test Upload'):
sc = SlackClient(TOKEN)
with open(filepath, 'rb') as file_content:
sc.api_call(
"files.upload",
channels=channel_id,
file=file_content,
title=tile,
username='mybot',
)
查看files.upload的slack API 文档,似乎username
不可用。
如何使用机器人名称发送files.upload图像?
您必须使用机器人用户的机器人用户令牌发送文件。 您可以在官方文档https://api.slack.com/bot-users 中找到更多信息
import slack
import json
import os
def pureimg(data1):
data1 = '[{"text": "", "image_url": "'+data1+'"}]'
data1 = [json.loads(data1[1:-1])]
return data1
#This function will make the image url to correct format.
slacker = slack.WebClient(token='your-token-here')
payoff=os.path.join(os.path.dirname(os.path.realpath(__file__)), 'filename.png')
#It gives cross OS compatibility on filepath.
response=slacker.files_upload(channel='#theta',file=payoff)
payoff=response['file']['permalink']
#First We upload the local file to Slack and fetch permalink.
#If you do not have any local file just put the external image URL in the payoff.
response=slacker.chat_postMessage(channel='#channel_name', text="Sample Text", username='Bot name', attachments=pureimg(payoff), icon_emoji=':emoji:')
#Then, We post to Slack Channel as a bot!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.