ニジカのスカトロ,ニジカトロ. https://bsky.app/profile/deerjika-bot.bsky.social
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

306 lines
12 KiB

  1. from __future__ import annotations
  2. import asyncio
  3. import os
  4. import time
  5. from datetime import datetime
  6. from io import BytesIO
  7. from typing import Any, TypedDict
  8. import atproto # type: ignore
  9. import requests
  10. from atproto import Client # type: ignore
  11. from atproto_client.models import AppBskyEmbedExternal, AppBskyEmbedImages, ComAtprotoRepoStrongRef # type: ignore
  12. from atproto_client.models.app.bsky.feed.get_timeline import Response # type: ignore
  13. from atproto_client.models.app.bsky.feed.post import ReplyRef # type: ignore
  14. from requests.exceptions import Timeout
  15. import account
  16. import nicolib
  17. from nizika_ai.consts import Character, GPTModel, Platform, QueryType
  18. from nizika_ai.models import Answer, AnsweredFlag, Query, User
  19. TARGET_WORDS = ['deerjika', 'ニジカ', 'ぼっち', '虹夏', '郁代', 'バーカ',
  20. 'kfif', 'kita-flatten-ikuyo-flatten', 'ラマ田', 'ゴートう',
  21. 'ぼざクリ', 'オオミソカ', '伊地知', '喜多ちゃん',
  22. '喜タイ', '洗澡鹿', 'シーザオ', '今日は本当に',
  23. 'ダイソーで', '変なチンチン', 'daisoで', 'だね~(笑)',
  24. 'おやつタイム', 'わさしが', 'わさび県', 'たぬマ', 'にくまる',
  25. 'ルイズマリー', '餅', 'ニジゴ', 'ゴニジ', 'ニジニジ',
  26. '新年だよね', 'うんこじゃん', 'ほくほくのジャガイモ']
  27. time.sleep (60)
  28. client = Client (base_url = 'https://bsky.social')
  29. client.login (account.USER_ID, account.PASSWORD)
  30. async def main (
  31. ) -> None:
  32. """
  33. メーン処理
  34. """
  35. await asyncio.gather (like_posts (),
  36. check_mentions (),
  37. answer ())
  38. async def like_posts (
  39. ) -> None:
  40. while True:
  41. try:
  42. for post in fetch_target_posts ():
  43. client.like (**post)
  44. except Exception as e:
  45. print (f"[like_posts] { type (e).__name__ }: { e }")
  46. await asyncio.sleep (60)
  47. async def check_mentions (
  48. ) -> None:
  49. while True:
  50. try:
  51. for uri in check_notifications ():
  52. records = fetch_thread_contents (uri, 20)
  53. if records:
  54. record = records[0]
  55. image_url: str | None = None
  56. if record['embed'] and hasattr (record['embed'], 'images'):
  57. image_url = ('https://cdn.bsky.app/img/feed_fullsize/plain'
  58. f"/{ record['did'] }"
  59. f"/{ record['embed'].images[0].image.ref.link }")
  60. user = _fetch_user (record['did'], record['name'])
  61. _add_query (user, record['text'], image_url, {
  62. 'uri': record['strong_ref']['uri'],
  63. 'cid': record['strong_ref']['cid'] })
  64. except Exception as e:
  65. print (f"[check_mentions] { type (e).__name__ }: { e }")
  66. await asyncio.sleep (60)
  67. async def answer (
  68. ) -> None:
  69. while True:
  70. answered_flags = (
  71. AnsweredFlag
  72. .where ('platform', Platform.BLUESKY.value)
  73. .where ('answered', False)
  74. .get ())
  75. for answered_flag in answered_flags:
  76. td: dict[str, Any]
  77. answer = answered_flag.answer
  78. answered_flag.answered = True
  79. answered_flag.save ()
  80. match QueryType (answer.query_rel.query_type):
  81. case QueryType.BLUESKY_COMMENT:
  82. td = answer.query_rel.transfer_data or { }
  83. uri: str | None = td.get ('uri')
  84. cid: str | None = td.get ('cid')
  85. if (not uri) or (not cid):
  86. continue
  87. strong_ref = ComAtprotoRepoStrongRef.Main (uri = uri, cid = cid)
  88. reply_ref = ReplyRef (root = strong_ref, parent = strong_ref)
  89. try:
  90. client.post (answer.content[:250], reply_to = reply_ref)
  91. except Exception as e:
  92. print (f"[answer/reply] { type (e).__name__ }: { e }")
  93. continue
  94. case QueryType.KIRIBAN | QueryType.NICO_REPORT:
  95. td = answer.query_rel.transfer_data or { }
  96. video_code: str | None = td.get ('video_code')
  97. if not video_code:
  98. continue
  99. uri = f"https://www.nicovideo.jp/watch/{ video_code }"
  100. (title, description, thumbnail) = nicolib.fetch_embed_info (uri)
  101. try:
  102. resp = requests.get (thumbnail, timeout = 60)
  103. resp.raise_for_status ()
  104. upload = client.com.atproto.repo.upload_blob (BytesIO (resp.content))
  105. thumb = upload.blob
  106. except Timeout:
  107. thumb = None
  108. except Exception as e:
  109. print (f"[answer/nico-thumb] { type (e).__name__ }: { e }")
  110. thumb = None
  111. external = AppBskyEmbedExternal.External (
  112. title = title,
  113. description = description,
  114. thumb = thumb,
  115. uri = uri)
  116. embed_external = AppBskyEmbedExternal.Main (external = external)
  117. try:
  118. client.post (answer.content[:250], embed = embed_external)
  119. except Exception as e:
  120. print (f"[answer/nico-post] { type (e).__name__ }: { e }")
  121. continue
  122. case QueryType.SNACK_TIME:
  123. try:
  124. with open ('./assets/snack-time.jpg', 'rb') as f:
  125. image = AppBskyEmbedImages.Image (
  126. alt = (
  127. '左に喜多ちゃん、右に人面鹿のニジカが'
  128. 'V字に並んでいる。'
  129. '喜多ちゃんは右手でピースサインをして'
  130. '片目をウインクしている。'
  131. 'ニジカは両手を広げ、'
  132. '右手にスプーンを持って'
  133. 'ポーズを取っている。'
  134. '背景には'
  135. '赤と黄色の放射線状の模様が広がり、'
  136. '下部に「おやつタイムだ!!!!」という'
  137. '日本語のテキストが表示されている。'),
  138. image = client.com.atproto.repo.upload_blob (f).blob)
  139. client.post (answer.content[:250],
  140. embed = AppBskyEmbedImages.Main (images = [image]))
  141. except Exception:
  142. pass
  143. case QueryType.HOT_SPRING:
  144. try:
  145. with open ('./assets/hot-spring.jpg', 'rb') as f:
  146. image = AppBskyEmbedImages.Image (
  147. alt = ('左に喜多ちゃん、右にわさび県産滋賀県が'
  148. 'V字に並んでいる。'
  149. '喜多ちゃんは右手でピースサインをして'
  150. '片目をウインクしている。'
  151. 'わさび県産滋賀県はただ茫然と'
  152. '立ち尽くしている。'
  153. '背景には'
  154. '血と空の色をした放射線状の模様が広がり、'
  155. '下部に「温泉に入ろう!!!」という'
  156. '日本語のテキストが表示されている。'),
  157. image = client.com.atproto.repo.upload_blob (f).blob)
  158. client.post (answer.content[:250],
  159. embed = AppBskyEmbedImages.Main (images = [image]))
  160. except Exception:
  161. pass
  162. await asyncio.sleep (10)
  163. def check_notifications (
  164. ) -> list[str]:
  165. uris: list[str] = []
  166. last_seen_at = client.get_current_time_iso ()
  167. notifications = client.app.bsky.notification.list_notifications ()
  168. for notification in notifications.notifications:
  169. if not notification.is_read:
  170. match notification.reason:
  171. case 'mention' | 'reply' | 'quote':
  172. uris.append (notification.uri)
  173. case 'follow':
  174. client.follow (notification.author.did)
  175. client.app.bsky.notification.update_seen ({ 'seen_at': last_seen_at })
  176. return uris
  177. def fetch_thread_contents (
  178. uri: str,
  179. parent_height: int,
  180. ) -> list[Record]:
  181. post_thread = client.get_post_thread (uri = uri, parent_height = parent_height)
  182. if not post_thread:
  183. return []
  184. res = post_thread.thread
  185. records: list[Record] = []
  186. while res:
  187. if hasattr (res, 'post'):
  188. records.append ({ 'strong_ref': { 'uri': res.post.uri,
  189. 'cid': res.post.cid },
  190. 'did': res.post.author.did,
  191. 'handle': res.post.author.handle,
  192. 'name': (res.post.author.display_name
  193. or res.post.author.handle),
  194. 'datetime': res.post.record.created_at,
  195. 'text': getattr (res.post.record, 'text', None) or '',
  196. 'embed': getattr (res.post.record, 'embed', None) })
  197. res = res.parent
  198. else:
  199. break
  200. return records
  201. def fetch_target_posts (
  202. ) -> list[LikeParams]:
  203. posts: list[LikeParams] = []
  204. timeline: Response = client.get_timeline ()
  205. for feed in timeline.feed:
  206. me = getattr (client, 'me', None)
  207. my_did = me.did if me else ''
  208. if (feed.post.author.did != my_did
  209. and (feed.post.viewer.like is None)
  210. and any (target_word in (feed.post.record.text or '').casefold ()
  211. for target_word in TARGET_WORDS)):
  212. posts.append (LikeParams ({ 'uri': feed.post.uri, 'cid': feed.post.cid }))
  213. return posts
  214. def _add_query (
  215. user: User,
  216. content: str,
  217. image_url: str | None = None,
  218. transfer_data: dict[str, Any] | None = None,
  219. ) -> None:
  220. query = Query ()
  221. query.user_id = user.id
  222. query.target_character = Character.DEERJIKA.value
  223. query.content = content
  224. query.image_url = image_url or None
  225. query.query_type = QueryType.BLUESKY_COMMENT.value
  226. query.model = GPTModel.GPT3_TURBO.value
  227. query.sent_at = datetime.now ()
  228. query.answered = False
  229. query.transfer_data = transfer_data
  230. query.save ()
  231. # TODO: 履歴情報の追加
  232. def _fetch_user (
  233. did: str,
  234. name: str,
  235. ) -> User:
  236. user = User.where ('platform', Platform.BLUESKY.value).where ('code', did).first ()
  237. if user is None:
  238. user = User ()
  239. user.platform = Platform.BLUESKY.value
  240. user.code = did
  241. user.name = name
  242. user.save ()
  243. return user
  244. class LikeParams (TypedDict):
  245. uri: str
  246. cid: str
  247. class Record (TypedDict):
  248. strong_ref: StrongRef
  249. did: str
  250. handle: str
  251. name: str
  252. datetime: str
  253. text: str
  254. embed: object
  255. class StrongRef (TypedDict):
  256. uri: str
  257. cid: str
  258. if __name__ == '__main__':
  259. asyncio.run (main ())