【问题标题】:Edit Discord message with the before content replaced使用替换之前的内容编辑 Discord 消息
【发布时间】:2022-11-26 03:05:11
【问题描述】:

我目前正在使用 discord.py 开发一个 Discord 机器人。我创建了一个名为underscored 的命令,目标是编辑机器人发送的每条消息,只需将空格替换为下划线。这是一个例子:

User: /test
Bot: This is a test command.
User: /underscored
User: /test
Bot: This_is_a_test_command.

所以这是命令:

@bot.command()
async def underscored(ctx):
    underscored == True

另一方面,这是我制作的 on_message 事件:

@bot.event
async def on_message(message, before):
    if underscored == True:
        await message.edit(content=before.replace(' ', '_'))

现在,这是我得到的错误:

Traceback (most recent call last):
  File "C:\Users\cold\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
TypeError: on_message() missing 1 required positional argument: 'before'

有人能帮我吗?我完全不明白这是怎么回事。

【问题讨论】:

  • 为什么你认为on_message可以接受第二个论点?不能
  • beforeafter 参数在on_message_edit 函数内部而不是在on_message 内部
  • 感谢 Conner Wolf 08,难道我想做的事情就做不到了吗?
  • 如果“我想做的”是向库方法中添加随机参数,那么不会。 before 的价值从何而来?您当然可以只在命令中设置一个标志并在另一个命令中检查它的值,但这不是这样做的方法。在创建 Discord 机器人之前,您可能想学习更多 Python。

标签: python discord discord.py bots


【解决方案1】:

你得到那个错误是因为on_message事件只有一个参数,即消息(discord.Message类)。可以参考文档here

您必须手动对每个命令实施它,而不是使用 on_message 事件

# global variable that can be accessed by every command
underscored_s = False

@bot.command()
async def underscored(ctx):
    global underscored_s

    # toggle underscored status, turn on if off, turn off if on
    if underscored_s is True:
        underscored_s = False
        await ctx.send("changed underscored to False")
    else:
        underscored_s = True
        await ctx.send("changed underscored to True")

@bot.command()
async def on_message(ctx):
    global underscored_s

    message = "This is a test command."
    if underscored_s is True:
        await ctx.send(message)
    else:
        await ctx.send(message.replace(' ', '_'))

on_message 事件将在用户发送新消息时使用,由机器人进行处理。我认为它不能用于编辑机器人发送的消息作为对 on_message 事件的回复

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-03
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-03
    • 2022-01-05
    相关资源
    最近更新 更多