這是我的代碼的骨架版本:
僵尸軟體
import discord
client = discord.Client()
async def send_notification(notification):#this method is tested and works when called from same file
for guild in client.guilds:
for channel in guild.text_channels:
if channel.name == CHANNEL_NAME:
await channel.sent(notification)
def start_bot():
client.run(TOKEN)
def notification(notification):
asyncio.create_task(send_notification(notification))#likely error here
主檔案
import bot
from time import sleep
def main():
bot.start_bot()
sleep(10)
bot.notification('some notification')
main()
您好,我正在嘗試從不同的 python 檔案向所有行會發送訊息。我知道我在處理異步任務的方式上犯了一些基本錯誤。目前main.py甚至沒有進入sleep()陳述句。
- 是否有某種方法可以從main.py參考客戶端,以便可以使用它呼叫方法
- 我可以創建一些 api 以便任何 python 檔案都可以訪問機器人內部的方法嗎
提前致謝。
uj5u.com熱心網友回復:
找到解決方法。更多地查看discord.py的檔案,很明顯它喜歡成為它自己獨立的東西,這就是為什么我從其他檔案參考它的方法并不理想。我最終不斷地從一個json檔案中讀取:
async def update_notifications():
while True:
with open(JSON_PATH, 'r') as file:# extract all content from json file
content = json.load(file)
while len(content['notifications']) > 0:# send all notifications one by one
await send_notification(content['notifications'][0])
content['notifications'].pop(0)
with open(JSON_PATH, 'w') as file:# write the now empty content back to json file
json.dump(content, file, indent=4)
await asyncio.sleep(20)# sleep in seconds
json 檔案的結構如下:
{
"notifications":["notification1","notification2",...]
}
為了觸發協程,update_notifications()創建了一個回圈on_ready。
@client.event
async def on_ready():
client.loop.create_task(update_notifications())
這種方法的優點是任何 python 腳本,甚至其他語言都可以通過寫入 json 檔案來告訴機器人發送通知。
uj5u.com熱心網友回復:
client.run(TOKEN)阻止主執行緒的執行,因為它啟動了一個異步事件回圈。如果您只想在機器人啟動后運行任務,您可以使用機器人的on_ready處理程式:
import discord
client = discord.Client()
CHANNEL_NAME = "some-channel"
@client.event
async def on_ready():
for guild in client.guilds:
for channel in guild.text_channels:
if channel.name == CHANNEL_NAME:
await channel.send("hello world!")
client.run('your token here')
請參閱:https : //discordpy.readthedocs.io/en/stable/quickstart.html
要回答您的 2 個問題:
bot.client應該這樣做,但是在制作 Discord 機器人時,您正在做的是一種反模式。最好堅持檔案。但是,您可以使用繼承對您的機器人進行子類化,但這有點高級。- 您已經可以訪問機器人方法。往上看。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/406954.html
標籤:
