Make a garbage reminder with line-bot-sdk-java

Overview

Use the LINE Messaging API SDK (for Java) (https://github.com/line/line-bot-sdk-java) to send reminders before the garbage collection date.

Concept

The part that responds to the response is realized by "Webhook", and the part that pushes the reminder is realized by "Messaging API".

environment

Creating a project

Create a project with "SPRING INITIALIZR". Check "lombok" and "Devtool". Artifact is "garbage-reminder".

init.png

Once the download is complete, open it in the IDE.

Add dependency

pom.xml


<dependency>
    <groupId>com.linecorp.bot</groupId>
    <artifactId>line-bot-spring-boot</artifactId>
    <version>1.11.0</version>
</dependency>

Add the LINE Messaging API SDK.

Property

application.properties


line.bot.channelSecret = XXXXX
line.bot.channelToken = XXXXX
line.bot.handler.path = /callback

Set the information of the channel opened on LINE.

Implementation of message push

confirm.png Use the Confirmation Templates (https://developers.line.me/ja/docs/messaging-api/message-types/#confirm-template) to confirm that the garbage removal is complete.

PushConfirmController


@Slf4j
@RestController
public class PushConfirmController {

    private final LineMessagingClient lineMessagingClient;

    ConfirmService(LineMessagingClient lineMessagingClient) {
        this.lineMessagingClient = lineMessagingClient;
    }

    //Push reminders
    @GetMapping("alarm")
    public void pushAlarm() throws URISyntaxException {

        try {
            BotApiResponse response = lineMessagingClient
                                            .pushMessage(new PushMessage("/*UserId of the person you want to push*/",
                                                         new TemplateMessage("Tomorrow is a burning garbage day!",
                                                                 new ConfirmTemplate("Have you finished dumping garbage?",
                                                                         new MessageAction("Yes", "Yes"),
                                                                         new MessageAction("No", "No")
                                                                 )
                                                         )))
                                            .get();
            log.info("Sent messages: {}", response);
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }
    }
}

It is not necessary to make it a controller, but it is easier to check if you can call it with GET.

Verification

notification

message

Since the response has not been implemented, there is no response yet even if the button is pressed.

Implementation of response

Webhooks can return a response when something is sent, such as a message or stamp. I made it so that "yes" or "no" is returned in the confirmation, so I picked up these two words If "Yes", return "Sassuga!", And if "No", return "Let's throw it away!".

Webhook


@Slf4j
@LineMessageHandler
public class WebhookController {

    //Response when text is sent
    @EventMapping
    public void handleTextMessageEvent(MessageEvent<TextMessageContent> event) throws Exception {

        //Get the entered text
        String text = content.getText();

        switch (text) {
            case "Yes": {
                this.reply(replyToken,
                        new TextMessage("That's right!")
                );
                break;
            }
            case "No": {
                this.reply(replyToken,
                        new TextMessage("Let's throw it away!")
                );
                break;
            }
            default:
                log.info("Returns echo message {}: {}", replyToken, text);
                this.replyText(
                        replyToken,
                        text
                );
                break;
        }
    }
}

Verification

Remarks

response

The example returns text, but you can have multiple messages in an array.

reply


this.reply(replyToken,
            Arrays.asList(
                new StickerMessage("1", "13"),    //stamp
                new TextMessage("That's right!")    //text
            )
);

Environment variable

You can have an environment variable on heroku and refer to its value from the properties file.

ss.png

application.properties


line.bot.channelSecret = ${LINE_BOT_CHANNEL_SECRET}
line.bot.channelToken = ${LINE_BOT_CHANNEL_TOKEN}
line.bot.handler.path = /callback

Scheduling

Once you get here, all you have to do is push it on time! Use Spring's scheduling function @Scheduled.

ScheduledTask


@Slf4j
@Service
public class ScheduledTaskService {

    private static final SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(cron="/*Description of cron*/", zone = "Asia/Tokyo")
    public void executeAlarm() {
        try {
            //Call the process to push
            pushAlarm();
        } catch (URISyntaxException e) {
            log.error("{}", e);
        }
        log.info("cron executed : " + sdf.format(new Date()));
    }
}

That's all there is to it!

Finally

I think you can have a little fun with the garbage that you tend to forget (´ω` *)

The "kitchen sink" in LINE Messaging API SDK (for Java) was very helpful in making it. At first, the part that pushes the message, I implemented it myself without using the SDK ... w It's easier to write clearly using the SDK.

This time, the alert is only for burning garbage days, but you can expand it to create non-burnable garbage days. You can also increase the number of messages and send random messages or send stamps. Please make an original reminder;)

Source code

https://github.com/aytdm/garbage-reminder-bot/tree/v.1.0 (The message may be in English or a stamp may be displayed, but the basics are the same as what is written here.)

Recommended Posts

Make a garbage reminder with line-bot-sdk-java
Make a digging maze with Ruby2D
Make a slideshow tool with JavaFX
Make a Christmas tree with swift
Make a list map with LazyMap
Make a typing game with ruby
Let's make a Christmas card with Processing!
Make a family todo list with Sinatra
Make a family todo list with Sinatra
Let's make a smart home with Ruby!
Make a login function with Rails anyway
[docker] [nginx] Make a simple ALB with nginx
Make a site template easily with Rails
Let's make a search function with Rails (ransack)
Make System.out a Mock with Spock Test Framework
Run Scala with GraalVM & make it a native image
Let's make a LINE Bot with Ruby + Sinatra --Part 2
[Java basics] Let's make a triangle with a for statement
[Personal application work memo] Make a calendar with simple_calendar
Make a reflection utility ②
Make a reflection utility ③
Let's make a LINE Bot with Ruby + Sinatra --Part 1
Make a reflection utility ①
[Beginner] Try to make a simple RPG game with Java ①
I want to make a list with kotlin and java!
I want to make a function with kotlin and java!
Make a simple CRUD with SpringBoot + JPA + Thymeleaf ① ~ Hello World ~
Learning Ruby with AtCoder 13 How to make a two-dimensional array
Let's make a simple API with EC2 + RDS + Spring boot ①
Make a simple CRUD with SpringBoot + JPA + Thymeleaf ⑤ ~ Template standardization ~
Microservices with DevOps Make Changes
Create a playground with Xcode 12
Draw a gradient with CAGradientLayer
[Java] Make it a constant
[Rails] Make a breadcrumb trail
Make a rhombus using Java
A story stuck with NotSerializableException
Let's make a book management web application with Spring Boot part1
How to make a jar file with no dependencies in Maven
Let's make a book management web application with Spring Boot part3
Let's make a book management web application with Spring Boot part2
Make a C compiler to use with Rust x CLion with Docker
I tried to make a group function (bulletin board) with Rails