Create a LINE BOT that only sends messages regularly using Azure Function. (C #)

6 minute read

background

I need to do work that should not be leaked on a daily basis, what should I do? I was consulted by a friend, so I was wondering if I could do something about it, but I wondered if I could use LINE, which is deeply rooted in our lives, and decided to create a BOT. Also, although I am involved in the development of web applications as an SE, I have never touched cloud services such as Azure in my work, and I was always wondering if there was a timing to use it.

Requirements

The requirement was very simple: [Notify “Is the task of the day completed?” At 21:00 every day (no need to judge business days, etc.)]. Also, I had never touched Azure Function or Azure Bot (I will not use Bot this time), but I was able to create it well in about 2 hours.

  • Please note that the content of this post was created in August 2020, and the portal screen and specifications may change after that.

Creation procedure

0: Assumption

・ You must have a LINE personal account.
-You have an Azure account. (It is assumed that subscriptions and resource groups have already been created.)

1: Create LINE BOT

Go to LINE Developers and log in with your personal ID.
There is no problem with the ID and password of the LINE account you normally use.
Enter your name and email address to create a developer account.

After logging in, create a new provider from the screen below and from the screen below.
Enter your name, company name, and organization name on the official LINE website.
Here, I entered “test organization”.
image.png

Once you have created your provider, select the Message API and press Enter.
image.png

Set the channel name and channel icon freely, check I accept the terms, and create a Message API. The BOT has been created so far, but the items you want to check will be needed in the subsequent work, so leave them as they are.

3: Create Azure Function

Next, create an Azure Function (function app) for regular execution from the Azure portal screen.
Here, it is used as a task scheduler for windows or a UNIX-like Coulomb.

image.png

Please decide the function name appropriately and enter it. I also wanted to write the process in C #, so I set it as follows. When you’re done, move on to hosting settings.
image.png

When creating an Azure Function, you need to create a storage account and set up a plan.
The ~~ plan has a lot to do with monthly payments, so be sure to set it to the “F1 free” plan of the “App Service Plan”. ~~ (★ 1) Select “Consumption (Serverless)” for the plan. Also, I chose “Windows” as the OS because I want to use the template “TimerTrigger” for regular execution. After completing the settings here, set the monitoring settings and click the “Confirm and Create” button and then the “Create” button to create the Azure Function and complete the deployment.

★ 1 There was an error in the content. I’m sorry. In the “F1 free” plan of the “App Service plan”, the function is executed only when you log in to the portal (the function application cannot always be connected), so the plan is “ consumption (serverless). Please set it to "”.

image.png

4: Create TimeTrigger template

When the AzureFunction is created, it uses the TimerTrigger template to create a function that runs periodically.
Please move from the “Function” tab and press the “+ Add” button to use the “Timer Trigger Template”.

image.png

Here, the execution frequency and timing are decided. The input format is NCRONTAB type.
A half-width space is inserted between each unit to indicate when to execute.
For details, please see Microsoft Official Doc.
In this case, enter 0 for the first second and minute because it is 21:00 every day, 21 for the hour because it is 21:00, and * because there is no specification such as the day, month, and day of the week.

{second} {minute} {hour} {day} {month} {day-of-week}
0 0 21 * * *

image.png

5: Define various setting values.

As the title suggests, in order to include the purpose of separating the access key to LINE from the code and the setting to match the definition of time to Tokyo, etc.
We will define the setting values. The definition can be created from the “Settings”-“Configuration” tab of the Azure Function app created in 3.

image.png

① Time setting
By default, it will be executed at 21:00 in the time zone of another country, so add the following.
■ Name: “WEBSITE_TIME_ZONE”
■ Value: “Tokyo Standard Time”

② LINE BOT channel access token
Since the message will be sent by specifying the BOT created in 1, it is necessary to issue a LINE BOT channel access token from LINE Developers and add it.

Click the BOT Messaging API setting created in 1 from LINE Developers.
image.png

Click the “Publish” button at the bottom right.
image.png

Set the issued character string to the value and add it.
■ Name: “CHANNEL_ACCESS_TOKEN”
■ Value: It will be the value checked by LINE Developers

Make sure to press the save button when you have finished setting the values.

6: Create a transmission processing program in C

After completing the settings, write the code from TimeTrigger to decide what kind of processing (what kind of message is displayed). Click the TimerTrigger1 you created earlier and press the “Code and Test” tab to display a text editor where you can enter the program.

image.png

I want to add the date and time to the sent message, so rewrite it with the following code.

AzureFunction.cs


#r "Newtonsoft.Json"

using System;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

public static async void Run(TimerInfo myTimer, ILogger log)
{
    //Store channel access token in variable
    var channelAccessToken = System.Environment.GetEnvironmentVariable("CHANNEL_ACCESS_TOKEN");
    
    DateTime dt = DateTime.Now;
    var mm = dt.ToString( "MM" ).TrimStart('0');
    var dd = dt.ToString( "dd" ).TrimStart('0');
    var HH = dt.ToString( "HH" ).TrimStart('0');
    //Create reply message
    ReplyMessage rm = new ReplyMessage
    {
        messages = new List<Message>()
        {
            new Message(){
                type="text",
                text=mm + "Month"+ dd +"Of the day"+ HH + "時になりました。本Of the dayタスクは完了していますか?"

            }
        }
    };

    //Serialize reply message
    string json = JsonConvert.SerializeObject(rm, Formatting.Indented);

    //Make a request to the Line Messaging API
    var apiUrl = "https://api.line.me/v2/bot/message/broadcast";
    var req = new HttpRequestMessage(HttpMethod.Post, apiUrl);
    
    //Add channel access token to header
    req.Headers.Add(@"Authorization", @"Bearer {" + channelAccessToken + "}");

    //Serialize the request to JSON format
    req.Content = new System.Net.Http.StringContent(json, System.Text.Encoding.UTF8, "application/json");
    
    //Send a request
    using (var client = new HttpClient())
    {
        var response = await client.SendAsync(req);
        log.LogInformation($"{response}");
    }
}

public class ReplyMessage
{
    public List<Message> messages { get; set; }
}

public class Message
{
    public string type { get; set; }
    public string text { get; set; }
}

7: Actually debug and execute.

Test if the message is actually sent to your LINE account.
Read the QR code of LINE BOT created from LINE Developers and make friends.

IMG_3537.PNG

Click “Test and Run” from the “Code and Test” screen, and then click the “Run” button in the displayed window. You can confirm that “202 Accepted” is returned and that the message has been received on LINE.
Since the execution time was around 16:00, a message was displayed saying 16:00, and it was confirmed that there was no problem with the setting values and programs.
image.png

IMG_3538.PNG

I will leave the QR code for the time being.

image.png

This is the simple procedure for creating a notification BOT. If you have any suggestions or advice, please do not hesitate to write them.