2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

discord.js + canvasjsでユーザーの入室通知を作る

Last updated at Posted at 2019-04-11

はじめまして、Discord.jsでdiscordのBOTを作っている者です。
まだまだ初心者ですが、よろしくお願いします。

※説明が下手くそです、すみません

手始めに

まずNode.jsをインストールしてください。
(自分の場合はUbuntuなのでUbuntuでやる方法を教えます。)

  1. ターミナルを開いてください
  2. ターミナルに〈sudo apt install -y nodejs npm〉を打ち込みます
  3. パッケージのダウンロード、インストールが開始されるのでコーヒーでも飲んで待ってましょう
  4. インストールが終わったら、これでnode.js導入は完了です。

必要なパッケージのインストール

(コマンドはnpm install <パッケージ名>です)
・discord.js
・canvas
・snekfetch

コードを書く

パッケージのインストールが終わったら、コードを書き始めます。

index.js
const Discord = require('discord.js');
const client = new Discord.Client
const Canvas = require('canvas');
const snekfetch = require('snekfetch');

client.on('ready', () => {
  console.log("起動しました。")
 });

client.on('guildMemberAdd', async member => {
	const channel = member.guild.channels.find(ch => ch.name === 'member-log');//member-logというチャンネルを作ると、そこにメッセージが送信される
	if (!channel) return;

	const canvas = Canvas.createCanvas(1050, 250);
	const ctx = canvas.getContext('2d');

	const background = await Canvas.loadImage('./背景画像.jpg');

	ctx.drawImage(background, 0, 0, canvas.width, canvas.height);

  
ctx.strokeStyle = '#74037b';
	ctx.strokeRect(0, 0, canvas.width, canvas.heigh)

  ctx.font = '28px DejaVu';
	ctx.fillStyle = '#ffff00';
	ctx.fillText(`Welcome to ${member.guild.name},`, canvas.width / 3.0, canvas.height / 3.5);

  ctx.font = '28px DejaVu';
	ctx.fillStyle = '#ffff00';
	ctx.fillText(`${member.user.tag}!`, canvas.width / 3.0, canvas.height / 1.8);
  
  ctx.font = '28px DejaVu';
	ctx.fillStyle = '#ffff00';
	ctx.fillText(`id: ${member.user.id}`, canvas.width / 3.0, canvas.height / 1.3);

	ctx.beginPath();
	ctx.arc(125, 125, 100, 0, Math.PI * 2, true);
	ctx.closePath();
	ctx.clip();

	const { body: buffer } = await snekfetch.get(member.user.displayAvatarURL);
	const avatar = await Canvas.loadImage(buffer);
	ctx.drawImage(avatar, 25, 25, 200, 200);
  
  const attachment = new Discord.Attachment(canvas.toBuffer(), 'welcome-image.png');
  
	channel.send(`ようこそ ${member}さん!`, attachment);
});

client.login("トークン");

トークンを取得

client.login("トークン");

この〈トークン〉はここから取得します(https://discordapp.com/developers/applications/)

  1. URLにアクセス
  2. Discordにログイン
  3. New Applicationを押し、BOTの名前を決める、そしてcreateを押す
  4. 左側のBOTを押し、Add Botを押す、警告みたいなのが出るので、Yes, do it!を押す
  5. 色々表示されるので、その中のCopyを押して、トークンのところにペーストします

これでnode index.jsと打てば起動するはずです。
初めての投稿だったのでガバガバなところが多いと思いますが、暖かい目で見守ってください。
それでは。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?