开发Discord AI聊天机器人时出现Session关闭类RuntimeError
Discord AI机器人RuntimeError报错说明与解决方法
问题背景
- 开发Discord AI聊天机器人,此前程序运行正常,再次启动即触发RuntimeError报错,无法定位报错含义
- 终端直接运行(不接入Discord交互逻辑)时所有功能正常,适配Discord交互格式后报错,怀疑问题出在Discord代码段
- 此前使用discord.py实现的同类版本可正常运行,当前版本无法工作
问题代码
nltk.download('punkt') from nltk import word_tokenize,sent_tokenize from nltk.stem.lancaster import LancasterStemmer stemmer = LancasterStemmer() import numpy as np import tflearn import tensorflow as tf import random import json import pickle import discord TOKEN = 'TOKEN' with open("intents.json") as file: data = json.load(file) try: with open("data.pickle","rb") as f: words, labels, training, output = pickle.load(f) except: words = [] labels = [] docs_x = [] docs_y = [] for intent in data["intents"]: for pattern in intent["patterns"]: wrds = nltk.word_tokenize(pattern) words.extend(wrds) docs_x.append(wrds) docs_y.append(intent["tag"]) if intent["tag"] not in labels: labels.append(intent["tag"]) words = [stemmer.stem(w.lower()) for w in words if w != "?"] words = sorted(list(set(words))) labels = sorted(labels) training = [] output = [] out_empty = [0 for _ in range(len(labels))] for x, doc in enumerate(docs_x): bag = [] wrds = [stemmer.stem(w.lower()) for w in doc] for w in words: if w in wrds: bag.append(1) else: bag.append(0) output_row = out_empty[:] output_row[labels.index(docs_y[x])] = 1 training.append(bag) output.append(output_row) training = np.array(training) output = np.array(output) with open("data.pickle","wb") as f: pickle.dump((words, labels, training, output), f) net = tflearn.input_data(shape=[None, len(training[0])]) net = tflearn.fully_connected(net, 8) net = tflearn.fully_connected(net, 8) net = tflearn.fully_connected(net, len(output[0]), activation="softmax") net = tflearn.regression(net) model = tflearn.DNN(net) try: model.load("model.tflearn") except: model.fit(training, output, n_epoch=1000, batch_size=8, show_metric=True) model.save("model.tflearn") def bag_of_words(s, words): bag = [0 for _ in range(len(words))] s_words = nltk.word_tokenize(s) s_words = [stemmer.stem(word.lower()) for word in s_words] for se in s_words: for i, w in enumerate(words): if w == se: bag[i] = 1 return np.array(bag) class MyClient(discord.Client): async def on_ready(self): print('Logged in as') print(self.user.name) print(self.user.id) print('Bot is Online') async def on_message(self, message): if message.author.id == self.user.id: return else: inp = message.content result = model.predict([bag_of_words(inp, words)])[0] result_index = np.argmax(result) tag = labels[result_index] for tg in data["intents"]: if tg['tag'] == tag: responses = tg['responses'] bot_response=random.choice(responses) await message.channel.send(bot_response.format(message)) client = MyClient() client.run(TOKEN)
完整报错栈
Traceback (most recent call last): File "c:/Users/mwkje_h8e091g/OneDrive/Documents/VSCODEPROD/DiscordAI ver.last/main.py", line 86, in <module> model.fit(training, output, n_epoch=1000, batch_size=8, show_metric=True) File "C:\Users\mwkje_h8e091g\AppData\Local\Programs\Python\Python37\lib\site-packages\tflearn\models\dnn.py", line 206, in fit callbacks=callbacks) File "C:\Users\mwkje_h8e091g\AppData\Local\Programs\Python\Python37\lib\site-packages\tflearn\helpers\trainer.py", line 344, in fit show_metric) File "C:\Users\mwkje_h8e091g\AppData\Local\Programs\Python\Python37\lib\site-packages\tflearn\helpers\trainer.py", line 826, in _train tflearn.is_training(True, session=self.session) File "C:\Users\mwkje_h8e091g\AppData\Local\Programs\Python\Python37\lib\site-packages\tflearn\config.py", line 95, in is_training tf.get_collection('is_training_ops')[0].eval(session=session) File "C:\Users\mwkje_h8e091g\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\framework\ops.py", line 913, in eval return _eval_using_default_session(self, feed_dict, self.graph, session) File "C:\Users\mwkje_h8e091g\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\framework\ops.py", line 5512, in _eval_using_default_session return session.run(tensors, feed_dict) File "C:\Users\mwkje_h8e091g\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\client\session.py", line 958, in run run_metadata_ptr) File "C:\Users\mwkje_h8e091g\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\client\session.py", line 1104, in _run raise RuntimeError('Attempted to use a closed Session.') RuntimeError: Attempted to use a closed Session.
报错含义
RuntimeError: Attempted to use a closed Session 表示程序尝试调用已经被销毁关闭的TensorFlow计算会话。
问题原因
- 代码在最顶部直接导入
discord库,tflearn基于TensorFlow 1.x的全局会话机制会被discord.py的导入逻辑干扰,导致会话被意外回收关闭 - 未显式禁用TensorFlow 2.x的eager执行模式,与tflearn默认的图执行模式冲突
- 本地缓存的
model.tflearn或data.pickle文件损坏,导致model.load()失败后触发会话关闭,后续进入model.fit()分支时就会报错 - 代码中
on_message函数的缩进逻辑错误,也会在运行时触发额外异常
解决方法
- 调整导入顺序:将
import discord语句移动到所有tflearn、tensorflow相关的训练、加载逻辑之后,完成AI模型初始化后再导入discord库 - 导入tensorflow后立刻添加禁用eager执行的语句:
import tensorflow as tf tf.compat.v1.disable_eager_execution()
- 手动删除本地已有的
model.tflearn、data.pickle文件,重新运行程序生成缓存 - 修正
on_message函数的缩进逻辑,把遍历intents匹配responses的循环移入else分支内,避免逻辑错误
内容的提问来源于stack exchange,提问作者Hoot Loot
相关产品推荐
相关产品推荐

