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

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