LoginSignup
15
13

More than 1 year has passed since last update.

Next.jsでLINEメッセージを送ってみる。【Let's ハンズオン!】

Posted at

流行のNext.jsを使ってLINEメッセージを送信してみるやで。

Next.js環境構築

まずはなにがともあれNext.jsのプロジェクトを立ち上げてみる。

npx create-next-app line-app --typescript

プロジェクトの作成が完了したら、とりあえず動かしてみるやで。

cd line-app
npm run dev

プロジェクトの構成はこんな感じ。
しんぷるいずべすと。

スクリーンショット 2021-11-06 18.04.30.png

まずは、LINEのSDKを使用するので、以下をinstall

yarn add @line/bot-sdk

編集するのは、以下の3つ。
- pages/api/[word].ts
- pages/index.tsx
- .env.local

それぞれ紹介すると、pages/api/[word].tsがサーバー側でLINEのSDKを使用してメッセージを送信。
pages/index.tsxが画面表示となります。

pages/api/[word].ts
import { NextApiResponse } from 'next'
import * as line from '@line/bot-sdk';

console.log(process.env.NEXT_PUBLIC_LINE_ACCESS_TOKEN!)

const config = {
  channelAccessToken: process.env.NEXT_PUBLIC_LINE_ACCESS_TOKEN!,
  channelSecret: process.env.NEXT_PUBLIC_LINE_CHANNEL_SECRET!
};

const client = new line.Client(config);

export default ({ query: { word } }: { query: { word: string } }, res: NextApiResponse) => {
  console.info('res data', word)
  client.broadcast({
    type: "text",
    text: word
  }).then(data => console.log(data))
    .catch(e => console.log(e))
  res.status(200).json({ message: `you requested for ${word} ` });
};
pages/index.tsx
import { useState } from 'react';
import type { NextPage } from 'next';
import styles from '../styles/Home.module.css';

const Home: NextPage = () => {
  const [text, setText] = useState<string>('');
  const sendLine = async () => {
    const response = await fetch(`http://localhost:3000/api/${text}`);
    const data = await response.json();
    console.log('🚀 ~ file: index.tsx ~ line 11 ~ sendLine ~ data', data);
  };
  return (
    <div className={styles.container}>
      <main className={styles.main}>
        <h1>LINE message送信</h1>
        <br />
        <input type="text" onChange={(e) => setText(e.target.value)} />
        <button onClick={sendLine}>送信</button>
      </main>
    </div>
  );
};

export default Home;

env.local
NEXT_PUBLIC_LINE_ACCESS_TOKEN="xxxxxxxxxxx"
NEXT_PUBLIC_LINE_CHANNEL_SECRET="xxxxxxxxxxxxxxx"

超絶シンプル画面ができましたか?

スクリーンショット 2021-11-06 18.11.42.png

このテキストエリアに文字を入力して、送信ボタンをクリックでLINEのメッセージが飛びます。

スクリーンショット 2021-11-06 18.12.53.png

みんなもLINEBotを作ってみてね。

ゆうじろうが運営しているプログラミングスクールです。
是非遊びにきてね。

15
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
13