使用 flask 和 discord bot 循环导入
Circular import using flask and discord bot
我有这两个文件:
main.py
import os
import discord
from keep_alive import keep_alive
client = discord.Client()
my_secret = os.environ['Token']
async def SendMeMessage():
user = await client.fetch_user('my id')
await user.create_dm()
await user.dm_channel.send("Someone needs help")
keep_alive()
client.run(my_secret)
keep_alive.py
from flask import Flask
from threading import Thread
#from main import SendMeMessage
app = Flask('')
@app.route('/')
def home():
#SendMeMessage()
return "Hello. I am alive!"
def run():
app.run(host='0.0.0.0', port=8080)
def keep_alive():
t = Thread(target=run)
t.start()
我想导入 SendMessage。因此,当有人在 Flask 服务器上发送获取请求时,我想从我的 discord 机器人接收消息。当我实施注释代码时,我陷入错误“循环导入”。
我会将 discord 机器人代码移出 main.py
,因此它不再依赖于 keep_alive
.
的导入
bot.py:
import os
import discord
client = discord.Client()
async def SendMeMessage():
user = await client.fetch_user('my id')
await user.create_dm()
await user.dm_channel.send("Someone needs help")
keep_alive.py:
from flask import Flask
from threading import Thread
from bot import SendMeMessage
app = Flask('')
@app.route('/')
def home():
SendMeMessage()
return "Hello. I am alive!"
def run():
app.run(host='0.0.0.0', port=8080)
def keep_alive():
t = Thread(target=run)
t.start()
main.py:
import os
from keep_alive import keep_alive
from bot import client
my_secret = os.environ['Token']
keep_alive()
client.run(my_secret)
这样,bot.py
在keep_alive.py
运行的时候就已经完全导入了,所以不再循环导入。
我有这两个文件:
main.py
import os
import discord
from keep_alive import keep_alive
client = discord.Client()
my_secret = os.environ['Token']
async def SendMeMessage():
user = await client.fetch_user('my id')
await user.create_dm()
await user.dm_channel.send("Someone needs help")
keep_alive()
client.run(my_secret)
keep_alive.py
from flask import Flask
from threading import Thread
#from main import SendMeMessage
app = Flask('')
@app.route('/')
def home():
#SendMeMessage()
return "Hello. I am alive!"
def run():
app.run(host='0.0.0.0', port=8080)
def keep_alive():
t = Thread(target=run)
t.start()
我想导入 SendMessage。因此,当有人在 Flask 服务器上发送获取请求时,我想从我的 discord 机器人接收消息。当我实施注释代码时,我陷入错误“循环导入”。
我会将 discord 机器人代码移出 main.py
,因此它不再依赖于 keep_alive
.
bot.py:
import os
import discord
client = discord.Client()
async def SendMeMessage():
user = await client.fetch_user('my id')
await user.create_dm()
await user.dm_channel.send("Someone needs help")
keep_alive.py:
from flask import Flask
from threading import Thread
from bot import SendMeMessage
app = Flask('')
@app.route('/')
def home():
SendMeMessage()
return "Hello. I am alive!"
def run():
app.run(host='0.0.0.0', port=8080)
def keep_alive():
t = Thread(target=run)
t.start()
main.py:
import os
from keep_alive import keep_alive
from bot import client
my_secret = os.environ['Token']
keep_alive()
client.run(my_secret)
这样,bot.py
在keep_alive.py
运行的时候就已经完全导入了,所以不再循环导入。