0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Discord】YouTube以外のURLを投稿したらBotがユーザーにお知らせしてくれる機能

0
Posted at

やりたいこと

Discordチャンネルに特定のURL以外(今回はYoutube)はDBに保存させないようかつ、Botが投稿者に対し「受け付けないよ!」とすればよりベターなのではないかと思い、この実装に至りました😊

実装方法

bot.message(with_text: "Ping!") do |event|
  event.respond "Pong!"
end

上記のコードはPing!という完全一致のテキストが送られたらPong!と返信するという簡単なコードです。
これを利用しますが、まずはYouTube以外のみ許可するというコードを実装しなくてはなりません。

app/modelsの中に新しいファイルを作ります。今回はyoutube_url.rbというファイルを作りました。

module YoutubeUrl
  # 固定で許可されたホストを指定
  ALLOWED_HOSTS = %w[youtube.com www.youtube.com music.youtube.com youtu.be].freeze

  def self.valid?(url)
    return false unless url

    host = Addressable::URI.parse(url).host
    ALLOWED_HOSTS.include?(host)
  end
end

モジュールにした理由は

  • 役割が明確になる
  • 修正箇所が1つで済む
  • どこからでも呼び出すことが出来る

引数で渡されたurlが許可されていないものだったらreturn falseが返ってきます。
ここまでできれば9割出来たものと同じです😊

def except_youtube(event)
    return if YoutubeUrl.valid?(event.content)

    event.respond("#{event.author.mention}\n無効のURLです😓 YoutubeまたはYoutube MusicのURLを入力してください👍")
end

↑最終的に出来たのがこれです。アプリを起動し確認すると

スクリーンショット 2026-10-23 22.14.18.png

参考サイト

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?