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

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