【问题标题】:How can I get the last message that arrives in discord我怎样才能得到最后一条不和谐的消息
【发布时间】:2021-03-08 08:04:51
【问题描述】:

我正在尝试从 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()

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

【问题讨论】:

  • 这个example 获取频道的消息历史记录对您有帮助吗?看起来你可以适应你的场景,并且更通用。

标签: python discord


【解决方案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')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多