是否有一种简单的方法可以将单个消息同步发送给不和谐?

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

我正在开发一个程序,该程序会定期向我的不和谐频道发布消息。由于发布到discord并不是该程序的主要功能,因此我已同步编写了该程序,因此无法与异步discord.py API进行交互。

到目前为止,我能做的最好的事情是:

import discord
import asyncio

discord_token = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456"
discord_channel_ids = { 'test_channel': 012345678901234567 }

async def send_msg_async(client, channel_ids, message):
    await client.wait_until_ready()
    for cid in channel_ids:
        channel = client.get_channel(cid)
        await channel.send(message)
    await client.logout()

def send_message(channel_names, message):
    try:
        loop = asyncio.new_event_loop()
        client = discord.Client(loop=loop)

        channel_ids = [discord_channel_ids[cname] for cname in channel_names]
        client.loop.create_task(send_msg_async(client, channel_ids, message))
        client.run(discord_token)
    except Exception as e:
        print(f"Exception sending message to discord: {e}")

if __name__ == "__main__":
    send_message(["test_channel"], "This is a test.")

以上内容实质上创建了一个新的事件循环,登录,发送消息,注销,然后关闭事件循环。但是,它非常不稳定,执行所需的任务需要5到6秒钟(到目前为止,最昂贵的操作是client.wait_until_ready(),该命令登录到discord)。我想知道,除了将我的整个程序重写为异步之外,是否还有更好的方法可以做到这一点。

python asynchronous discord message synchronous
1个回答
-1
投票

如果您想每n次执行something,则discord扩展库提供了异步运行的tasks

示例:

import discord
from discord.ext import commands, tasks

client = commands.Bot()

@tasks.loop(seconds=15.0)
async def my_task():
    print('I am a task, hello')

@client.event
async def on_ready():
  my_task.start()
© www.soinside.com 2019 - 2024. All rights reserved.