ニジカのスカトロ,ニジカトロ. 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.

307 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 # 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. sref = { 'uri': uri, 'cid': cid }
  88. strong_ref = atproto.models.create_strong_ref (sref) # type: ignore
  89. reply_ref = ReplyRef (root = strong_ref, parent = strong_ref)
  90. try:
  91. client.post (answer.content[:250], reply_to = reply_ref)
  92. except Exception as e:
  93. print (f"[answer/reply] { type (e).__name__ }: { e }")
  94. continue
  95. case QueryType.KIRIBAN | QueryType.NICO_REPORT:
  96. td = answer.query_rel.transfer_data or { }
  97. video_code: str | None = td.get ('video_code')
  98. if not video_code:
  99. continue
  100. uri = f"https://www.nicovideo.jp/watch/{ video_code }"
  101. (title, description, thumbnail) = nicolib.fetch_embed_info (uri)
  102. try:
  103. resp = requests.get (thumbnail, timeout = 60)
  104. resp.raise_for_status ()
  105. upload = client.com.atproto.repo.upload_blob (BytesIO (resp.content))
  106. thumb = upload.blob
  107. except Timeout:
  108. thumb = None
  109. except Exception as e:
  110. print (f"[answer/nico-thumb] { type (e).__name__ }: { e }")
  111. thumb = None
  112. external = AppBskyEmbedExternal.External (
  113. title = title,
  114. description = description,
  115. thumb = thumb,
  116. uri = uri)
  117. embed_external = AppBskyEmbedExternal.Main (external = external)
  118. try:
  119. client.post (answer.content[:250], embed = embed_external)
  120. except Exception as e:
  121. print (f"[answer/nico-post] { type (e).__name__ }: { e }")
  122. continue
  123. case QueryType.SNACK_TIME:
  124. try:
  125. with open ('./assets/snack-time.jpg', 'rb') as f:
  126. image = AppBskyEmbedImages.Image (
  127. alt = (
  128. '左に喜多ちゃん、右に人面鹿のニジカが'
  129. 'V字に並んでいる。'
  130. '喜多ちゃんは右手でピースサインをして'
  131. '片目をウインクしている。'
  132. 'ニジカは両手を広げ、'
  133. '右手にスプーンを持って'
  134. 'ポーズを取っている。'
  135. '背景には'
  136. '赤と黄色の放射線状の模様が広がり、'
  137. '下部に「おやつタイムだ!!!!」という'
  138. '日本語のテキストが表示されている。'),
  139. image = client.com.atproto.repo.upload_blob (f).blob)
  140. client.post (answer.content[:250],
  141. embed = AppBskyEmbedImages.Main (images = [image]))
  142. except Exception:
  143. pass
  144. case QueryType.HOT_SPRING:
  145. try:
  146. with open ('./assets/hot-spring.jpg', 'rb') as f:
  147. image = AppBskyEmbedImages.Image (
  148. alt = ('左に喜多ちゃん、右にわさび県産滋賀県が'
  149. 'V字に並んでいる。'
  150. '喜多ちゃんは右手でピースサインをして'
  151. '片目をウインクしている。'
  152. 'わさび県産滋賀県はただ茫然と'
  153. '立ち尽くしている。'
  154. '背景には'
  155. '血と空の色をした放射線状の模様が広がり、'
  156. '下部に「温泉に入ろう!!!」という'
  157. '日本語のテキストが表示されている。'),
  158. image = client.com.atproto.repo.upload_blob (f).blob)
  159. client.post (answer.content[:250],
  160. embed = AppBskyEmbedImages.Main (images = [image]))
  161. except Exception:
  162. pass
  163. await asyncio.sleep (10)
  164. def check_notifications (
  165. ) -> list[str]:
  166. uris: list[str] = []
  167. last_seen_at = client.get_current_time_iso ()
  168. notifications = client.app.bsky.notification.list_notifications ()
  169. for notification in notifications.notifications:
  170. if not notification.is_read:
  171. match notification.reason:
  172. case 'mention' | 'reply' | 'quote':
  173. uris.append (notification.uri)
  174. case 'follow':
  175. client.follow (notification.author.did)
  176. client.app.bsky.notification.update_seen ({ 'seen_at': last_seen_at })
  177. return uris
  178. def fetch_thread_contents (
  179. uri: str,
  180. parent_height: int,
  181. ) -> list[Record]:
  182. post_thread = client.get_post_thread (uri = uri, parent_height = parent_height)
  183. if not post_thread:
  184. return []
  185. res = post_thread.thread
  186. records: list[Record] = []
  187. while res:
  188. if hasattr (res, 'post'):
  189. records.append ({ 'strong_ref': { 'uri': res.post.uri,
  190. 'cid': res.post.cid },
  191. 'did': res.post.author.did,
  192. 'handle': res.post.author.handle,
  193. 'name': (res.post.author.display_name
  194. or res.post.author.handle),
  195. 'datetime': res.post.record.created_at,
  196. 'text': getattr (res.post.record, 'text', None) or '',
  197. 'embed': getattr (res.post.record, 'embed', None) })
  198. res = res.parent
  199. else:
  200. break
  201. return records
  202. def fetch_target_posts (
  203. ) -> list[LikeParams]:
  204. posts: list[LikeParams] = []
  205. timeline: Response = client.get_timeline ()
  206. for feed in timeline.feed:
  207. me = getattr (client, 'me', None)
  208. my_did = me.did if me else ''
  209. if (feed.post.author.did != my_did
  210. and (feed.post.viewer.like is None)
  211. and any (target_word in (feed.post.record.text or '').casefold ()
  212. for target_word in TARGET_WORDS)):
  213. posts.append (LikeParams ({ 'uri': feed.post.uri, 'cid': feed.post.cid }))
  214. return posts
  215. def _add_query (
  216. user: User,
  217. content: str,
  218. image_url: str | None = None,
  219. transfer_data: dict[str, Any] | None = None,
  220. ) -> None:
  221. query = Query ()
  222. query.user_id = user.id
  223. query.target_character = Character.DEERJIKA.value
  224. query.content = content
  225. query.image_url = image_url or None
  226. query.query_type = QueryType.BLUESKY_COMMENT.value
  227. query.model = GPTModel.GPT3_TURBO.value
  228. query.sent_at = datetime.now ()
  229. query.answered = False
  230. query.transfer_data = transfer_data
  231. query.save ()
  232. # TODO: 履歴情報の追加
  233. def _fetch_user (
  234. did: str,
  235. name: str,
  236. ) -> User:
  237. user = User.where ('platform', Platform.BLUESKY.value).where ('code', did).first ()
  238. if user is None:
  239. user = User ()
  240. user.platform = Platform.BLUESKY.value
  241. user.code = did
  242. user.name = name
  243. user.save ()
  244. return user
  245. class LikeParams (TypedDict):
  246. uri: str
  247. cid: str
  248. class Record (TypedDict):
  249. strong_ref: StrongRef
  250. did: str
  251. handle: str
  252. name: str
  253. datetime: str
  254. text: str
  255. embed: object
  256. class StrongRef (TypedDict):
  257. uri: str
  258. cid: str
  259. if __name__ == '__main__':
  260. asyncio.run (main ())