### Complete Example Source: https://github.com/evolution-foundation/evolution-client-python/blob/main/README.md A comprehensive example showing the initialization of the EvolutionClient, configuration of WebSocket, registration of handlers, and connection management. ```python from evolutionapi.client import EvolutionClient from evolutionapi.models.websocket import WebSocketConfig import logging import time # Logging configuration logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) logger = logging.getLogger(__name__) def handle_message(data): logger.info(f"New message received: {data}") def handle_qrcode(data): logger.info(f"QR Code updated: {data}") def handle_connection(data): logger.info(f"Connection status: {data}") def main(): # Initialize client client = EvolutionClient( base_url="http://localhost:8081", api_token="your-api-token" ) # Configure WebSocket websocket_config = WebSocketConfig( enabled=True, events=[ "MESSAGES_UPSERT", "QRCODE_UPDATED", "CONNECTION_UPDATE" ] ) # Set WebSocket configuration client.websocket.set_websocket("instance_id", websocket_config, "instance_token") # Create WebSocket manager websocket = client.create_websocket( instance_id="instance_id", api_token="your_api_token", max_retries=5, retry_delay=1.0 ) # Register handlers websocket.on("messages.upsert", handle_message) websocket.on("qrcode.updated", handle_qrcode) websocket.on("connection.update", handle_connection) try: # Connect to WebSocket websocket.connect() logger.info("Connected to WebSocket. Waiting for events...") # Keep the program running while True: time.sleep(1) except KeyboardInterrupt: logger.info("Closing connection...") websocket.disconnect() except Exception as e: logger.error(f"Error: {e}") websocket.disconnect() if __name__ == "__main__": main() ``` -------------------------------- ### Installation Source: https://github.com/evolution-foundation/evolution-client-python/blob/main/README.md Install the evolutionapi package using pip. ```bash pip install evolutionapi ``` -------------------------------- ### Logging Configuration Source: https://github.com/evolution-foundation/evolution-client-python/blob/main/README.md Example of how to adjust the log level for the WebSocket service to get more detailed logs during debugging. ```python # For more details logging.getLogger("evolutionapi.services.websocket").setLevel(logging.DEBUG) ``` -------------------------------- ### Get Instance Info Source: https://github.com/evolution-foundation/evolution-client-python/blob/main/README.md Retrieve detailed information about a specific instance. ```python response = client.instances.get_instance_info(instance_id, instance_token) ``` -------------------------------- ### Example with Specific Events Source: https://github.com/evolution-foundation/evolution-client-python/blob/main/README.md Demonstrates how to register specific event handlers for different WebSocket events like messages, contacts, groups, and presence updates. ```python def handle_messages(data): logger.info(f"New message: {data}") def handle_contacts(data): logger.info(f"Contacts updated: {data}") def handle_groups(data): logger.info(f"Groups updated: {data}") def handle_presence(data): logger.info(f"Presence status: {data}") # Registering handlers for different events websocket.on("messages.upsert", handle_messages) websocket.on("contacts.upsert", handle_contacts) websocket.on("groups.upsert", handle_groups) websocket.on("presence.update", handle_presence) ``` -------------------------------- ### Media Message Examples Source: https://github.com/evolution-foundation/evolution-client-python/blob/main/README.md Sending various media types including images, videos, and documents, with options for captions, filenames, and mentions. ```python from evolutionapi.models.message import MediaMessage, MediaType, QuotedMessage # Mensagem com imagem message = MediaMessage( number="5511999999999", mediatype=MediaType.IMAGE.value, mimetype="image/jpeg", caption="Minha imagem", media="base64_da_imagem_ou_url", fileName="imagem.jpg", delay=1000 # delay opcional ) # Mensagem com vídeo message = MediaMessage( number="5511999999999", mediatype=MediaType.VIDEO.value, mimetype="video/mp4", caption="Meu vídeo", media="base64_do_video_ou_url", fileName="video.mp4" ) # Mensagem com documento message = MediaMessage( number="5511999999999", mediatype=MediaType.DOCUMENT.value, mimetype="application/pdf", caption="Meu documento", media="base64_do_documento_ou_url", fileName="documento.pdf" ) # Mensagem com menções message = MediaMessage( number="5511999999999", mediatype=MediaType.IMAGE.value, mimetype="image/jpeg", caption="@everyone Olhem esta imagem!", media="base64_da_imagem", mentionsEveryOne=True, mentioned=["5511999999999", "5511888888888"] ) response = client.messages.send_media(instance_id, message, instance_token) ``` -------------------------------- ### Button Message Examples Source: https://github.com/evolution-foundation/evolution-client-python/blob/main/README.md Creating button messages with different types: reply, URL, and phone number. ```python from evolutionapi.models.message import ButtonMessage, Button # Botão de resposta simples buttons = [ Button( type="reply", displayText="Opção 1", id="1" ), Button( type="reply", displayText="Opção 2", id="2" ) ] # Botão com URL buttons = [ Button( type="url", displayText="Visitar Site", url="https://exemplo.com" ) ] # Botão com número de telefone buttons = [ Button( type="phoneNumber", displayText="Ligar", phoneNumber="5511999999999" ) ] ``` -------------------------------- ### Registering Event Handlers Source: https://github.com/evolution-foundation/evolution-client-python/blob/main/README.md Example of registering handlers for specific WebSocket events. ```python def handle_message(data): print(f"New message received: {data}") def handle_qrcode(data): print(f"QR Code updated: {data}") # Registering handlers websocket.on("messages.upsert", handle_message) websocket.on("qrcode.updated", handle_qrcode) ``` -------------------------------- ### Status Message Examples Source: https://github.com/evolution-foundation/evolution-client-python/blob/main/README.md Sending status updates including text, image, video, and audio, with options for background color and font. ```python from evolutionapi.models.message import StatusMessage, StatusType, FontType # Status de texto message = StatusMessage( type=StatusType.TEXT, content="Meu status de texto", caption="Legenda opcional", backgroundColor="#FF0000", font=FontType.BEBASNEUE_REGULAR, allContacts=True ) # Status de imagem message = StatusMessage( type=StatusType.IMAGE, content="base64_da_imagem", caption="Minha imagem de status" ) # Status de vídeo message = StatusMessage( type=StatusType.VIDEO, content="base64_do_video", caption="Meu vídeo de status" ) # Status de áudio message = StatusMessage( type=StatusType.AUDIO, content="base64_do_audio", caption="Meu áudio de status" ) response = client.messages.send_status(instance_id, message, instance_token) ``` -------------------------------- ### Create New Instance - Basic Configuration Source: https://github.com/evolution-foundation/evolution-client-python/blob/main/README.md Create a new instance with basic configuration including instance name, integration, and QR code option. ```python from evolutionapi.models.instance import InstanceConfig # Configuração básica config = InstanceConfig( instanceName="minha-instancia", integration="WHATSAPP-BAILEYS", qrcode=True ) ``` -------------------------------- ### Get Instance Status Source: https://github.com/evolution-foundation/evolution-client-python/blob/main/README.md Get the current status of a specific instance. ```python response = client.instances.get_instance_status(instance_id, instance_token) ``` -------------------------------- ### Create New Instance - Full Configuration Source: https://github.com/evolution-foundation/evolution-client-python/blob/main/README.md Create a new instance with comprehensive configuration options. ```python from evolutionapi.models.instance import InstanceConfig # Configuração completa config = InstanceConfig( instanceName="minha-instancia", integration="WHATSAPP-BAILEYS", token="token_da_instancia", number="5511999999999", qrcode=True, rejectCall=True, msgCall="Mensagem de chamada rejeitada", groupsIgnore=True, alwaysOnline=True, readMessages=True, readStatus=True, syncFullHistory=True ) new_instance = client.instances.create_instance(config) ``` -------------------------------- ### Initializing the Client Source: https://github.com/evolution-foundation/evolution-client-python/blob/main/README.md Initialize the EvolutionClient with base URL and API token. ```python from evolutionapi.client import EvolutionClient client = EvolutionClient( base_url='http://your-server:port', api_token='your-api-token' ) ``` -------------------------------- ### Get Chat Profile Picture Source: https://github.com/evolution-foundation/evolution-client-python/blob/main/README.md Retrieves the profile picture for a given WhatsApp number. ```python from evolutionapi.models.chat import ProfilePicture config = ProfilePicture( number="5511999999999" ) response = client.chat.get_chat_profile_picture(instance_id, config, instance_token) ``` -------------------------------- ### Get Instance QR Code Source: https://github.com/evolution-foundation/evolution-client-python/blob/main/README.md Retrieve the QR code for a specific instance, typically used for initial connection. ```python response = client.instances.get_instance_qrcode(instance_id, instance_token) ```