(Python) I made an app from Trello that periodically notifies slack of tasks that are about to expire.

Preamble

Our team uses Trello to manage the tasks that everyone has to do. (Tasks are listed on the card, personal names are listed on the checklist, and ☑ is added to those who have completed the task)

Your boss must open Trello every time and open each card to see the progress. Absolutely troublesome. And with Trello Alert, you can send a slack notification when you change or create a new card, add ☑ to the list, etc., but every time you add ☑, you will be notified and you can see the completed and incomplete people in the list. Is not. Basically, notifications pollute slack's channels (in my opinion). And it's annoying that you can't see it in the list.

Then, let's make an app that notifies people who have not completed the task on a regular basis (as long as it does not pollute the channel). And if you do, let's implement it using AWS. I came up with the idea and tried to make it.

development of

Development flow

The rough development flow is

① Hit Trello's API ② Write code ③ Implemented on AWS lambda ④ Trigger Event Bridge (CloudWatch Events) ⑤ Create a Slack app ⑥ Post to slack It's like that. Let's look at each one.

Hit Trello's API

Go to Here (https://trello.com/app-key). image.png

Trello API Keys Make a copy of the Key at the top. (If you put it in a memo pad, ◎) Trello API Token Click the Token link in ToKen: under Key :. Then Would you like to give the following application access to your account? Will be asked, so scroll and Allow. image.png When you move to the above page, the Token Key is written, so copy it as well.

Next, let's install the library (py-trello). This time, I plan to use Lambda, so install the library in the same folder as the python code (trello_alert). (Leave the inside of the folder dirty)

powershell


mkdir trello_alert
cd trello_alert
pip install py-trello --target .

Now you're ready to hit the API. Let's actually hit it.

trello_api.py



from trello import TrelloClient
#API connection to trello
client=TrelloClient(
    api_key='Write API Key here',
    api_secret='Write API Token here'
)
print(client.list_boards())

If you run it and the list of trello is output, the task of hitting the API is completed.

Write code

Now, let's get the list and output the people who have not completed the task that is near the deadline. Basically, the code of the TrelloClient class is posted on This GitHub, so check it if necessary. please try. I will refer to the code I wrote. (Since it is raised to lamda, it is the code for lamda)

lambda_function.py


#Get Task incomplete person whose Date is approaching
import re
import datetime
from trello import TrelloClient
import json

def lambda_handler(event, context):
    result = {}
    
    #Get dates for today and next week
    today = datetime.date.today()
    next_week = today + datetime.timedelta(weeks=1)
    
    #API connection to trello
    client = TrelloClient(
        api_key='Write API Key here',
        api_secret='Write API Token here'
    )
    
    #Get a trello card
    board = client.get_board(`Note ①:Write the board id here`) #Get the board
    target_list = board.get_list(`Note ②:Write the list id here`) #Get list
    cards = target_list.list_cards() #Get a list of cards on the list
    
    #Get task incomplete and deadline for each card
    #Notify the deadline one week later and today
    for c in cards:
        #Get a card
        card = client.get_card(c.id)
        card.fetch()
        #Get card expiration
        due = re.match("[0-9]{4}-[0-9]{2}-[0-9]{2}", c.due).group()
        #Get a checklist of today's and one week's deadlines
        if(str(due) == str(today) or str(due) == str(next_week)):
            #Get checklist one by one
            for checklist in card.checklists:
                not_finish = []
                for i, item in enumerate(checklist.items):
                    #Output task incomplete person
                    if(item["checked"]== False):
                        not_finish.append(item["name"])
            #Store card name and task incomplete person in dictionary format
            result[c.name] = not_finish
    return {
        'statusCode': 200,
        'body': json.dumps(result, ensure_ascii=False)
    }

Note 1: The board id is after b in the url when you open the trello board. https://trello.com/b/board id/ board name Note 2: Since there is an all_list function in the board class, output it to find the list id. print(board.all_list())

With this kind of feeling, I was able to get tasks that are close to the deadline and those who have not completed the tasks. (If you want to run it locally, comment out 8th line, 45th to 48th lines and add` print (result) at the end.) Please note that if you do not name the file'lambda_function', it will not work when you upload it to lamda.

For the time being, the code is ready. I will raise it to lambda.

Implemented on AWS lambda

Zip file

I need to make a zip file to put the code in lambda, so Select everything in the trello_alert folder, zip it and make it a zip file. The zip file name should be trello.

Log in to AWS

If you search for lambda from Find Services, AWS Lambda will appear as a candidate, so select it. image.png

After moving to this page, click create function. image.png

On the next page, select the far left and scroll down. image.png

Fill in like this. (Trello_alert is in the red because it is said that it already exists) Then click create function. image.png

Trello_alert will be added to Lambda. Click trello_alert to upload the code. image.png

After moving to this page, click the Action part at the bottom right. image.png

Select ʻUpload a .zip file` and upload the trello.zip you created earlier. image.png

The file will be uploaded like this. (If the default lambda_function gets in the way, delete it) image.png

After that, press save on the above screen to execute test. When you press test, the following screen will appear, so set Event name to test and create. image.png You will be returned to the previous screen, so run test again.

If 200 responses are returned to Execution Result, uploading to lambda is complete.

Environment variable setting (optional)

For those who want to write API Key and API Token raw in the code .. Since there are Enviroment variables under the Function code, Set the environment variable there, and in the code, api_key=os.environ['API_KEY'] If you write, it will be executed without any problem.

Trigger Event Bridge (CloudWatch Events)

I want to run it regularly, so I use CloudWatch Events.

Select Add trigger from the Lambda (trello_alert) screen. image.png

Fill in the setting screen as follows and add it. image.png

This time, I wanted to post regularly at 9 am on weekdays, so cron(0 9 ? * MON-FRI *) And write a Schedule expression. If you want every minute rate(1 minute) If you set it as OK!

Create Slack app

I created the Slack app by referring to the following article. [2020 version] Create and set bot application to post messages with slack API (detailed explanation of scope authority)

Post to slack

lambda_function.py Add the following code.

lambda_function.py


import requests

#Post to slack
url = "https://slack.com/api/chat.postMessage"
msg = {
   "token": "Write ACCESS TOKEN here",
   "channel": "Write the channel ID you want to post here",
   "text": result
}
requests.post(url, data=msg)

Summary

It was a good experience to be able to use AWS, hit APIs, and expect improvements in business.

Recommended Posts

(Python) I made an app from Trello that periodically notifies slack of tasks that are about to expire.
[Python] I made an app to practice the subtle voice distinction of English words.
I made a slack bot that notifies me of the temperature
I made an appdo command to execute a command in the context of the app
With LINEBot, I made an app that informs me of the "bus time"
I made a github action that notifies Slack of the visual regression test
I made an action to automatically format python code
I made a program in Python that changes the 1-minute data of FX to an arbitrary time frame (1 hour frame, etc.)
[Python] I started Poetry & Impression that I moved from Pipenv to poetry
I want to start a lot of processes from python
[Python3] List of sites that I referred to when I started Python
Post from Python to Slack
I tried to build an estimation model of article titles that are likely to buzz with Qiita
I made a Line bot that guesses the gender and age of a person from an image
I want to extract an arbitrary URL from the character string of the html source with python
I made a garbled generator that encodes favorite sentences from UTF-8 to Shift-JIS (cp932) in Python
I made an app to find out who the members of the Straw Hat Pirates look like
[Python] I tried to explain words that are difficult for beginners to understand in an easy-to-understand manner.
Create an app that notifies LINE of the weather every morning
Various ways to create an array of numbers from 1 to 10 in Python.
I made a library that adds docstring to a Python stub file.
Heroku deployment of the first Django app that beginners are addicted to
[Python] I made a decorator that doesn't seem to have any use.
I made a web application in Python that converts Markdown to HTML
I want to color a part of an Excel string in Python
I made a program to check the size of a file in Python
[Lambda] I tried to incorporate an external module of python via S3
I made a function to see the movement of a two-dimensional array (Python)
[Python] I tried to analyze the characteristics of thumbnails that are easy to play on YouTube by deep learning
[Python] I made a script that automatically cuts and pastes files on a local PC to an external SSD.
I created a Slack bot that confirms and notifies AWS Lambda of the expiration date of an SSL certificate