Give me solution how can i get log directly to slack channel using python and flask.I am able to use logging and save it in log file but i want that info,warning,error,critical,debug logs should directly send to slack channel.
2 Answers
4
votes
Here is an example of sending a message to a Slack channel via. Python. You must have a Slack web hook configured for your Slack group, which you can then add onto the hook var.
import json, requests
def sendMessageToSlack():
hook = "https://hooks.slack.com/services/<hook goes here>"
headers = {'content-type': 'application/json'}
payload = {"attachments":[
{
"fallback":"",
"pretext":"",
"color":"#fff",
"fields":[
{
"title":"",
"value":"",
"short": False
}
]
}
]
}
r = requests.post(hook, data=json.dumps(payload), headers=headers)
print("Response: " + str(r.status_code) + "," + str(r.reason))
Providing the response returns a 200 code, you should have a message in your channel.
2
votes
I don't know why you want to utilize flask...
I think you can just use Slack API client together with its Documentation. Basic usage is what you're looking for (coloring etc.).
Using your own solutions isn't recommended - sometimes API changes and you would have to maintain it. Official API client gives you level of abstraction and you don't have to worry about sudden errors.
Posting message (copied from github):
from slackclient import SlackClient
slack_token = os.environ["SLACK_API_TOKEN"]
sc = SlackClient(slack_token)
sc.api_call(
"chat.postMessage",
channel="#python",
text="Hello from Python! :tada:"
)
You can generate test token on this website and try it for yourself.