コミットを比較
58 コミット
51d0854ab6
...
main
| 作成者 | SHA1 | 日付 | |
|---|---|---|---|
| 99a5dca5a3 | |||
| a6af306204 | |||
| 9f36cfea28 | |||
| a103093e9c | |||
| 7ff729b256 | |||
| 3e8c2c5fe0 | |||
| 6eb191a7f4 | |||
| 82fabebe2f | |||
| 47dc881537 | |||
| 658b15ac52 | |||
| 6d4e826439 | |||
| e6f90611fa | |||
| 4f2056b347 | |||
| 64279b2eca | |||
| 4bd15d0cc9 | |||
| 26867f5269 | |||
| 0dd27b4ec7 | |||
| fb920a1f2c | |||
| 5041b91485 | |||
| 06b9d015d0 | |||
| fad7ffe969 | |||
| d6654c41ba | |||
| a4e0a5fcd8 | |||
| f3c8f5fa27 | |||
| f6ab471e04 | |||
| ad9f5256e5 | |||
| 0cbc20c898 | |||
| 95331ec835 | |||
| d1b1bf2a14 | |||
| 5769314b6f | |||
| 27d7cfe972 | |||
| 10c1218caf | |||
| 9835907f8a | |||
| 539333bd0e | |||
| 9ec4e67a99 | |||
| e4ed73007f | |||
| 76abbe4fdd | |||
| 0002b48269 | |||
| 55049cdc2d | |||
| d28882a241 | |||
| 7dc19465ca | |||
| 5f748ed1c2 | |||
| 9690cf145b | |||
| 36327878e8 | |||
| b7433ade9f | |||
| 4ebe43dd05 | |||
| e54fe9e313 | |||
| c8cff9a3dd | |||
| 5da0335c50 | |||
| 2e75eabf71 | |||
| f6ef60b619 | |||
| 6f8d2ef4db | |||
| 0e6fe12510 | |||
| 3229f1b6c0 | |||
| 0e034b31b1 | |||
| d4a6f6d328 | |||
| 080d454684 | |||
| 2bca371d4d |
@@ -1,3 +1,5 @@
|
|||||||
/__pycache__
|
/__pycache__
|
||||||
/account.py
|
/account.py
|
||||||
/connection.py
|
/connection.py
|
||||||
|
/db
|
||||||
|
/eloquent.pyi
|
||||||
|
|||||||
+6
-4
@@ -1,4 +1,6 @@
|
|||||||
[submodule "ai"]
|
[submodule "nizika_ai"]
|
||||||
path = ai
|
path = nizika_ai
|
||||||
url = https://git.miteruzo.com/miteruzo/nizika_broadcast
|
url = https://git.miteruzo.com/miteruzo/nizika_ai.git
|
||||||
branch = main
|
[submodule "nicolib"]
|
||||||
|
path = nicolib
|
||||||
|
url = https://git.miteruzo.com/miteruzo/nicolib.git
|
||||||
|
|||||||
-1
サブモジュール ai が dfa09e1e66 から削除されました
バイナリファイルは表示されません.
|
変更後 幅: | 高さ: | サイズ: 221 KiB |
バイナリファイルは表示されません.
|
変更後 幅: | 高さ: | サイズ: 171 KiB |
@@ -1,95 +1,305 @@
|
|||||||
from datetime import datetime, timedelta
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import os
|
||||||
import time
|
import time
|
||||||
import sys
|
from datetime import datetime
|
||||||
|
from io import BytesIO
|
||||||
|
from typing import Any, TypedDict
|
||||||
|
|
||||||
from atproto import Client, models
|
import atproto # type: ignore
|
||||||
|
import requests
|
||||||
|
from atproto import Client # type: ignore
|
||||||
|
from atproto_client.models import AppBskyEmbedExternal, AppBskyEmbedImages, ComAtprotoRepoStrongRef # type: ignore
|
||||||
|
from atproto_client.models.app.bsky.feed.get_timeline import Response # type: ignore
|
||||||
|
from atproto_client.models.app.bsky.feed.post import ReplyRef # type: ignore
|
||||||
|
from requests.exceptions import Timeout
|
||||||
|
|
||||||
from ai.talk import Talk
|
|
||||||
import account
|
import account
|
||||||
|
import nicolib
|
||||||
|
from nizika_ai.consts import Character, GPTModel, Platform, QueryType
|
||||||
|
from nizika_ai.models import Answer, AnsweredFlag, Query, User
|
||||||
|
|
||||||
|
TARGET_WORDS = ['deerjika', 'ニジカ', 'ぼっち', '虹夏', '郁代', 'バーカ',
|
||||||
|
'kfif', 'kita-flatten-ikuyo-flatten', 'ラマ田', 'ゴートう',
|
||||||
|
'ぼざクリ', 'オオミソカ', '伊地知', '喜多ちゃん',
|
||||||
|
'喜タイ', '洗澡鹿', 'シーザオ', '今日は本当に',
|
||||||
|
'ダイソーで', '変なチンチン', 'daisoで', 'だね~(笑)',
|
||||||
|
'おやつタイム', 'わさしが', 'わさび県', 'たぬマ', 'にくまる',
|
||||||
|
'ルイズマリー', '餅', 'ニジゴ', 'ゴニジ', 'ニジニジ',
|
||||||
|
'新年だよね', 'うんこじゃん', 'ほくほくのジャガイモ']
|
||||||
|
|
||||||
|
time.sleep (60)
|
||||||
|
|
||||||
|
client = Client (base_url = 'https://bsky.social')
|
||||||
|
client.login (account.USER_ID, account.PASSWORD)
|
||||||
|
|
||||||
|
|
||||||
|
async def main (
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
メーン処理
|
||||||
|
"""
|
||||||
|
|
||||||
|
await asyncio.gather (like_posts (),
|
||||||
|
check_mentions (),
|
||||||
|
answer ())
|
||||||
|
|
||||||
|
|
||||||
|
async def like_posts (
|
||||||
|
) -> None:
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
for post in fetch_target_posts ():
|
||||||
|
client.like (**post)
|
||||||
|
except Exception as e:
|
||||||
|
print (f"[like_posts] { type (e).__name__ }: { e }")
|
||||||
|
|
||||||
|
await asyncio.sleep (60)
|
||||||
|
|
||||||
|
|
||||||
|
async def check_mentions (
|
||||||
|
) -> None:
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
for uri in check_notifications ():
|
||||||
|
records = fetch_thread_contents (uri, 20)
|
||||||
|
if records:
|
||||||
|
record = records[0]
|
||||||
|
image_url: str | None = None
|
||||||
|
if record['embed'] and hasattr (record['embed'], 'images'):
|
||||||
|
image_url = ('https://cdn.bsky.app/img/feed_fullsize/plain'
|
||||||
|
f"/{ record['did'] }"
|
||||||
|
f"/{ record['embed'].images[0].image.ref.link }")
|
||||||
|
user = _fetch_user (record['did'], record['name'])
|
||||||
|
_add_query (user, record['text'], image_url, {
|
||||||
|
'uri': record['strong_ref']['uri'],
|
||||||
|
'cid': record['strong_ref']['cid'] })
|
||||||
|
except Exception as e:
|
||||||
|
print (f"[check_mentions] { type (e).__name__ }: { e }")
|
||||||
|
|
||||||
|
await asyncio.sleep (60)
|
||||||
|
|
||||||
|
|
||||||
|
async def answer (
|
||||||
|
) -> None:
|
||||||
|
while True:
|
||||||
|
answered_flags = (
|
||||||
|
AnsweredFlag
|
||||||
|
.where ('platform', Platform.BLUESKY.value)
|
||||||
|
.where ('answered', False)
|
||||||
|
.get ())
|
||||||
|
for answered_flag in answered_flags:
|
||||||
|
td: dict[str, Any]
|
||||||
|
answer = answered_flag.answer
|
||||||
|
answered_flag.answered = True
|
||||||
|
answered_flag.save ()
|
||||||
|
match QueryType (answer.query_rel.query_type):
|
||||||
|
case QueryType.BLUESKY_COMMENT:
|
||||||
|
td = answer.query_rel.transfer_data or { }
|
||||||
|
uri: str | None = td.get ('uri')
|
||||||
|
cid: str | None = td.get ('cid')
|
||||||
|
if (not uri) or (not cid):
|
||||||
|
continue
|
||||||
|
|
||||||
|
strong_ref = ComAtprotoRepoStrongRef.Main (uri = uri, cid = cid)
|
||||||
|
reply_ref = ReplyRef (root = strong_ref, parent = strong_ref)
|
||||||
|
try:
|
||||||
|
client.post (answer.content[:250], reply_to = reply_ref)
|
||||||
|
except Exception as e:
|
||||||
|
print (f"[answer/reply] { type (e).__name__ }: { e }")
|
||||||
|
continue
|
||||||
|
case QueryType.KIRIBAN | QueryType.NICO_REPORT:
|
||||||
|
td = answer.query_rel.transfer_data or { }
|
||||||
|
video_code: str | None = td.get ('video_code')
|
||||||
|
if not video_code:
|
||||||
|
continue
|
||||||
|
|
||||||
|
uri = f"https://www.nicovideo.jp/watch/{ video_code }"
|
||||||
|
(title, description, thumbnail) = nicolib.fetch_embed_info (uri)
|
||||||
|
try:
|
||||||
|
resp = requests.get (thumbnail, timeout = 60)
|
||||||
|
resp.raise_for_status ()
|
||||||
|
upload = client.com.atproto.repo.upload_blob (BytesIO (resp.content))
|
||||||
|
thumb = upload.blob
|
||||||
|
except Timeout:
|
||||||
|
thumb = None
|
||||||
|
except Exception as e:
|
||||||
|
print (f"[answer/nico-thumb] { type (e).__name__ }: { e }")
|
||||||
|
thumb = None
|
||||||
|
|
||||||
|
external = AppBskyEmbedExternal.External (
|
||||||
|
title = title,
|
||||||
|
description = description,
|
||||||
|
thumb = thumb,
|
||||||
|
uri = uri)
|
||||||
|
embed_external = AppBskyEmbedExternal.Main (external = external)
|
||||||
|
try:
|
||||||
|
client.post (answer.content[:250], embed = embed_external)
|
||||||
|
except Exception as e:
|
||||||
|
print (f"[answer/nico-post] { type (e).__name__ }: { e }")
|
||||||
|
continue
|
||||||
|
case QueryType.SNACK_TIME:
|
||||||
|
try:
|
||||||
|
with open ('./assets/snack-time.jpg', 'rb') as f:
|
||||||
|
image = AppBskyEmbedImages.Image (
|
||||||
|
alt = (
|
||||||
|
'左に喜多ちゃん、右に人面鹿のニジカが'
|
||||||
|
'V字に並んでいる。'
|
||||||
|
'喜多ちゃんは右手でピースサインをして'
|
||||||
|
'片目をウインクしている。'
|
||||||
|
'ニジカは両手を広げ、'
|
||||||
|
'右手にスプーンを持って'
|
||||||
|
'ポーズを取っている。'
|
||||||
|
'背景には'
|
||||||
|
'赤と黄色の放射線状の模様が広がり、'
|
||||||
|
'下部に「おやつタイムだ!!!!」という'
|
||||||
|
'日本語のテキストが表示されている。'),
|
||||||
|
image = client.com.atproto.repo.upload_blob (f).blob)
|
||||||
|
client.post (answer.content[:250],
|
||||||
|
embed = AppBskyEmbedImages.Main (images = [image]))
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
case QueryType.HOT_SPRING:
|
||||||
|
try:
|
||||||
|
with open ('./assets/hot-spring.jpg', 'rb') as f:
|
||||||
|
image = AppBskyEmbedImages.Image (
|
||||||
|
alt = ('左に喜多ちゃん、右にわさび県産滋賀県が'
|
||||||
|
'V字に並んでいる。'
|
||||||
|
'喜多ちゃんは右手でピースサインをして'
|
||||||
|
'片目をウインクしている。'
|
||||||
|
'わさび県産滋賀県はただ茫然と'
|
||||||
|
'立ち尽くしている。'
|
||||||
|
'背景には'
|
||||||
|
'血と空の色をした放射線状の模様が広がり、'
|
||||||
|
'下部に「温泉に入ろう!!!」という'
|
||||||
|
'日本語のテキストが表示されている。'),
|
||||||
|
image = client.com.atproto.repo.upload_blob (f).blob)
|
||||||
|
client.post (answer.content[:250],
|
||||||
|
embed = AppBskyEmbedImages.Main (images = [image]))
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
await asyncio.sleep (10)
|
||||||
|
|
||||||
|
|
||||||
def check_notifications (
|
def check_notifications (
|
||||||
client: Client,
|
) -> list[str]:
|
||||||
) -> list:
|
uris: list[str] = []
|
||||||
(uris, last_seen_at) = ([], client.get_current_time_iso ())
|
last_seen_at = client.get_current_time_iso ()
|
||||||
|
|
||||||
for notification in (client.app.bsky.notification.list_notifications ()
|
notifications = client.app.bsky.notification.list_notifications ()
|
||||||
.notifications):
|
for notification in notifications.notifications:
|
||||||
if not notification.is_read:
|
if not notification.is_read:
|
||||||
if notification.reason in ['mention', 'reply']:
|
match notification.reason:
|
||||||
uris += [notification.uri]
|
case 'mention' | 'reply' | 'quote':
|
||||||
elif notification.reason == 'follow':
|
uris.append (notification.uri)
|
||||||
client.follow (notification.author.did)
|
case 'follow':
|
||||||
|
client.follow (notification.author.did)
|
||||||
|
|
||||||
client.app.bsky.notification.update_seen ({ 'seen_at': last_seen_at })
|
client.app.bsky.notification.update_seen ({ 'seen_at': last_seen_at })
|
||||||
|
|
||||||
return uris
|
return uris
|
||||||
|
|
||||||
|
|
||||||
def get_thread_contents (
|
def fetch_thread_contents (
|
||||||
client: Client,
|
|
||||||
uri: str,
|
uri: str,
|
||||||
parent_height: int,
|
parent_height: int,
|
||||||
) -> list:
|
) -> list[Record]:
|
||||||
response = (client.get_post_thread (uri = uri,
|
post_thread = client.get_post_thread (uri = uri, parent_height = parent_height)
|
||||||
parent_height = parent_height)
|
if not post_thread:
|
||||||
.thread)
|
return []
|
||||||
records = []
|
|
||||||
while response is not None:
|
res = post_thread.thread
|
||||||
records += [{ 'strong_ref': models.create_strong_ref (response.post),
|
|
||||||
'did': response.post.author.did,
|
records: list[Record] = []
|
||||||
'handle': response.post.author.handle,
|
while res:
|
||||||
'name': response.post.author.display_name,
|
if hasattr (res, 'post'):
|
||||||
'datetime': response.post.record.created_at,
|
records.append ({ 'strong_ref': { 'uri': res.post.uri,
|
||||||
'text': response.post.record.text }]
|
'cid': res.post.cid },
|
||||||
response = response.parent
|
'did': res.post.author.did,
|
||||||
|
'handle': res.post.author.handle,
|
||||||
|
'name': (res.post.author.display_name
|
||||||
|
or res.post.author.handle),
|
||||||
|
'datetime': res.post.record.created_at,
|
||||||
|
'text': getattr (res.post.record, 'text', None) or '',
|
||||||
|
'embed': getattr (res.post.record, 'embed', None) })
|
||||||
|
res = res.parent
|
||||||
|
else:
|
||||||
|
break
|
||||||
|
|
||||||
return records
|
return records
|
||||||
|
|
||||||
|
|
||||||
def main () -> None:
|
def fetch_target_posts (
|
||||||
client = Client (base_url = 'https://bsky.social')
|
) -> list[LikeParams]:
|
||||||
|
posts: list[LikeParams] = []
|
||||||
|
|
||||||
client.login (account.USER_ID, account.PASSWORD)
|
timeline: Response = client.get_timeline ()
|
||||||
|
for feed in timeline.feed:
|
||||||
|
me = getattr (client, 'me', None)
|
||||||
|
my_did = me.did if me else ''
|
||||||
|
if (feed.post.author.did != my_did
|
||||||
|
and (feed.post.viewer.like is None)
|
||||||
|
and any (target_word in (feed.post.record.text or '').casefold ()
|
||||||
|
for target_word in TARGET_WORDS)):
|
||||||
|
posts.append (LikeParams ({ 'uri': feed.post.uri, 'cid': feed.post.cid }))
|
||||||
|
|
||||||
last_posted_at = datetime.now () - timedelta (hours = 6)
|
return posts
|
||||||
has_got_snack_time = False
|
|
||||||
while True:
|
|
||||||
now = datetime.now ()
|
|
||||||
|
|
||||||
for uri in check_notifications (client):
|
|
||||||
records = get_thread_contents (client, uri, 20)
|
|
||||||
if len (records) > 0:
|
|
||||||
answer = Talk.main (records[0]['text'],
|
|
||||||
records[0]['name'],
|
|
||||||
[*map (lambda record: {
|
|
||||||
'role': ('assistant'
|
|
||||||
if (record['handle']
|
|
||||||
== account.USER_ID)
|
|
||||||
else 'user'),
|
|
||||||
'content':
|
|
||||||
record['text']},
|
|
||||||
reversed (records[1:]))])
|
|
||||||
client.send_post (answer,
|
|
||||||
reply_to = models.AppBskyFeedPost.ReplyRef (
|
|
||||||
parent = records[0]['strong_ref'],
|
|
||||||
root = records[-1]['strong_ref']))
|
|
||||||
|
|
||||||
if now.hour == 14 and has_got_snack_time:
|
def _add_query (
|
||||||
has_got_snack_time = False
|
user: User,
|
||||||
|
content: str,
|
||||||
|
image_url: str | None = None,
|
||||||
|
transfer_data: dict[str, Any] | None = None,
|
||||||
|
) -> None:
|
||||||
|
query = Query ()
|
||||||
|
query.user_id = user.id
|
||||||
|
query.target_character = Character.DEERJIKA.value
|
||||||
|
query.content = content
|
||||||
|
query.image_url = image_url or None
|
||||||
|
query.query_type = QueryType.BLUESKY_COMMENT.value
|
||||||
|
query.model = GPTModel.GPT3_TURBO.value
|
||||||
|
query.sent_at = datetime.now ()
|
||||||
|
query.answered = False
|
||||||
|
query.transfer_data = transfer_data
|
||||||
|
query.save ()
|
||||||
|
# TODO: 履歴情報の追加
|
||||||
|
|
||||||
if now.hour == 15 and not has_got_snack_time:
|
|
||||||
client.send_post (Talk.main ('おやつタイムだ!!!!'))
|
|
||||||
last_posted_at = now
|
|
||||||
|
|
||||||
has_got_snack_time = True
|
def _fetch_user (
|
||||||
|
did: str,
|
||||||
|
name: str,
|
||||||
|
) -> User:
|
||||||
|
user = User.where ('platform', Platform.BLUESKY.value).where ('code', did).first ()
|
||||||
|
if user is None:
|
||||||
|
user = User ()
|
||||||
|
user.platform = Platform.BLUESKY.value
|
||||||
|
user.code = did
|
||||||
|
user.name = name
|
||||||
|
user.save ()
|
||||||
|
return user
|
||||||
|
|
||||||
if now - last_posted_at >= timedelta (hours = 6):
|
|
||||||
client.send_post (Talk.main (''))
|
|
||||||
last_posted_at = now
|
|
||||||
|
|
||||||
time.sleep (60)
|
class LikeParams (TypedDict):
|
||||||
|
uri: str
|
||||||
|
cid: str
|
||||||
|
|
||||||
|
|
||||||
|
class Record (TypedDict):
|
||||||
|
strong_ref: StrongRef
|
||||||
|
did: str
|
||||||
|
handle: str
|
||||||
|
name: str
|
||||||
|
datetime: str
|
||||||
|
text: str
|
||||||
|
embed: object
|
||||||
|
|
||||||
|
|
||||||
|
class StrongRef (TypedDict):
|
||||||
|
uri: str
|
||||||
|
cid: str
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
main (*sys.argv[1:])
|
asyncio.run (main ())
|
||||||
|
|||||||
サブモジュール
+1
サブモジュール nicolib が 85670982f0 で追加されました
サブモジュール
+1
サブモジュール nizika_ai が 1f75763038 で追加されました
新しい課題から参照
ユーザをブロックする