python - 发送到通道时接受参数
问题描述
我正在尝试创建一个不和谐的机器人,它接受 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.
解决方案
而不是检查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)
推荐阅读
- ansible - 在 playbook 中全局获取文件和变量
- powershell - 当有些是可选的时,Powershell 比较订单项
- c# - 即使编写为忽略异常,try-catch 块内的代码也会引发异常并中断执行
- javascript - 关闭响应式菜单“点击”JavaScript
- c++ - 虚拟地整理碎片内存,就好像它在 C++ 中是连续的一样
- jestjs - 如何测试使用 apollo 客户端 Reactive Var 的组件
- django - 本地建设成功 | CodeBuild AWS 的成功与失败 | 构建日志显示应用程序启动并运行 | 状态永远在进行中
- bash - 将查找文件中的信息写入另一个文件
- javascript - Angular - 图像之间的交叉淡入淡出
- java - 当位移 16 位时,为什么输出因类型转换不同而不同