Skip to content

Commit

Permalink
statusコマンドで何番目にアカウントを作ったかわかるようにした
Browse files Browse the repository at this point in the history
  • Loading branch information
kojira committed Jun 3, 2023
1 parent e74f341 commit 23d4fee
Show file tree
Hide file tree
Showing 3 changed files with 355 additions and 46 deletions.
171 changes: 171 additions & 0 deletions aggregate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
from atproto import Client, models
import atproto
import os
from dotenv import load_dotenv
import openai
import time
import sqlite3
from tqdm import tqdm
import inspect

connection = sqlite3.connect("bluesky.db")
cur = connection.cursor()

cur.execute("""
CREATE TABLE IF NOT EXISTS users
(id INTEGER PRIMARY KEY AUTOINCREMENT,
did TEXT,
handle TEXT,
displayName TEXT,
indexed_at DATETIME,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
)
""")
cur.execute("""
CREATE TABLE IF NOT EXISTS posts
(id INTEGER PRIMARY KEY AUTOINCREMENT,
did TEXT,
count INTEGER,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
)
""")
cur.execute("""
CREATE TRIGGER IF NOT EXISTS update_timestamp
AFTER UPDATE ON users
FOR EACH ROW
BEGIN
UPDATE users SET updated_at = CURRENT_TIMESTAMP WHERE id = OLD.id;
END;
""")
connection.commit()

dotenv_path = os.path.join(os.path.dirname(__file__), ".env")
load_dotenv(dotenv_path)

username = os.environ.get("BOT_HANDLE")
password = os.environ.get("BOT_PASSWORD")

client = Client()


def login(username, password):
profile = client.login(username, password)
return profile


def get_follow(actor, cursor):
response = None
try:
response = client.bsky.graph.get_follows(
{"actor": actor, "cursor": cursor, "limit": 100}
)
except atproto.exceptions.RequestException as e:
print(actor)
print(e)
if e.args[0].content.error == 'ExpiredToken':
login(username, password)
try:
response = get_follow(actor, cursor)
except atproto.exceptions.RequestException as e:
print(e)

return response


def get_profile_detail(actor):
profile = None
while True and profile is None:
try:
profile = client.bsky.actor.get_profile({"actor": actor})
except atproto.exceptions.RequestException as e:
print(actor)
print(e)
if e.args[0].content.error == 'ExpiredToken':
login(username, password)
try:
profile = get_profile_detail(actor)
except atproto.exceptions.RequestException as e:
print(e)
break
except atproto.exceptions.InvokeTimeoutError as e:
print(e)
break

return profile


profile = login(username, password)

actor = "kojira.bsky.social"
# actor = "masonicursa.bsky.social"
# actor = "peelingoranges.bsky.social"
cursor = None

member_index = 0

cur.execute("SELECT * FROM users ORDER BY RANDOM()")
rows = cur.fetchall()
columns = [column[0] for column in cur.description]
all_members = [dict(zip(columns, row)) for row in rows]

prev_actor = None

while True:
if actor != prev_actor:
profile = get_profile_detail(actor)
if profile:
print(f"{profile.displayName}@{profile.handle}")
sql = "INSERT INTO posts (did, count) VALUES (?, ?)"
cur.execute(sql, (profile.did, profile.postsCount, ))
connection.commit()

response = get_follow(actor, cursor)
if response:
follows = response.follows
members = [{"did": follow.did,
"handle": follow.handle,
"displayName": follow.displayName,
"indexed_at": follow.indexedAt}
for follow in follows
if all(item["did"] != follow.did for item in all_members)
]
print(len(members))
all_members.extend(members)
sql = """
INSERT INTO users (did, handle, displayName, indexed_at)
VALUES (:did, :handle, :displayName, :indexed_at)
"""
cur.executemany(sql, members)

connection.commit()
prev_actor = actor
if response.cursor is None:
cursor = None
if member_index > (len(all_members) - 1):
member_index = 0
actor = all_members[member_index]["handle"]
member_index += 1
print("all:", len(all_members))
else:
# print("cursor:", response.cursor)
cursor = response.cursor
else:
if member_index > (len(all_members) - 1):
member_index = 0
actor = all_members[member_index]["handle"]
member_index += 1
print("all:", len(all_members))
else:
if member_index > (len(all_members) - 1):
member_index = 0
actor = all_members[member_index]["handle"]
member_index += 1
print("all:", len(all_members))

