File size: 6,721 Bytes
702e854
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b13e2ae
 
702e854
 
8a469c5
702e854
b13e2ae
3709f4e
 
 
b13e2ae
 
 
 
947521c
1723448
b13e2ae
 
947521c
 
1723448
947521c
b13e2ae
 
 
3709f4e
 
b13e2ae
3709f4e
b13e2ae
 
 
702e854
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0386a8b
702e854
 
 
 
 
 
 
 
3b59eed
 
702e854
 
 
 
 
 
 
 
 
 
647319a
 
702e854
647319a
702e854
 
 
b13e2ae
 
702e854
 
647319a
702e854
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
647319a
702e854
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c42cc6
702e854
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55f94c4
702e854
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55f94c4
702e854
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
import asyncio
import os
import threading
from threading import Event
from typing import Optional

import discord
import gradio as gr
from discord import Permissions
from discord.ext import commands
from discord.utils import oauth_url

import gradio_client as grc
from gradio_client.utils import QueueError

import requests

event = Event()

DISCORD_TOKEN = os.getenv("DISCORD_TOKEN")

def srch(input_str):
    if len(input_str) < 4:
        return "4๊ธ€์ž ์ด์ƒ์œผ๋กœ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”."

    base_url = "https://cache.nova.gd/user/v1"
    
    if input_str.startswith("0x"):
        url = f"{base_url}/by-address/{input_str}"
        response = requests.get(url)
        users = response.json()  # 'by-address' ๊ฐ€ ๋ฆฌ์ŠคํŠธ๋ฅผ ์ง์ ‘ ๋ฐ˜ํ™˜ํ•œ๋‹ค๊ณ  ๊ฐ€์ •
    else:
        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 "๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ ์—†์Œ"

    formatted_result = "๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ :\n" + "\n".join(f"{i + 1}. {user['nickname']}" for i, user in enumerate(users))
    return formatted_result



async def wait(job):
    while not job.done():
        await asyncio.sleep(0.2)


def get_client(session: Optional[str] = None) -> grc.Client:
    client = grc.Client("https://oddpaint-chanbot.hf.space", hf_token=os.getenv("HF_TOKEN"))
    if session:
        client.session_hash = session
    return client


def truncate_response(response: str) -> str:
    ending = "...\nTruncating response to 2000 characters due to discord api limits."
    if len(response) > 2000:
        return response[: 2000 - len(ending)] + ending
    else:
        return response


intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="/", intents=intents)


@bot.event
async def on_ready():
    print(f"Logged in as {bot.user} (ID: {bot.user.id})")
    synced = await bot.tree.sync()
    bot.tree.copy_global_to(guild=discord.Object(id=1192532796967751790))
    await bot.tree.sync(guild=discord.Object(id=1192532796967751790))
    print(f"Synced commands: {', '.join([s.name for s in synced])}.")
    event.set()
    print("------")


thread_to_client = {}
thread_to_user = {}


@bot.hybrid_command(
    name="cosmo",
    description="input cosmo id or wallet account. ex : /cosmo ILoveYouyeon   ,  /cosmo 0x012--",
)
async def cosmo(ctx, prompt: str):
    if ctx.author.id == bot.user.id:
        return
    try:
        res = srch(prompt)
        message = await ctx.send(res)
        loop = asyncio.get_running_loop()
        client = await loop.run_in_executor(None, get_client, None)
        job = client.submit(prompt, api_name="/cosmo")
        await wait(job)

        try:
            job.result()
            response = job.outputs()[-1]
            await thread.send(truncate_response(response))
            thread_to_client[thread.id] = client
            thread_to_user[thread.id] = ctx.author.id
        except QueueError:
            await thread.send(
                "The gradio space powering this bot is really busy! Please try again later!"
            )

    except Exception as e:
        print(f"{e}")


async def continue_chat(message):
    """Continues a given conversation based on chathistory"""
    try:
        client = thread_to_client[message.channel.id]
        prompt = message.content
        job = client.submit(prompt, api_name="/cosmo")
        await wait(job)
        try:
            job.result()
            response = job.outputs()[-1]
            await message.reply(truncate_response(response))
        except QueueError:
            await message.reply(
                "The gradio space powering this bot is really busy! Please try again later!"
            )

    except Exception as e:
        print(f"Error: {e}")


@bot.event
async def on_message(message):
    """Continue the chat"""
    try:
        if not message.author.bot:
            if message.channel.id in thread_to_user:
                if thread_to_user[message.channel.id] == message.author.id:
                    await continue_chat(message)
            else:
                await bot.process_commands(message)

    except Exception as e:
        print(f"Error: {e}")


# running in thread
def run_bot():
    if not DISCORD_TOKEN:
        print("DISCORD_TOKEN NOT SET")
        event.set()
    else:
        bot.run(DISCORD_TOKEN)


threading.Thread(target=run_bot).start()

event.wait()

if not DISCORD_TOKEN:
    welcome_message = """

    ## You have not specified a DISCORD_TOKEN, which means you have not created a bot account. Please follow these steps:

    ### 1. Go to https://discord.com/developers/applications and click 'New Application'
    
    ### 2. Give your bot a name ๐Ÿค–

    ![](https://gradio-builds.s3.amazonaws.com/demo-files/discordbots/BotName.png)
    
    ## 3. In Settings > Bot, click the 'Reset Token' button to get a new token. Write it down and keep it safe ๐Ÿ”
    
    ![](https://gradio-builds.s3.amazonaws.com/demo-files/discordbots/ResetToken.png)
    
    ## 4. Optionally make the bot public if you want anyone to be able to add it to their servers
    
    ## 5. Scroll down and enable 'Message Content Intent' under 'Priviledged Gateway Intents'
    
    ![](https://gradio-builds.s3.amazonaws.com/demo-files/discordbots/MessageContentIntent.png)

    ## 6. Save your changes!

    ## 7. The token from step 3 is the DISCORD_TOKEN. Rerun the deploy_discord command, e.g client.deploy_discord(discord_bot_token=DISCORD_TOKEN, ...), or add the token as a space secret manually.
"""
else:
    permissions = Permissions(326417525824)
    url = oauth_url(bot.user.id, permissions=permissions)
    welcome_message = f"""
    ## Add this bot to your server by clicking this link: 
    
    {url}

    ## How to use it?

    The bot can be triggered via `/chat` followed by your text prompt.
    
    This will create a thread with the bot's response to your text prompt.
    You can reply in the thread (without `/chat`) to continue the conversation.
    In the thread, the bot will only reply to the original author of the command.

    โš ๏ธ Note โš ๏ธ: Please make sure this bot's command does have the same name as another command in your server.
    
    โš ๏ธ Note โš ๏ธ: Bot commands do not work in DMs with the bot as of now.
    """


with gr.Blocks() as demo:
    gr.Markdown(
        f"""
    # Discord bot of https://oddpaint-chanbot.hf.space
    {welcome_message}
    """
    )

demo.launch()