I have a python script that collect the data from aws cloudwatch and send it to slack. Its working completely fine. Its sending logs to slack in the form of text in slack channel.
I would want the same logs data to be stored in a text file and send it to slack. I am not into python so, please excuse my code.
In the code below I am trying to create a file and write the txt file with the message variable to store text.
Also remove json=message
with files=file_dict
# json=message
response = requests.post(slack_webhook_url,files=file_dict)
Python
import boto3
import requests
import json
def lambda_handler(event, context):
print(event)
build_id = event['detail']['build-id'].split(':')[-1]
logs_client = boto3.client('logs')
log_group_name = "/aws/codebuild/" + event['detail']['project-name']
log_stream_name = build_id
response = logs_client.get_log_events(
logGroupName=log_group_name,
logStreamName=log_stream_name,
startFromHead=True
)
message = {
'text': 'Logs for build {0}:\n'.format(build_id)
}
for event in response['events']:
message['text'] += event['message'] + '\n'
slack_webhook_url = 'https://hooks.slack.com/services/123123123/123123123/123123123';
with open("/tmp/codebuild-logs.txt", "w") as a_file:
a_file.write(message)
file_dict = {"/tmp/codebuild-logs.txt": a_file}
# json=message
response = requests.post(slack_webhook_url,files=file_dict)
if response.status_code == 200:
return {
'statusCode': 200,
'body': 'Message is sent to Slack successfully.'
}
else:
return {
'statusCode': response.status_code,
'body': 'Failed to send message to Slack.'
}
After running this script I get lambda error.
Response
{
"errorMessage": "write() argument must be str, not dict",
"errorType": "TypeError",
"stackTrace": [
" File \"/var/task/lambda_function.py\", line 36, in lambda_handler\n a_file.write(message)\n"
]
}
Any help will be greatly appreciated. Thanks in advance.