Let's make some notification processing samples in Python

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.

environment

Conducted at google cola boratory. The Python version is below. image.png

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?

Notify yourself

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)

Notify by BOT

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.

    1. Specify Webhooks as a trigger in New Applet. image.png
  1. Webhooks only has Receive a web request, so select it.

    1. I'll give you an event name. (Note that this name will also be included in the URL of the webhook)
  2. Choose the action you like For the time being, set the output contents assuming that it is LINE

  3. 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

  1. Press Settings
  1. Since the URL is described, enter the URL in the browser. This screen is the IFTTT Webhook setting screen. image.png

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.

Summary

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

Let's make some notification processing samples in Python
Let's make a combination calculation in Python
File processing in Python
Multithreaded processing in python
Text processing in Python
Queue processing in Python
Let's use def in python
UTF8 text processing in python
Asynchronous processing (threading) in python
Don't make test.py in Python!
Make a bookmarklet in Python
Make Opencv available in Python
Make python segfault in 2 lines
Image Processing Collection in Python
Let's find pi in Python
Using Python mode in Processing
Let's make a spot sale service 4 (in Python mini Hack-a-thon)
Make python segfault in one line
Signal processing in Python (1): Fourier transform
100 Language Processing Knock Chapter 1 in Python
Let's make a GUI with python.
Let's try Fizz Buzz in Python
Make standard output non-blocking in Python
Let's see using input in python
Make python segfault in three lines
Let's make a graph with python! !!
I tried Line notification in Python
Let's make a voice slowly with Python
[Python] Let's make matplotlib compatible with Japanese
Easy image processing in Python with Pillow
Let's make a web framework with Python! (1)
Make cron-like jobs run regularly in Python
Let's make a Twitter Bot with Python!
Duplicate prohibition processing in GAE / Python Datastore
Let's make a web framework with Python! (2)
Status of each Python processing system in 2020
Asynchronous processing in Python: asyncio reverse lookup reference
Let's parse the git commit log in Python!
Type Python scripts to run in QGIS Processing
View the result of geometry processing in Python
I investigated in detail about variable processing in python
Let's judge emotions using Emotion API in Python
Let's implement English voice dialogue in Python [offline]
Make a rock-paper-scissors game in one line (python)
Python: Deep Learning in Natural Language Processing: Basics
Let's replace UWSC with Python (5) Let's make a Robot
Make a joyplot-like plot of R in python
Y / n processing in bash, python and Go
Parallel processing with no deep meaning in Python
Let's make a module for Python using SWIG
How to make Python Interpreter changes in Pycharm
Quadtree in Python --2
Python in optimization
CURL in python
Metaprogramming in Python
Python 3.3 in Anaconda
Geocoding in python
SendKeys in Python
python image processing
Meta-analysis in Python
Unittest in python