With alerts after making judgments in processing and notifications at the end of processing There are occasional cases where you want to be notified by email or a specific service, Every time I got tired of thinking, I summarized it.
Conducted at google cola boratory. The Python version is below.
Mail First of all, email notification to solid.
SMTP server assumes Gmail
import smtplib
from email.mime.text import MIMEText
from email.utils import formatdate
#Sender's email address, name, and password (in the case of Gmail, issue and use the app password)
FROM_ADDRESS = '[email protected]'
FROM_NAME = 'XXXXXX'
MY_PASSWORD = 'xxxxx'
#Make the destination a list type
TO_ADDRESS = ['[email protected]', '[email protected]']
from_mail_addr = FROM_ADDRESS
_from_name = FROM_NAME
_from_addr = "{} <{}>".format(_from_name, from_mail_addr)
#Create a message to send
## https://docs.python.org/ja/3.5/library/email-examples.html
def create_message(list_to_addr, subject, body):
msg = MIMEText(body)
msg['Subject'] = subject
# msg['From'] = _from_addr
msg['From'] = _from_name
msg['To'] = ','.join(list_to_addr)
#I'm not sure, but even if I put it in BCC, it will only be displayed in the column called BCC, so stop
# msg['Bcc'] = ','.join(list_bcc_addrs)
msg['Date'] = formatdate()
return msg
#Send using Gmail's SMTP server
def send_gmail(list_to_addr, msg):
smtpobj = smtplib.SMTP('smtp.gmail.com', 587)
smtpobj.ehlo()
smtpobj.starttls()
smtpobj.ehlo()
smtpobj.login(FROM_ADDRESS, MY_PASSWORD)
smtpobj.sendmail(from_mail_addr, list_to_addr, msg.as_string())
smtpobj.close()
#Process to actually send
##Message composition
list_to_addr = TO_ADDRESS
subject = "<Notification sample>"
import datetime
dt_now = datetime.datetime.now()
#Line breaks\Just set with n
body = "It is the content to be sent\Will line breaks be reflected?\n{}"
body = body.format(dt_now.strftime('%Y year%m month%d day%H:%M:%S'))
msg = create_message(list_to_addr, subject, body)
##Transmission process
send_gmail(list_to_addr, msg)
LINE Then LINE. If you want to notify LINE, there are two main types. Should I just notify myself, or should I notify a specific user as a BOT?
Issue tokens for rooms below https://notify-bot.line.me/ja/
import requests
line_notify_api = 'https://notify-api.line.me/api/notify'
payload = {'message': send_message}
headers = {'Authorization': 'Bearer ' + line_notify_token}
line_notify = requests.post(line_notify_api, data=payload, headers=headers)
You can also use the LINE Bot API to push to specific users of your friends
This is to create a BOT from the following https://developers.line.biz/console
import json
import requests
#Set HTTP header
header = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + _access_token,
}
#Set transmission data
send_data = {
'to': to_user_id,
'messages': [
{
'type': 'text',
'text': send_message
}
]
}
#Run
url = 'https://api.line.me/v2/bot/message/push'
res = requests.post(url, headers=header, data=json.dumps(send_data))
if(res.status_code != 200):
print("error : [{}]".format(res.text))
Slack
Is it a recent trend to want to notify chat tools?
Create a URL in the target channel as an incoming-webhook and throw it in POST OK
import requests
import json
requests.post(slack_url, data=json.dumps({'text': send_message}))
Easy.
Teams
Basically with Slack. Create a URL on the target channel as an incoming-webhook and throw it in POST. It's just a feature of Teams that is different from Slack, but it can be titled
Since it is output in HTML, it will not be broken in \ n, so if you want to combine it with other notifications, you should add replacement processing.
import requests
import json
send_message = send_message.replace('\n', '<BR>')
requests.post(teams_webhook_url, data=json.dumps({'title': subject, 'text': send_message}))
IFTTT
At the end I will try to jump to IFTTT's Webhook so that I can jump to anything
Because I will only briefly describe a little complicated procedure If you have never created a webhook with IFTTT, you should give up and go to another page.
Webhooks only has Receive a web request, so select it.
Choose the action you like For the time being, set the output contents assuming that it is LINE
Decide the applet name and press Finish.
Tend to be confusing from here 6. Select My services in the upper right to display the webhooks service
The URL of the IFTTT Webhook is determined by the key displayed on this setting screen and the event name mentioned earlier.
Https://maker.ifttt.com/trigger/
/ with / key /
If you come to this point, you can just throw it in the URL by POST like Slack or TEAMS Webhook. There are three parameters, value1, value2, and value3.
import requests
requests.post(url_ifttt, data={'value1': subject, 'value2': send_message, 'value3': ''})
If I can go through IFTTT, I think that the destination will be irrelevant, so I think that I can notify my favorite notification destination.
If you put everything together and notify them all at once, it will look like this.
import smtplib
from email.mime.text import MIMEText
from email.utils import formatdate
import requests
import json
#Sender's email address, name, and password (in the case of Gmail, issue and use the app password)
FROM_ADDRESS = '[email protected]'
FROM_NAME = 'XXXXXX'
MY_PASSWORD = 'xxxxx'
#Make the destination a list type
TO_ADDRESS = ['[email protected]', '[email protected]']
def create_message(list_to_addr, subject, body):
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = FROM_NAME
msg['To'] = ','.join(list_to_addr)
#I'm not sure, but even if I put it in BCC, it will only be displayed in the column called BCC, so stop
# msg['Bcc'] = ','.join(list_bcc_addrs)
msg['Date'] = formatdate()
return msg
def send_gmail(list_to_addr, msg):
smtpobj = smtplib.SMTP('smtp.gmail.com', 587)
smtpobj.ehlo()
smtpobj.starttls()
smtpobj.ehlo()
smtpobj.login(FROM_ADDRESS, MY_PASSWORD)
smtpobj.sendmail(FROM_ADDRESS, list_to_addr, msg.as_string())
smtpobj.close()
def Notice_Mail(subject, send_message):
list_to_addr = TO_ADDRESS
msg = create_message(list_to_addr, subject, send_message)
send_gmail(list_to_addr, msg)
line_notify_token = 'xxxxxxxxxxx'
def Notice_LINE_Self(send_message):
line_notify_api = 'https://notify-api.line.me/api/notify'
payload = {'message': send_message}
headers = {'Authorization': 'Bearer ' + line_notify_token}
line_notify = requests.post(line_notify_api, data=payload, headers=headers)
_access_token ='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
def Notice_LINE_push(to_user_id, send_message):
#Set HTTP header
header = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + _access_token,
}
#Set transmission data
send_data = {
'to': to_user_id,
'messages': [
{
'type': 'text',
'text': send_message
}
]
}
#Run
url = 'https://api.line.me/v2/bot/message/push'
res = requests.post(url, headers=header, data=json.dumps(send_data))
if(res.status_code != 200):
print("error : [{}]".format(res.text))
slack_url = 'https://hooks.slack.com/services/xxxxxxxx/xxxxxxxx/xxxxxx'
def Notice_Slack(send_message):
requests.post(slack_url, data=json.dumps({'text': send_message}))
teams_webhook_url = 'https://outlook.office.com/webhook/xxxxxxx/IncomingWebhook/xxxxxxx/xxxxxx'
def Notice_TEAMS(subject, send_message):
send_message = send_message.replace('\n', '<BR>')
requests.post(teams_webhook_url, data=json.dumps({'title': subject, 'text': send_message}))
url_ifttt = 'https://maker.ifttt.com/trigger/eventid/with/key/xxxxx'
def Notice_IFTTT(subject, send_message):
requests.post(url_ifttt, data={'value1': subject, 'value2': send_message, 'value3': ''})
def Notice(subject, body):
#Notification processing: Email
Notice_Mail(subject, body)
#Notification processing: LINE_Notify
Notice_LINE_Self(body)
#Notification processing: LINE_push
userid = 'xxxxxxxxxx'
Notice_LINE_push(userid, body)
#Notification processing: Slack
Notice_Slack(body)
#Notification processing: TEAMS
Notice_TEAMS(subject, body)
#Notification processing: IFTTT (to LINE via)
Notice_IFTTT(subject, body)
import datetime
dt_now = datetime.datetime.now()
#Line breaks\Just set with n
body = "It is the content to be sent\Will line breaks be reflected?\n{}"
body = body.format(dt_now.strftime('%Y year%m month%d day%H:%M:%S'))
subject = "<Notification sample: {}>".format(dt_now.strftime('%Y%m%d %H%M%S'))
#notification
Notice(subject, body)
Recommended Posts