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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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 logging
  17. import discord
  18. import requests
  19. import base64
  20. import asyncio
  21. URL = '{YOUR_IP_ADDRESS:PORT}/v1/api/completion_aibotk' # Default: https://demo.ragflow.io/v1/api/completion_aibotk
  22. JSON_DATA = {
  23. "conversation_id": "xxxxxxxxxxxxxxxxxxxxxxxxxxx", # Get conversation id from /api/new_conversation
  24. "Authorization": "ragflow-xxxxxxxxxxxxxxxxxxxxxxxxxxxxx", # RAGFlow Assistant Chat Bot API Key
  25. "word": "" # User question, don't need to initialize
  26. }
  27. DISCORD_BOT_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxx" #Get DISCORD_BOT_KEY from Discord Application
  28. intents = discord.Intents.default()
  29. intents.message_content = True
  30. client = discord.Client(intents=intents)
  31. @client.event
  32. async def on_ready():
  33. logging.info(f'We have logged in as {client.user}')
  34. @client.event
  35. async def on_message(message):
  36. if message.author == client.user:
  37. return
  38. if client.user.mentioned_in(message):
  39. if len(message.content.split('> ')) == 1:
  40. await message.channel.send("Hi~ How can I help you? ")
  41. else:
  42. JSON_DATA['word']=message.content.split('> ')[1]
  43. response = requests.post(URL, json=JSON_DATA)
  44. response_data = response.json().get('data', [])
  45. image_bool = False
  46. for i in response_data:
  47. if i['type'] == 1:
  48. res = i['content']
  49. if i['type'] == 3:
  50. image_bool = True
  51. image_data = base64.b64decode(i['url'])
  52. with open('tmp_image.png','wb') as file:
  53. file.write(image_data)
  54. image= discord.File('tmp_image.png')
  55. await message.channel.send(f"{message.author.mention}{res}")
  56. if image_bool:
  57. await message.channel.send(file=image)
  58. loop = asyncio.get_event_loop()
  59. try:
  60. loop.run_until_complete(client.start(DISCORD_BOT_KEY))
  61. except KeyboardInterrupt:
  62. loop.run_until_complete(client.close())
  63. finally:
  64. loop.close()