背景
自宅作業をしながら、出社している感を出すために、discordで何かできないかなぁと考えて、ボイスチャンネルに入っている時を出社、抜けたら退社したみたいなことができるbotを作ってみた。
作成物
使った技術
- discord.py
- gspread
やったこと
- ボイスチャンネルのin/outの検知
- google spread sheetへの保存
- テキストへのリアクション付与
ボイスチャンネルのin/outの検知
discord.Clinent
のon_voice_state_update(self, member, before, after)
を用いて検知
async def on_voice_state_update(self, member, before, after):
if(before.channel is None):
# ボイスチャンネルにinした時の処理
start_work(member)
elif(after.channel is None):
# ボイスチャンネルからoutした時の処理
end_work(member)
google spread sheetへの保存
ⅰ. spread sheetを適当なところに作る(説明略)
ⅱ. GCPでサービスアカウント作成+driveAPI/sheetsAPIの有効化
ⅲ. Pythonにて実装
GCPでサービスアカウント作成+driveAPI/sheetsAPIの有効化
こちらのサイトを参考に行いました。
ⅰ.で作成したspread sheetに作成したサービスアカウントを共同編集者として招待しておく。また、ここで保存した秘密鍵のファイル名を仮にhimitsu.json
としておく。
Pythonにて実装
以下のように実装した。
import json
import gspread
from oauth2client.service_account import ServiceAccountCredentials
def register(record: Dict[str, str]):
scope = [
'https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive'
]
credentials = ServiceAccountCredentials.from_json_keyfile_name('himitsu.json', scope)
gc = gspread.authorize(credentials)
workbook = gc.open_by_key('作成したspread sheetのkey')
sheet = workbook.sheet1
sheet.insert_row(list(record.values()))
テキストへのリアクション付与
保存できたこととかがわかったほうが良いと思ったので、一番最新の投稿にリアクションするようにしました。
discord.Message
のadd_reaction(emoji)
を用いて実装。また、一番最近の投稿を取得するためにはdiscord.TextChannel
のhistory(*)
を用いた。
import discord
class Clinet(discord.Client)
def success_reaction(self, member, is_end=False)
channel = self.get_channel('discordのテキストチャンネルのid')
async for msg in channel.history(limit=10):
if msg.author == member:
await msg.add_reaction("👍") if is_end else await msg.add_reaction("👀")
break
感想
次は、出勤情報のサマリーを出す機能を作ってみよう。