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

main.py 9.5 KiB

2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. """
  2. Bluesky のニジカがいろいろする.
  3. (近々機能ごとにファイル分けて systemd でイベント管理する予定)
  4. """
  5. import io
  6. import time
  7. import sys
  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. client = Client (base_url = 'https://bsky.social')
  52. client.login (account.USER_ID, account.PASSWORD)
  53. last_posted_at = datetime.now () - timedelta (hours = 6)
  54. has_got_snack_time = False
  55. has_taken_hot_spring = False
  56. watched_videos = []
  57. while True:
  58. time.sleep (60)
  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. def get_embed_info (
  167. url: str
  168. ) -> tuple[str, str, str]:
  169. title: str = ''
  170. description: str = ''
  171. thumbnail: str = ''
  172. try:
  173. res = requests.get (url, timeout = 60)
  174. except Timeout:
  175. return ('', '', '')
  176. if res.status_code != 200:
  177. return ('', '', '')
  178. soup = BeautifulSoup (res.text, 'html.parser')
  179. tmp = soup.find ('title')
  180. if tmp is not None:
  181. title = tmp.text
  182. tmp = soup.find ('meta', attrs = { 'name': 'description' })
  183. if tmp is not None and hasattr (tmp, 'get'):
  184. try:
  185. description = cast (str, tmp.get ('content'))
  186. except Exception:
  187. pass
  188. tmp = soup.find ('meta', attrs = { 'name': 'thumbnail' })
  189. if tmp is not None and hasattr (tmp, 'get'):
  190. try:
  191. thumbnail = cast (str, tmp.get ('content'))
  192. except Exception:
  193. pass
  194. return (title, description, thumbnail)
  195. if __name__ == '__main__':
  196. main (*sys.argv[1:])