You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

discord_svr.py 2.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #
  2. # Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import discord
  17. import requests
  18. import base64
  19. import asyncio
  20. URL = '{YOUR_IP_ADDRESS:PORT}/v1/api/completion_aibotk' # Default: https://demo.ragflow.io/v1/api/completion_aibotk
  21. JSON_DATA = {
  22. "conversation_id": "xxxxxxxxxxxxxxxxxxxxxxxxxxx", # Get conversation id from /api/new_conversation
  23. "Authorization": "ragflow-xxxxxxxxxxxxxxxxxxxxxxxxxxxxx", # RAGFlow Assistant Chat Bot API Key
  24. "word": "" # User question, don't need to initialize
  25. }
  26. DISCORD_BOT_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxx" #Get DISCORD_BOT_KEY from Discord Application
  27. intents = discord.Intents.default()
  28. intents.message_content = True
  29. client = discord.Client(intents=intents)
  30. @client.event
  31. async def on_ready():
  32. print(f'We have logged in as {client.user}')
  33. @client.event
  34. async def on_message(message):
  35. if message.author == client.user:
  36. return
  37. if client.user.mentioned_in(message):
  38. if len(message.content.split('> ')) == 1:
  39. await message.channel.send("Hi~ How can I help you? ")
  40. else:
  41. JSON_DATA['word']=message.content.split('> ')[1]
  42. response = requests.post(URL, json=JSON_DATA)
  43. response_data = response.json().get('data', [])
  44. image_bool = False
  45. for i in response_data:
  46. if i['type'] == 1:
  47. res = i['content']
  48. if i['type'] == 3:
  49. image_bool = True
  50. image_data = base64.b64decode(i['url'])
  51. with open('tmp_image.png','wb') as file:
  52. file.write(image_data)
  53. image= discord.File('tmp_image.png')
  54. await message.channel.send(f"{message.author.mention}{res}")
  55. if image_bool:
  56. await message.channel.send(file=image)
  57. loop = asyncio.get_event_loop()
  58. try:
  59. loop.run_until_complete(client.start(DISCORD_BOT_KEY))
  60. except KeyboardInterrupt:
  61. loop.run_until_complete(client.close())
  62. finally:
  63. loop.close()