File size: 12,158 Bytes
d1e2e7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
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()