首页 > 解决方案 > 基于 Python 的不和谐机器人回复错误(无限循环)

问题描述

我已经学习 java 几个月了,对 python 还是很陌生。我目前正在为不和谐构建一个简单的深度学习 AI 机器人,它从用户那里获取消息,然后从预先建立的数据库中回复消息。我已经成功地完成了 AI,但我目前在设置不和谐代码时遇到了一些问题。

下面是我的最终代码块,负责接收来自不和谐的消息并以不和谐的方式回复用户。

当前错误:我的代码在不和谐聊天中发送第一条消息后不会停止执行,导致机器人不停地重复发送消息。这很可能是由while函数内的循环引起的。

我尝试的解决方案: python 新手,我不确定如何像在 java 中那样创建布尔类型类变量。我试图使用布尔变量new_message作为 while 循环的条件语句。一旦发送了机器人的回复,此变量设置为 false,以确保程序不会扫描机器人自己的回复并导致无限循环。该解决方案似乎不起作用,因为我似乎无法找到new_message在函数之外创建变量的方法。

注意:我不能简单地删除 while 循环,因为一旦用户输入“退出”,我需要程序终止。

@client.event
async def on_message(message):
     bot_testing = client.get_channel(0000000000)
     user_input = message.content
     new_message = True

  while new_message:
    if user_input.lower() == "quit": # type quit to stop the program
        print("Program Terminated")
        break

    results = model.predict([bag_of_words(user_input, words)])[0]
    results_index = numpy.argmax(results) # returns the greatest value's index
    tag = labels[results_index]

    print(results)
    print(tag)

    if results[results_index] > 0.9: # accuracy threshold for a database reply
        for tg in data["replyData"]:
            if tg['tag'] == tag:
                responses = tg['responses']

        await bot_testing.send(random.choice(responses))
        new_message = False
    else:
        await bot_testing.send("I'm not sure I understand. Please try again or ask a different question!")
        new_message = False

client.run('some-bot-code')

另外,除了上面的问题,如果有人知道如何设置一个机器人,它只在机器人本身被用户标记时才响应,请告诉我这是怎么做的!

提前致谢!

标签: pythondeep-learningdiscord

解决方案


尽管我不确定您的代码应该做什么,但我坚信您看到的无限循环不是由您的while循环引起的,而是由您的on_message处理程序引起的。基本上,机器人看到您的消息,发送另一条消息作为响应,看到该消息,发送另一条消息作为响应,等等。

你可以做些什么来避免这种情况

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

    # Also desirable
    if message.author.bot:
        return

    # Process user message

推荐阅读