如何让我的聊天机器人记住不和谐中的自定义响应,然后将其放入intents.json python

问题描述 投票:0回答:1

你好,我试图让我的不和谐机器人记住我关闭它后学到的东西,但每次我再次启动它来测试它时,都会忘记它学到的所有东西 这是代码

import discord
from discord.ext import commands
import json
import asyncio
import random

# Load intents from intents.json
with open('intents.json', 'r') as intents_file:
    intents_data = json.load(intents_file)
    intents = intents_data.get('intents', [])

# Load custom responses from custom_responses.json
try:
    with open('custom_responses.json', 'r') as custom_responses_file:
        custom_responses = json.load(custom_responses_file)
except FileNotFoundError:
    custom_responses = {}  # Initialize an empty dictionary if the file doesn't exist

# Initialize the bot
bot = commands.Bot(command_prefix='!', intents=discord.Intents.all())


@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name} ({bot.user.id})')


@bot.event
async def on_message(message):
    if message.author.bot:
        return  # Ignore messages from other bots

    # Check for custom responses first
    if message.content.lower() in custom_responses:
        await message.channel.send(custom_responses[message.content.lower()])
    else:
        # If no custom response, check predefined intents
        for intent in intents:
            if any(pattern.lower() in message.content.lower() for pattern in intent['patterns']):
                response = random.choice(intent['responses'])
            `your text`    await message.channel.send(response)
                break
        else:
            await message.channel.send("I'm not sure how to respond. Could you provide a custom response?")

    await bot.process_commands(message)


@bot.command()
async def learn(ctx, *, response: str):
    """
    Command to add a custom response.
    Usage: !learn <user_input> <custom_response>
    Example: !learn favorite_color Blue
    """
    user_input, custom_response = response.split(maxsplit=1)
    custom_responses[user_input.lower()] = custom_response
    await ctx.send(f"Learned: '{user_input}' -> '{custom_response}'")


@bot.event
async def on_disconnect():
    # Save custom responses to custom_responses.json when the bot disconnects
    with open('custom_responses.json', 'w') as custom_responses_file:
        json.dump(custom_responses, custom_responses_file, indent=4)


print("Bot is starting...")
loop = asyncio.get_event_loop()
loop.run_until_complete(bot.start('TOKEN'))

然后你就得到了custom_responses.json

{ "user_input_1": "custom_response_1", “user_input_2”:“custom_response_2” }

然后是intents.json

{ “意图”:[

    {
        "tag": "google",
        "patterns": [
            "google",
            "search",
            "internet"
        ],
        "responses": [
            "https://www.youtube.com/watch?v=dQw4w9WgXcQ&pp=ygUXbmV2ZXIgZ29ubmEgZ2l2ZSB5b3UgdXA%3D"
        ]
    },
    {
        "tag": "greeting",
        "patterns": [
            "Hi there",
            "How are you",
            "Is anyone there?",
            "Hey",
            "Hola",
            "Hello",
            "Good day",
            "Namaste",
            "yo"
        ],
        "responses": [
            "Hello",
            "Good to see you again",
            "Hi there, how can I help?"
        ],
        "context": [
            ""
        ]
    }

等等

任何帮助都会对我有帮助,也谢谢您的时间

我希望它记住你告诉它的内容,就像你说的那样!学习猫猫很好,下次你启动它时,你说猫,我希望它说猫很好

python discord.py artificial-intelligence
1个回答
0
投票

我只是添加了一个关闭命令,我希望这对那里的人有帮助

@bot.event
async def on_message(message):
    if message.author.bot:
        return  # Ignore messages from other bots

    # Check for custom responses first
    if message.content.lower() in custom_responses:
        await message.channel.send(custom_responses[message.content.lower()])
    elif message.content.lower() == "quitquit":
        await message.channel.send("Goodnight! Shutting down...")
        await bot.close()  # Shut down the bot
    else:
        # If no custom response, check predefined intents
        for intent in intents:
            if any(pattern.lower() in message.content.lower() for pattern in intent['patterns']):
                response = random.choice(intent['responses'])
                await message.channel.send(response)
                break
        else:
            await message.channel.send("I'm not sure how to respond. Could you provide a custom response?")

    await bot.process_commands(message)
© www.soinside.com 2019 - 2024. All rights reserved.