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

  1. """
  2. Bluesky のニジカがいろいろする.
  3. (近々機能ごとにファイル分けて systemd でイベント管理する予定)
  4. """
  5. import io
  6. import random
  7. import sys
  8. import time
  9. from datetime import date, datetime
  10. from datetime import time as dt_time
  11. from datetime import timedelta
  12. from typing import cast
  13. import requests
  14. from atproto import Client, models
  15. from bs4 import BeautifulSoup
  16. from requests.exceptions import Timeout
  17. import account
  18. import nico
  19. from ai.talk import Talk
  20. def check_notifications (
  21. client: Client,
  22. ) -> list:
  23. (uris, last_seen_at) = ([], client.get_current_time_iso ())
  24. for notification in (client.app.bsky.notification.list_notifications ()
  25. .notifications):
  26. if not notification.is_read:
  27. if notification.reason in ['mention', 'reply', 'quote']:
  28. uris += [notification.uri]
  29. elif notification.reason == 'follow':
  30. client.follow (notification.author.did)
  31. client.app.bsky.notification.update_seen ({ 'seen_at': last_seen_at })
  32. return uris
  33. def get_thread_contents (
  34. client: Client,
  35. uri: str,
  36. parent_height: int,
  37. ) -> list:
  38. response = (client.get_post_thread (uri = uri,
  39. parent_height = parent_height)
  40. .thread)
  41. records = []
  42. while response is not None:
  43. records += [{ 'strong_ref': models.create_strong_ref (response.post),
  44. 'did': response.post.author.did,
  45. 'handle': response.post.author.handle,
  46. 'name': response.post.author.display_name,
  47. 'datetime': response.post.record.created_at,
  48. 'text': response.post.record.text,
  49. 'embed': response.post.record.embed }]
  50. response = response.parent
  51. return records
  52. def main (
  53. ) -> None:
  54. time.sleep (60)
  55. client = Client (base_url = 'https://bsky.social')
  56. client.login (account.USER_ID, account.PASSWORD)
  57. got_kiriban_at: date = datetime.now ().date () - timedelta (days = datetime.now ().hour < 15)
  58. kiriban_list: list[tuple[int, nico.VideoInfo, datetime]] = (
  59. nico.get_kiriban_list (got_kiriban_at))
  60. kiriban_interval: timedelta = ((get_kiriban_dt_to_update () - datetime.now ())
  61. / len (kiriban_list))
  62. next_kiriban_at = datetime.now ()
  63. last_posted_at = datetime.now () - timedelta (hours = 6)
  64. has_got_snack_time = False
  65. has_taken_hot_spring = False
  66. watched_videos = []
  67. while True:
  68. now = datetime.now ()
  69. for uri in check_notifications (client):
  70. records = get_thread_contents (client, uri, 20)
  71. if len (records) > 0:
  72. answer = Talk.main ((records[0]['text']
  73. if (records[0]['embed'] is None
  74. or not hasattr (records[0]['embed'],
  75. 'images'))
  76. else [
  77. { 'type': 'text', 'text': records[0]['text'] },
  78. { 'type': 'image_url', 'image_url': {
  79. 'url': f"https://cdn.bsky.app/img/feed_fullsize/plain/{ records[0]['did'] }/{ records[0]['embed'].images[0].image.ref.link }" } }]),
  80. records[0]['name'],
  81. [*map (lambda record: {
  82. 'role': ('assistant'
  83. if (record['handle']
  84. == account.USER_ID)
  85. else 'user'),
  86. 'content':
  87. record['text']},
  88. reversed (records[1:]))])
  89. client.post (answer,
  90. reply_to = models.AppBskyFeedPost.ReplyRef (
  91. parent = records[0]['strong_ref'],
  92. root = records[-1]['strong_ref']))
  93. if kiriban_list and datetime.now () >= next_kiriban_at:
  94. (views_count, video_info, uploaded_at) = (
  95. kiriban_list.pop (random.randint (0, len (kiriban_list) - 1)))
  96. since_posted = datetime.now () - uploaded_at
  97. uri = f"https://www.nicovideo.jp/watch/{ video_info['contentId'] }"
  98. (title, description, thumbnail) = get_embed_info (uri)
  99. try:
  100. upload = client.com.atproto.repo.upload_blob (
  101. io.BytesIO (requests.get (thumbnail,
  102. timeout = 60).content))
  103. thumb = upload.blob
  104. except Timeout:
  105. thumb = None
  106. comments = nico.get_comments (video_info['contentId'])
  107. popular_comments = sorted (comments,
  108. key = lambda c: c.nico_count,
  109. reverse = True)[:10]
  110. latest_comments = sorted (comments,
  111. key = lambda c: c.posted_at,
  112. reverse = True)[:10]
  113. embed_external = models.AppBskyEmbedExternal.Main (
  114. external = models.AppBskyEmbedExternal.External (
  115. title = title,
  116. description = description,
  117. thumb = thumb,
  118. uri = uri))
  119. prompt = f"{ since_posted.days }日と{ since_posted.seconds }秒前にニコニコに投稿された『{ video_info['title'] }』という動画が{ views_count }再生を突破しました。\n"
  120. if video_info['tags']:
  121. prompt += f"つけられたタグは「{ '」、「'.join (video_info['tags']) }」です。\n"
  122. if comments:
  123. prompt += f"人気のコメントは次の通りです:「{ '」、「'.join (c.content for c in popular_comments) }」\n"
  124. prompt += f"最新のコメントは次の通りです:「{ '」、「'.join (c.content for c in latest_comments) }」\n"
  125. prompt += f"""
  126. 概要には次のように書かれています:
  127. ```html
  128. { video_info['description'] }
  129. ```
  130. このことについて、ニジカちゃんからのお祝いメッセージを下さい。
  131. ただし、そのメッセージ内には再生数の数値とその多さに応じたリアクション(「すっご~い!」や「しょぼ~い」など)を添えてください。
  132. また、ぜひ投稿からこの再生数に至るまでにかかった時間や、つけられたタグ、コメントに対して思いを馳せてください。"""
  133. client.post (Talk.main (prompt), embed = embed_external)
  134. next_kiriban_at += kiriban_interval
  135. last_posted_at = now
  136. latest_deerjika = nico.get_latest_deerjika ()
  137. if latest_deerjika is not None:
  138. for datum in [e for e in [latest_deerjika]
  139. if e['contentId'] not in watched_videos]:
  140. watched_videos += [datum['contentId']]
  141. uri = f"https://www.nicovideo.jp/watch/{ datum['contentId'] }"
  142. (title, description, thumbnail) = get_embed_info (uri)
  143. try:
  144. upload = client.com.atproto.repo.upload_blob (
  145. io.BytesIO (requests.get (thumbnail,
  146. timeout = 60).content))
  147. thumb = upload.blob
  148. except Timeout:
  149. thumb = None
  150. embed_external = models.AppBskyEmbedExternal.Main (
  151. external = models.AppBskyEmbedExternal.External (
  152. title = title,
  153. description = description,
  154. thumb = thumb,
  155. uri = uri))
  156. client.post (Talk.main (f"""
  157. ニコニコに『{ datum['title'] }』という動画がアップされました。
  158. つけられたタグは「{ '」、「'.join (datum['tags']) }」です。
  159. 概要には次のように書かれています:
  160. ```html
  161. { datum['description'] }
  162. ```
  163. このことについて、みんなに告知するとともに、ニジカちゃんの感想を教えてください。 """),
  164. embed = embed_external)
  165. last_posted_at = now
  166. if now.hour == 14 and has_got_snack_time:
  167. has_got_snack_time = False
  168. if now.hour == 15:
  169. if got_kiriban_at < datetime.now ().date ():
  170. kiriban_list = nico.get_kiriban_list (datetime.now ().date ())
  171. got_kiriban_at = datetime.now ().date ()
  172. kiriban_interval = ((get_kiriban_dt_to_update () - datetime.now ())
  173. / len (kiriban_list))
  174. next_kiriban_at = datetime.now ()
  175. if not has_got_snack_time:
  176. try:
  177. with open ('./assets/snack-time.jpg', 'rb') as f:
  178. image = models.AppBskyEmbedImages.Image (
  179. alt = ('左に喜多ちゃん、右に人面鹿のニジカが'
  180. 'V字に並んでいる。'
  181. '喜多ちゃんは右手でピースサインをして'
  182. '片目をウインクしている。'
  183. 'ニジカは両手を広げ、'
  184. '右手にスプーンを持って'
  185. 'ポーズを取っている。'
  186. '背景には'
  187. '赤と黄色の放射線状の模様が広がり、'
  188. '下部に「おやつタイムだ!!!!」という'
  189. '日本語のテキストが表示されている。'),
  190. image = client.com.atproto.repo.upload_blob (f).blob)
  191. client.post (Talk.main ('おやつタイムだ!!!!'),
  192. embed = models.app.bsky.embed.images.Main (
  193. images = [image]))
  194. last_posted_at = now
  195. except Exception:
  196. pass
  197. has_got_snack_time = True
  198. if now.hour == 20 and has_taken_hot_spring:
  199. has_taken_hot_spring = False
  200. if now.hour == 21 and not has_taken_hot_spring:
  201. try:
  202. with open ('./assets/hot-spring.jpg', 'rb') as f:
  203. image = models.AppBskyEmbedImages.Image (
  204. alt = ('左に喜多ちゃん、右にわさび県産滋賀県が'
  205. 'V字に並んでいる。'
  206. '喜多ちゃんは右手でピースサインをして'
  207. '片目をウインクしている。'
  208. 'わさび県産滋賀県はただ茫然と'
  209. '立ち尽くしている。'
  210. '背景には'
  211. '血と空の色をした放射線状の模様が広がり、'
  212. '下部に「温泉に入ろう!!!」という'
  213. '日本語のテキストが表示されている。'),
  214. image = client.com.atproto.repo.upload_blob (f).blob)
  215. client.post (Talk.main ('温泉に入ろう!!!'),
  216. embed = models.app.bsky.embed.images.Main (
  217. images = [image]))
  218. last_posted_at = now
  219. except Exception:
  220. pass
  221. has_taken_hot_spring = True
  222. if now - last_posted_at >= timedelta (hours = 6):
  223. client.post (Talk.main ('今どうしてる?'))
  224. last_posted_at = now
  225. time.sleep (60)
  226. def get_embed_info (
  227. url: str
  228. ) -> tuple[str, str, str]:
  229. title: str = ''
  230. description: str = ''
  231. thumbnail: str = ''
  232. try:
  233. res = requests.get (url, timeout = 60)
  234. except Timeout:
  235. return ('', '', '')
  236. if res.status_code != 200:
  237. return ('', '', '')
  238. soup = BeautifulSoup (res.text, 'html.parser')
  239. tmp = soup.find ('title')
  240. if tmp is not None:
  241. title = tmp.text
  242. tmp = soup.find ('meta', attrs = { 'name': 'description' })
  243. if tmp is not None and hasattr (tmp, 'get'):
  244. try:
  245. description = cast (str, tmp.get ('content'))
  246. except Exception:
  247. pass
  248. tmp = soup.find ('meta', attrs = { 'name': 'thumbnail' })
  249. if tmp is not None and hasattr (tmp, 'get'):
  250. try:
  251. thumbnail = cast (str, tmp.get ('content'))
  252. except Exception:
  253. pass
  254. return (title, description, thumbnail)
  255. def get_kiriban_dt_to_update (
  256. ) -> datetime:
  257. now = datetime.now ()
  258. today = now.date ()
  259. dt = datetime.combine (today, dt_time (15, 0))
  260. if dt <= now:
  261. dt += timedelta (days = 1)
  262. return dt
  263. if __name__ == '__main__':
  264. main (*sys.argv[1:])