python - 基于 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')
另外,除了上面的问题,如果有人知道如何设置一个机器人,它只在机器人本身被用户标记时才响应,请告诉我这是怎么做的!
提前致谢!
解决方案
尽管我不确定您的代码应该做什么,但我坚信您看到的无限循环不是由您的while
循环引起的,而是由您的on_message
处理程序引起的。基本上,机器人看到您的消息,发送另一条消息作为响应,看到该消息,发送另一条消息作为响应,等等。
你可以做些什么来避免这种情况
async def on_message(message):
if message.author == client.user:
return
# Also desirable
if message.author.bot:
return
# Process user message
推荐阅读
- javascript - 替换 div 内容而不是添加
- amazon-web-services - 如何使用自动扩展服务自动扩展 AWS lambda
- angular5 - 无限滚动在旧的星云站点中不起作用
- javascript - 如何在本机反应中修改json响应
- javascript - 如何在 js 对象中添加多个新属性?
- perl - 如何判断一个对象是否有特定的重载方法?
- reactjs - wepack5 的 DEV 和 PROD 的单独配置不起作用
- spring - spring-boot 依赖覆盖:依赖升级最佳实践?
- twilio - 如何从 Twilio 号码接收和发送语音邮件?
- reactjs - React:如何在回调中更改状态?