booming-kr 오토 보팅 테스트 중

in #kr2 days ago (edited)

오랜만에 PC에 파이썬을 최신버전으로 설치하려고 봤더니...

대박 벌써 3.13.x 가 되었군요

파이썬을 설치하자 마자 beem을 설치했구요

image.png

코드를 넣고 실행을 했는데...

image.png

코드가 막 헤매고만 있네요...
아무리 chat gpt가 많이 발전했어도 최근 steem 개발 코드가 부족한지 얘도 힘들어 하는군요...

사용한 코드는 아래와 같습니다.

from beem import Steem
from beem.comment import Comment
from beem.blockchain import Blockchain
from beem.instance import set_shared_steem_instance
from beem.account import Account
from beem.exceptions import AccountDoesNotExistsException
import time

===== 설정 =====

MY_ACCOUNT = "A_account" # A 계정
POSTING_KEY = "your_posting_key" # A posting key
STEEM_NODES = ["https://api.steemit.com"] # 반드시 STEEM 노드로 지정

허용 계정 + 보팅 비율(%)

ALLOWED = {
"B1": 100,
"B2": 75,
"B3": 50
}

“가장 최근 댓글만” 처리하기 위한 디바운스(대기) 시간

DEBOUNCE_SECONDS = 10

===== Steem 인스턴스 =====

stm = Steem(node=STEEM_NODES, keys=[POSTING_KEY], num_retries=5, timeout=30)
set_shared_steem_instance(stm)

계정 확인

try:
_ = Account(MY_ACCOUNT, steem_instance=stm)
except AccountDoesNotExistsException:
raise SystemExit(
f"@{MY_ACCOUNT} 계정을 {STEEM_NODES[0]}(STEEM)에서 찾을 수 없습니다. "
"계정명/노드를 확인하세요."
)

bchain = Blockchain(steem_instance=stm, mode="head")

중복 처리 방지

processed_ids = set()

디바운스용 최신 댓글 후보

latest_candidate = None # dict(comment-op)
latest_candidate_time = 0.0 # 마지막 후보 갱신 시각(Unix time)

def is_reply_to_my_post(cop):
"""A의 원글에 달린 1단계 댓글인지"""
return cop.get("parent_author") == MY_ACCOUNT

def commenter_voted_on_my_post(cop):
"""댓글 작성자(B)가 A의 '원글'에 보팅했는지 확인"""
commenter = cop["author"]
parent_permlink = cop["parent_permlink"]
try:
parent_post = Comment(f"@{MY_ACCOUNT}/{parent_permlink}")
for v in parent_post["active_votes"]:
if v.get("voter") == commenter and float(v.get("percent", 0)) > 0:
return True
except Exception as e:
print(f"[WARN] 부모 글 보팅 조회 실패: {e}")
return False

def maybe_process_latest():
"""디바운스 시간이 지났고 후보가 있으면 조건 검사 후 보팅"""
global latest_candidate, latest_candidate_time

if latest_candidate is None:
    return

# 최신 후보가 DEBOUNCE_SECONDS 동안 갱신되지 않았을 때만 처리
if time.time() - latest_candidate_time < DEBOUNCE_SECONDS:
    return

cop = latest_candidate
cid = f"{cop['author']}/{cop['permlink']}"

# 이미 처리했으면 패스
if cid in processed_ids:
    latest_candidate = None
    return

author = cop["author"]

# 0) 허용 계정만
if author not in ALLOWED:
    latest_candidate = None
    return

# 1) A의 포스팅에 단 1단계 댓글인가?
if not is_reply_to_my_post(cop):
    latest_candidate = None
    return

# 2) 댓글 작성자가 A의 '원글'에 보팅했는가?
if not commenter_voted_on_my_post(cop):
    latest_candidate = None
    return

# 3) 조건 충족 → 댓글에 지정 %로 보팅
try:
    weight = ALLOWED[author]
    c = Comment(f"@{author}/{cop['permlink']}")
    c.upvote(weight=weight, voter=MY_ACCOUNT)
    print(f"[VOTE] @{MY_ACCOUNT} → @{author}/{cop['permlink']} ({weight}%)")
    processed_ids.add(cid)
except Exception as e:
    print(f"[ERROR] 보팅 실패: {e}")

# 처리 후 후보 비우기
latest_candidate = None

def run():
global latest_candidate, latest_candidate_time

print(f"🔁 Auto voting (latest-only) as @{MY_ACCOUNT} on {STEEM_NODES[0]}")
stream = bchain.stream(opNames=["comment"], raw_ops=False)

for cop in stream:
    try:
        # 댓글이 들어오면 “최신 후보”로 교체
        latest_candidate = cop
        latest_candidate_time = time.time()

        # 짧게 기다리면서 더 최신 댓글이 오는지 관찰
        # (루프가 빠르게 돌 때 과도한 CPU 사용 방지)
        maybe_process_latest()
        time.sleep(0.5)

    except KeyboardInterrupt:
        print("종료 요청 감지. 프로그램을 종료합니다.")
        break
    except Exception as e:
        print(f"[ERROR] 루프 처리 중 오류: {e}")
        time.sleep(1)

if name == "main":
run()

Sort:  

오 화이팅입니다. 형님
퐈이썬을 직접 ^^

오~ 완전 프로그래머이신걸요!
멋지십니다~ 응원합니다~! 👍