3 回答

TA貢獻1906條經(jīng)驗 獲得超10個贊
您可以創(chuàng)建一個后臺任務來執(zhí)行此操作并將消息發(fā)布到所需的頻道。
您還需要使用asyncio.sleep()而不是time.sleep()因為后者會阻塞并且可能會凍結并崩潰您的機器人。
我還添加了一項檢查,以便該頻道不會在早上 7 點的每一秒都收到垃圾郵件。
discord.pyv2.0
from discord.ext import commands, tasks
import discord
import datetime
time = datetime.datetime.now
class MyClient(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.msg_sent = False
async def on_ready(self):
channel = bot.get_channel(123456789) # replace with channel ID that you want to send to
await self.timer.start(channel)
@tasks.loop(seconds=1)
async def timer(self, channel):
if time().hour == 7 and time().minute == 0:
if not self.msg_sent:
await channel.send('Its 7 am')
self.msg_sent = True
else:
self.msg_sent = False
bot = MyClient(command_prefix='!', intents=discord.Intents().all())
bot.run('token')
discord.pyv1.0
from discord.ext import commands
import datetime
import asyncio
time = datetime.datetime.now
bot = commands.Bot(command_prefix='!')
async def timer():
await bot.wait_until_ready()
channel = bot.get_channel(123456789) # replace with channel ID that you want to send to
msg_sent = False
while True:
if time().hour == 7 and time().minute == 0:
if not msg_sent:
await channel.send('Its 7 am')
msg_sent = True
else:
msg_sent = False
await asyncio.sleep(1)
bot.loop.create_task(timer())
bot.run('TOKEN')

TA貢獻1847條經(jīng)驗 獲得超7個贊
從Discord.py 文檔中,當您設置了客戶端時,您可以使用以下格式直接向頻道發(fā)送消息:
channel?=?client.get_channel(12324234183172) await?channel.send('hello')
擁有頻道后(設置客戶端后),您可以根據(jù)需要編輯該代碼片段,以選擇適當?shù)念l道以及所需的消息。請記住"You can only use await inside async def functions and nowhere else."
,您需要設置一個異步函數(shù)來執(zhí)行此操作,并且您的簡單While True:
循環(huán)可能不起作用

TA貢獻1862條經(jīng)驗 獲得超6個贊
根據(jù)discord.py的文檔,您首先需要通過其id獲取頻道,然后才能發(fā)送消息。
您必須直接獲取通道,然后調(diào)用適當?shù)姆椒?。例子?/p>
channel?=?client.get_channel(12324234183172) await?channel.send('hello')
希望這可以幫助。
添加回答
舉報