LoginSignup
0
1

More than 1 year has passed since last update.

【20日目】discord.jsで受け取ったメッセージをすべてLINEに転送する

Last updated at Posted at 2022-12-19

はじめに

こんにちは、なりかくんです。
今回は、discord.jsを使って受け取ったメッセージをすべてLINEに転送するプログラムを作ってみようと思います。

LINEでメッセージを送信する

まず、LINEにメッセージを送る方法ですがLINE Notifyというシステムを使いたいと思います。
LINE上でまず一人のグループを作ります。作れたらLINE Notifyのサイトにログインします。
https://notify-bot.line.me/ja/

image.png

ログインしたらマイページに移動して、開発者向けのアクセストークンを発行してください。
image.png

なお、送信するトークルームは先ほど作成したグループを選びます。トークン名はなんでもいいです。
image.png

発行したらトークンをメモしておきます。
image.png

また、作ったグループにLINE Notifyを追加してあげます。

これでLINEの設定は終わりです。

次にLINE Notifyに送信するコードです。今回は受け取ったメッセージをすべて送信するというクソみたいなコードを作りました。そのコードが以下のコードです。

linenotify.js
const request = require("request");
const { Client, GatewayIntentBits, IntentsBitField } = require('discord.js');
const { token } = require('./config.json');

const client = new Client({ intents: [GatewayIntentBits.Guilds, IntentsBitField.Flags.GuildMessages, IntentsBitField.Flags.MessageContent] });

client.on('ready', () => {
	console.log(`${client.user.tag}でログインしました。`);
});

client.login(token);

client.on('messageCreate', async message => {
	try {
        if (message.author.bot) return;
        await sendLineNotify(message.content);
	} catch (error) {
		console.error(error);
	}
});

function sendLineNotify(msg) {
    return new Promise((resolve, reject) => {
        request({
            url: "https://notify-api.line.me/api/notify",
            method: "POST",
            json: true,
            form: {
                message: msg
            },
            headers: {
                'Authorization': "Bearer <Token>",
                'Content-Type': 'application/x-www-form-urlencoded',
            }
        }, function (error, response, body) {
            if (error) {
                reject(error);
            } else {
                resolve(body);
            }
        });
    });
}

内容としては、messageCreateで受け取ったイベントのメッセージをすべてリクエストにかけているだけです。
なお、LINE Notifyには以下のURLにPOSTして送信します。

https://notify-api.line.me/api/notify

詳細の仕様は以下のドキュメントをご覧ください。

実際に動かしてみる

実際にメッセージを送ってみると
image.png
LINE側にも送信されることが確認できました。
image.png

注意点

最後に注意点です。LINE Notifyにはレートリミットという1時間に何回APIを叩けるかを制限システムが導入されています。詳しくは、ドキュメントをご覧ください。

以上です、最後までお読みいただきありがとうございました。

0
1
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
0
1