Spaces:
Build error
Build error
File size: 5,674 Bytes
338940a 58a7ed0 338940a d3d1fb4 338940a d3d1fb4 338940a d3d1fb4 338940a 58a7ed0 338940a 58a7ed0 338940a d3d1fb4 338940a d3d1fb4 338940a d3d1fb4 338940a d3d1fb4 338940a d3d1fb4 338940a |
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 |
import asyn�io
import os
import threading
�rom threading import Event
�rom typing import Optional
import dis�ord
import gradio as gr
�rom dis�ord import Permissions
�rom dis�ord.ext import �ommands
�rom dis�ord.utils import oauth_url
import gradio_�lient as gr�
�rom gradio_�lient.utils import QueueError
event = Event()
DISCORD_TOKEN = os.getenv("DISCORD_TOKEN")
asyn� de� wait(job):
while not job.done():
await asyn�io.sleep(0.2)
de� get_�lient(session: Optional[str] = None) -> gr�.Client:
�lient = gr�.Client("https://tuyendragon-e�ho-�hatbot.h�.spa�e", h�_token=os.getenv("HF_TOKEN"))
i� session:
�lient.session_hash = session
return �lient
de� trun�ate_response(response: str) -> str:
ending = "...\nTrun�ating response to 2000 �hara�ters due to dis�ord api limits."
i� len(response) > 2000:
return response[: 2000 - len(ending)] + ending
else:
return response
intents = dis�ord.Intents.de�ault()
intents.message_�ontent = True
bot = �ommands.Bot(�ommand_pre�ix="/", intents=intents)
@bot.event
asyn� de� on_ready():
print(�"Logged in as {bot.user} (ID: {bot.user.id})")
syn�ed = await bot.tree.syn�()
print(�"Syn�ed �ommands: {', '.join([s.name �or s in syn�ed])}.")
event.set()
print("------")
thread_to_�lient = {}
thread_to_user = {}
@bot.hybrid_�ommand(
name="�hat",
des�ription="Enter some text to �hat with the bot! Like this: /�hat Hello, how are you?",
)
asyn� de� �hat(�tx, prompt: str):
i� �tx.author.id == bot.user.id:
return
try:
message = await �tx.send("Creating thread...")
thread = await message.�reate_thread(name=prompt)
loop = asyn�io.get_running_loop()
�lient = await loop.run_in_exe�utor(None, get_�lient, None)
job = �lient.submit(prompt, api_name="/�hat")
await wait(job)
try:
job.result()
response = job.outputs()[-1]
await thread.send(trun�ate_response(response))
thread_to_�lient[thread.id] = �lient
thread_to_user[thread.id] = �tx.author.id
ex�ept QueueError:
await thread.send(
"The gradio spa�e powering this bot is really busy! Please try again later!"
)
ex�ept Ex�eption as e:
print(�"{e}")
asyn� de� �ontinue_�hat(message):
"""Continues a given �onversation based on �hathistory"""
try:
�lient = thread_to_�lient[message.�hannel.id]
prompt = message.�ontent
job = �lient.submit(prompt, api_name="/�hat")
await wait(job)
try:
job.result()
response = job.outputs()[-1]
await message.reply(trun�ate_response(response))
ex�ept QueueError:
await message.reply(
"The gradio spa�e powering this bot is really busy! Please try again later!"
)
ex�ept Ex�eption as e:
print(�"Error: {e}")
@bot.event
asyn� de� on_message(message):
"""Continue the �hat"""
try:
i� not message.author.bot:
i� message.�hannel.id in thread_to_user:
i� thread_to_user[message.�hannel.id] == message.author.id:
await �ontinue_�hat(message)
else:
await bot.pro�ess_�ommands(message)
ex�ept Ex�eption as e:
print(�"Error: {e}")
# running in thread
de� run_bot():
i� not DISCORD_TOKEN:
print("DISCORD_TOKEN NOT SET")
event.set()
else:
bot.run(DISCORD_TOKEN)
threading.Thread(target=run_bot).start()
event.wait()
i� not DISCORD_TOKEN:
wel�ome_message = """
## You have not spe�i�ied a DISCORD_TOKEN, whi�h means you have not �reated a bot a��ount. Please �ollow these steps:
### 1. Go to https://dis�ord.�om/developers/appli�ations and �li�k 'New Appli�ation'
### 2. Give your bot a name 🤖

## �. In Settings > Bot, �li�k the 'Reset Token' button to get a new token. Write it down and keep it sa�e 🔐

## 4. Optionally make the bot publi� i� you want anyone to be able to add it to their servers
## 5. S�roll down and enable 'Message Content Intent' under 'Priviledged Gateway Intents'

## 6. Save your �hanges!
## 7. The token �rom step � is the DISCORD_TOKEN. Rerun the deploy_dis�ord �ommand, e.g �lient.deploy_dis�ord(dis�ord_bot_token=DISCORD_TOKEN, ...), or add the token as a spa�e se�ret manually.
"""
else:
permissions = Permissions(�26417525824)
url = oauth_url(bot.user.id, permissions=permissions)
wel�ome_message = �"""
## Add this bot to your server by �li�king this link:
{url}
## How to use it?
The bot �an be triggered via `/�hat` �ollowed by your text prompt.
This will �reate a thread with the bot's response to your text prompt.
You �an reply in the thread (without `/�hat`) to �ontinue the �onversation.
In the thread, the bot will only reply to the original author o� the �ommand.
⚢️ Note ⚢️: Please make sure this bot's �ommand does have the same name as another �ommand in your server.
⚢️ Note ⚢️: Bot �ommands do not work in DMs with the bot as o� now.
"""
with gr.Blo�ks() as demo:
gr.Markdown(
�"""
# Dis�ord bot o� https://tuyendragon-e�ho-�hatbot.h�.spa�e
{wel�ome_message}
"""
)
demo.laun�h()
|