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

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

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

我尝试过使用不和谐机器人,但似乎这些机器人主要用于机器人命令,那么我如何才能随时执行此操作?

我尝试过以下方法:

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”函数前面添加等待时,如果出现此错误:

SyntaxError: 'await' outside function

提前致谢。

python discord discord.py
1个回答
0
投票
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.
© www.soinside.com 2019 - 2024. All rights reserved.