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

215 lines
8.2 KiB

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