0
4

More than 3 years have passed since last update.

あなたは何柱?お館様による柱任命bot (Discord)

Last updated at Posted at 2020-11-09

はじめに

もし、自分が鬼滅の刃に登場でき、柱になれるとしたら何柱になれるのか疑問に思いました。
なので、お館様を作ってしまい、柱に認定していただくことにしました。

実装

前準備

まず下記の環境構築をしていきます。
Discord Bot(基礎編)

メインとなる処理部分を変更

glitch内に仕込んだserver.jsを変更していきます。

server.js
const http = require('http');
const querystring = require('querystring');
const discord = require('discord.js');
const client = new discord.Client();

http.createServer(function(req, res){
  if (req.method == 'POST'){
    let data = "";
    req.on('data', function(chunk){
      data += chunk;
    });
    req.on('end', function(){
      if(!data){
        res.end("No post data");
        return;
      }
      const dataObject = querystring.parse(data);
      console.log("post:" + dataObject.type);
      if(dataObject.type == "wake"){
        console.log("Woke up in post");
        res.end();
        return;
      }
      res.end();
    });
  }
  else if (req.method == 'GET'){
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Discord Bot is active now\n');
  }
}).listen(3000);

client.on('ready', message =>{
 client.user.setActivity('永遠というのは人の想いだ');
});

client.on('message', message =>{
 if (message.author.id == client.user.id){
   return;
 }
 if(message.isMemberMentioned(client.user)){
   var text = "<@" + message.author.id + ">";

   const PillarName = ['炎柱:', '水柱:', '恋柱:', '蟲柱:', '音柱:', '岩柱:', '霞柱:', '蛇柱:', '風柱:']
   const random = Math.round(Math.random() * 9);
   const name = PillarName[random];

   message.guild.member(message.author.id).setNickname(name + message.member.displayName);

   text = "これからは<@!" + message.author.id + ">として鬼殺隊を支えてくれるかい?";
   message.channel.send(text);
   return;
 }
});

if(process.env.DISCORD_BOT_TOKEN == undefined){
 console.log('DISCORD_BOT_TOKENが設定されていません。');
 process.exit(0);
}

client.login( process.env.DISCORD_BOT_TOKEN );

function sendReply(message, text){
  message.reply(text)
    .then(console.log("リプライ送信: " + text))
    .catch(console.error);
}

function sendMsg(channelId, text, option={}){
  client.channels.get(channelId).send(text, option)
    .then(console.log("メッセージ送信: " + text + JSON.stringify(option)))
    .catch(console.error);
}

実行

まずは、下記のような感じにお館様と僕がいることを確認します。

スクリーンショット 2020-11-10 0.08.09.png

それでは、お館様を呼んでみましょう。
スクリーンショット 2020-11-10 0.00.46.png
やった、蛇柱ですねw
ちなみに柱は、arrayリストにしてあり、ランダムで何が出るかは分かりません。

['炎柱:', '水柱:', '恋柱:', '蟲柱:', '音柱:', '岩柱:', '霞柱:', '蛇柱:', '風柱:']

そして任命とともに、Discord上のニックネームが下記のように自動で変更されます。
これで今日から蛇柱と名乗れます。

スクリーンショット 2020-11-10 0.13.35.png

おわり

ちなみに上記のコードは、botを追加したサーバの管理者での実行はできないです。(ロールの問題により)

参考

Discord Bot(基礎編)
湯婆婆bot

0
4
2

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
4