Update app.py
Browse files
app.py
CHANGED
|
@@ -17,17 +17,19 @@ event = Event()
|
|
| 17 |
|
| 18 |
DISCORD_TOKEN = os.getenv("DISCORD_TOKEN")
|
| 19 |
|
|
|
|
| 20 |
async def wait(job):
|
| 21 |
while not job.done():
|
| 22 |
await asyncio.sleep(0.2)
|
| 23 |
|
| 24 |
|
| 25 |
def get_client(session: Optional[str] = None) -> grc.Client:
|
| 26 |
-
client = grc.Client("https://
|
| 27 |
if session:
|
| 28 |
client.session_hash = session
|
| 29 |
return client
|
| 30 |
|
|
|
|
| 31 |
def truncate_response(response: str) -> str:
|
| 32 |
ending = "...\nTruncating response to 2000 characters due to discord api limits."
|
| 33 |
if len(response) > 2000:
|
|
@@ -35,14 +37,12 @@ def truncate_response(response: str) -> str:
|
|
| 35 |
else:
|
| 36 |
return response
|
| 37 |
|
|
|
|
| 38 |
intents = discord.Intents.default()
|
| 39 |
intents.message_content = True
|
| 40 |
bot = commands.Bot(command_prefix="/", intents=intents)
|
| 41 |
|
| 42 |
|
| 43 |
-
|
| 44 |
-
## BOT COMMANDS ##
|
| 45 |
-
|
| 46 |
@bot.event
|
| 47 |
async def on_ready():
|
| 48 |
print(f"Logged in as {bot.user} (ID: {bot.user.id})")
|
|
@@ -51,16 +51,22 @@ async def on_ready():
|
|
| 51 |
event.set()
|
| 52 |
print("------")
|
| 53 |
|
| 54 |
-
# Generate OAuth URL when the bot is ready
|
| 55 |
-
permissions = Permissions(326417525824)
|
| 56 |
-
url = oauth_url(bot.user.id, permissions=permissions)
|
| 57 |
-
print(f"Add this bot to your server by clicking this link: {url}")
|
| 58 |
|
| 59 |
thread_to_client = {}
|
| 60 |
thread_to_user = {}
|
| 61 |
|
| 62 |
-
|
| 63 |
-
@bot.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
async def chat(ctx, prompt: str):
|
| 65 |
if ctx.author.id == bot.user.id:
|
| 66 |
return
|
|
@@ -76,7 +82,7 @@ async def chat(ctx, prompt: str):
|
|
| 76 |
thread = await message.create_thread(name=prompt)
|
| 77 |
loop = asyncio.get_running_loop()
|
| 78 |
client = await loop.run_in_executor(None, get_client, None)
|
| 79 |
-
job = client.submit(prompt, api_name="/
|
| 80 |
await wait(job)
|
| 81 |
|
| 82 |
try:
|
|
@@ -93,24 +99,43 @@ async def chat(ctx, prompt: str):
|
|
| 93 |
except Exception as e:
|
| 94 |
print(f"{e}")
|
| 95 |
|
| 96 |
-
|
| 97 |
-
async def
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
|
| 106 |
@bot.event
|
| 107 |
async def on_message(message):
|
| 108 |
-
|
| 109 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
|
| 111 |
-
if message.content.startswith(bot.command_prefix):
|
| 112 |
-
await bot.process_commands(message)
|
| 113 |
|
|
|
|
| 114 |
def run_bot():
|
| 115 |
if not DISCORD_TOKEN:
|
| 116 |
print("DISCORD_TOKEN NOT SET")
|
|
@@ -118,16 +143,20 @@ def run_bot():
|
|
| 118 |
else:
|
| 119 |
bot.run(DISCORD_TOKEN)
|
| 120 |
|
|
|
|
| 121 |
threading.Thread(target=run_bot).start()
|
| 122 |
|
| 123 |
event.wait()
|
| 124 |
-
|
| 125 |
if not DISCORD_TOKEN:
|
| 126 |
welcome_message = """
|
|
|
|
| 127 |
## You have not specified a DISCORD_TOKEN, which means you have not created a bot account. Please follow these steps:
|
|
|
|
| 128 |
### 1. Go to https://discord.com/developers/applications and click 'New Application'
|
| 129 |
|
| 130 |
### 2. Give your bot a name 🤖
|
|
|
|
| 131 |

|
| 132 |
|
| 133 |
## 3. In Settings > Bot, click the 'Reset Token' button to get a new token. Write it down and keep it safe 🔐
|
|
@@ -139,7 +168,9 @@ if not DISCORD_TOKEN:
|
|
| 139 |
## 5. Scroll down and enable 'Message Content Intent' under 'Priviledged Gateway Intents'
|
| 140 |
|
| 141 |

|
|
|
|
| 142 |
## 6. Save your changes!
|
|
|
|
| 143 |
## 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.
|
| 144 |
"""
|
| 145 |
else:
|
|
@@ -149,15 +180,20 @@ else:
|
|
| 149 |
## Add this bot to your server by clicking this link:
|
| 150 |
|
| 151 |
{url}
|
|
|
|
| 152 |
## How to use it?
|
|
|
|
| 153 |
The bot can be triggered via `!echo` followed by your text prompt.
|
|
|
|
| 154 |
## Enabling slash commands
|
|
|
|
| 155 |
If you are the owner of this bot, call the `!sync` command from your discord server.
|
| 156 |
This will allow anyone in your server to call the bot via `/echo`.
|
| 157 |
This is known as a slash command and is a nicer experience than calling the bot via `!echo`.
|
| 158 |
|
| 159 |
After calling `!sync`, it may take a few minutes for `/echo` to be recognized as a valid command
|
| 160 |
in your server.
|
|
|
|
| 161 |
⚠️ Note ⚠️: It is best to create a separate bot per command if you intend to use slash commands. Also make sure
|
| 162 |
none of your bots have matching command names.
|
| 163 |
"""
|
|
@@ -166,8 +202,9 @@ else:
|
|
| 166 |
with gr.Blocks() as demo:
|
| 167 |
gr.Markdown(
|
| 168 |
f"""
|
| 169 |
-
# Discord bot of
|
| 170 |
{welcome_message}
|
| 171 |
"""
|
| 172 |
)
|
| 173 |
-
|
|
|
|
|
|
| 17 |
|
| 18 |
DISCORD_TOKEN = os.getenv("DISCORD_TOKEN")
|
| 19 |
|
| 20 |
+
|
| 21 |
async def wait(job):
|
| 22 |
while not job.done():
|
| 23 |
await asyncio.sleep(0.2)
|
| 24 |
|
| 25 |
|
| 26 |
def get_client(session: Optional[str] = None) -> grc.Client:
|
| 27 |
+
client = grc.Client("https://freddyaboulton-echo-chatbot.hf.space", hf_token=os.getenv("HF_TOKEN"))
|
| 28 |
if session:
|
| 29 |
client.session_hash = session
|
| 30 |
return client
|
| 31 |
|
| 32 |
+
|
| 33 |
def truncate_response(response: str) -> str:
|
| 34 |
ending = "...\nTruncating response to 2000 characters due to discord api limits."
|
| 35 |
if len(response) > 2000:
|
|
|
|
| 37 |
else:
|
| 38 |
return response
|
| 39 |
|
| 40 |
+
|
| 41 |
intents = discord.Intents.default()
|
| 42 |
intents.message_content = True
|
| 43 |
bot = commands.Bot(command_prefix="/", intents=intents)
|
| 44 |
|
| 45 |
|
|
|
|
|
|
|
|
|
|
| 46 |
@bot.event
|
| 47 |
async def on_ready():
|
| 48 |
print(f"Logged in as {bot.user} (ID: {bot.user.id})")
|
|
|
|
| 51 |
event.set()
|
| 52 |
print("------")
|
| 53 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
thread_to_client = {}
|
| 56 |
thread_to_user = {}
|
| 57 |
|
| 58 |
+
|
| 59 |
+
# @bot.command()
|
| 60 |
+
# @commands.is_owner()
|
| 61 |
+
# async def sync(ctx) -> None:
|
| 62 |
+
# synced = await bot.tree.sync()
|
| 63 |
+
# await ctx.send(f"Synced commands: {', '.join([s.name for s in synced])}.")
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
@bot.hybrid_command(
|
| 67 |
+
name="echo",
|
| 68 |
+
description="Enter some text to chat with the bot! Like this: /echo Hello, how are you?",
|
| 69 |
+
)
|
| 70 |
async def chat(ctx, prompt: str):
|
| 71 |
if ctx.author.id == bot.user.id:
|
| 72 |
return
|
|
|
|
| 82 |
thread = await message.create_thread(name=prompt)
|
| 83 |
loop = asyncio.get_running_loop()
|
| 84 |
client = await loop.run_in_executor(None, get_client, None)
|
| 85 |
+
job = client.submit(prompt, api_name="/chat")
|
| 86 |
await wait(job)
|
| 87 |
|
| 88 |
try:
|
|
|
|
| 99 |
except Exception as e:
|
| 100 |
print(f"{e}")
|
| 101 |
|
| 102 |
+
|
| 103 |
+
async def continue_chat(message):
|
| 104 |
+
"""Continues a given conversation based on chathistory"""
|
| 105 |
+
try:
|
| 106 |
+
client = thread_to_client[message.channel.id]
|
| 107 |
+
prompt = message.content
|
| 108 |
+
job = client.submit(prompt, api_name="/chat")
|
| 109 |
+
await wait(job)
|
| 110 |
+
try:
|
| 111 |
+
job.result()
|
| 112 |
+
response = job.outputs()[-1]
|
| 113 |
+
await message.reply(truncate_response(response))
|
| 114 |
+
except QueueError:
|
| 115 |
+
await message.reply(
|
| 116 |
+
"The gradio space powering this bot is really busy! Please try again later!"
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
except Exception as e:
|
| 120 |
+
print(f"Error: {e}")
|
| 121 |
+
|
| 122 |
|
| 123 |
@bot.event
|
| 124 |
async def on_message(message):
|
| 125 |
+
"""Continue the chat"""
|
| 126 |
+
try:
|
| 127 |
+
if not message.author.bot:
|
| 128 |
+
if message.channel.id in thread_to_user:
|
| 129 |
+
if thread_to_user[message.channel.id] == message.author.id:
|
| 130 |
+
await continue_chat(message)
|
| 131 |
+
else:
|
| 132 |
+
await bot.process_commands(message)
|
| 133 |
+
|
| 134 |
+
except Exception as e:
|
| 135 |
+
print(f"Error: {e}")
|
| 136 |
|
|
|
|
|
|
|
| 137 |
|
| 138 |
+
# running in thread
|
| 139 |
def run_bot():
|
| 140 |
if not DISCORD_TOKEN:
|
| 141 |
print("DISCORD_TOKEN NOT SET")
|
|
|
|
| 143 |
else:
|
| 144 |
bot.run(DISCORD_TOKEN)
|
| 145 |
|
| 146 |
+
|
| 147 |
threading.Thread(target=run_bot).start()
|
| 148 |
|
| 149 |
event.wait()
|
| 150 |
+
|
| 151 |
if not DISCORD_TOKEN:
|
| 152 |
welcome_message = """
|
| 153 |
+
|
| 154 |
## You have not specified a DISCORD_TOKEN, which means you have not created a bot account. Please follow these steps:
|
| 155 |
+
|
| 156 |
### 1. Go to https://discord.com/developers/applications and click 'New Application'
|
| 157 |
|
| 158 |
### 2. Give your bot a name 🤖
|
| 159 |
+
|
| 160 |

|
| 161 |
|
| 162 |
## 3. In Settings > Bot, click the 'Reset Token' button to get a new token. Write it down and keep it safe 🔐
|
|
|
|
| 168 |
## 5. Scroll down and enable 'Message Content Intent' under 'Priviledged Gateway Intents'
|
| 169 |
|
| 170 |

|
| 171 |
+
|
| 172 |
## 6. Save your changes!
|
| 173 |
+
|
| 174 |
## 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.
|
| 175 |
"""
|
| 176 |
else:
|
|
|
|
| 180 |
## Add this bot to your server by clicking this link:
|
| 181 |
|
| 182 |
{url}
|
| 183 |
+
|
| 184 |
## How to use it?
|
| 185 |
+
|
| 186 |
The bot can be triggered via `!echo` followed by your text prompt.
|
| 187 |
+
|
| 188 |
## Enabling slash commands
|
| 189 |
+
|
| 190 |
If you are the owner of this bot, call the `!sync` command from your discord server.
|
| 191 |
This will allow anyone in your server to call the bot via `/echo`.
|
| 192 |
This is known as a slash command and is a nicer experience than calling the bot via `!echo`.
|
| 193 |
|
| 194 |
After calling `!sync`, it may take a few minutes for `/echo` to be recognized as a valid command
|
| 195 |
in your server.
|
| 196 |
+
|
| 197 |
⚠️ Note ⚠️: It is best to create a separate bot per command if you intend to use slash commands. Also make sure
|
| 198 |
none of your bots have matching command names.
|
| 199 |
"""
|
|
|
|
| 202 |
with gr.Blocks() as demo:
|
| 203 |
gr.Markdown(
|
| 204 |
f"""
|
| 205 |
+
# Discord bot of https://freddyaboulton-echo-chatbot.hf.space
|
| 206 |
{welcome_message}
|
| 207 |
"""
|
| 208 |
)
|
| 209 |
+
|
| 210 |
+
demo.launch()
|