我怎样才能获得不和谐到达的最后一条消息

时间:2021-03-07 23:18:47

标签: python discord

我正在尝试从 X GUILD 和 Y CHANNEL 获取最后一条消息,这些消息不和谐地到达,只是为了读取它并将其打印到 Phyton 控制台中,但这太令人困惑了,有机器人令牌和官方 API,这是一个以我目前的知识水平,我一个人完成这一切有点困难。

所以,这是我现在的代码。 我也很难理解同步和异步函数。

import discord
import asyncio

client = discord.Client()

async def get_message(CHANNEL_ID):
    msg = await client.get_channel(CHANNEL_ID).history(limit=1).flatten()
    msg = msg[0]
    print(msg)

def main():
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    loop.run_until_complete(get_message("XXXXXXXXXXXXXXXXXXX"))

main()

请问,有人可以帮忙吗?我将不胜感激!!! 我想做的事情很简单,但对我来说太难了。

1 个答案:

答案 0 :(得分:1)

Python Discord 库完全基于事件。例如,当一条消息发生时,您将收到一个可以响应的事件。我们使用异步函数是因为 Discord API 的大多数操作都有延迟,我们希望在等待 API 响应的同时继续做其他事情。

这使得很难获得最后一条消息。我们仍然可以通过创建一个等待 API 连接、获取消息然后退出的后台任务来实现。

基于此处的示例: https://github.com/Rapptz/discord.py/blob/master/examples/background_task.py

import discord
import asyncio

class MyClient(discord.Client):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # create the background task and run it in the background
        self.loop.create_task(self.get_message(1111111111111))

    async def get_message(self, CHANNEL_ID):
        await self.wait_until_ready()
        msg = await self.get_channel(CHANNEL_ID).history(limit=1).flatten()
        msg = msg[0]
        print(msg)
        await self.close() # close client once we are done


client = MyClient()
client.run('your token here')