12
9

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のボイスチャンネルに誰かが入ったら通知するbot

Last updated at Posted at 2018-08-11

はじめに

discordrbの記事が少ない!
rubyでbotが書きたい!

今回作るもの

タイトル通り

手順

discordrbのインストール

$ gem install discordrb

Discord botのtokenを取得

ここにアクセスし「Create an application」を押して1つapplicationを作る

CLIENT IDを取得

https://discordapp.com/oauth2/authorize?client_id=ここに取得したClientID&scope=bot&permissions=0

にアクセスしbotをServerに接続させる

するとさきほどのページのbotページからTOKENを取得することができる.

botを作る

とりあえずソースコード

bot.rb
TOKEN = '自分で取得してね'
CLIENT_ID = ID(数字)

# 通知用のチャンネルID
inform_channel = チャンネルID または '#チャンネルname'

# bot
bot = Discordrb::Commands::CommandBot.new token: TOKEN, client_id: CLIENT_ID, prefix:'/'

# 誰かがvoice channelに出入りしたら発火
bot.voice_state_update do |event|
    # 発火させたユーザー名を取得
    user = event.user.name

    # もしデータが空だと抜けていったチャンネルを取得
    if event.channel == nil then
        # チャンネル名を取得
        channel_name = event.old_channel.name

        # 退出したことをinform_channelに通知
        bot.send_message(inform_channel, "@everyone #{user}#{channel_name}を出たで~")
    else
        # チャンネル名を取得
        channel_name = event.channel.name

        # 入室したことをinform_channelに通知
        bot.send_message(inform_channel, "@everyone #{user}#{channel_name}に入ったで~")
    end
end

# botを起動
bot.run

説明?

voice_state_update:ボイスチャンネルで変更があれば発火するイベント
event.user.name:発生されたユーザ名を取得
event.channel:ボイスチャンネルに入室したとき情報が入る.退出したときはnilが入る
bot.send_message(channel_id, '送りたい内容'):channel_id(#channel_nameでも可)にメッセージを送信する

テスト

$ ruby bot.rb

03.png
動いた

12
9
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
12
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?