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

Account bug fix #13

Merged
merged 2 commits into from
Oct 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1 @@
# letusc: `v7.0.0`
# letusc: `v7.0.2`
94 changes: 90 additions & 4 deletions letusc/cogs/task.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
from datetime import datetime
import asyncio
from datetime import datetime, timedelta

import discord
from discord.ext import commands, tasks

from letusc.tasks.account_task import RegisterAccountLoopTask, RegisterAccountTask

from ..chat import DiscordChatThread, EmbedBuilder
from ..db import DBManager
from ..logger import L
Expand All @@ -21,23 +24,45 @@ def __init__(self, bot_: discord.Bot):
self._l = L(self.__class__.__name__)
_l = self._l.gm("__init__")
self.bot = bot_
self.cookie_ready = asyncio.Event()
self.fetchAll.start()
self.checkAllAccount.start()

def cog_unload(self):
self.fetchAll.cancel()
self.checkAllAccount.cancel()

@tasks.loop(minutes=int(env("CRAWLER_INTERVAL")))
async def fetchAll(self):
_l = self._l.gm("fetchAll")
_l.info("task started")

await self.bot.wait_until_ready()
await self.cookie_ready.wait()

await self.bot.change_presence(
activity=discord.Activity(
application_id=env("APP_DISCORD_CLIENT_ID"),
name="Letusc",
type=discord.ActivityType.playing,
state="fetching pages",
details="fetching all pages",
timestamps={"start": datetime.now().timestamp()},
assets={"large_image": "letusc-icon", "large_text": "Letusc"},
)
)

collection = DBManager.get_collection("letus", "pages")
cursor = collection.find({})

count = 0
async for page in cursor:
task = await FetchPageLoopTask.create(page)
await task.run()
_l.info(task.code)
try:
task = await FetchPageLoopTask.create(page)
await task.run()
_l.info(task.code)
except Exception as e:
_l.error(e)
count += 1

chat = await DiscordChatThread.get(
Expand All @@ -53,3 +78,64 @@ async def fetchAll(self):
timestamp=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
)
)

await self.bot.change_presence(
activity=discord.Activity(
application_id=env("APP_DISCORD_CLIENT_ID"),
name="Letusc",
type=discord.ActivityType.playing,
state="waiting for next fetch",
details="waiting for next fetch",
timestamps={
"end": (
datetime.now() + timedelta(minutes=int(env("CRAWLER_INTERVAL")))
).timestamp()
},
assets={"large_image": "letusc-icon", "large_text": "Letusc"},
)
)

@tasks.loop(hours=12)
async def checkAllAccount(self):
_l = self._l.gm("checkAllAccount")
_l.info("task started")

await self.bot.wait_until_ready()

# wait for maintenance time to end
maintenance_start = datetime.strptime("04:00", "%H:%M").time()
maintenance_end = datetime.strptime("05:30", "%H:%M").time()
while True:
now = datetime.now().time()
if maintenance_start <= now <= maintenance_end:
_l.info("waiting for maintenance time to end")
await asyncio.sleep(10 * 60)
else:
break

await self.bot.change_presence(
activity=discord.Activity(
application_id=env("APP_DISCORD_CLIENT_ID"),
name="Letusc",
type=discord.ActivityType.playing,
state="checking accounts",
details="checking all accounts",
timestamps={"start": datetime.now().timestamp()},
assets={"large_image": "letusc-icon", "large_text": "Letusc"},
)
)

collection = DBManager.get_collection("letus", "accounts")
cursor = collection.find({})

count = 0
async for account in cursor:
try:
task = await RegisterAccountLoopTask.create(account)
await task.run()
_l.info(task.multi_id)
except Exception as e:
_l.error(e)
count += 1

self.cookie_ready.set()
8 changes: 8 additions & 0 deletions letusc/embed_settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -83,5 +83,13 @@
"inline": true
}
]
},
"task.account.registered": {
"content": "",
"title": "アカウントの登録",
"description": "アカウントの登録が完了しました。",
"color": 4176208,
"url": "",
"fields": []
}
}
29 changes: 29 additions & 0 deletions letusc/tasks/account_task.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,3 +105,32 @@ async def run(self): # TODO: fix this
account = Account(self.multi_id)
# _SessionManager(account).login()
# account.push()


@dataclass
class RegisterAccountLoopTask(AccountTaskBase):
_l = L()
task: str = field(init=False, default="account:register")
account: Account

def __post_init__(self):
self._l = L(self.__class__.__name__)
_l = self._l.gm("__post_init__")

@classmethod
async def create(cls, object: dict):
_l = L(cls.__name__).gm("create")
account = Account(object["student_id"])
account.from_api(object)
return cls(
account=account,
)

async def run(self):
_l = self._l.gm("run")
_l.info("Registering account")

await Authenticator(self.account).register()
await self.account.push()
chat = await DiscordChatUser.get(int(self.account.discord_id))
await chat.SendMessage("Letusにログインしました。")
32 changes: 28 additions & 4 deletions letusc/tasks/page_task.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,10 +213,10 @@ def __post_init__(self):
self._l = L(self.__class__.__name__)
_l = self._l.gm("__post_init__")

@classmethod
async def from_api(cls, task: dict) -> "FetchPageLoopTask":
_l = L(cls.__name__).gm("from_api")
return cls(multi_id=task["discord_id"], code=PageCode.create(task["code"]))
# @classmethod
# async def from_api(cls, task: dict) -> "FetchPageLoopTask":
# _l = L(cls.__name__).gm("from_api")
# return cls(multi_id=task["discord_id"], code=PageCode.create(task["code"]))

@classmethod
async def create(cls, object: dict):
Expand Down Expand Up @@ -244,6 +244,30 @@ async def run(self):
parser = await Parser.from_page(_page)
push = await parser.compare()

if len(_page.chat) == 0:
_l.warn("No chat bound to the page")
pairs: list[tuple[str, str]] = [
("126936", "1152968855434571867"),
("163437", "1152969064214438030"),
("163553", "1152969125648412792"),
("164484", "1152969427390845029"),
("164486", "1152969614742011995"),
("164493", "1152969663542734879"),
("164503", "1152969706328834138"),
("164505", "1152969770560393287"),
("164512", "1152969809181544580"),
("164519", "1152969835488219276"),
("173694", "1152969890475548682"),
("173522", "1152970007119155302"),
("173491", "1152970071770157087"),
("173391", "1152970144260300891"),
("172880", "1152970218252009502"),
]
for page_id, thread_id in pairs:
if page_id == self.code.page_id:
_page.chat.update({env("DEFAULT_CHANNEL"): thread_id})
push = True

parser.page.chat = _page.chat
parser.page.accounts = _page.accounts

Expand Down