1
5

More than 3 years have passed since last update.

discord.py+gspreadで出退勤を管理してみる

Last updated at Posted at 2020-06-29

背景

自宅作業をしながら、出社している感を出すために、discordで何かできないかなぁと考えて、ボイスチャンネルに入っている時を出社、抜けたら退社したみたいなことができるbotを作ってみた。

作成物

kintai.gif

使った技術

  • discord.py
  • gspread

やったこと

  • ボイスチャンネルのin/outの検知
  • google spread sheetへの保存
  • テキストへのリアクション付与

ボイスチャンネルのin/outの検知

discord.Clinenton_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.Messageadd_reaction(emoji)を用いて実装。また、一番最近の投稿を取得するためにはdiscord.TextChannelhistory(*)を用いた。

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

感想

次は、出勤情報のサマリーを出す機能を作ってみよう。

参考サイト

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