我做了一個不和諧的機器人。它檢查訊息何時包含單詞“kdaj”和“zoom”。當它這樣做時,它將向服務器發送一條訊息。我想知道如何讓這個程式也檢查時間是否是 12:00 然后發送另一條訊息。有任何想法嗎?程式:
import discord
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
my_secret = 'Here's my key'
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(msg):
print(msg)
msg_words1 = msg.content.split(' ')
msg_words = []
for i in msg_words1:
msg_words.append(i.lower())
if msg.author == client.user:
return
if ('zoom' in msg_words and 'kdaj' in msg_words) or ('zoom' in msg_words and 'kdaj?' in msg_words) or ('zoom?' in msg_words and 'kdaj' in msg_words):
await msg.channel.send('Zoom imamo vsak torek od 16:00 do 17:30')
client.run(my_secret)
uj5u.com熱心網友回復:
邊注
我注意到的第一件事是您問題中的語法著色有點奇怪。經過進一步檢查,我注意到在第 8 行你的字串中有一個撇號。如果您使用這樣的雙引號,這很好:
my_secret = "Here's my key"
或者像這樣的轉義字符:
my_secret = 'Here\'s my key'
但是在當前的設定中,Python 會認為你的字串在“Here”之后結束,所以它會拋出一個錯誤。
實際答案
關于您的實際問題,您可以采取幾種方法,我不熟悉 Discord API,因此我將為您提供另一個潛在的解決方案。
您可以撰寫一個單獨的函式以在給定時間同時運行并讓它發送自己的訊息。
這篇文章描述了如何在給定的時間運行一個函式
這是一個設定示例,該設定將導致每天中午 12 點運行一個函式(列印 hello world),改編自上述鏈接。注意:這是一種快速而骯臟的方法,肯定有更好的方法
from datetime import datetime
from threading import Timer
def hello_world():
print("hello world")
# 86400 seconds in a day
Timer(86400, hello_world).start()
if __name__ == "__main__":
currentDateTime = datetime.today()
desiredTime = currentDateTime.replace(hour=12, minute=0, second=0, microsecond=0)
dt = desiredTime - currentDateTime
secs = dt.total_seconds()
t = Timer(secs, hello_world)
t.start()
此功能可以調整為通過您的 Discord 機器人發送訊息,這應該可以實作您的目標。讓我知道這是否適合你。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/512605.html