time.sleep(0.05)


# params = models.AppBskyActorGetProfile.Params("kojira.bsky.social")
# print(follow)
# print(client.com.atproto.identity.resolve_handle(params))
# client.send_post(text="Hello World!")
78 changes: 32 additions & 46 deletions bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@
import pytz
from dateutil.parser import parse
import random
import util

connection = sqlite3.connect("bluesky.db")
cur = connection.cursor()
connection_atp = sqlite3.connect("atp.db")

dotenv_path = os.path.join(os.path.dirname(__file__), ".env")
load_dotenv(dotenv_path)
Expand Down Expand Up @@ -46,46 +46,8 @@ def reply_to(session, text, cid, uri):
session.postBloot(text, reply_to=reply_ref)


def record_reaction(connection, eline):
reaction = {"did": eline.post.author.did,
"handle": eline.post.author.handle,
"displayName": eline.post.author.displayName,
"created_at": eline.post.indexedAt}
sql = """
INSERT INTO reactions (did, handle, displayName, created_at)
VALUES (:did, :handle, :displayName, :created_at)
"""
cur = connection.cursor()
cur.execute(sql, reaction)
connection.commit()


def get_latest_record_by_did(connection, did):
sql = """
SELECT *
FROM reactions
WHERE did = :did
ORDER BY created_at DESC
LIMIT 1
"""
cur = connection.cursor()
cur.execute(sql, {'did': did})
row = cur.fetchone()
return row


def has_mention(bot_names, text):
found = False
for bot_name in bot_names:
if bot_name in text:
found = True
break
print("found:", found)
return found


def fortune(connection, prompt, eline):
row = get_latest_record_by_did(connection, eline.post.author.did)
row = util.get_latest_record_by_did(connection, eline.post.author.did)
fortuneOk = False
if row:
now = datetime.now(pytz.utc)
Expand All @@ -106,11 +68,24 @@ def fortune(connection, prompt, eline):
f"その結果に従って占いの内容を運の良さは★マークを5段階でラッキーアイテム、ラッキーカラーとかも教えて。{user_text}"
print("fortune")
answer = gpt.get_answer(prompt, text)
record_reaction(connection, eline)
util.record_reaction(connection, eline)
print(answer)
reply_to(session, answer[:300], eline.post.cid, eline.post.uri)


def status(connection_atp, eline):
did = eline.post.author.did.replace("did:plc:", "")
result = util.get_user_info(connection_atp, did)
startDateTime = result["created_at"]
order = result["order"]
status_text = "ふふ、あなたのステータスをお知らせしますわ。\n" +\
f"あなたは{order}番目のアカウントのようですわ。\n" + \
f"作られた日時は{startDateTime} ですわね。\n" + \
"ごきげんよう。"

return status_text


session = Session(username, password)

personality = """
Expand All @@ -130,8 +105,12 @@ def fortune(connection, prompt, eline):

bot_names = [
"Blueskyちゃん", "Bluesky ちゃん", "bluesky ちゃん", "blueskyちゃん",
"ブルースカイちゃん", "ぶるすこちゃん", "ブルスコちゃん",
"ブルースカイちゃん", "ぶるすこちゃん", "ブルスコちゃん", "ブルス子ちゃん",
]
# bot_names = [
# "テストちゃん"
# ]


prompt = f"これはあなたの人格です。'{personality}'\nこの人格を演じて次の文章に対して30〜200文字以内で返信してください。"

Expand Down Expand Up @@ -165,13 +144,19 @@ def fortune(connection, prompt, eline):
if not detect_mention:
text = eline.post.record.text
if "占って" in text and\
has_mention(bot_names, text):
util.has_mention(bot_names, text):
print(line)
fortune(connection, prompt, eline)
elif "status" in text and\
util.has_mention(bot_names, text):
print(line)
answer = status(connection_atp, eline)
print(answer)
reply_to(session, answer[:300], eline.post.cid, eline.post.uri)
else:
print(line)
bonus = 0
if has_mention(bot_names, text):
if util.has_mention(bot_names, text):
bonus = 5
if answered is None or (now - answered) >= timedelta(minutes=20):
bonus = 100
Expand All @@ -186,4 +171,5 @@ def fortune(connection, prompt, eline):
else:
print("hazure")
now = postDatetime
time.sleep(5)
time.sleep(3)
util.aggregate_users(connection_atp)
Loading

0 comments on commit 23d4fee

Please sign in to comment.