因此,我没有使用 slack 进行 AWS 聊天,而是设法通过 python 3.7 脚本使其与 AWS Lambda 一起使用。
您需要在 Slack 中创建一个私人/公共频道,以便所有这些提交源都将显示在那里。我创建了一个私人频道。然后按照以下步骤创建一个 Slack 应用程序。
如何创建 Slack 传入 Webhook URL?
在本文中,您将需要 Slack 传入 Webhook URL 将您的 AWS SNS 连接到 Slack。请按照以下步骤从头开始创建 Slack 传入 Webhook URL:
Step 1:将 SNS 连接到 Slack 的第一步要求您创建一个 Slack 应用程序。您可以点击此链接开始 –Slack API:应用程序 https://api.slack.com/apps?new_app=1.
Step 2:启用传入 Webhook 以将 SNS 连接到 Slack。为此,请转至设置 → 传入 Webhooks → 激活传入 Webhooks。您的页面将会刷新。
Step 3:通过单击“将新 Webhook 添加到工作区”来创建传入 Webhook。
Step 4:选择您所需的频道以将消息从 SNS 发布到 Slack,然后单击“授权”。
Step 5:您将被重定向到应用程序设置,现在您应该注意到“工作区”部分的 Webhook URL 下有一个新条目,其 Webhook URL 如下所示:
https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXX https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXX
您需要复制该 webhook url 并转到 AWS Lambda 以创建 python 3.7 代码。
Lambda python 3.7 代码
import json
import boto3
import urllib3
codecommit = boto3.client('codecommit')
def lambda_handler(event, context):
# Log the updated references from the event
references = {reference['ref'] for reference in event['Records'][0]['codecommit']['references']}
print("References: " + str(references))
# Get the repository from the event and show its git clone URL
repository = event['Records'][0]['eventSourceARN'].split(':')[5]
try:
user = event['Records'][0]['userIdentityARN'].split(':')[5].split('/')[1]
references = event['Records'][0]['codecommit']['references']
for reference in references:
commit = reference['commit']
branch = reference['ref'].split('/')[2]
commit_resp = codecommit.get_commit(repositoryName=repository, commitId=commit)
message = commit_resp['commit']['message']
parent_commit = commit_resp['commit']['parents'][0]
commit_name = commit_resp['commit']['author']['name']
diff_resp = codecommit.get_differences(
repositoryName=repository,
beforeCommitSpecifier=parent_commit,
afterCommitSpecifier=commit
)
files = ''
i = 1
for blobs in diff_resp['differences']:
files = files + f'\n\t{blobs["afterBlob"]["path"]}'
i = i+1
if i > 4:
files = files + f'\n\t ...more files'
break
webhook = 'paste your webhook url here.'
data = {
"text": f" <@{commit_name}> (<@{user}>) committed code to {branch} branch of {repository} \nCommit message : {message} \nCommit Id: {commit} \nFiles:{files}"}
http = urllib3.PoolManager()
r = http.request("POST", webhook,
body=json.dumps(data),
headers={"Content-type": "application/json"})
return 'Success'
except Exception as e:
print(e)
print(
'Error getting repository {}. Make sure it exists and that your repository is in the same region as this function.'.format(repository))
raise e
在此处更新您的 webhook url。
webhook = 'paste your webhook url here.'
之后添加 Lambda 函数的触发器以进行代码提交。
还要添加 lambda 函数访问代码提交的权限。每次提交之后,您都会在频道中看到提要。