import requests
import json

# --- PLEASE REPLACE THESE PLACEHOLDERS --- #
BITRIX24_DOMAIN = "youmats.bitrix24.com"  # e.g., "mycompany.bitrix24.com"
# Choose ONE of the following authentication methods:
# 1. Webhook (Simpler for testing, less secure for production)
WEBHOOK_ENDPOINT = "https://youmats.bitrix24.com/rest/1/b8flxxfaq10oo3ql/"
AUTH_TOKEN = None # Not needed if using webhook

# 2. OAuth 2.0 Access Token (More secure, standard for applications)
# WEBHOOK_ENDPOINT = "https://{}/rest/".format(BITRIX24_DOMAIN)
# AUTH_TOKEN = "YOUR_OAUTH_ACCESS_TOKEN"
# --- END OF PLACEHOLDERS --- #

CHAT_ID = 236901
METHOD = "imopenlines.session.join"

api_url = f"{WEBHOOK_ENDPOINT}{METHOD}"

params = {
    'CHAT_ID': CHAT_ID
}

# Add auth token if using OAuth
if AUTH_TOKEN:
    params['auth'] = AUTH_TOKEN

print(f"Attempting to join chat ID: {CHAT_ID}")
print(f"Calling API method: {METHOD}")
print(f"Using endpoint: {api_url.split('rest/')[0]}rest/...") # Mask sensitive part

try:
    response = requests.post(api_url, json=params)
    response.raise_for_status()  # Raise an exception for bad status codes (4xx or 5xx)

    print("\n--- Response ---")
    try:
        result = response.json()
        print(json.dumps(result, indent=2))

        if result.get("result") is True:
            print("\nSuccessfully joined the chat session.")
        elif "error" in result:
            print(f"\nError joining chat: {result.get('error')} - {result.get('error_description')}")
            print("Possible reasons (check documentation):")
            print("- ACCESS_DENIED: User lacks permission.")
            print("- CHAT_TYPE: Chat is not an open line.")
            print("- CHAT_ID: Incorrect chat ID provided.")
        else:
            print("\nUnexpected response format.")

    except json.JSONDecodeError:
        print(f"Error: Could not decode JSON response. Status Code: {response.status_code}")
        print(f"Response text: {response.text}")

except requests.exceptions.RequestException as e:
    print(f"\nError making request: {e}")
except Exception as e:
    print(f"\nAn unexpected error occurred: {e}") 