Hello, I’m trying to use the following code to add a multi-line comment to a merge request thread. However, I encountered the following error:
“Comment created: {‘message’: ‘400 Bad Request - Note {:line_code=>[“can’t be blank”, “must be a valid line code”], :position=>[“is incomplete”]}’}”
I have searched online and reviewed various discussions, but I still cannot find a solution.
And I have searched on the Net for all discussions, but still cannot find the answer.
# Step 1: Get the latest version details for SHAs
versions_url = f"{GITLAB_URL}/api/v4/projects/{PROJECT_ID}/merge_requests/{MERGE_REQUEST_ID}/versions"
headers = {"Authorization": f"Bearer {ACCESS_TOKEN}"}
versions_response = requests.get(versions_url, headers=headers)
print(versions_response)
# Extract necessary SHAs
latest_version = versions_response.json()[0]
base_sha = latest_version['base_commit_sha']
head_sha = latest_version['head_commit_sha']
start_sha = latest_version['start_commit_sha']
# Step 2: Calculate line codes for multiline comment
def generate_line_code(old_line, new_line):
sha1_hash = hashlib.sha1(FILE_PATH.encode()).hexdigest()
return f"{sha1_hash}_{old_line}_{new_line}"
start_line_code = generate_line_code(6, 9) # Starting line code (line 1)
end_line_code = generate_line_code(6, 13) # Ending line code (line 10)
print(start_line_code)
print(end_line_code)
# Step 3: Construct the payload
discussion_url = f"{GITLAB_URL}/api/v4/projects/{PROJECT_ID}/merge_requests/{MERGE_REQUEST_ID}/discussions"
# discussion_url = f"https://gitlab.com/api/v4/projects/{PROJECT_ID}/repository/commits/{COMMIT_ID}/comments"
data = {
"body": COMMENT_BODY,
"position": {
"base_sha": base_sha,
"head_sha": head_sha,
"start_sha": start_sha,
"position_type": "text",
"new_path": FILE_PATH,
"old_path": FILE_PATH,
"line_range": {
"start": {
"line_code": start_line_code,
"type": "new"
},
"end": {
"line_code": end_line_code,
"type": "new"
}
}
}
}
# Step 4: Post the comment
response = requests.post(discussion_url, headers=headers, json=data)
print(response)
print("Comment created:", response.json())