I would like to implement the function to post the string 'dialogs' as a text file to Slack Channels using AWS Lambda. The runtime is Python 3.8 and the code is below.
import os
import requests
def lambda_handler(event, context):
SLACK_TOKEN = os.environ['SLACK_TOKEN']
SLACK_CHANNEL = os.environ['SLACK_CHANNEL']
data = {
"token": SLACK_TOKEN,
"channels": SLACK_CHANNEL,
"title": "Dialog_Bot",
"initial_comment": "New post"
}
f = open('/tmp/Slack.txt','w+b')
f.write(dialogs.encode('utf-8'))
f.seek(0)
f.read()
f.close()
file_name = open('/tmp/Slack.txt', 'rb')
files = {'file': ('/tmp/Slack.txt', file_name, 'text/plain')}
response = requests.post(url="https://slack.com/api/files.upload", params=data, files=files)
print(response.text)
However, when I looked at the value of response.text, the following error was displayed.
{
"ok": false,
"error": "invalid_auth"
}
I was wondering if the token value was wrong, but when I ran the curl command in my local environment with the same token value, the process was successful.
%curl --request POST \
--form channels=XXXXXXXXXXXX(Same value as SLACK_CHANNEL) \
--form token=xoxb-XXXXXXXXXXXX-XXXXXXXXXXXX-XXXXXXXXXXXXXXXXXXXXXXXX(Same value as SLACK_TOKEN) \
--form file=@/./test.txt \
--form title=test \
--form initial_comment=test \
https://slack.com/api/files.upload
{"ok":true,"file":{"id":……(Status information follows)
I also tried the chat.postMessage method with an environment variable of the same token and it succeeded.
data = {
"token": SLACK_TOKEN,
"channel": SLACK_CHANNEL,
"title": "Dialog_Bot",
"text": "New post"
}
response = requests.post(url="https://slack.com/api/chat.postMessage", data=data)
{"ok":true,"channel":……(Status information follows)
I have the Slack app's IP address range set to default (nothing is set).
If you know the cause and solution, I would appreciate it if you could let me know.