3
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 1 year has passed since last update.

Kaggle用にプログラム終了後にdiscordで通知を送りたい

3
Posted at

はじめに

Kaggleのコンペティションや機械学習を回しているときに、学習が終了したら教えてほしいなぁ。
そう思ったことはありませんか?

以前はLine Notifyを使って、通知してもらっていたがLine Notifyは2025年4月でサービスが終了してしまったらしい。

何を使うか?

個人的にslackとdiscordで迷った。

よく悩んだ結果、自分は趣味で機械学習を動かすことが多いので、普段使いしているdiscordにした。
(プライベートと仕事の通知を分けられて良いとも思った。)

どうやってやる?

Webhookを使って、discordのチャンネルに投稿するのが良さそう。

ちなみにWebhookとは??という人は↓のLinkを見るとわかりやすいかも

何かのイベントが起きたらとあるURLへ向けってmessageを送るような仕組みだと考えると良い

手順

discordチャンネルからwebhookのurlを取得する

  1. Discord で通知を送りたいチャンネルに移動
  2. チャンネル名の横の「⚙️設定アイコン」をクリック → 「連携サービス」へ
  3. 「Webhook」→「新しい Webhook を作成」→ 任意の名前とチャンネルを設定して「保存」
  4. 「Webhook URL」をコピー(例:https://discord.com/api/webhooks/xxxxxxxxxx/xxxxxxxxxx)
上記のURLが他の方にバレると悪用される可能性があるので取扱注意!!

以下のコードをコードの最後のcellにコピペする

discord_bot.py
import requests
import traceback

DISCORD_WEBHOOK_URL = "https://discord.com/api/webhooks/xxxxxxx/xxxxxxx" 
# 自分のdiscordのWebhook URLに置き換え

def send_discord_notification(message):
    data = {"content": message}
    response = requests.post(DISCORD_WEBHOOK_URL, json=data)
    if response.status_code != 204:
        print(f"通知失敗: {response.status_code}, {response.text}")


send_discord_notification("✅ プログラムが正常に終了しました ")

ちなみに....
以下のようにメイン処理のところに好きな処理を書けば,エラーの時はエラー通知もできます。

discord_bot.py
import requests
import traceback

DISCORD_WEBHOOK_URL = "https://discord.com/api/webhooks/xxxxxxx/xxxxxxx" 
# 自分のdiscordのWebhook URLに置き換え

def send_discord_notification(message):
    data = {"content": message}
    response = requests.post(DISCORD_WEBHOOK_URL, json=data)
    if response.status_code != 204:
        print(f"通知失敗: {response.status_code}, {response.text}")

try:
    # ======= メイン処理 =======
    print("処理を開始します")
    # ここに実行したいコードを書く(例:機械学習の学習、データ処理など)
    
    # =========================

    send_discord_notification("✅ プログラムが正常に終了しました ")

except Exception as e:
    error_message = f"❌ プログラムがエラーで終了しました\n```\n{traceback.format_exc()}\n```"
    send_discord_notification(error_message)
    raise  

という感じです

3
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
3
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?