如何让 Discord 机器人通过命令编辑它自己的上一条消息?

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

我似乎不知道如何让用户的命令编辑 Discord 机器人之前发送的消息。我正在使用discord.py。

我正在创建一个机器人,为我们玩的大型战略视频游戏中的国家保留玩家。机器人将创建一条消息,其中包含所有可用国家/地区的列表,Discord 用户必须执行诸如“!reserve (X Nation)”之类的命令,机器人将更新其列表消息以包括用户选择的国家/地区和他们的国家/地区其后的用户名。

问题是,我能想到的唯一能实现机器人消息编辑的函数是“fetch_message(ID)”函数。但这是行不通的,因为机器人会在我们的游戏结束后删除他们的列表消息,并在下一场游戏中重新发布它。所以消息ID会不断变化。

我需要一个“!reserve (X Nation)”命令,它可以立即了解它希望影响的所需列表所在的位置,并成功编辑该列表。

这是我到目前为止的代码:

import discord
from discord import app_commands
from discord.ext import commands
from discord.utils import get

intents = discord.Intents.all()
client = commands.Bot(command_prefix='!', intents = intents)
tree = app_commands.CommandTree

@client.event
async def on_ready():
    print("The bot is now ready")
    try:
        synced = await tree.sync(guild=discord.Object(id=1210361385112961024))
        print(f"Synced {len(synced)} command(s)")
    except Exception as e:
        print(e)

@client.command()
async def host(ctx):
    message = await ctx.send("Reservations :star: USA")

@client.command()
async def reserve(ctx):
    channel = client.get_channel(CHANNEL ID)
    message = await client.fetch_message() #A fetch message function won't work as the message it's going to be fetching from will have a different ID every few days.
    await message.edit(content="Reservations :star: USA :star: Japan")
python python-3.x discord discord.py
1个回答
0
投票

您需要将消息 ID 存储在某个地方,最好是数据库,但如果它只是 ID 而没有其他内容,则可以使用文本文件来存储消息 ID,并在调用 reserve 命令时检索它。

import discord
from discord import app_commands
from discord.ext import commands
from discord.utils import get

intents = discord.Intents.all()
client = commands.Bot(command_prefix='!', intents = intents)
tree = app_commands.CommandTree

@client.event
async def on_ready():
    print("The bot is now ready")
    try:
        synced = await tree.sync(guild=discord.Object(id=1210361385112961024))
        print(f"Synced {len(synced)} command(s)")
    except Exception as e:
        print(e)

@client.command()
async def host(ctx):
    message = await ctx.send("Reservations :star: USA") # If this is the message, then store its ID in a file
    with open("message.txt", "w") as f:
        f.write(str(message.id))

@client.command()
async def reserve(ctx):
    channel = client.get_channel(CHANNEL ID)
    # Then, later on in the command
    with open("message.txt", "r") as f:
        message_id = int(f.read())
    message = await client.fetch_message(message_id) # There you have the message.
    await message.edit(content="Reservations :star: USA :star: Japan")
© www.soinside.com 2019 - 2024. All rights reserved.