编写不和谐自动发送消息

问题描述 投票:0回答:1

我需要在不和谐聊天中及时发送消息

我使用discord.py和时间表

enter image description here 从 Schedule_message 我正在获取时间和我想在某个时间发送的文本 但没有任何错误发生 日程安排消息 = { “11:55”:“扫雷”, “19:55”:“戈尔莫尔”, "01:49": "每日重置" }

async def send_scheduled_message(message):
    channel_id = 1160338542329860116  
    channel = client.get_channel(channel_id)
    if channel is not None:
        await channel.send(message)
    else:
        print(f"Channel with ID {channel_id} not found.")

for time_str, message in schedule_messages.items():
    schedule.every().day.at(time_str, timezone('Europe/London')).do(asyncio.run, send_scheduled_message, message)
python discord.py schedule
1个回答
0
投票

您可以使用

discord.ext.tasks
,这是运行后台任务的官方方式。

文档提供了有关如何使用

Cog
方法的详细信息。由于您似乎使用的是
discord.Client
而不是
discord.ext.commands.Bot
,您可能想做这样的事情:

import asyncio
import schedule
from discord import Client, Intents
from discord.ext import tasks

client = Client(intents=Intents.all())

async def send_scheduled_message(message):
    channel_id = 1160338542329860116
    channel = client.get_channel(channel_id) or await client.fetch_channel(channel_id)
    if channel is not None:
        await channel.send(message)
    else:
        print(f"Channel with ID {channel_id} not found.")

def run_async(coro, *args):
    loop = asyncio.get_running_loop()
    loop.create_task(coro(*args))

# replace with your schedules
schedule.every().second.do(run_async, send_scheduled_message, 'test this')

@tasks.loop(seconds=1.0)
async def loop():
    schedule.run_pending()

@client.event
async def on_ready():
    print('Starting schedule loop.')
    try:
        loop.start()
    except RuntimeError:
        # loop already started
        pass

client.run('...')

run_async
函数是必需的,因为当discord.py已经启动事件循环时,您无法调用
asyncio.run
。它获取当前事件循环并在其中运行
send_scheduled_message

loop
函数是由discord.py管理的循环。开始于
on_ready

© www.soinside.com 2019 - 2024. All rights reserved.