LoginSignup
7
1

More than 3 years have passed since last update.

前書き

みなさんチャットツールなに使ってますかー?
テレワークが増えてきて、何かと使う機会が増えてきているかと思います。その中で"偏見"と"偏見"と"偏見"だけで一番使われているであろうdiscord(前から自分が使ってたから)のbot君を紹介したいと思います

今回はdiscordの特定サーバにユーザがjoinしたらslackに通知するようにしたいと思います

環境

  • discord.py: 1.5.1
  • python: 3.8.1
  • requests: 2.25.0

書かないこと

  • discordbotのTOKEN準備
  • slack Incoming Webhooksの作成

(一応参考記事だけ載せておきます)

slack

【2020年度版】Slack通知はSlack AppのIncoming Webhooksを使おう!やり方を解説

discord

Discord Botアカウント初期設定ガイド for Developer

discord.py

discordのapiをwrapperしているライブラリです。
公式ドキュメントがしっかりとしているので、何か困ったら、まず見ることをお勧めします
(https://discordpy.readthedocs.io/ja/latest/api.html)

最小構成でお為しbot

公式に最小構成コードが乗っていますので、まずはこちらを動かしたいと思います

コード

Main.py
import discord

client = discord.Client()

# botが起動したら行われる処理
@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

# テキストチャンネルに投稿されたことをトリガーに動く
@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if message.content.startswith('$hello'):
        await message.channel.send('Hello!')

client.run('your token here')

実際に起動してみましょう

$ python Main.py

discordのチャットで、$helloと入力すると、botからHello!と返ってくると思います

slackにjoin通知を送る

次に特定のdiscordにユーザがjoinしたらslackに通知を飛ばしたいと思います

コード

import discord
import requests
import json

# client = discord.Client()
TOKEN = "discordbotのTOKEN"
MY_SERVER = "serverのID"

client = discord.Client()

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

@client.event
async def on_member_join(member):
    if member.guild.id == MY_SERVER:
        payload = {
            "text": f"領域展開: {member.name}"
        }
        headers = {'content-type': 'application/json'}
        url = # slack Incoming WebhooksのURL
        response = requests.post(url, data=json.dumps(payload), headers=headers)

client.run(TOKEN)

ユーザがjoinしたことをトリガーにon_member_join(member)の中が動きます
中身の処理では、requestsを使用してPOSTをslackのIncoming Webhooksに送っています

では、実際にユーザをJOINして動作確認してみましょう

...

..

.

う...うごかない...

discord APIの仕様が変わり、既存のままだと動かなくなってしまったようです
discord.py君が教えてくれました
A Primer to Gateway Intents

discord.py1.5以降の場合は以下コードに修正・追加してください

intents = discord.Intents.all()
intents.members = True
client = discord.Client(intents=intents)

動作確認

Slackのチャンネル
image.png

ちゃんと見ててくれてますね!

なんで作ったの?

image.png

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