Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat:GoogleCalendarにイベントを追加するコマンド #6

Open
wants to merge 41 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 30 commits
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
d3ea4ef
feat: GoogleCalenderにイベント追加コマンド
peijun Aug 8, 2020
730e4b3
test: GoogleCalenderのコマンドパースのテスト
peijun Aug 8, 2020
865304d
Update: .env-example
peijun Aug 9, 2020
d44414c
refactor: function name
peijun Aug 9, 2020
686c91c
refactor: command split in logic
peijun Aug 9, 2020
a8d2e89
fix: レビューni
peijun Aug 9, 2020
9874d79
fix: レビューによる変更に対する修正
peijun Aug 9, 2020
eafa8a0
Merge remote-tracking branch 'origin/feature-calender' into feature-c…
peijun Aug 9, 2020
047e83f
refactor: code formatting
peijun Aug 9, 2020
377ac3e
fix: 変更漏れ
peijun Aug 9, 2020
63f1f74
fix: 関数名の変更漏れ
peijun Aug 9, 2020
78148e0
bot.pyにプラグインを追加
peijun Aug 9, 2020
1a65312
fix カンマ忘れ
peijun Aug 9, 2020
240420e
refactor:返り値Noneの明示
peijun Aug 10, 2020
1fd908a
refactor: import文のsort
peijun Aug 10, 2020
02000b6
feat: WEBHOOKをIFTTTからazure functionsに変更
peijun Aug 11, 2020
5b62191
dataclassの導入
peijun Aug 12, 2020
5c91aa0
webhookを使わないで実装
peijun Aug 13, 2020
c6a7351
依存の更新
peijun Aug 13, 2020
2f0f2ab
webhookを使わない実装
peijun Aug 13, 2020
a6c4e2d
Merge remote-tracking branch 'origin/feature-calender' into feature-c…
peijun Aug 13, 2020
f02aa29
ミス
peijun Aug 13, 2020
e3b743c
Eventを扱いやすく
peijun Aug 13, 2020
4f703fa
scheduleからeventへ統一
peijun Aug 13, 2020
913e915
Eventの一部をproperty化
peijun Aug 13, 2020
78f0f6d
関数の返り値の間違いを修正
peijun Aug 13, 2020
5ee9186
突貫工事テスト
peijun Aug 13, 2020
f7a619d
使ってないモジュールの削除
peijun Aug 13, 2020
da6aa58
key.jsonをignore
peijun Aug 15, 2020
a4339c3
Merge branch 'master' into feature-calender
peijun Aug 15, 2020
a68c363
staticmethod化
peijun Aug 15, 2020
94a471d
dictの方ヒント
peijun Aug 15, 2020
e311c65
変数の重複を解消
peijun Aug 15, 2020
0050558
unusedな変数を削除
peijun Aug 15, 2020
d6e6954
add_eventにdictかNoneを返すように指定
peijun Aug 15, 2020
df42a5d
_create_event_objをstaticmethod化
peijun Aug 15, 2020
1f59b70
型ヒントを追加
peijun Aug 15, 2020
d603b91
テスト用classの作成
peijun Aug 15, 2020
5a3bce8
unusedなモジュールの削除
peijun Aug 15, 2020
181c9e8
余分な改行を削除
peijun Aug 15, 2020
e04e232
変数名を変更
peijun Aug 15, 2020
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .env-example
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
DISCORD_BOT_TOKEN=xxxxxxxx
CALENDAR_WEBHOOK_URL=xxxxxxxx
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -138,4 +138,5 @@ dmypy.json
cython_debug/

# Custom
.DS_Store
.DS_Store
key.json
2 changes: 2 additions & 0 deletions Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ black = "*"

[packages]
"discord.py" = "*"
google-api-python-client = "*"
google-auth = "*"

[requires]
python_version = "3.8"
Expand Down
8 changes: 4 additions & 4 deletions bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@

# bot = commands.Bot(command_prefix="!")
token = getenv("DISCORD_BOT_TOKEN")
INITIAL_PLUGINS = [
"plugin.echo"
]
INITIAL_PLUGINS = ["plugin.echo", "plugin.calendar"]

# bot.run(token)
class TheGeneralBot(commands.Bot):
Expand All @@ -18,7 +16,9 @@ def __init__(self, **kwargs):
self.load_extension(cog)
print(f"loaded {cog}")
except Exception as exc:
print(f"Could not load extension {cog} due to {exc.__class__.__name__}: {exc}")
print(
f"Could not load extension {cog} due to {exc.__class__.__name__}: {exc}"
)


