我正在为不和谐应用开发一个简单的机器人。我正在使用 flask 和discord.py library。事情是,一旦机器人登录,它会在20-30秒后自动退出。我的代码如下:
@app.route('/login', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
emaild = str(request.form['email'])
passwordd = str(request.form['password'])
key = str(request.form['osu_key'])
hchid = str(request.form['help_id'])
print(emaild + passwordd)
app_thread = threading.Thread(target=bot_run, args=(emaild, passwordd))
print('hello')
app_thread.setDaemon(True)
app_thread.start()
print('bye')
session['logged_in'] = True
flash('You are logged in')
return redirect(url_for('welcome_screen'))
return render_template('login.html', error=error)
def bot_run(email, password):
bot.run(email, password)
print('thread died :<')
问题是,它登录并执行其2个功能(未在上面的代码中显示)。但过了一段时间后它退出了。所以我想到使用无限循环来保持线程活着: -
def bot_run(email, password):
command = None
while command != 'terminate':
bot.run(email, password)
print('thread died :<')
但如果我这样做,那么我会收到以下错误:
追踪(最近一次通话): 文件“C:\ Users \ dell \ AppData \ Local \ Programs \ Python \ Python35-32 \ lib \ threading.py”,第914行,在_bootstrap_inner中 self.run()
文件“C:\ Users \ dell \ AppData \ Local \ Programs \ Python \ Python35-32 \ lib \ threading.py”,第862行,运行中 self._target(* self._args,** self._kwargs)
文件“E:/ PyCharm Projects / lapzbot - heroku / run.py”,第48行,在bot_run中 bot.run(电子邮件,密码)
文件“C:\ Users \ dell \ AppData \ Local \ Programs \ Python \ Python35-32 \ lib \ site-packages \ discord \ client.py”,第579行,在运行中 self.loop.run_until_complete(self.start(email,password))
文件“C:\ Users \ dell \ AppData \ Local \ Programs \ Python \ Python35-32 \ lib \ asyncio \ base_events.py”,第314行,在run_until_complete中 self._check_closed()
_check_closed中的文件“C:\ Users \ dell \ AppData \ Local \ Programs \ Python \ Python35-32 \ lib \ asyncio \ base_events.py”,第284行 引发RuntimeError('事件循环已关闭')
RuntimeError:事件循环已关闭
TLDR:有人可以告诉我如何让线程持续运行吗?