CryptoScoutv1 commited on
Commit
3a72aaa
·
verified ·
1 Parent(s): ef043bc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -78
app.py CHANGED
@@ -17,19 +17,17 @@ event = Event()
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://cryptoscoutv1-discord-chatbot-cs-pmv2.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,12 +35,14 @@ def truncate_response(response: str) -> str:
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,91 +51,56 @@ async def on_ready():
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="cryptoadvisor",
68
- description="Enter a Cryptocurrency symbol or name for a investment plan. NOTE: Output takes about 2 minutes",
69
- )
70
  async def chat(ctx, prompt: str):
71
  if ctx.author.id == bot.user.id:
72
  return
73
  try:
74
- message = await ctx.send("Creating thread...")
 
75
 
76
- # User triggered bot via !echo
77
- if ctx.message.content:
78
- prompt = ctx.message.content.replace(
79
- f"{bot.command_prefix}echo", ""
80
- ).strip()
81
-
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="/predict")
86
  await wait(job)
87
 
88
  try:
89
  job.result()
90
  response = job.outputs()[-1]
91
- await thread.send(truncate_response(response))
92
- thread_to_client[thread.id] = client
93
- thread_to_user[thread.id] = ctx.author.id
94
  except QueueError:
95
- await thread.send(
96
- "The gradio space powering this bot is really busy! Please try again later!"
97
- )
98
-
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,20 +108,15 @@ def run_bot():
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
  ![](https://gradio-builds.s3.amazonaws.com/demo-files/discordbots/BotName.png)
161
 
162
  ## 3. In Settings > Bot, click the 'Reset Token' button to get a new token. Write it down and keep it safe 🔐
@@ -168,9 +128,7 @@ if not DISCORD_TOKEN:
168
  ## 5. Scroll down and enable 'Message Content Intent' under 'Priviledged Gateway Intents'
169
 
170
  ![](https://gradio-builds.s3.amazonaws.com/demo-files/discordbots/MessageContentIntent.png)
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,20 +138,15 @@ 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,9 +155,8 @@ else:
202
  with gr.Blocks() as demo:
203
  gr.Markdown(
204
  f"""
205
- # Discord bot of crewai crypto investment guidance
206
  {welcome_message}
207
  """
208
  )
209
-
210
  demo.launch()
 
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
+ ## GRADIO UI API LINK ##
25
  def get_client(session: Optional[str] = None) -> grc.Client:
26
+ client = grc.Client("https://cryptoscoutv1-discord-chatbot-cs-pmv2.hf.space/", hf_token=os.getenv("HF_TOKEN"))
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
  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
  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
+ ## /echo command to return the llm repsonse ##
63
 
64
+ @bot.hybrid_command(name="cryptoadvisor", description="Type a crypto symbol or name for a investment plan around 2 minutes for output")
 
 
 
 
 
 
 
 
 
 
65
  async def chat(ctx, prompt: str):
66
  if ctx.author.id == bot.user.id:
67
  return
68
  try:
69
+ # Acknowledge the command immediately - This is the discord message after the command / is called ##
70
+ await ctx.send(f"Processing: {prompt}")
71
 
 
 
 
 
 
 
 
72
  loop = asyncio.get_running_loop()
73
  client = await loop.run_in_executor(None, get_client, None)
74
+ job = client.submit(prompt, api_name="/predict") ## /predict can be used for gradio interface ##
75
  await wait(job)
76
 
77
  try:
78
  job.result()
79
  response = job.outputs()[-1]
80
+ await ctx.send(f"```{truncate_response(response)}```") # Send the LLM response
 
 
81
  except QueueError:
82
+ await ctx.send("The gradio space powering this bot is really busy! Please try again later!")
 
 
 
83
  except Exception as e:
84
  print(f"{e}")
85
 
86
+ @bot.hybrid_command(name="cshelp", description="Get information on how to use this bot.")
87
+ async def help_command(ctx):
88
+ help_message = """
89
+ **How to Use This Bot**
90
+ - Use `/echo your_message` to interact with the bot.
91
+ - Your message will be processed, and you will get a response.
92
+ - If you need any assistance, contact the server admins.
93
+ """
94
+ await ctx.send(help_message)
 
 
 
 
 
 
 
 
 
 
 
95
 
96
  @bot.event
97
  async def on_message(message):
98
+ if message.author.bot:
99
+ return
 
 
 
 
 
 
 
 
 
100
 
101
+ if message.content.startswith(bot.command_prefix):
102
+ await bot.process_commands(message)
103
 
 
104
  def run_bot():
105
  if not DISCORD_TOKEN:
106
  print("DISCORD_TOKEN NOT SET")
 
108
  else:
109
  bot.run(DISCORD_TOKEN)
110
 
 
111
  threading.Thread(target=run_bot).start()
112
 
113
  event.wait()
 
114
  if not DISCORD_TOKEN:
115
  welcome_message = """
 
116
  ## You have not specified a DISCORD_TOKEN, which means you have not created a bot account. Please follow these steps:
 
117
  ### 1. Go to https://discord.com/developers/applications and click 'New Application'
118
 
119
  ### 2. Give your bot a name 🤖
 
120
  ![](https://gradio-builds.s3.amazonaws.com/demo-files/discordbots/BotName.png)
121
 
122
  ## 3. In Settings > Bot, click the 'Reset Token' button to get a new token. Write it down and keep it safe 🔐
 
128
  ## 5. Scroll down and enable 'Message Content Intent' under 'Priviledged Gateway Intents'
129
 
130
  ![](https://gradio-builds.s3.amazonaws.com/demo-files/discordbots/MessageContentIntent.png)
 
131
  ## 6. Save your changes!
 
132
  ## 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.
133
  """
134
  else:
 
138
  ## Add this bot to your server by clicking this link:
139
 
140
  {url}
 
141
  ## How to use it?
 
142
  The bot can be triggered via `!echo` followed by your text prompt.
 
143
  ## Enabling slash commands
 
144
  If you are the owner of this bot, call the `!sync` command from your discord server.
145
  This will allow anyone in your server to call the bot via `/echo`.
146
  This is known as a slash command and is a nicer experience than calling the bot via `!echo`.
147
 
148
  After calling `!sync`, it may take a few minutes for `/echo` to be recognized as a valid command
149
  in your server.
 
150
  ⚠️ Note ⚠️: It is best to create a separate bot per command if you intend to use slash commands. Also make sure
151
  none of your bots have matching command names.
152
  """
 
155
  with gr.Blocks() as demo:
156
  gr.Markdown(
157
  f"""
158
+ # Discord bot of TITLE HERE
159
  {welcome_message}
160
  """
161
  )
 
162
  demo.launch()