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

292 lines
12 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]] = nico.get_kiriban_list (got_kiriban_at)
  59. kiriban_interval: timedelta = ((get_kiriban_dt_to_update () - datetime.now ())
  60. / len (kiriban_list))
  61. next_kiriban_at = datetime.now ()
  62. last_posted_at = datetime.now () - timedelta (hours = 6)
  63. has_got_snack_time = False
  64. has_taken_hot_spring = False
  65. watched_videos = []
  66. while True:
  67. now = datetime.now ()
  68. for uri in check_notifications (client):
  69. records = get_thread_contents (client, uri, 20)
  70. if len (records) > 0:
  71. answer = Talk.main ((records[0]['text']
  72. if (records[0]['embed'] is None
  73. or not hasattr (records[0]['embed'],
  74. 'images'))
  75. else [
  76. { 'type': 'text', 'text': records[0]['text'] },
  77. { 'type': 'image_url', 'image_url': {
  78. 'url': f"https://cdn.bsky.app/img/feed_fullsize/plain/{ records[0]['did'] }/{ records[0]['embed'].images[0].image.ref.link }" } }]),
  79. records[0]['name'],
  80. [*map (lambda record: {
  81. 'role': ('assistant'
  82. if (record['handle']
  83. == account.USER_ID)
  84. else 'user'),
  85. 'content':
  86. record['text']},
  87. reversed (records[1:]))])
  88. client.post (answer,
  89. reply_to = models.AppBskyFeedPost.ReplyRef (
  90. parent = records[0]['strong_ref'],
  91. root = records[-1]['strong_ref']))
  92. if kiriban_list and datetime.now () >= next_kiriban_at:
  93. (views_count, video_info) = (
  94. kiriban_list.pop (random.randint (0, len (kiriban_list) - 1)))
  95. uri = f"https://www.nicovideo.jp/watch/{ video_info['contentId'] }"
  96. (title, description, thumbnail) = get_embed_info (uri)
  97. try:
  98. upload = client.com.atproto.repo.upload_blob (
  99. io.BytesIO (requests.get (thumbnail,
  100. timeout = 60).content))
  101. thumb = upload.blob
  102. except Timeout:
  103. thumb = None
  104. embed_external = models.AppBskyEmbedExternal.Main (
  105. external = models.AppBskyEmbedExternal.External (
  106. title = title,
  107. description = description,
  108. thumb = thumb,
  109. uri = uri))
  110. client.post (Talk.main (f"""
  111. ニコニコの『{ video_info['title'] }』という動画が{ views_count }再生を突破しました。
  112. つけられたタグは「{ '」、「'.join (video_info['tags']) }」です。
  113. 概要には次のように書かれています:
  114. ```html
  115. { video_info['description'] }
  116. ```
  117. このことについて、ニジカちゃんからのお祝いメッセージを下さい。"""),
  118. embed = embed_external)
  119. next_kiriban_at += kiriban_interval
  120. last_posted_at = now
  121. latest_deerjika = nico.get_latest_deerjika ()
  122. if latest_deerjika is not None:
  123. for datum in [e for e in [latest_deerjika]
  124. if e['contentId'] not in watched_videos]:
  125. watched_videos += [datum['contentId']]
  126. uri = f"https://www.nicovideo.jp/watch/{ datum['contentId'] }"
  127. (title, description, thumbnail) = get_embed_info (uri)
  128. try:
  129. upload = client.com.atproto.repo.upload_blob (
  130. io.BytesIO (requests.get (thumbnail,
  131. timeout = 60).content))
  132. thumb = upload.blob
  133. except Timeout:
  134. thumb = None
  135. embed_external = models.AppBskyEmbedExternal.Main (
  136. external = models.AppBskyEmbedExternal.External (
  137. title = title,
  138. description = description,
  139. thumb = thumb,
  140. uri = uri))
  141. client.post (Talk.main (f"""
  142. ニコニコに『{ datum['title'] }』という動画がアップされました。
  143. つけられたタグは「{ '」、「'.join (datum['tags']) }」です。
  144. 概要には次のように書かれています:
  145. ```html
  146. { datum['description'] }
  147. ```
  148. このことについて、みんなに告知するとともに、ニジカちゃんの感想を教えてください。 """),
  149. embed = embed_external)
  150. last_posted_at = now
  151. if now.hour == 14 and has_got_snack_time:
  152. has_got_snack_time = False
  153. if now.hour == 15:
  154. if got_kiriban_at < datetime.now ().date ():
  155. kiriban_list = nico.get_kiriban_list (datetime.now ().date ())
  156. got_kiriban_at = datetime.now ().date ()
  157. kiriban_interval = ((get_kiriban_dt_to_update () - datetime.now ())
  158. / len (kiriban_list))
  159. next_kiriban_at = datetime.now ()
  160. if not has_got_snack_time:
  161. try:
  162. with open ('./assets/snack-time.jpg', 'rb') as f:
  163. image = models.AppBskyEmbedImages.Image (
  164. alt = ('左に喜多ちゃん、右に人面鹿のニジカが'
  165. 'V字に並んでいる。'
  166. '喜多ちゃんは右手でピースサインをして'
  167. '片目をウインクしている。'
  168. 'ニジカは両手を広げ、'
  169. '右手にスプーンを持って'
  170. 'ポーズを取っている。'
  171. '背景には'
  172. '赤と黄色の放射線状の模様が広がり、'
  173. '下部に「おやつタイムだ!!!!」という'
  174. '日本語のテキストが表示されている。'),
  175. image = client.com.atproto.repo.upload_blob (f).blob)
  176. client.post (Talk.main ('おやつタイムだ!!!!'),
  177. embed = models.app.bsky.embed.images.Main (
  178. images = [image]))
  179. last_posted_at = now
  180. except Exception:
  181. pass
  182. has_got_snack_time = True
  183. if now.hour == 20 and has_taken_hot_spring:
  184. has_taken_hot_spring = False
  185. if now.hour == 21 and not has_taken_hot_spring:
  186. try:
  187. with open ('./assets/hot-spring.jpg', 'rb') as f:
  188. image = models.AppBskyEmbedImages.Image (
  189. alt = ('左に喜多ちゃん、右にわさび県産滋賀県が'
  190. 'V字に並んでいる。'
  191. '喜多ちゃんは右手でピースサインをして'
  192. '片目をウインクしている。'
  193. 'わさび県産滋賀県はただ茫然と'
  194. '立ち尽くしている。'
  195. '背景には'
  196. '血と空の色をした放射線状の模様が広がり、'
  197. '下部に「温泉に入ろう!!!」という'
  198. '日本語のテキストが表示されている。'),
  199. image = client.com.atproto.repo.upload_blob (f).blob)
  200. client.post (Talk.main ('温泉に入ろう!!!'),
  201. embed = models.app.bsky.embed.images.Main (
  202. images = [image]))
  203. last_posted_at = now
  204. except Exception:
  205. pass
  206. has_taken_hot_spring = True
  207. if now - last_posted_at >= timedelta (hours = 6):
  208. client.post (Talk.main ('今どうしてる?'))
  209. last_posted_at = now
  210. time.sleep (60)
  211. def get_embed_info (
  212. url: str
  213. ) -> tuple[str, str, str]:
  214. title: str = ''
  215. description: str = ''
  216. thumbnail: str = ''
  217. try:
  218. res = requests.get (url, timeout = 60)
  219. except Timeout:
  220. return ('', '', '')
  221. if res.status_code != 200:
  222. return ('', '', '')
  223. soup = BeautifulSoup (res.text, 'html.parser')
  224. tmp = soup.find ('title')
  225. if tmp is not None:
  226. title = tmp.text
  227. tmp = soup.find ('meta', attrs = { 'name': 'description' })
  228. if tmp is not None and hasattr (tmp, 'get'):
  229. try:
  230. description = cast (str, tmp.get ('content'))
  231. except Exception:
  232. pass
  233. tmp = soup.find ('meta', attrs = { 'name': 'thumbnail' })
  234. if tmp is not None and hasattr (tmp, 'get'):
  235. try:
  236. thumbnail = cast (str, tmp.get ('content'))
  237. except Exception:
  238. pass
  239. return (title, description, thumbnail)
  240. def get_kiriban_dt_to_update (
  241. ) -> datetime:
  242. now = datetime.now ()
  243. today = now.date ()
  244. dt = datetime.combine (today, dt_time (15, 0))
  245. if dt <= now:
  246. dt += timedelta (days = 1)
  247. return dt
  248. if __name__ == '__main__':
  249. main (*sys.argv[1:])