1
0
Autopost/main.py

73 lines
2.3 KiB
Python
Raw Normal View History

2023-11-23 14:42:39 +09:00
import asyncio
import os
2023-11-23 17:24:00 +09:00
import random
2023-11-23 14:42:39 +09:00
import gspread
from aiohttp import ClientWebSocketResponse
2023-11-23 15:42:58 +09:00
from gspread.worksheet import Worksheet
2023-11-23 17:24:00 +09:00
from mipac.models.notification import NotificationNote
2023-11-23 14:42:39 +09:00
from mipa.ext import commands
from dotenv import load_dotenv
load_dotenv()
2023-11-24 09:15:54 +09:00
class Autoposter(commands.Bot):
2023-11-23 14:42:39 +09:00
def __init__(self):
super().__init__()
2023-11-24 09:15:54 +09:00
self.max_count = int(os.getenv("MAX_DUPLICATE_COUNT"))
2023-11-23 14:42:39 +09:00
2023-11-23 15:42:58 +09:00
def get_worksheet(self) -> Worksheet:
2023-11-23 14:42:39 +09:00
gc = gspread.service_account()
sh = gc.open_by_url(os.getenv("SPREADSHEET_URL"))
worksheet = sh.get_worksheet(0)
return worksheet
2023-11-24 09:15:54 +09:00
def get_random_line(self) -> str:
2023-11-23 17:24:00 +09:00
sheet: Worksheet = self.get_worksheet()
2023-11-23 15:42:58 +09:00
response = sheet.get("F4")
if response is None or response == "":
return
count = int(response[0][0])
result = random.randint(1, count)
number = result + 2
res = sheet.get(f"D{number}")
text = res[0][0].strip()
return text
2023-11-24 09:15:54 +09:00
def get_info(self, line: str) -> dict:
sheet = self.get_worksheet()
result = sheet.find(line, in_column=4)
number = result.row - 2
where = sheet.get(f"C{result.row}")
where = where[0][0]
return {"number": number, "from": where}
2023-11-23 15:42:58 +09:00
2023-11-23 14:42:39 +09:00
async def _connect_channel(self):
await self.router.connect_channel(['main', 'global'])
async def on_ready(self, ws: ClientWebSocketResponse):
2023-11-24 09:15:54 +09:00
print(f"Connected as @{self.user.username}@{self.user.host}")
2023-11-23 14:42:39 +09:00
await self._connect_channel()
2023-11-24 09:15:54 +09:00
extensions = [
"exts.post"
]
for extension in extensions:
await self.load_extension(extension)
2023-11-23 14:42:39 +09:00
async def on_reconnect(self, ws: ClientWebSocketResponse):
2023-11-24 09:15:54 +09:00
print("Disconnected from server.")
2023-11-23 14:42:39 +09:00
await self._connect_channel()
2023-11-23 15:42:58 +09:00
async def on_mention(self, notice: NotificationNote):
2023-11-24 09:15:54 +09:00
line = self.get_random_line()
info = self.get_info(line)
await notice.note.api.action.reply(content=f"{line}\n \n<small>- {info['where']}에서 발췌됨. ({info['number']}번 대사)</small>", reply_id=notice.note.id)
2023-11-23 14:42:39 +09:00
if __name__ == '__main__':
2023-11-24 09:15:54 +09:00
bot = Autoposter()
2023-11-23 14:42:39 +09:00
loop = asyncio.get_event_loop()
2023-11-24 09:15:54 +09:00
origin = os.getenv("MISSKEY_ORIGIN")
loop.run_until_complete(bot.start(f"wss://{origin}/streaming", os.getenv("MISSKEY_TOKEN")))