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

283 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. kiriban_list: list[tuple[int, nico.VideoInfo]] = nico.get_kiriban_list ()
  58. got_kiriban_at: date = datetime.now ().date () - timedelta (days = datetime.now ().hour < 15)
  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_code) = (
  94. kiriban_list.pop (random.randint (0, len (kiriban_list) - 1)))
  95. embed_external = models.AppBskyEmbedExternal.Main (
  96. external = models.AppBskyEmbedExternal.External (
  97. title = title,
  98. description = description,
  99. thumb = thumb,
  100. uri = uri))
  101. client.post (Talk.main (f"""
  102. ニコニコの『{ datum['title'] }』という動画が{ views_count }再生を突破しました。
  103. つけられたタグは「{ '」、「'.join (datum['tags']) }」です。
  104. 概要には次のように書かれています:
  105. ```html
  106. { datum['description'] }
  107. ```
  108. このことについて、ニジカちゃんからのお祝いメッセージを下さい。"""),
  109. embed = embed_external)
  110. next_kiriban_at += kiriban_interval
  111. last_posted_at = now
  112. latest_deerjika = nico.get_latest_deerjika ()
  113. if latest_deerjika is not None:
  114. for datum in [e for e in [latest_deerjika]
  115. if e['contentId'] not in watched_videos]:
  116. watched_videos += [datum['contentId']]
  117. uri = f"https://www.nicovideo.jp/watch/{ datum['contentId'] }"
  118. (title, description, thumbnail) = get_embed_info (uri)
  119. try:
  120. upload = client.com.atproto.repo.upload_blob (
  121. io.BytesIO (requests.get (thumbnail,
  122. timeout = 60).content))
  123. thumb = upload.blob
  124. except Timeout:
  125. thumb = None
  126. embed_external = models.AppBskyEmbedExternal.Main (
  127. external = models.AppBskyEmbedExternal.External (
  128. title = title,
  129. description = description,
  130. thumb = thumb,
  131. uri = uri))
  132. client.post (Talk.main (f"""
  133. ニコニコに『{ datum['title'] }』という動画がアップされました。
  134. つけられたタグは「{ '」、「'.join (datum['tags']) }」です。
  135. 概要には次のように書かれています:
  136. ```html
  137. { datum['description'] }
  138. ```
  139. このことについて、みんなに告知するとともに、ニジカちゃんの感想を教えてください。 """),
  140. embed = embed_external)
  141. last_posted_at = now
  142. if now.hour == 14 and has_got_snack_time:
  143. has_got_snack_time = False
  144. if now.hour == 15:
  145. if got_kiriban_at < datetime.now ().date ():
  146. kiriban_list = nico.get_kiriban_list ()
  147. got_kiriban_at = datetime.now ().date ()
  148. kiriban_interval = ((get_kiriban_dt_to_update () - datetime.now ())
  149. / len (kiriban_list))
  150. next_kiriban_at = datetime.now ()
  151. if not has_got_snack_time:
  152. try:
  153. with open ('./assets/snack-time.jpg', 'rb') as f:
  154. image = models.AppBskyEmbedImages.Image (
  155. alt = ('左に喜多ちゃん、右に人面鹿のニジカが'
  156. 'V字に並んでいる。'
  157. '喜多ちゃんは右手でピースサインをして'
  158. '片目をウインクしている。'
  159. 'ニジカは両手を広げ、'
  160. '右手にスプーンを持って'
  161. 'ポーズを取っている。'
  162. '背景には'
  163. '赤と黄色の放射線状の模様が広がり、'
  164. '下部に「おやつタイムだ!!!!」という'
  165. '日本語のテキストが表示されている。'),
  166. image = client.com.atproto.repo.upload_blob (f).blob)
  167. client.post (Talk.main ('おやつタイムだ!!!!'),
  168. embed = models.app.bsky.embed.images.Main (
  169. images = [image]))
  170. last_posted_at = now
  171. except Exception:
  172. pass
  173. has_got_snack_time = True
  174. if now.hour == 20 and has_taken_hot_spring:
  175. has_taken_hot_spring = False
  176. if now.hour == 21 and not has_taken_hot_spring:
  177. try:
  178. with open ('./assets/hot-spring.jpg', 'rb') as f:
  179. image = models.AppBskyEmbedImages.Image (
  180. alt = ('左に喜多ちゃん、右にわさび県産滋賀県が'
  181. 'V字に並んでいる。'
  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_taken_hot_spring = True
  198. if now - last_posted_at >= timedelta (hours = 6):
  199. client.post (Talk.main ('今どうしてる?'))
  200. last_posted_at = now
  201. time.sleep (60)
  202. def get_embed_info (
  203. url: str
  204. ) -> tuple[str, str, str]:
  205. title: str = ''
  206. description: str = ''
  207. thumbnail: str = ''
  208. try:
  209. res = requests.get (url, timeout = 60)
  210. except Timeout:
  211. return ('', '', '')
  212. if res.status_code != 200:
  213. return ('', '', '')
  214. soup = BeautifulSoup (res.text, 'html.parser')
  215. tmp = soup.find ('title')
  216. if tmp is not None:
  217. title = tmp.text
  218. tmp = soup.find ('meta', attrs = { 'name': 'description' })
  219. if tmp is not None and hasattr (tmp, 'get'):
  220. try:
  221. description = cast (str, tmp.get ('content'))
  222. except Exception:
  223. pass
  224. tmp = soup.find ('meta', attrs = { 'name': 'thumbnail' })
  225. if tmp is not None and hasattr (tmp, 'get'):
  226. try:
  227. thumbnail = cast (str, tmp.get ('content'))
  228. except Exception:
  229. pass
  230. return (title, description, thumbnail)
  231. def get_kiriban_dt_to_update (
  232. ) -> datetime:
  233. now = datetime.now ()
  234. today = now.date ()
  235. dt = datetime.combine (today, dt_time (15, 0))
  236. if dt <= now:
  237. dt += timedelta (days = 1)
  238. return dt
  239. if __name__ == '__main__':
  240. main (*sys.argv[1:])