bot = TheGeneralBot()
Expand Down
88 changes: 88 additions & 0 deletions logic/calendar.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import datetime
from abc import ABCMeta, abstractmethod
from dataclasses import dataclass
from os import getenv

from google.oauth2 import service_account
from googleapiclient.discovery import build


@dataclass
class Event:
title: str
date: str
starttime: str
endtime: str
location: str

def _get_datetime(date, time) -> str:
peijun marked this conversation as resolved.
Show resolved Hide resolved
today = datetime.datetime.today()
splitteddate = date.split("/")
splittedtime = time.split(":")

return datetime.datetime(
today.year,
int(splitteddate[0]),
int(splitteddate[1]),
int(splittedtime[0]),
int(splittedtime[1]),
).isoformat()

@property
def get_starttime(self) -> str:
datetime = Event._get_datetime(self.date, self.starttime)

return datetime
peijun marked this conversation as resolved.
Show resolved Hide resolved

@property
def get_endtime(self) -> str:
datetime = Event._get_datetime(self.date, self.endtime)

return datetime


class ICalendar(metaclass=ABCMeta):
@abstractmethod
peijun marked this conversation as resolved.
Show resolved Hide resolved
def _get_service():
pass

@abstractmethod
peijun marked this conversation as resolved.
Show resolved Hide resolved
def _create_event_obj(newevent: Event) -> bytes:
peijun marked this conversation as resolved.
Show resolved Hide resolved
pass

@classmethod
@abstractmethod
def add_event(cls, newevent: Event) -> None:
pass


class GoogleCalendarImpl(ICalendar):
def _get_service():
peijun marked this conversation as resolved.
Show resolved Hide resolved
credentials = service_account.Credentials.from_service_account_file("key.json")
scoped_credentials = credentials.with_scopes(
["https://www.googleapis.com/auth/calendar"]
)
service = build("calendar", "v3", credentials=scoped_credentials)

return service

peijun marked this conversation as resolved.
Show resolved Hide resolved
def _create_event_obj(self, newevent) -> dict:
peijun marked this conversation as resolved.
Show resolved Hide resolved
body = {
"summary": newevent.title,
"location": newevent.location,
"start": {"dateTime": newevent.get_starttime, "timeZone": "Japan",},
"end": {"dateTime": newevent.get_endtime, "timeZone": "Japan"},
}

return body

@classmethod
def add_event(cls, newevent) -> None:
body = GoogleCalendarImpl._create_event_obj(newevent)
service = GoogleCalendarImpl._get_service()

event = (
peijun marked this conversation as resolved.
Show resolved Hide resolved
service.events()
.insert(calendarId=getenv("CALENDAR_ID"), body=body)
.execute()
)
27 changes: 27 additions & 0 deletions plugin/calendar.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from discord.ext.commands import Bot, Cog, Context, command

from logic.calendar import GoogleCalendarImpl, Event


class Calendar(Cog):
def __init__(self, bot: Bot) -> None:
self.bot = bot

@command()
async def add_event(
self,
ctx: Context,
title: str,
date: str,
starttime: str,
endtime: str,
location: str,
) -> None:
calendar = GoogleCalendarImpl()
newevent = Event(title, date, starttime, endtime, location)
calendar.add_event(newevent)
await ctx.send("Success!")


def setup(bot):
bot.add_cog(Calendar(bot))
2 changes: 2 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ async-timeout==3.0.1; python_full_version >= '3.5.3'
attrs==19.3.0; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'
chardet==3.0.4
discord.py==1.3.4
google-api-python-client==1.10.0
google-auth==1.20.1
idna==2.10; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'
multidict==4.7.6; python_version >= '3.5'
typing-extensions==3.7.4.2
Expand Down
16 changes: 16 additions & 0 deletions tests/test_calendar.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import json

from logic.calendar import GoogleCalendarImpl, Event


def test_command_parse():
calendar = GoogleCalendarImpl()
newevent = Event("testtitle", "10/10", "10:00", "11:00", "japan")
result = calendar._create_event_obj(newevent)
obj = {
"summary": "testtitle",
"location": "japan",
"start": {"dateTime": "2020-10-10T10:00:00", "timeZone": "Japan"},
"end": {"dateTime": "2020-10-10T11:00:00", "timeZone": "Japan"},
}
assert result == obj