首页 > 解决方案 > 发送到通道时接受参数

问题描述

我正在尝试创建一个不和谐的机器人,它接受 2 个参数,用文本格式化它们,然后发送到一个频道。使用此代码它可以工作,但它不会发送自定义内容。它只能预定义我将如何做到这一点?

    if message.content == '!settrend':
    async def args(arg1, arg2):
        output = ''
        output += f"Changed trend of {arg1} to {arg2}"
        await message.channel.send(output)

    await args("test", "test") # I want this to be able to have custom arguments by the command.

标签: pythondiscorddiscord.py

解决方案


而不是检查message.content == '!settrend',你需要先message.content用空格分割,然后检查你得到的第一个标记是'!settrend'.

所以将第一行替换为:

arguments = message.content.split()
if arguments[0] == '!settrend':

然后,最后:

await args(arguments[1], arguments[2])

请注意,此解决方案要求两个参数不包含空格。如果您希望能够使用引号指定间隔参数(例如:)!settrend "first argument" "second argument",请使用shlex.split而不是标准字符串拆分方法:

import shlex
arguments = shlex.split(message.content)

推荐阅读