代码之家  ›  专栏  ›  技术社区  ›  Ian Weed

如何在不和频道中找到第一条消息?

  •  0
  • Ian Weed  · 技术社区  · 2 年前

    我希望能够使用python在特定的discord通道中找到最早的消息,而不是绑定到discord命令。

    我试过使用discordbot,但这些似乎主要用于bot命令,所以我如何在任何时候都能做到这一点?

    我尝试了以下操作:

    import discord
    
    client = Client(intents=discord.Intents.all())
    
    async def getfirstmessage():
        channel = client.get_guild(guildid).get_channel(channelid)
        messages = [message async for message in channel.history(limit=1, oldest_first=True)]
        print(messages)
    

    我得到了这个错误:

    RuntimeWarning: coroutine 'getfirstmessage' was never awaited getfirstmessage()
    

    当我尝试在“getfirstmessage”函数前面添加wait时,如果出现以下错误:

    SyntaxError: 'await' outside function
    

    提前谢谢。

    1 回复  |  直到 2 年前
        1
  •  2
  •   Afaq Ali Shah    2 年前
    import discord
    import asyncio
    
    intents = discord.Intents.default()
    intents.message_content = True  # Enable message content for intents
    
    client = discord.Client(intents=intents)
    
    @client.event
    async def on_ready():
        print(f'Logged in as {client.user.name}')
        await get_first_message()
    
    async def get_first_message():
        guild_id = 1234567890  # Replace with your guild ID
        channel_id = 1234567890  # Replace with your channel ID
    
        guild = client.get_guild(guild_id)
        channel = guild.get_channel(channel_id)
    
        async for message in channel.history(limit=1, oldest_first=True):
            print(f'Earliest message: {message.content}')
            break  # Exit the loop after retrieving the first message
    
    # Run the bot
    loop = asyncio.get_event_loop()
    loop.run_until_complete(client.start('YOUR_BOT_TOKEN'))  # Replace with your bot token
    # Make sure to replace guild_id, channel_id, and 'YOUR_BOT_TOKEN' with your specific values.