LoginSignup
4
1

More than 3 years have passed since last update.

DiscordのwebhookにEmbedデータを送る

Last updated at Posted at 2019-12-17

定期的にsqlite3のDBに保存したデータをチェックして人気の作品をピックアップ。
Discordのembed形式でシンプルにpostでDiscordチャンネルのWebhookへ通知します。
雑談Slack Advent Calendar 2019 18日目の関連記事でもあります。

実行イメージ

Qiita説明用1-Discordページ.png

ソース

1.36時間以内の投稿で、260以上のfav値になっているものを投稿日順でピックアップ。
2.元データに含まれる特殊な文字等をreで除去。
3.投稿データをjson形式のEMBEDデータに整形。
4.requests.postでWebhookへ送る。

import glob,re,sqlite3,os,ssl,json,datetime,time
import requests

webhook_url = '<https://discordapp.com/api/webhooks/~チャンネルに設定したWebHookのURL>'
conn = sqlite3.connect("/media/pi/iwaiwadata/hoge.db")
conn.text_factory = str
csr = conn.cursor()

#無視するユーザー名、ユーザーid
ignoreUsernames = ['','','','']
ignoreUserids = ['9999999','1234567']

#36時間前
timedelta       = datetime.timedelta(hours=36)
dtnow           = datetime.datetime.now()
beforedate      = dtnow - timedelta
after_postdate  = beforedate.strftime('%Y-%m-%d %H:%M:%S')
csr.execute('select * from videoinfo WHERE fav > 259 AND postdate > "'+ after_postdate +'"  ORDER BY postdate ASC')
pickupvids = csr.fetchall()

infocount = 0
if(pickupvids is None):
    quit

for col in pickupvids:
    videoUrl    = "https://特定動画サイト/videos/" + str(col[0])
    fav         = str(col[2])
    views       = str(col[3])
    userid      = str(col[4])
    username    = str(col[5])
    userurl     = str(col[6])
    title       = str(col[7])
    postdate    = str(col[8])
    title       = title.replace(' ','\u3000').replace('\\','¥').replace('/','/').replace('|','|').replace('>','>').replace('<','<')
    title       = title.replace('*','*').replace('?','?').replace(':',':').replace('"','”')
    title       = re.sub(" +",' ',title)
    title       = re.sub("^ ",'',title)
    title       = re.sub(" $",'',title)
    title       = re.sub('\u200E','',title)
    postdate    = re.sub(":00$","",postdate)

    if((username not in ignoreUsernames)and(userid not in ignoreUserids)):
    #投稿するEMBEDなJSONデータ作成
        main_content = {
            "content": "",
            "embeds": [
                {
                    "author": {
                        "name": username ,
                        "url": userurl
                    },
                    "title": title ,
                    "url": videoUrl ,
                    "fields": [
                        {
                            "name": "postdate / views / favo",
                            "value": postdate +" :eye:" + views + " :heart:" + fav,
                            "inline": True
                        }
                    ],
                    "color": 5620992
                    }
                ]
            }
        if(infocount == 0):
            #初回のみrequests.postでWebhookへ最初の1文送る
            requests.post(webhook_url,json.dumps({"content": "36時間以内の投稿より、:heart:260以上の作品をピックアップします"}),headers={'Content-Type': 'application/json'})
            time.sleep(5)
        #requests.postでWebhookへEMBEDデータ送る
        requests.post(webhook_url,json.dumps(main_content),headers={'Content-Type': 'application/json'})
        time.sleep(10)
        infocount = infocount + 1

いかがでしたか

適当に作ってみましたがそこそこ普通に動いています。
わからないことあったらDiscord EmbedなどでQiita検索すると良いと思います!

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