nova2 / niva - 복사본.py
chohj06ms's picture
Upload 22 files
d1e2e7a verified
import requests
import typing
from typing import Optional
import discord
from discord.ext import commands
from discord import app_commands
from PIL import Image, ImageDraw, ImageFont, ImageColor, ImageFilter, ImageSequence
import json
# 사용자 데이터를 저장할 파일 이름을 정의합니다.
USER_DATA_FILE = 'user_data.json'
# 사용자 데이터를 저장하는 딕셔너리를 초기화합니다.
# 서버 시작 시 파일에서 사용자 데이터를 로드합니다.
with open(USER_DATA_FILE, 'r') as file:
user_data = json.load(file)
print(user_data)
print("load")
# PolygonScan API 키
api_key = "4H655NPT5229MKFE2NNHIS2GNZ3U4UTGT2"
with open("token.txt", "r", encoding='utf-8') as f:
token = f.read()
def obj_srch(account_address):
# PolygonScan API URL 구성
contract_address = "0xA4B37bE40F7b231Ee9574c4b16b7DDb7EAcDC99B"
url = f"https://api.polygonscan.com/api?module=account&action=tokenbalance&contractaddress={contract_address}&address={account_address}&tag=latest&apikey={api_key}"
# API 요청
response = requests.get(url)
# 응답 확인 및 처리
if response.status_code == 200:
data = response.json()
balance = data.get('result')
if balance is not None:
# ERC-721은 보통 1 NFT당 1을 가지므로, balance를 직접 반환
real_balance = int(balance)
print(f"계정 주소 {account_address}는(은) 토큰 컨트랙트 {contract_address}의 NFT를 {real_balance}개 가지고 있습니다.")
return real_balance
else:
print("NFT 잔액 정보를 가져올 수 없습니다.")
else:
print("API 요청에 실패했습니다.")
def obj_srch_art(account_address):
# PolygonScan API URL 구성
contract_address = "0x0fB69F54bA90f17578a59823E09e5a1f8F3FA200"
url = f"https://api.polygonscan.com/api?module=account&action=tokenbalance&contractaddress={contract_address}&address={account_address}&tag=latest&apikey={api_key}"
# API 요청
response = requests.get(url)
# 응답 확인 및 처리
if response.status_code == 200:
data = response.json()
balance = data.get('result')
if balance is not None:
# ERC-721은 보통 1 NFT당 1을 가지므로, balance를 직접 반환
real_balance = int(balance)
print(f"계정 주소 {account_address}는(은) 토큰 컨트랙트 {contract_address}의 NFT를 {real_balance}개 가지고 있습니다.")
return real_balance
else:
print("NFT 잔액 정보를 가져올 수 없습니다.")
else:
print("API 요청에 실패했습니다.")
def como_srch(account_address):
tok = "0x58AeABfE2D9780c1bFcB713Bf5598261b15dB6e5"
url = f"https://api.polygonscan.com/api?module=account&action=tokenbalance&contractaddress={tok}&address={account_address}&tag=latest&apikey={api_key}"
response = requests.get(url)
# 응답 확인
if response.status_code == 200:
data = response.json()
# 토큰 수량 출력
balance = data.get('result')
if balance is not None:
real_balance = int(balance) / 10 ** 18
print(f"계정 주소 {account_address}는(은) 토큰 주소 {tok}의 토큰을 {int(real_balance)}개 가지고 있습니다.")
return int(real_balance)
else:
print("토큰 수량 정보를 가져올 수 없습니다.")
else:
print("API 요청에 실패했습니다.")
def como_srch_art(account_address):
tok = "0x8254D8D2903B20187cBC4Dd833d49cECc219F32E"
url = f"https://api.polygonscan.com/api?module=account&action=tokenbalance&contractaddress={tok}&address={account_address}&tag=latest&apikey={api_key}"
response = requests.get(url)
# 응답 확인
if response.status_code == 200:
data = response.json()
# 토큰 수량 출력
balance = data.get('result')
if balance is not None:
real_balance = int(balance) / 10 ** 18
print(f"계정 주소 {account_address}는(은) 토큰 주소 {tok}의 토큰을 {int(real_balance)}개 가지고 있습니다.")
return int(real_balance)
else:
print("토큰 수량 정보를 가져올 수 없습니다.")
else:
print("API 요청에 실패했습니다.")
def srch(input_str):
if len(input_str) < 4:
return "4글자 이상으로 작성해주세요."
base_url = "https://cache.nova.gd/user/v1"
url = f"{base_url}/search?query={input_str}"
response = requests.get(url)
data = response.json()
# 'address' 값 추출
address = data['results'][0]['address']
print(address)
return address
def como_txt(text):
image_size = (180, 50)
image = Image.new('RGBA', image_size, (255, 255, 255, 0))
draw = ImageDraw.Draw(image)
font = ImageFont.truetype("Helvetica_Neue_LT_Std_75_Bold.otf", 50)
text_color = (200, 200, 200)
# 텍스트의 경계 상자 계산
text_bbox = draw.textbbox((0, 0), text, font=font)
text_width = text_bbox[2] - text_bbox[0]
text_height = text_bbox[3] - text_bbox[1]
# 텍스트를 이미지 중앙에 정렬
text_x = (image_size[0] - text_width) / 2
text_y = (image_size[1] - text_height) / 2
draw.text((text_x, text_y), text, fill=text_color, font=font)
return image
def acom(input_str):
if len(input_str) < 4:
return ["4글자 이상으로 작성해주세요."]
base_url = "https://cache.nova.gd/user/v1"
url = f"{base_url}/search?query={input_str}"
response = requests.get(url)
data = response.json()
users = data.get("results", []) # 'search' 가 {"results": [...]} 형식을 반환한다고 가정
if response.status_code != 200:
raise Exception(f"Request failed with status code {response.status_code}")
if not users:
return ["검색 결과 없음"]
# 결과를 리스트 형태로 반환
result_list = [user['nickname'] for user in users]
return result_list
def names(text, img):
# 이미지 크기와 글꼴 크기 설정
image_size = (1280, 706)
# 이미지와 드로잉 객체 생성
image = img
draw = ImageDraw.Draw(image)
font = ImageFont.truetype("Helvetica_Neue_LT_Std_75_Bold.otf", 42)
# 글꼴 설정
text_color = (208, 211, 214)
# 텍스트 크기 계산
draw.text((124, 26), text, fill=text_color, font=font)
return image
async def name_auto(interaction: discord.Interaction, current: str) -> typing.List[app_commands.Choice[str]]:
#all_files = os.listdir(".\\obj")
#matching_files = sorted(list(set([re.split(',', file)[1] for file in all_files if current.lower() in re.split(',', file)[1].lower()])))
acs = acom(current)
matching_files = acs
return [app_commands.Choice(name=num, value=num) for num in matching_files]
async def group(interaction: discord.Interaction, current: str) -> typing.List[app_commands.Choice[str]]:
#all_files = os.listdir(".\\obj")
#matching_files = sorted(list(set([re.split(',', file)[1] for file in all_files if current.lower() in re.split(',', file)[1].lower()])))
matching_files = ["tripleS", "ARTMS"]
return [app_commands.Choice(name=num, value=num) for num in matching_files]
def save_user(user_id, nickname):
user_data[user_id] = nickname
print(f"사용자 {user_id} ({nickname}) 가 성공적으로 저장되었습니다.")
# 모든 사용자 데이터를 파일에 저장하는 함수입니다.
def save_data_to_file():
print(user_data)
with open(USER_DATA_FILE, 'w') as file:
json.dump(user_data, file)
print("모든 사용자 데이터가 파일에 저장되었습니다.")
def find_nickname_by_id(user_id):
# 해당 ID가 존재할 경우 닉네임을 반환하고, 그렇지 않으면 None을 반환합니다.
return user_data.get(user_id, None)
# 주어진 닉네임으로 모든 사용자의 ID를 찾는 함수입니다.
def find_ids_by_nickname(nickname):
# 닉네임과 일치하는 모든 사용자의 ID를 리스트로 수집합니다.
matching_ids = [user_id for user_id, user_nickname in user_data.items() if user_nickname == nickname]
return matching_ids
def run():
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="!", intents=intents)
@bot.event
async def on_ready():
bot.tree.copy_global_to(guild=discord.Object(id=1192532796967751790))
await bot.tree.sync(guild=discord.Object(id=1192532796967751790))
print("ready")
@app_commands.autocomplete(name=name_auto)
@app_commands.autocomplete(group=group)
@bot.tree.command()
async def me(interaction: discord.Interaction, name: Optional[str] = None, group: Optional[str] = None):
if group == "ARTMS":
if name:
nid = srch(name)
nid = str(nid)
print(nid)
else:
# name이 제공되지 않았을 때의 로직
did = interaction.user.id
nid = find_nickname_by_id(did)
print(nid)
ad = srch(str(nid))
ad1 = ad[0]
nid = ad
print(nid)
como = como_srch_art(nid)
como_img = como_txt(str(como))
base_img = Image.open("base_img_art.png")
name_paste_position = (219, 295)
base_img.paste(como_img, name_paste_position, como_img)
obj = obj_srch_art(nid)
como_img = como_txt(str(obj))
name_paste_position = (219, 205)
base_img.paste(como_img, name_paste_position, como_img)
base_img = names(name, base_img)
base_img.save("img.png")
await interaction.response.send_message(f"", ephemeral=False, file=discord.File("img.png"))
else:
if name:
nid = srch(name)
nid = str(nid)
print(nid)
else:
# name이 제공되지 않았을 때의 로직
did = interaction.user.id
nid = find_nickname_by_id(did)
print(nid)
ad = srch(str(nid))
ad1 = ad[0]
nid = ad
print(nid)
como = como_srch(nid)
como_img = como_txt(str(como))
base_img = Image.open("base_img.png")
name_paste_position = (219, 295)
base_img.paste(como_img, name_paste_position, como_img)
obj = obj_srch(nid)
como_img = como_txt(str(obj))
name_paste_position = (219, 205)
base_img.paste(como_img, name_paste_position, como_img)
base_img = names(name, base_img)
base_img.save("img.png")
await interaction.response.send_message(f"", ephemeral=False, file=discord.File("img.png"))
@app_commands.autocomplete(cosmo_id=name_auto)
@bot.tree.command(name="synk",
description="input YOUR cosmo id",)
async def synk(interaction: discord.Interaction, cosmo_id: str):
did = interaction.user.id
save_user(did, cosmo_id)
await interaction.response.send_message(f"Connect <@!{did}> to {cosmo_id}")
@app_commands.autocomplete(cosmo_id=name_auto)
@bot.tree.command()
async def find(interaction: discord.Interaction, cosmo_id: str):
did = interaction.user.id
did = find_ids_by_nickname(cosmo_id)
mentions = [f"<@{user_id}>" for user_id in did]
# 멘션 문자열을 공백으로 구분하여 하나의 메시지로 결합
mentions_message = " ".join(mentions)
# 멘션을 포함한 메시지 전송
await interaction.response.send_message(f"Cosmo({cosmo_id}) is {mentions_message}", ephemeral=False)
@bot.tree.command()
async def save(interaction: discord.Interaction):
save_data_to_file()
await interaction.response.send_message(f"Saved", ephemeral=True)
bot.run(token)
if __name__ == "__main__":
run()