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

236 lines
9.5 KiB

  1. """
  2. Bluesky のニジカがいろいろする.
  3. (近々機能ごとにファイル分けて systemd でイベント管理する予定)
  4. """
  5. import io
  6. import sys
  7. import time
  8. from datetime import datetime, timedelta
  9. from typing import cast
  10. import requests
  11. from atproto import Client, models
  12. from bs4 import BeautifulSoup
  13. from requests.exceptions import Timeout
  14. import account
  15. import nico
  16. from ai.talk import Talk
  17. def check_notifications (
  18. client: Client,
  19. ) -> list:
  20. (uris, last_seen_at) = ([], client.get_current_time_iso ())
  21. for notification in (client.app.bsky.notification.list_notifications ()
  22. .notifications):
  23. if not notification.is_read:
  24. if notification.reason in ['mention', 'reply', 'quote']:
  25. uris += [notification.uri]
  26. elif notification.reason == 'follow':
  27. client.follow (notification.author.did)
  28. client.app.bsky.notification.update_seen ({ 'seen_at': last_seen_at })
  29. return uris
  30. def get_thread_contents (
  31. client: Client,
  32. uri: str,
  33. parent_height: int,
  34. ) -> list:
  35. response = (client.get_post_thread (uri = uri,
  36. parent_height = parent_height)
  37. .thread)
  38. records = []
  39. while response is not None:
  40. records += [{ 'strong_ref': models.create_strong_ref (response.post),
  41. 'did': response.post.author.did,
  42. 'handle': response.post.author.handle,
  43. 'name': response.post.author.display_name,
  44. 'datetime': response.post.record.created_at,
  45. 'text': response.post.record.text,
  46. 'embed': response.post.record.embed }]
  47. response = response.parent
  48. return records
  49. def main (
  50. ) -> None:
  51. time.sleep (60)
  52. client = Client (base_url = 'https://bsky.social')
  53. client.login (account.USER_ID, account.PASSWORD)
  54. last_posted_at = datetime.now () - timedelta (hours = 6)
  55. has_got_snack_time = False
  56. has_taken_hot_spring = False
  57. watched_videos = []
  58. while True:
  59. now = datetime.now ()
  60. for uri in check_notifications (client):
  61. records = get_thread_contents (client, uri, 20)
  62. if len (records) > 0:
  63. answer = Talk.main ((records[0]['text']
  64. if (records[0]['embed'] is None
  65. or not hasattr (records[0]['embed'],
  66. 'images'))
  67. else [
  68. { 'type': 'text', 'text': records[0]['text'] },
  69. { 'type': 'image_url', 'image_url': {
  70. 'url': f"https://cdn.bsky.app/img/feed_fullsize/plain/{ records[0]['did'] }/{ records[0]['embed'].images[0].image.ref.link }" } }]),
  71. records[0]['name'],
  72. [*map (lambda record: {
  73. 'role': ('assistant'
  74. if (record['handle']
  75. == account.USER_ID)
  76. else 'user'),
  77. 'content':
  78. record['text']},
  79. reversed (records[1:]))])
  80. client.post (answer,
  81. reply_to = models.AppBskyFeedPost.ReplyRef (
  82. parent = records[0]['strong_ref'],
  83. root = records[-1]['strong_ref']))
  84. latest_deerjika = nico.get_latest_deerjika ()
  85. if latest_deerjika is not None:
  86. for datum in [e for e in [latest_deerjika]
  87. if e['contentId'] not in watched_videos]:
  88. watched_videos += [datum['contentId']]
  89. uri = f"https://www.nicovideo.jp/watch/{ datum['contentId'] }"
  90. (title, description, thumbnail) = get_embed_info (uri)
  91. try:
  92. upload = client.com.atproto.repo.upload_blob (
  93. io.BytesIO (requests.get (thumbnail,
  94. timeout = 60).content))
  95. thumb = upload.blob
  96. except Timeout:
  97. thumb = None
  98. embed_external = models.AppBskyEmbedExternal.Main (
  99. external = models.AppBskyEmbedExternal.External (
  100. title = title,
  101. description = description,
  102. thumb = thumb,
  103. uri = uri))
  104. client.post (Talk.main (f"""
  105. ニコニコに『{ datum['title'] }』という動画がアップされました。
  106. つけられたタグは「{ '」、「'.join (datum['tags']) }」です。
  107. 概要には次のように書かれています:
  108. ```html
  109. { datum['description'] }
  110. ```
  111. このことについて、みんなに告知するとともに、ニジカちゃんの感想を教えてください。 """),
  112. embed = embed_external)
  113. last_posted_at = now
  114. if now.hour == 14 and has_got_snack_time:
  115. has_got_snack_time = False
  116. if now.hour == 15 and not has_got_snack_time:
  117. try:
  118. with open ('./assets/snack-time.jpg', 'rb') as f:
  119. image = models.AppBskyEmbedImages.Image (
  120. alt = ('左に喜多ちゃん、右に人面鹿のニジカが'
  121. 'V字に並んでいる。'
  122. '喜多ちゃんは右手でピースサインをして'
  123. '片目をウインクしている。'
  124. 'ニジカは両手を広げ、'
  125. '右手にスプーンを持って'
  126. 'ポーズを取っている。'
  127. '背景には'
  128. '赤と黄色の放射線状の模様が広がり、'
  129. '下部に「おやつタイムだ!!!!」という'
  130. '日本語のテキストが表示されている。'),
  131. image = client.com.atproto.repo.upload_blob (f).blob)
  132. client.post (Talk.main ('おやつタイムだ!!!!'),
  133. embed = models.app.bsky.embed.images.Main (
  134. images = [image]))
  135. last_posted_at = now
  136. except Exception:
  137. pass
  138. has_got_snack_time = True
  139. if now.hour == 20 and has_taken_hot_spring:
  140. has_taken_hot_spring = False
  141. if now.hour == 21 and not has_taken_hot_spring:
  142. try:
  143. with open ('./assets/hot-spring.jpg', 'rb') as f:
  144. image = models.AppBskyEmbedImages.Image (
  145. alt = ('左に喜多ちゃん、右にわさび県産滋賀県が'
  146. 'V字に並んでいる。'
  147. '喜多ちゃんは右手でピースサインをして'
  148. '片目をウインクしている。'
  149. 'わさび県産滋賀県はただ茫然と'
  150. '立ち尽くしている。'
  151. '背景には'
  152. '血と空の色をした放射線状の模様が広がり、'
  153. '下部に「温泉に入ろう!!!」という'
  154. '日本語のテキストが表示されている。'),
  155. image = client.com.atproto.repo.upload_blob (f).blob)
  156. client.post (Talk.main ('温泉に入ろう!!!'),
  157. embed = models.app.bsky.embed.images.Main (
  158. images = [image]))
  159. last_posted_at = now
  160. except Exception:
  161. pass
  162. has_taken_hot_spring = True
  163. if now - last_posted_at >= timedelta (hours = 6):
  164. client.post (Talk.main ('今どうしてる?'))
  165. last_posted_at = now
  166. time.sleep (60)
  167. def get_embed_info (
  168. url: str
  169. ) -> tuple[str, str, str]:
  170. title: str = ''
  171. description: str = ''
  172. thumbnail: str = ''
  173. try:
  174. res = requests.get (url, timeout = 60)
  175. except Timeout:
  176. return ('', '', '')
  177. if res.status_code != 200:
  178. return ('', '', '')
  179. soup = BeautifulSoup (res.text, 'html.parser')
  180. tmp = soup.find ('title')
  181. if tmp is not None:
  182. title = tmp.text
  183. tmp = soup.find ('meta', attrs = { 'name': 'description' })
  184. if tmp is not None and hasattr (tmp, 'get'):
  185. try:
  186. description = cast (str, tmp.get ('content'))
  187. except Exception:
  188. pass
  189. tmp = soup.find ('meta', attrs = { 'name': 'thumbnail' })
  190. if tmp is not None and hasattr (tmp, 'get'):
  191. try:
  192. thumbnail = cast (str, tmp.get ('content'))
  193. except Exception:
  194. pass
  195. return (title, description, thumbnail)
  196. if __name__ == '__main__':
  197. main (*sys.argv[1:])