discord_svr.py


Overview

discord_svr.py is a Python script designed to create a Discord bot that integrates with the RAGFlow Assistant Chat Bot API. The bot listens for messages in Discord channels where it is mentioned, forwards user queries to the RAGFlow API, and returns the bot’s response back to the Discord channel. It can handle both text responses and images encoded in base64 format, which it decodes and sends as attachments to the Discord channel.

This file primarily serves as a bridge between Discord users and an AI-powered chat service, enabling interactive conversations within Discord servers using external AI completion services.


Detailed Explanation

Constants and Configuration


Imports


Discord Client Setup

intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)

Event Handlers

on_ready()

@client.event
async def on_ready():
    logging.info(f'We have logged in as {client.user}')

on_message(message)

@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if client.user.mentioned_in(message):

        if len(message.content.split('> ')) == 1:
            await message.channel.send("Hi~ How can I help you? ")
        else:
            JSON_DATA['word']=message.content.split('> ')[1]
            response = requests.post(URL, json=JSON_DATA)
            response_data = response.json().get('data', [])
            image_bool = False

            for i in response_data:
                if i['type'] == 1:
                    res = i['content']
                if i['type'] == 3:
                    image_bool = True
                    image_data = base64.b64decode(i['url'])
                    with open('tmp_image.png','wb') as file:
                        file.write(image_data)
                    image= discord.File('tmp_image.png')

            await message.channel.send(f"{message.author.mention}{res}")

            if image_bool:
                await message.channel.send(file=image)

Main Execution Loop

loop = asyncio.get_event_loop()

try:
    loop.run_until_complete(client.start(DISCORD_BOT_KEY))
except KeyboardInterrupt:
    loop.run_until_complete(client.close())
finally:
    loop.close()

Usage Example

  1. Set the constants URL, JSON_DATA['conversation_id'], JSON_DATA['Authorization'], and DISCORD_BOT_KEY with valid values.

  2. Run the script:

    python discord_svr.py
    
  3. In a Discord server where the bot is added, mention the bot with a query:

    @BotName> What is the weather today?
    
  4. The bot will respond with the answer from the RAGFlow API, optionally sending an image if included.


Important Implementation Details and Algorithms


Interaction with Other System Components


Mermaid Class Diagram

classDiagram
    class DiscordClient {
        +intents: discord.Intents
        +client: discord.Client
        +on_ready()
        +on_message(message)
    }
    
    class RAGFlowAPI {
        +URL: str
        +JSON_DATA: dict
        +post_query(word: str) dict
    }
    
    DiscordClient --> RAGFlowAPI : uses

Note:


Summary

discord_svr.py is a focused integration script that connects Discord users with an AI chatbot via the RAGFlow API. It listens for mentions, sends queries, and returns responses including images, enabling natural language interaction inside Discord. The architecture is straightforward, leveraging Discord.py and synchronous HTTP calls, with potential for enhancements in concurrency and error handling.